upfynai-code 0.1.0

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 (65) hide show
  1. package/LICENSE +22 -0
  2. package/bin/cli.js +86 -0
  3. package/dist/assets/CanvasPanel-B48gAKVY.js +538 -0
  4. package/dist/assets/CanvasPanel-B48gAKVY.js.map +1 -0
  5. package/dist/assets/CanvasPanel-BsOG3EVs.css +1 -0
  6. package/dist/assets/index-CEhTwG68.css +1 -0
  7. package/dist/assets/index-GqAGWpJI.js +70 -0
  8. package/dist/assets/index-GqAGWpJI.js.map +1 -0
  9. package/dist/index.html +18 -0
  10. package/index.html +17 -0
  11. package/package.json +67 -0
  12. package/src/App.tsx +226 -0
  13. package/src/components/canvas/CanvasPanel.tsx +62 -0
  14. package/src/components/canvas/layout/graph-builder.ts +136 -0
  15. package/src/components/canvas/shapes/CompactionNodeShape.tsx +76 -0
  16. package/src/components/canvas/shapes/SessionNodeShape.tsx +93 -0
  17. package/src/components/canvas/shapes/StatuslineWidgetShape.tsx +125 -0
  18. package/src/components/canvas/shapes/TextResponseNodeShape.tsx +86 -0
  19. package/src/components/canvas/shapes/ToolCallNodeShape.tsx +107 -0
  20. package/src/components/canvas/shapes/ToolResultNodeShape.tsx +87 -0
  21. package/src/components/canvas/shapes/shared-styles.ts +35 -0
  22. package/src/components/chat/ChatPanel.tsx +96 -0
  23. package/src/components/chat/InputBar.tsx +81 -0
  24. package/src/components/chat/MessageList.tsx +130 -0
  25. package/src/components/chat/PermissionDialog.tsx +70 -0
  26. package/src/components/layout/FolderSelector.tsx +152 -0
  27. package/src/components/layout/ModelSelector.tsx +65 -0
  28. package/src/components/layout/SessionManager.tsx +115 -0
  29. package/src/components/statusline/StatuslineBar.tsx +114 -0
  30. package/src/main.tsx +10 -0
  31. package/src/server/claude-session.ts +156 -0
  32. package/src/server/index.ts +149 -0
  33. package/src/services/stream-consumer.ts +330 -0
  34. package/src/statusline-core/bin/statusline.sh +121 -0
  35. package/src/statusline-core/commands/sls-config.md +42 -0
  36. package/src/statusline-core/commands/sls-doctor.md +35 -0
  37. package/src/statusline-core/commands/sls-help.md +48 -0
  38. package/src/statusline-core/commands/sls-layout.md +38 -0
  39. package/src/statusline-core/commands/sls-preview.md +34 -0
  40. package/src/statusline-core/commands/sls-theme.md +40 -0
  41. package/src/statusline-core/installer.js +228 -0
  42. package/src/statusline-core/layouts/compact.sh +21 -0
  43. package/src/statusline-core/layouts/full.sh +62 -0
  44. package/src/statusline-core/layouts/standard.sh +39 -0
  45. package/src/statusline-core/lib/core.sh +389 -0
  46. package/src/statusline-core/lib/helpers.sh +81 -0
  47. package/src/statusline-core/lib/json-parser.sh +71 -0
  48. package/src/statusline-core/themes/catppuccin.sh +32 -0
  49. package/src/statusline-core/themes/default.sh +37 -0
  50. package/src/statusline-core/themes/gruvbox.sh +32 -0
  51. package/src/statusline-core/themes/nord.sh +32 -0
  52. package/src/statusline-core/themes/tokyo-night.sh +32 -0
  53. package/src/store/canvas-store.ts +50 -0
  54. package/src/store/chat-store.ts +60 -0
  55. package/src/store/permission-store.ts +29 -0
  56. package/src/store/session-store.ts +52 -0
  57. package/src/store/statusline-store.ts +160 -0
  58. package/src/styles/global.css +117 -0
  59. package/src/themes/index.ts +149 -0
  60. package/src/types/canvas-graph.ts +24 -0
  61. package/src/types/sdk-messages.ts +156 -0
  62. package/src/types/statusline-fields.ts +67 -0
  63. package/src/vite-env.d.ts +1 -0
  64. package/tsconfig.json +26 -0
  65. package/vite.config.ts +24 -0
@@ -0,0 +1,538 @@
1
+ var h4=Object.defineProperty;var p4=(n,e,t)=>e in n?h4(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var E=(n,e,t)=>p4(n,typeof e!="symbol"?e+"":e,t);import{c as or,g as Ua,R as _e,r as x,j as p,a as f4,b as g4,d as L_,u as j_,e as Of,f as IP}from"./index-GqAGWpJI.js";const fx="__TLDRAW_LIBRARY_VERSIONS__";function m4(){if(globalThis[fx])return globalThis[fx];const n={versions:[],didWarn:!1,scheduledNotice:null};return Object.defineProperty(globalThis,fx,{value:n,writable:!1,configurable:!1,enumerable:!1}),n}function Wi(n,e,t){if(!n||!e||!t)throw new Error("Missing name/version/module system in built version of tldraw library");const r=m4();if(r.versions.push({name:n,version:e,modules:t}),!r.scheduledNotice)try{r.scheduledNotice=setTimeout(()=>{r.scheduledNotice=null,EP(r)},100)}catch{EP(r)}}function EP(n){if(!n.versions.length||n.didWarn)return;const e=n.versions.sort((a,l)=>kP(a.version,l.version)),t=e[e.length-1].version,r=new Set,s=new Map;for(const a of e){if(s.has(a.name)){r.delete(a.name),gx(s,a.name,new Set).add(a.version);continue}a.version===t?r.add(a.name):(r.delete(a.name),gx(s,a.name,new Set).add(a.version))}if(s.size>0){const a=[`${yi("[tldraw]",["bold","bgRed","textWhite"])} ${yi("You have multiple versions of tldraw libraries installed. This can lead to bugs and unexpected behavior.",["textRed","bold"])}`,"",`The latest version you have installed is ${yi(`v${t}`,["bold","textBlue"])}. The following libraries are on the latest version:`,...Array.from(r,l=>` • ✅ ${yi(l,["bold"])}`),"","The following libraries are not on the latest version, or have multiple versions installed:",...Array.from(s,([l,c])=>{const u=Array.from(c).sort(kP).map(d=>yi(`v${d}`,d===t?["textGreen"]:["textRed"]));return` • ❌ ${yi(l,["bold"])} (${u.join(", ")})`})];console.log(a.join(`
2
+ `)),n.didWarn=!0;return}const o=new Map;for(const a of e)gx(o,a.name,{version:a.version,modules:[]}).modules.push(a.modules);const i=new Map;for(const[a,l]of o)l.modules.length>1&&i.set(a,l);if(i.size>0){const a=[`${yi("[tldraw]",["bold","bgRed","textWhite"])} ${yi("You have multiple instances of some tldraw libraries active. This can lead to bugs and unexpected behavior. ",["textRed","bold"])}`,"","This usually means that your bundler is misconfigured, and is importing the same library multiple times - usually once as an ES Module, and once as a CommonJS module.","","The following libraries have been imported multiple times:",...Array.from(i,([l,c])=>{const u=c.modules.map((d,h)=>d==="esm"?` ${h+1}. ES Modules`:` ${h+1}. CommonJS`).join(`
3
+ `);return` • ❌ ${yi(l,["bold"])} v${c.version}:
4
+ ${u}`}),"","You should configure your bundler to only import one version of each library."];console.log(a.join(`
5
+ `)),n.didWarn=!0;return}}function kP(n,e){const t=n.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/),r=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(\w+))?$/);return!t||!r?n.localeCompare(e):t[1]!==r[1]?Number(t[1])-Number(r[1]):t[2]!==r[2]?Number(t[2])-Number(r[2]):t[3]!==r[3]?Number(t[3])-Number(r[3]):t[4]&&r[4]?t[4].localeCompare(r[4]):t[4]?1:r[4]?-1:0}const y4={bold:"1",textBlue:"94",textRed:"31",textGreen:"32",bgRed:"41",textWhite:"97"};function yi(n,e=[]){return`\x1B[${e.map(t=>y4[t]).join(";")}m${n}\x1B[m`}function gx(n,e,t){return n.has(e)?n.get(e):(n.set(e,t),t)}var tu={exports:{}};tu.exports;var _P;function S4(){return _P||(_P=1,(function(n,e){var t=200,r="__lodash_hash_undefined__",s=1,o=2,i=9007199254740991,a="[object Arguments]",l="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",d="[object Date]",h="[object Error]",f="[object Function]",g="[object GeneratorFunction]",m="[object Map]",y="[object Number]",S="[object Null]",b="[object Object]",w="[object Promise]",v="[object Proxy]",P="[object RegExp]",T="[object Set]",I="[object String]",k="[object Symbol]",A="[object Undefined]",R="[object WeakMap]",D="[object ArrayBuffer]",j="[object DataView]",_="[object Float32Array]",M="[object Float64Array]",O="[object Int8Array]",N="[object Int16Array]",B="[object Int32Array]",H="[object Uint8Array]",z="[object Uint8ClampedArray]",X="[object Uint16Array]",G="[object Uint32Array]",ae=/[\\^$.*+?()[\]{}|]/g,Ce=/^\[object .+?Constructor\]$/,fe=/^(?:0|[1-9]\d*)$/,oe={};oe[_]=oe[M]=oe[O]=oe[N]=oe[B]=oe[H]=oe[z]=oe[X]=oe[G]=!0,oe[a]=oe[l]=oe[D]=oe[u]=oe[j]=oe[d]=oe[h]=oe[f]=oe[m]=oe[y]=oe[b]=oe[P]=oe[T]=oe[I]=oe[R]=!1;var Te=typeof or=="object"&&or&&or.Object===Object&&or,te=typeof self=="object"&&self&&self.Object===Object&&self,re=Te||te||Function("return this")(),ge=e&&!e.nodeType&&e,de=ge&&!0&&n&&!n.nodeType&&n,Ne=de&&de.exports===ge,De=Ne&&Te.process,rt=(function(){try{return De&&De.binding&&De.binding("util")}catch{}})(),lt=rt&&rt.isTypedArray;function pt(L,U){for(var ee=-1,we=L==null?0:L.length,Tt=0,Xe=[];++ee<we;){var Ut=L[ee];U(Ut,ee,L)&&(Xe[Tt++]=Ut)}return Xe}function fn(L,U){for(var ee=-1,we=U.length,Tt=L.length;++ee<we;)L[Tt+ee]=U[ee];return L}function Yn(L,U){for(var ee=-1,we=L==null?0:L.length;++ee<we;)if(U(L[ee],ee,L))return!0;return!1}function Is(L,U){for(var ee=-1,we=Array(L);++ee<L;)we[ee]=U(ee);return we}function xn(L){return function(U){return L(U)}}function Sr(L,U){return L.has(U)}function Xn(L,U){return L==null?void 0:L[U]}function ri(L){var U=-1,ee=Array(L.size);return L.forEach(function(we,Tt){ee[++U]=[Tt,we]}),ee}function Zi(L,U){return function(ee){return L(U(ee))}}function Ji(L){var U=-1,ee=Array(L.size);return L.forEach(function(we){ee[++U]=we}),ee}var is=Array.prototype,si=Function.prototype,Qi=Object.prototype,oi=re["__core-js_shared__"],sl=si.toString,Y=Qi.hasOwnProperty,ce=(function(){var L=/[^.]+$/.exec(oi&&oi.keys&&oi.keys.IE_PROTO||"");return L?"Symbol(src)_1."+L:""})(),Re=Qi.toString,ft=RegExp("^"+sl.call(Y).replace(ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xr=Ne?re.Buffer:void 0,qn=re.Symbol,ii=re.Uint8Array,as=Qi.propertyIsEnumerable,br=is.splice,Es=qn?qn.toStringTag:void 0,Js=Object.getOwnPropertySymbols,ai=xr?xr.isBuffer:void 0,ec=Zi(Object.keys,Object),kd=fi(re,"DataView"),ea=fi(re,"Map"),ol=fi(re,"Promise"),Qs=fi(re,"Set"),_d=fi(re,"WeakMap"),il=fi(Object,"create"),US=Pe(kd),KS=Pe(ea),WS=Pe(ol),eo=Pe(Qs),VS=Pe(_d),bp=qn?qn.prototype:void 0,Md=bp?bp.valueOf:void 0;function li(L){var U=-1,ee=L==null?0:L.length;for(this.clear();++U<ee;){var we=L[U];this.set(we[0],we[1])}}function GS(){this.__data__=il?il(null):{},this.size=0}function ci(L){var U=this.has(L)&&delete this.__data__[L];return this.size-=U?1:0,U}function YS(L){var U=this.__data__;if(il){var ee=U[L];return ee===r?void 0:ee}return Y.call(U,L)?U[L]:void 0}function XS(L){var U=this.__data__;return il?U[L]!==void 0:Y.call(U,L)}function qS(L,U){var ee=this.__data__;return this.size+=this.has(L)?0:1,ee[L]=il&&U===void 0?r:U,this}li.prototype.clear=GS,li.prototype.delete=ci,li.prototype.get=YS,li.prototype.has=XS,li.prototype.set=qS;function to(L){var U=-1,ee=L==null?0:L.length;for(this.clear();++U<ee;){var we=L[U];this.set(we[0],we[1])}}function ZS(){this.__data__=[],this.size=0}function tc(L){var U=this.__data__,ee=hi(U,L);if(ee<0)return!1;var we=U.length-1;return ee==we?U.pop():br.call(U,ee,1),--this.size,!0}function JS(L){var U=this.__data__,ee=hi(U,L);return ee<0?void 0:U[ee][1]}function QS(L){return hi(this.__data__,L)>-1}function Io(L,U){var ee=this.__data__,we=hi(ee,L);return we<0?(++this.size,ee.push([L,U])):ee[we][1]=U,this}to.prototype.clear=ZS,to.prototype.delete=tc,to.prototype.get=JS,to.prototype.has=QS,to.prototype.set=Io;function di(L){var U=-1,ee=L==null?0:L.length;for(this.clear();++U<ee;){var we=L[U];this.set(we[0],we[1])}}function ex(){this.size=0,this.__data__={hash:new li,map:new(ea||to),string:new li}}function tx(L){var U=nc(this,L).delete(L);return this.size-=U?1:0,U}function nx(L){return nc(this,L).get(L)}function rx(L){return nc(this,L).has(L)}function sx(L,U){var ee=nc(this,L),we=ee.size;return ee.set(L,U),this.size+=ee.size==we?0:1,this}di.prototype.clear=ex,di.prototype.delete=tx,di.prototype.get=nx,di.prototype.has=rx,di.prototype.set=sx;function ui(L){var U=-1,ee=L==null?0:L.length;for(this.__data__=new di;++U<ee;)this.add(L[U])}function ox(L){return this.__data__.set(L,r),this}function wp(L){return this.__data__.has(L)}ui.prototype.add=ui.prototype.push=ox,ui.prototype.has=wp;function Eo(L){var U=this.__data__=new to(L);this.size=U.size}function ix(){this.__data__=new to,this.size=0}function ax(L){var U=this.__data__,ee=U.delete(L);return this.size=U.size,ee}function lx(L){return this.__data__.get(L)}function vp(L){return this.__data__.has(L)}function cx(L,U){var ee=this.__data__;if(ee instanceof to){var we=ee.__data__;if(!ea||we.length<t-1)return we.push([L,U]),this.size=++ee.size,this;ee=this.__data__=new di(we)}return ee.set(L,U),this.size=ee.size,this}Eo.prototype.clear=ix,Eo.prototype.delete=ax,Eo.prototype.get=lx,Eo.prototype.has=vp,Eo.prototype.set=cx;function dx(L,U){var ee=on(L),we=!ee&&Ge(L),Tt=!ee&&!we&&an(L),Xe=!ee&&!we&&!Tt&&vr(L),Ut=ee||we||Tt||Xe,vn=Ut?Is(L.length,String):[],Dn=vn.length;for(var Lt in L)Y.call(L,Lt)&&!(Ut&&(Lt=="length"||Tt&&(Lt=="offset"||Lt=="parent")||Xe&&(Lt=="buffer"||Lt=="byteLength"||Lt=="byteOffset")||px(Lt,Dn)))&&vn.push(Lt);return vn}function hi(L,U){for(var ee=L.length;ee--;)if(_t(L[ee][0],U))return ee;return-1}function ta(L,U,ee){var we=U(L);return on(L)?we:fn(we,ee(L))}function zr(L){return L==null?L===void 0?A:S:Es&&Es in Object(L)?_p(L):ie(L)}function Cp(L){return wn(L)&&zr(L)==a}function Pp(L,U,ee,we,Tt){return L===U?!0:L==null||U==null||!wn(L)&&!wn(U)?L!==L&&U!==U:ux(L,U,ee,we,Pp,Tt)}function ux(L,U,ee,we,Tt,Xe){var Ut=on(L),vn=on(U),Dn=Ut?l:ks(L),Lt=vn?l:ks(U);Dn=Dn==a?b:Dn,Lt=Lt==a?b:Lt;var ls=Dn==b,ro=Lt==b,Qn=Dn==Lt;if(Qn&&an(L)){if(!an(U))return!1;Ut=!0,ls=!1}if(Qn&&!ls)return Xe||(Xe=new Eo),Ut||vr(L)?Ip(L,U,ee,we,Tt,Xe):Ad(L,U,Dn,ee,we,Tt,Xe);if(!(ee&s)){var _s=ls&&Y.call(L,"__wrapped__"),Ms=ro&&Y.call(U,"__wrapped__");if(_s||Ms){var na=_s?L.value():L,mi=Ms?U.value():U;return Xe||(Xe=new Eo),Tt(na,mi,ee,we,Xe)}}return Qn?(Xe||(Xe=new Eo),Ep(L,U,ee,we,Tt,Xe)):!1}function hx(L){if(!bn(L)||F(L))return!1;var U=wr(L)?ft:Ce;return U.test(Pe(L))}function pi(L){return wn(L)&&$r(L.length)&&!!oe[zr(L)]}function Tp(L){if(!V(L))return ec(L);var U=[];for(var ee in Object(L))Y.call(L,ee)&&ee!="constructor"&&U.push(ee);return U}function Ip(L,U,ee,we,Tt,Xe){var Ut=ee&s,vn=L.length,Dn=U.length;if(vn!=Dn&&!(Ut&&Dn>vn))return!1;var Lt=Xe.get(L);if(Lt&&Xe.get(U))return Lt==U;var ls=-1,ro=!0,Qn=ee&o?new ui:void 0;for(Xe.set(L,U),Xe.set(U,L);++ls<vn;){var _s=L[ls],Ms=U[ls];if(we)var na=Ut?we(Ms,_s,ls,U,L,Xe):we(_s,Ms,ls,L,U,Xe);if(na!==void 0){if(na)continue;ro=!1;break}if(Qn){if(!Yn(U,function(mi,al){if(!Sr(Qn,al)&&(_s===mi||Tt(_s,mi,ee,we,Xe)))return Qn.push(al)})){ro=!1;break}}else if(!(_s===Ms||Tt(_s,Ms,ee,we,Xe))){ro=!1;break}}return Xe.delete(L),Xe.delete(U),ro}function Ad(L,U,ee,we,Tt,Xe,Ut){switch(ee){case j:if(L.byteLength!=U.byteLength||L.byteOffset!=U.byteOffset)return!1;L=L.buffer,U=U.buffer;case D:return!(L.byteLength!=U.byteLength||!Xe(new ii(L),new ii(U)));case u:case d:case y:return _t(+L,+U);case h:return L.name==U.name&&L.message==U.message;case P:case I:return L==U+"";case m:var vn=ri;case T:var Dn=we&s;if(vn||(vn=Ji),L.size!=U.size&&!Dn)return!1;var Lt=Ut.get(L);if(Lt)return Lt==U;we|=o,Ut.set(L,U);var ls=Ip(vn(L),vn(U),we,Tt,Xe,Ut);return Ut.delete(L),ls;case k:if(Md)return Md.call(L)==Md.call(U)}return!1}function Ep(L,U,ee,we,Tt,Xe){var Ut=ee&s,vn=kp(L),Dn=vn.length,Lt=kp(U),ls=Lt.length;if(Dn!=ls&&!Ut)return!1;for(var ro=Dn;ro--;){var Qn=vn[ro];if(!(Ut?Qn in U:Y.call(U,Qn)))return!1}var _s=Xe.get(L);if(_s&&Xe.get(U))return _s==U;var Ms=!0;Xe.set(L,U),Xe.set(U,L);for(var na=Ut;++ro<Dn;){Qn=vn[ro];var mi=L[Qn],al=U[Qn];if(we)var TP=Ut?we(al,mi,Qn,U,L,Xe):we(mi,al,Qn,L,U,Xe);if(!(TP===void 0?mi===al||Tt(mi,al,ee,we,Xe):TP)){Ms=!1;break}na||(na=Qn=="constructor")}if(Ms&&!na){var Ap=L.constructor,Dp=U.constructor;Ap!=Dp&&"constructor"in L&&"constructor"in U&&!(typeof Ap=="function"&&Ap instanceof Ap&&typeof Dp=="function"&&Dp instanceof Dp)&&(Ms=!1)}return Xe.delete(L),Xe.delete(U),Ms}function kp(L){return ta(L,ko,Dd)}function nc(L,U){var ee=L.__data__;return Mp(U)?ee[typeof U=="string"?"string":"hash"]:ee.map}function fi(L,U){var ee=Xn(L,U);return hx(ee)?ee:void 0}function _p(L){var U=Y.call(L,Es),ee=L[Es];try{L[Es]=void 0;var we=!0}catch{}var Tt=Re.call(L);return we&&(U?L[Es]=ee:delete L[Es]),Tt}var Dd=Js?function(L){return L==null?[]:(L=Object(L),pt(Js(L),function(U){return as.call(L,U)}))}:no,ks=zr;(kd&&ks(new kd(new ArrayBuffer(1)))!=j||ea&&ks(new ea)!=m||ol&&ks(ol.resolve())!=w||Qs&&ks(new Qs)!=T||_d&&ks(new _d)!=R)&&(ks=function(L){var U=zr(L),ee=U==b?L.constructor:void 0,we=ee?Pe(ee):"";if(we)switch(we){case US:return j;case KS:return m;case WS:return w;case eo:return T;case VS:return R}return U});function px(L,U){return U=U??i,!!U&&(typeof L=="number"||fe.test(L))&&L>-1&&L%1==0&&L<U}function Mp(L){var U=typeof L;return U=="string"||U=="number"||U=="symbol"||U=="boolean"?L!=="__proto__":L===null}function F(L){return!!ce&&ce in L}function V(L){var U=L&&L.constructor,ee=typeof U=="function"&&U.prototype||Qi;return L===ee}function ie(L){return Re.call(L)}function Pe(L){if(L!=null){try{return sl.call(L)}catch{}try{return L+""}catch{}}return""}function _t(L,U){return L===U||L!==L&&U!==U}var Ge=Cp((function(){return arguments})())?Cp:function(L){return wn(L)&&Y.call(L,"callee")&&!as.call(L,"callee")},on=Array.isArray;function Zn(L){return L!=null&&$r(L.length)&&!wr(L)}var an=ai||gi;function Jn(L,U){return Pp(L,U)}function wr(L){if(!bn(L))return!1;var U=zr(L);return U==f||U==g||U==c||U==v}function $r(L){return typeof L=="number"&&L>-1&&L%1==0&&L<=i}function bn(L){var U=typeof L;return L!=null&&(U=="object"||U=="function")}function wn(L){return L!=null&&typeof L=="object"}var vr=lt?xn(lt):pi;function ko(L){return Zn(L)?dx(L):Tp(L)}function no(){return[]}function gi(){return!1}n.exports=Jn})(tu,tu.exports)),tu.exports}var x4=S4();const So=Ua(x4);var nu={exports:{}};nu.exports;var MP;function b4(){return MP||(MP=1,(function(n,e){var t=200,r="__lodash_hash_undefined__",s=1,o=2,i=9007199254740991,a="[object Arguments]",l="[object Array]",c="[object Boolean]",u="[object Date]",d="[object Error]",h="[object Function]",f="[object GeneratorFunction]",g="[object Map]",m="[object Number]",y="[object Object]",S="[object Promise]",b="[object RegExp]",w="[object Set]",v="[object String]",P="[object Symbol]",T="[object WeakMap]",I="[object ArrayBuffer]",k="[object DataView]",A="[object Float32Array]",R="[object Float64Array]",D="[object Int8Array]",j="[object Int16Array]",_="[object Int32Array]",M="[object Uint8Array]",O="[object Uint8ClampedArray]",N="[object Uint16Array]",B="[object Uint32Array]",H=/[\\^$.*+?()[\]{}|]/g,z=/^\[object .+?Constructor\]$/,X=/^(?:0|[1-9]\d*)$/,G={};G[A]=G[R]=G[D]=G[j]=G[_]=G[M]=G[O]=G[N]=G[B]=!0,G[a]=G[l]=G[I]=G[c]=G[k]=G[u]=G[d]=G[h]=G[g]=G[m]=G[y]=G[b]=G[w]=G[v]=G[T]=!1;var ae=typeof or=="object"&&or&&or.Object===Object&&or,Ce=typeof self=="object"&&self&&self.Object===Object&&self,fe=ae||Ce||Function("return this")(),oe=e&&!e.nodeType&&e,Te=oe&&!0&&n&&!n.nodeType&&n,te=Te&&Te.exports===oe,re=te&&ae.process,ge=(function(){try{return re&&re.binding("util")}catch{}})(),de=ge&&ge.isTypedArray;function Ne(F,V){for(var ie=-1,Pe=F?F.length:0;++ie<Pe;)if(V(F[ie],ie,F))return!0;return!1}function De(F,V){for(var ie=-1,Pe=Array(F);++ie<F;)Pe[ie]=V(ie);return Pe}function rt(F){return function(V){return F(V)}}function lt(F,V){return F==null?void 0:F[V]}function pt(F){var V=!1;if(F!=null&&typeof F.toString!="function")try{V=!!(F+"")}catch{}return V}function fn(F){var V=-1,ie=Array(F.size);return F.forEach(function(Pe,_t){ie[++V]=[_t,Pe]}),ie}function Yn(F,V){return function(ie){return F(V(ie))}}function Is(F){var V=-1,ie=Array(F.size);return F.forEach(function(Pe){ie[++V]=Pe}),ie}var xn=Array.prototype,Sr=Function.prototype,Xn=Object.prototype,ri=fe["__core-js_shared__"],Zi=(function(){var F=/[^.]+$/.exec(ri&&ri.keys&&ri.keys.IE_PROTO||"");return F?"Symbol(src)_1."+F:""})(),Ji=Sr.toString,is=Xn.hasOwnProperty,si=Xn.toString,Qi=RegExp("^"+Ji.call(is).replace(H,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),oi=fe.Symbol,sl=fe.Uint8Array,Y=Xn.propertyIsEnumerable,ce=xn.splice,Re=Yn(Object.keys,Object),ft=ta(fe,"DataView"),xr=ta(fe,"Map"),qn=ta(fe,"Promise"),ii=ta(fe,"Set"),as=ta(fe,"WeakMap"),br=ta(Object,"create"),Es=pi(ft),Js=pi(xr),ai=pi(qn),ec=pi(ii),kd=pi(as),ea=oi?oi.prototype:void 0,ol=ea?ea.valueOf:void 0;function Qs(F){var V=-1,ie=F?F.length:0;for(this.clear();++V<ie;){var Pe=F[V];this.set(Pe[0],Pe[1])}}function _d(){this.__data__=br?br(null):{}}function il(F){return this.has(F)&&delete this.__data__[F]}function US(F){var V=this.__data__;if(br){var ie=V[F];return ie===r?void 0:ie}return is.call(V,F)?V[F]:void 0}function KS(F){var V=this.__data__;return br?V[F]!==void 0:is.call(V,F)}function WS(F,V){var ie=this.__data__;return ie[F]=br&&V===void 0?r:V,this}Qs.prototype.clear=_d,Qs.prototype.delete=il,Qs.prototype.get=US,Qs.prototype.has=KS,Qs.prototype.set=WS;function eo(F){var V=-1,ie=F?F.length:0;for(this.clear();++V<ie;){var Pe=F[V];this.set(Pe[0],Pe[1])}}function VS(){this.__data__=[]}function bp(F){var V=this.__data__,ie=ui(V,F);if(ie<0)return!1;var Pe=V.length-1;return ie==Pe?V.pop():ce.call(V,ie,1),!0}function Md(F){var V=this.__data__,ie=ui(V,F);return ie<0?void 0:V[ie][1]}function li(F){return ui(this.__data__,F)>-1}function GS(F,V){var ie=this.__data__,Pe=ui(ie,F);return Pe<0?ie.push([F,V]):ie[Pe][1]=V,this}eo.prototype.clear=VS,eo.prototype.delete=bp,eo.prototype.get=Md,eo.prototype.has=li,eo.prototype.set=GS;function ci(F){var V=-1,ie=F?F.length:0;for(this.clear();++V<ie;){var Pe=F[V];this.set(Pe[0],Pe[1])}}function YS(){this.__data__={hash:new Qs,map:new(xr||eo),string:new Qs}}function XS(F){return hi(this,F).delete(F)}function qS(F){return hi(this,F).get(F)}function to(F){return hi(this,F).has(F)}function ZS(F,V){return hi(this,F).set(F,V),this}ci.prototype.clear=YS,ci.prototype.delete=XS,ci.prototype.get=qS,ci.prototype.has=to,ci.prototype.set=ZS;function tc(F){var V=-1,ie=F?F.length:0;for(this.__data__=new ci;++V<ie;)this.add(F[V])}function JS(F){return this.__data__.set(F,r),this}function QS(F){return this.__data__.has(F)}tc.prototype.add=tc.prototype.push=JS,tc.prototype.has=QS;function Io(F){this.__data__=new eo(F)}function di(){this.__data__=new eo}function ex(F){return this.__data__.delete(F)}function tx(F){return this.__data__.get(F)}function nx(F){return this.__data__.has(F)}function rx(F,V){var ie=this.__data__;if(ie instanceof eo){var Pe=ie.__data__;if(!xr||Pe.length<t-1)return Pe.push([F,V]),this;ie=this.__data__=new ci(Pe)}return ie.set(F,V),this}Io.prototype.clear=di,Io.prototype.delete=ex,Io.prototype.get=tx,Io.prototype.has=nx,Io.prototype.set=rx;function sx(F,V){var ie=Ad(F)||Ip(F)?De(F.length,String):[],Pe=ie.length,_t=!!Pe;for(var Ge in F)is.call(F,Ge)&&!(_t&&(Ge=="length"||Cp(Ge,Pe)))&&ie.push(Ge);return ie}function ui(F,V){for(var ie=F.length;ie--;)if(Tp(F[ie][0],V))return ie;return-1}function ox(F){return si.call(F)}function wp(F,V,ie,Pe,_t){return F===V?!0:F==null||V==null||!Dd(F)&&!ks(V)?F!==F&&V!==V:Eo(F,V,wp,ie,Pe,_t)}function Eo(F,V,ie,Pe,_t,Ge){var on=Ad(F),Zn=Ad(V),an=l,Jn=l;on||(an=zr(F),an=an==a?y:an),Zn||(Jn=zr(V),Jn=Jn==a?y:Jn);var wr=an==y&&!pt(F),$r=Jn==y&&!pt(V),bn=an==Jn;if(bn&&!wr)return Ge||(Ge=new Io),on||px(F)?vp(F,V,ie,Pe,_t,Ge):cx(F,V,an,ie,Pe,_t,Ge);if(!(_t&o)){var wn=wr&&is.call(F,"__wrapped__"),vr=$r&&is.call(V,"__wrapped__");if(wn||vr){var ko=wn?F.value():F,no=vr?V.value():V;return Ge||(Ge=new Io),ie(ko,no,Pe,_t,Ge)}}return bn?(Ge||(Ge=new Io),dx(F,V,ie,Pe,_t,Ge)):!1}function ix(F){if(!Dd(F)||ux(F))return!1;var V=fi(F)||pt(F)?Qi:z;return V.test(pi(F))}function ax(F){return ks(F)&&_p(F.length)&&!!G[si.call(F)]}function lx(F){if(!hx(F))return Re(F);var V=[];for(var ie in Object(F))is.call(F,ie)&&ie!="constructor"&&V.push(ie);return V}function vp(F,V,ie,Pe,_t,Ge){var on=_t&o,Zn=F.length,an=V.length;if(Zn!=an&&!(on&&an>Zn))return!1;var Jn=Ge.get(F);if(Jn&&Ge.get(V))return Jn==V;var wr=-1,$r=!0,bn=_t&s?new tc:void 0;for(Ge.set(F,V),Ge.set(V,F);++wr<Zn;){var wn=F[wr],vr=V[wr];if(Pe)var ko=on?Pe(vr,wn,wr,V,F,Ge):Pe(wn,vr,wr,F,V,Ge);if(ko!==void 0){if(ko)continue;$r=!1;break}if(bn){if(!Ne(V,function(no,gi){if(!bn.has(gi)&&(wn===no||ie(wn,no,Pe,_t,Ge)))return bn.add(gi)})){$r=!1;break}}else if(!(wn===vr||ie(wn,vr,Pe,_t,Ge))){$r=!1;break}}return Ge.delete(F),Ge.delete(V),$r}function cx(F,V,ie,Pe,_t,Ge,on){switch(ie){case k:if(F.byteLength!=V.byteLength||F.byteOffset!=V.byteOffset)return!1;F=F.buffer,V=V.buffer;case I:return!(F.byteLength!=V.byteLength||!Pe(new sl(F),new sl(V)));case c:case u:case m:return Tp(+F,+V);case d:return F.name==V.name&&F.message==V.message;case b:case v:return F==V+"";case g:var Zn=fn;case w:var an=Ge&o;if(Zn||(Zn=Is),F.size!=V.size&&!an)return!1;var Jn=on.get(F);if(Jn)return Jn==V;Ge|=s,on.set(F,V);var wr=vp(Zn(F),Zn(V),Pe,_t,Ge,on);return on.delete(F),wr;case P:if(ol)return ol.call(F)==ol.call(V)}return!1}function dx(F,V,ie,Pe,_t,Ge){var on=_t&o,Zn=Mp(F),an=Zn.length,Jn=Mp(V),wr=Jn.length;if(an!=wr&&!on)return!1;for(var $r=an;$r--;){var bn=Zn[$r];if(!(on?bn in V:is.call(V,bn)))return!1}var wn=Ge.get(F);if(wn&&Ge.get(V))return wn==V;var vr=!0;Ge.set(F,V),Ge.set(V,F);for(var ko=on;++$r<an;){bn=Zn[$r];var no=F[bn],gi=V[bn];if(Pe)var L=on?Pe(gi,no,bn,V,F,Ge):Pe(no,gi,bn,F,V,Ge);if(!(L===void 0?no===gi||ie(no,gi,Pe,_t,Ge):L)){vr=!1;break}ko||(ko=bn=="constructor")}if(vr&&!ko){var U=F.constructor,ee=V.constructor;U!=ee&&"constructor"in F&&"constructor"in V&&!(typeof U=="function"&&U instanceof U&&typeof ee=="function"&&ee instanceof ee)&&(vr=!1)}return Ge.delete(F),Ge.delete(V),vr}function hi(F,V){var ie=F.__data__;return Pp(V)?ie[typeof V=="string"?"string":"hash"]:ie.map}function ta(F,V){var ie=lt(F,V);return ix(ie)?ie:void 0}var zr=ox;(ft&&zr(new ft(new ArrayBuffer(1)))!=k||xr&&zr(new xr)!=g||qn&&zr(qn.resolve())!=S||ii&&zr(new ii)!=w||as&&zr(new as)!=T)&&(zr=function(F){var V=si.call(F),ie=V==y?F.constructor:void 0,Pe=ie?pi(ie):void 0;if(Pe)switch(Pe){case Es:return k;case Js:return g;case ai:return S;case ec:return w;case kd:return T}return V});function Cp(F,V){return V=V??i,!!V&&(typeof F=="number"||X.test(F))&&F>-1&&F%1==0&&F<V}function Pp(F){var V=typeof F;return V=="string"||V=="number"||V=="symbol"||V=="boolean"?F!=="__proto__":F===null}function ux(F){return!!Zi&&Zi in F}function hx(F){var V=F&&F.constructor,ie=typeof V=="function"&&V.prototype||Xn;return F===ie}function pi(F){if(F!=null){try{return Ji.call(F)}catch{}try{return F+""}catch{}}return""}function Tp(F,V){return F===V||F!==F&&V!==V}function Ip(F){return kp(F)&&is.call(F,"callee")&&(!Y.call(F,"callee")||si.call(F)==a)}var Ad=Array.isArray;function Ep(F){return F!=null&&_p(F.length)&&!fi(F)}function kp(F){return ks(F)&&Ep(F)}function nc(F,V,ie){ie=typeof ie=="function"?ie:void 0;var Pe=ie?ie(F,V):void 0;return Pe===void 0?wp(F,V,ie):!!Pe}function fi(F){var V=Dd(F)?si.call(F):"";return V==h||V==f}function _p(F){return typeof F=="number"&&F>-1&&F%1==0&&F<=i}function Dd(F){var V=typeof F;return!!F&&(V=="object"||V=="function")}function ks(F){return!!F&&typeof F=="object"}var px=de?rt(de):ax;function Mp(F){return Ep(F)?sx(F):lx(F)}n.exports=nc})(nu,nu.exports)),nu.exports}var w4=b4();const v4=Ua(w4);var mx,AP;function C4(){if(AP)return mx;AP=1;var n="Expected a function",e=NaN,t="[object Symbol]",r=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,i=/^0o[0-7]+$/i,a=parseInt,l=typeof or=="object"&&or&&or.Object===Object&&or,c=typeof self=="object"&&self&&self.Object===Object&&self,u=l||c||Function("return this")(),d=Object.prototype,h=d.toString,f=Math.max,g=Math.min,m=function(){return u.Date.now()};function y(T,I,k){var A,R,D,j,_,M,O=0,N=!1,B=!1,H=!0;if(typeof T!="function")throw new TypeError(n);I=P(I)||0,b(k)&&(N=!!k.leading,B="maxWait"in k,D=B?f(P(k.maxWait)||0,I):D,H="trailing"in k?!!k.trailing:H);function z(re){var ge=A,de=R;return A=R=void 0,O=re,j=T.apply(de,ge),j}function X(re){return O=re,_=setTimeout(Ce,I),N?z(re):j}function G(re){var ge=re-M,de=re-O,Ne=I-ge;return B?g(Ne,D-de):Ne}function ae(re){var ge=re-M,de=re-O;return M===void 0||ge>=I||ge<0||B&&de>=D}function Ce(){var re=m();if(ae(re))return fe(re);_=setTimeout(Ce,G(re))}function fe(re){return _=void 0,H&&A?z(re):(A=R=void 0,j)}function oe(){_!==void 0&&clearTimeout(_),O=0,A=M=R=_=void 0}function Te(){return _===void 0?j:fe(m())}function te(){var re=m(),ge=ae(re);if(A=arguments,R=this,M=re,ge){if(_===void 0)return X(M);if(B)return _=setTimeout(Ce,I),z(M)}return _===void 0&&(_=setTimeout(Ce,I)),j}return te.cancel=oe,te.flush=Te,te}function S(T,I,k){var A=!0,R=!0;if(typeof T!="function")throw new TypeError(n);return b(k)&&(A="leading"in k?!!k.leading:A,R="trailing"in k?!!k.trailing:R),y(T,I,{leading:A,maxWait:I,trailing:R})}function b(T){var I=typeof T;return!!T&&(I=="object"||I=="function")}function w(T){return!!T&&typeof T=="object"}function v(T){return typeof T=="symbol"||w(T)&&h.call(T)==t}function P(T){if(typeof T=="number")return T;if(v(T))return e;if(b(T)){var I=typeof T.valueOf=="function"?T.valueOf():T;T=b(I)?I+"":I}if(typeof T!="string")return T===0?T:+T;T=T.replace(r,"");var k=o.test(T);return k||i.test(T)?a(T.slice(2),k?2:8):s.test(T)?e:+T}return mx=S,mx}var P4=C4();const N_=Ua(P4);var yx,DP;function T4(){if(DP)return yx;DP=1;var n=200,e="__lodash_hash_undefined__",t=1/0,r="[object Function]",s="[object GeneratorFunction]",o=/[\\^$.*+?()[\]{}|]/g,i=/^\[object .+?Constructor\]$/,a=typeof or=="object"&&or&&or.Object===Object&&or,l=typeof self=="object"&&self&&self.Object===Object&&self,c=a||l||Function("return this")();function u(Y,ce){var Re=Y?Y.length:0;return!!Re&&h(Y,ce,0)>-1}function d(Y,ce,Re,ft){for(var xr=Y.length,qn=Re+-1;++qn<xr;)if(ce(Y[qn],qn,Y))return qn;return-1}function h(Y,ce,Re){if(ce!==ce)return d(Y,f,Re);for(var ft=Re-1,xr=Y.length;++ft<xr;)if(Y[ft]===ce)return ft;return-1}function f(Y){return Y!==Y}function g(Y,ce){return Y.has(ce)}function m(Y,ce){return Y==null?void 0:Y[ce]}function y(Y){var ce=!1;if(Y!=null&&typeof Y.toString!="function")try{ce=!!(Y+"")}catch{}return ce}function S(Y){var ce=-1,Re=Array(Y.size);return Y.forEach(function(ft){Re[++ce]=ft}),Re}var b=Array.prototype,w=Function.prototype,v=Object.prototype,P=c["__core-js_shared__"],T=(function(){var Y=/[^.]+$/.exec(P&&P.keys&&P.keys.IE_PROTO||"");return Y?"Symbol(src)_1."+Y:""})(),I=w.toString,k=v.hasOwnProperty,A=v.toString,R=RegExp("^"+I.call(k).replace(o,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),D=b.splice,j=Xn(c,"Map"),_=Xn(c,"Set"),M=Xn(Object,"create");function O(Y){var ce=-1,Re=Y?Y.length:0;for(this.clear();++ce<Re;){var ft=Y[ce];this.set(ft[0],ft[1])}}function N(){this.__data__=M?M(null):{}}function B(Y){return this.has(Y)&&delete this.__data__[Y]}function H(Y){var ce=this.__data__;if(M){var Re=ce[Y];return Re===e?void 0:Re}return k.call(ce,Y)?ce[Y]:void 0}function z(Y){var ce=this.__data__;return M?ce[Y]!==void 0:k.call(ce,Y)}function X(Y,ce){var Re=this.__data__;return Re[Y]=M&&ce===void 0?e:ce,this}O.prototype.clear=N,O.prototype.delete=B,O.prototype.get=H,O.prototype.has=z,O.prototype.set=X;function G(Y){var ce=-1,Re=Y?Y.length:0;for(this.clear();++ce<Re;){var ft=Y[ce];this.set(ft[0],ft[1])}}function ae(){this.__data__=[]}function Ce(Y){var ce=this.__data__,Re=fn(ce,Y);if(Re<0)return!1;var ft=ce.length-1;return Re==ft?ce.pop():D.call(ce,Re,1),!0}function fe(Y){var ce=this.__data__,Re=fn(ce,Y);return Re<0?void 0:ce[Re][1]}function oe(Y){return fn(this.__data__,Y)>-1}function Te(Y,ce){var Re=this.__data__,ft=fn(Re,Y);return ft<0?Re.push([Y,ce]):Re[ft][1]=ce,this}G.prototype.clear=ae,G.prototype.delete=Ce,G.prototype.get=fe,G.prototype.has=oe,G.prototype.set=Te;function te(Y){var ce=-1,Re=Y?Y.length:0;for(this.clear();++ce<Re;){var ft=Y[ce];this.set(ft[0],ft[1])}}function re(){this.__data__={hash:new O,map:new(j||G),string:new O}}function ge(Y){return Sr(this,Y).delete(Y)}function de(Y){return Sr(this,Y).get(Y)}function Ne(Y){return Sr(this,Y).has(Y)}function De(Y,ce){return Sr(this,Y).set(Y,ce),this}te.prototype.clear=re,te.prototype.delete=ge,te.prototype.get=de,te.prototype.has=Ne,te.prototype.set=De;function rt(Y){var ce=-1,Re=Y?Y.length:0;for(this.__data__=new te;++ce<Re;)this.add(Y[ce])}function lt(Y){return this.__data__.set(Y,e),this}function pt(Y){return this.__data__.has(Y)}rt.prototype.add=rt.prototype.push=lt,rt.prototype.has=pt;function fn(Y,ce){for(var Re=Y.length;Re--;)if(si(Y[Re][0],ce))return Re;return-1}function Yn(Y){if(!oi(Y)||Zi(Y))return!1;var ce=Qi(Y)||y(Y)?R:i;return ce.test(Ji(Y))}function Is(Y,ce,Re){var ft=-1,xr=u,qn=Y.length,ii=!0,as=[],br=as;if(qn>=n){var Es=xn(Y);if(Es)return S(Es);ii=!1,xr=g,br=new rt}else br=as;e:for(;++ft<qn;){var Js=Y[ft],ai=Js;if(Js=Js!==0?Js:0,ii&&ai===ai){for(var ec=br.length;ec--;)if(br[ec]===ai)continue e;as.push(Js)}else xr(br,ai,Re)||(br!==as&&br.push(ai),as.push(Js))}return as}var xn=_&&1/S(new _([,-0]))[1]==t?function(Y){return new _(Y)}:sl;function Sr(Y,ce){var Re=Y.__data__;return ri(ce)?Re[typeof ce=="string"?"string":"hash"]:Re.map}function Xn(Y,ce){var Re=m(Y,ce);return Yn(Re)?Re:void 0}function ri(Y){var ce=typeof Y;return ce=="string"||ce=="number"||ce=="symbol"||ce=="boolean"?Y!=="__proto__":Y===null}function Zi(Y){return!!T&&T in Y}function Ji(Y){if(Y!=null){try{return I.call(Y)}catch{}try{return Y+""}catch{}}return""}function is(Y){return Y&&Y.length?Is(Y):[]}function si(Y,ce){return Y===ce||Y!==Y&&ce!==ce}function Qi(Y){var ce=oi(Y)?A.call(Y):"";return ce==r||ce==s}function oi(Y){var ce=typeof Y;return!!Y&&(ce=="object"||ce=="function")}function sl(){}return yx=is,yx}var I4=T4();const E4=Ua(I4);function ny(n,e){const t=[];e:for(const r of n){for(const s of t)if(e?e(r,s):r===s)continue e;t.push(r)}return t}function Le(n){return n.filter(e=>e!=null)}function gs(n){return n[n.length-1]}function F_(n,e){let t,r=1/0;for(const s of n){const o=e(s);o<r&&(t=s,r=o)}return t}function k4(n,e){let t,r=-1/0;for(const s of n){const o=e(s);o>r&&(t=s,r=o)}return t}function bg(n,e){if(n===e)return!0;if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Object.is(n[t],e[t]))return!1;return!0}function Mu(n,e,t){const r=new Set(e.map(o=>o[n])),s=[];for(const o of t)r.has(o[n])||s.push(o);for(const o of e)s.push(o);return s}function B_(n){const e=(...t)=>{try{return n(...t)}catch(r){throw r instanceof Error&&Error.captureStackTrace&&Error.captureStackTrace(r,e),r}};return e}const eh=()=>{},zs={ok(n){return{ok:!0,value:n}},err(n){return{ok:!1,error:n}},all(n){var e;return n.every(t=>t.ok)?zs.ok(n.map(t=>t.value)):zs.err((e=n.find(t=>!t.ok))==null?void 0:e.error)}};function it(n,e){const t=e&&n&&typeof n=="object"&&e in n?n[e]:n;throw new Error(`Unknown switch case ${t}`)}const be=B_((n,e)=>{if(!n)throw new Error(e||"Assertion Error")}),Pn=B_((n,e)=>{if(n==null)throw new Error(e??"value must be defined");return n});function hv(){let n,e;const t=new Promise((r,s)=>{n=r,e=s});return Object.assign(t,{resolve:n,reject:e})}function mw(n){return new Promise(e=>setTimeout(e,n))}/*!
6
+ * MIT License: https://github.com/NoHomey/bind-decorator/blob/master/License
7
+ * Copyright (c) 2016 Ivo Stratev
8
+ */function Xr(...n){if(n.length===2){const[e,t]=n;t.addInitializer(function(){be(Reflect.isExtensible(this),"Cannot bind to a non-extensible class.");const s=e.bind(this),o=Reflect.defineProperty(this,t.name,{value:s,writable:!0,configurable:!0});be(o,"Cannot bind a non-configurable class method.")})}else{const[e,t,r]=n;if(!r||typeof r.value!="function")throw new TypeError(`Only methods can be decorated with @bind. <${t}> is not a method!`);return{configurable:!0,get(){const s=r.value.bind(this);return Object.defineProperty(this,t,{value:s,configurable:!0,writable:!0}),s}}}}class Vn{constructor(){E(this,"items",new WeakMap)}get(e,t){return this.items.has(e)||this.items.set(e,t(e)),this.items.get(e)}}function ry(n,e){let t;const r=(...s)=>(t||(t={},t.promise=new Promise((o,i)=>{t.resolve=o,t.reject=i})),clearTimeout(t.timeout),t.latestArgs=s,t.timeout=setTimeout(()=>{const o=t;t=void 0;try{o.resolve(n(...o.latestArgs))}catch(i){o.reject(i)}},e),t.promise);return r.cancel=()=>{t&&clearTimeout(t.timeout)},r}const OP=new WeakMap;function pv(n,e){if(typeof n!="object"||n===null)return;let t=OP.get(n);t||(t={tags:{},extras:{}},OP.set(n,t)),e.tags&&(t.tags={...t.tags,...e.tags}),e.extras&&(t.extras={...t.extras,...e.extras})}async function $i(n,e){return window.fetch(n,{referrerPolicy:"strict-origin-when-cross-origin",...e})}const th=(n,e)=>{const t=new window.Image(n,e);return t.referrerPolicy="strict-origin-when-cross-origin",t};class ir{static async urlToArrayBuffer(e){return await(await $i(e)).arrayBuffer()}static async urlToBlob(e){return await(await $i(e)).blob()}static async urlToDataUrl(e){if(e.startsWith("data:"))return e;const t=await ir.urlToBlob(e);return await ir.blobToDataUrl(t)}static async blobToDataUrl(e){return await new Promise((t,r)=>{if(e){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsDataURL(e)}})}static async blobToText(e){return await new Promise((t,r)=>{if(e){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsText(e)}})}static rewriteMimeType(e,t){return e.type===t?e:e instanceof File?new File([e],e.name,{type:t}):new Blob([e],{type:t})}}function z_(n){let e=0;for(let t=0;t<n.length;t++)e=(e<<5)-e+n.charCodeAt(t),e|=0;return e+""}function $_(n){const e=new DataView(n);let t=0;for(let r=0;r<e.byteLength;r++)t=(t<<5)-t+e.getUint8(r),t|=0;return t+""}/*!
9
+ * MIT License: https://github.com/ai/nanoid/blob/main/LICENSE
10
+ * Modified code originally from <https://github.com/ai/nanoid>
11
+ * Copyright 2017 Andrey Sitnik <andrey@sitnik.ru>
12
+ *
13
+ * `nanoid` is currently only distributed as an ES module. Some tools (jest, playwright) don't
14
+ * properly support ESM-only code yet, and tldraw itself is distributed as both an ES module and a
15
+ * CommonJS module. By including nanoid here, we can make sure it works well in every environment
16
+ * where tldraw is used. We can also remove some unused features like custom alphabets.
17
+ */const RP=globalThis.crypto,_4="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",M4=128;let ul,kc;function A4(n){!ul||ul.length<n?(ul=new Uint8Array(n*M4),RP.getRandomValues(ul),kc=0):kc+n>ul.length&&(RP.getRandomValues(ul),kc=0),kc+=n}function D4(n=21){A4(n-=0);let e="";for(let t=kc-n;t<kc;t++)e+=_4[ul[t]&63];return e}let O4=D4;function at(n){return O4(n)}/*!
18
+ * MIT License: https://github.com/vHeemstra/is-apng/blob/main/license
19
+ * Copyright (c) Philip van Heemstra
20
+ */function R4(n){const e=new Uint8Array(n);if(!e||!(typeof Buffer<"u"&&Buffer.isBuffer(e)||e instanceof Uint8Array)||e.length<16||!(e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10))return!1;function r(o,i,a,l,c=1024){if(!i)return-1;i=new RegExp(i,"g");const u=i.source.length,d=new TextDecoder,h=o.length;if(typeof l>"u"&&(l=h),a>=h||l<=0||a>=l)return-1;o=o.subarray(a,l);let f=-1,g=0,m=0,y="";e:for(;g<o.length;){const S=g+c,b=o.subarray(g,S),w=d.decode(b,{stream:!0}),v=y+w;let P,T=-1;for(;(P=i.exec(v))!==null;){T=P.index-y.length,f=m+T;break e}g=S,m+=w.length;const I=T>-1?T+u:w.length-u;y=w.slice(I)}return f>=0&&(f+=a>=0?a:h+a),f}const s=r(e,"IDAT",12);return s>=12?r(e,"acTL",8,s)>=8:!1}const L4=n=>new Uint8Array(n)[3]===44;/*!
21
+ * MIT License
22
+ * Modified code originally from <https://github.com/qzb/is-animated>
23
+ * Copyright (c) 2016 Józef Sokołowski <j.k.sokolowski@gmail.com>
24
+ */function LP(n,e){let t=0;for(;n[e+t];)t+=n[e+t]+1;return t+1}function j4(n){return new TextDecoder("ascii").decode(n.slice(0,3))==="GIF"}function N4(n){const e=new Uint8Array(n);let t,r,s=0,o=0;if(!j4(n))return!1;for(t=e[10]&128,r=e[10]&7,s+=6,s+=7,s+=t?3*Math.pow(2,r+1):0;o<2&&s<e.length;)switch(e[s]){case 44:o+=1,t=e[s+9]&128,r=e[s+9]&7,s+=10,s+=t?3*Math.pow(2,r+1):0,s+=LP(e,s+1)+1;break;case 33:s+=2,s+=LP(e,s);break;case 59:s=e.length;break;default:s=e.length;break}return o>1}/*!
25
+ * MIT License: https://github.com/alexgorbatchev/crc/blob/master/LICENSE
26
+ * Copyright: 2014 Alex Gorbatchev
27
+ * Code: crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts
28
+ */let yw=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];typeof Int32Array<"u"&&(yw=new Int32Array(yw));const F4=(n,e)=>{let t=-1;for(let r=0;r<n.length;r++)t=yw[(t^n[r])&255]^t>>>8;return t^-1},jP=4,NP=4;class Fo{static isPng(e,t){return e.getUint8(t+0)===137&&e.getUint8(t+1)===80&&e.getUint8(t+2)===78&&e.getUint8(t+3)===71&&e.getUint8(t+4)===13&&e.getUint8(t+5)===10&&e.getUint8(t+6)===26&&e.getUint8(t+7)===10}static getChunkType(e,t){return[String.fromCharCode(e.getUint8(t)),String.fromCharCode(e.getUint8(t+1)),String.fromCharCode(e.getUint8(t+2)),String.fromCharCode(e.getUint8(t+3))].join("")}static readChunks(e,t=0){const r={};if(!Fo.isPng(e,t))throw new Error("Not a PNG");for(t+=8;t<=e.buffer.byteLength;){const s=t,o=e.getInt32(t);t+=4;const i=Fo.getChunkType(e,t);if(i==="IDAT"&&r[i]){t+=o+jP+NP;continue}if(i==="IEND")break;r[i]={start:s,dataOffset:t+4,size:o},t+=o+jP+NP}return r}static parsePhys(e,t){return{ppux:e.getUint32(t),ppuy:e.getUint32(t+4),unit:e.getUint8(t+8)}}static findChunk(e,t){return Fo.readChunks(e)[t]}static setPhysChunk(e,t=1,r){let s=46,o=0;const i=Fo.findChunk(e,"pHYs");i&&(s=i.start,o=i.size);const a=Fo.findChunk(e,"IDAT");a&&(s=a.start,o=0);const l=new ArrayBuffer(21),c=new DataView(l);c.setUint32(0,9),c.setUint8(4,112),c.setUint8(5,72),c.setUint8(6,89),c.setUint8(7,115);const u=2835.5;c.setInt32(8,u*t),c.setInt32(12,u*t),c.setInt8(16,1);const d=new Uint8Array(l.slice(4,17));c.setInt32(17,F4(d));const h=e.buffer.slice(0,s),f=e.buffer.slice(s+o);return new Blob([h,l,f],r)}}/*!
29
+ * MIT License: https://github.com/sindresorhus/is-webp/blob/main/license
30
+ * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
31
+ */function B4(n){return!n||n.length<12?!1:n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80}function z4(n){const e=new Uint8Array(n);return!B4(e)||!e||e.length<21?!1:(e[20]>>1&1)===1}const H_=Object.freeze(["image/svg+xml"]),U_=Object.freeze(["image/jpeg","image/png","image/webp"]),K_=Object.freeze(["image/gif","image/apng","image/avif"]),fd=Object.freeze([...U_,...H_,...K_]),sy=Object.freeze(["video/mp4","video/webm","video/quicktime"]),$4=Object.freeze([...fd,...sy]);$4.join(",");class fs{static loadVideo(e){return new Promise((t,r)=>{const s=document.createElement("video");s.onloadeddata=()=>t(s),s.onerror=o=>{console.error(o),r(new Error("Could not load video"))},s.crossOrigin="anonymous",s.src=e})}static async getVideoFrameAsDataUrl(e,t=0){const r=hv();let s=!1;const o=()=>{if(!s)if(e.readyState>=e.HAVE_METADATA)s=!0,e.currentTime=t;else return;if(e.readyState>=e.HAVE_CURRENT_DATA){const a=document.createElement("canvas");a.width=e.videoWidth,a.height=e.videoHeight;const l=a.getContext("2d");if(!l)throw new Error("Could not get 2d context");l.drawImage(e,0,0),r.resolve(a.toDataURL())}},i=a=>{console.error(a),r.reject(new Error("Could not get video frame"))};e.addEventListener("loadedmetadata",o),e.addEventListener("loadeddata",o),e.addEventListener("canplay",o),e.addEventListener("seeked",o),e.addEventListener("error",i),e.addEventListener("stalled",i),o();try{return await r}finally{e.removeEventListener("loadedmetadata",o),e.removeEventListener("loadeddata",o),e.removeEventListener("canplay",o),e.removeEventListener("seeked",o),e.removeEventListener("error",i),e.removeEventListener("stalled",i)}}static getImageAndDimensions(e){return new Promise((t,r)=>{const s=th();s.onload=()=>{let o;s.naturalWidth?o={w:s.naturalWidth,h:s.naturalHeight}:(document.body.appendChild(s),o={w:s.clientWidth,h:s.clientHeight},document.body.removeChild(s)),t({...o,image:s})},s.onerror=o=>{console.error(o),r(new Error("Could not load image"))},s.crossOrigin="anonymous",s.referrerPolicy="strict-origin-when-cross-origin",s.style.visibility="hidden",s.style.position="absolute",s.style.opacity="0",s.style.zIndex="-9999",s.src=e})}static async getVideoSize(e){return fs.usingObjectURL(e,async t=>{const r=await fs.loadVideo(t);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(e){const{w:t,h:r}=await fs.usingObjectURL(e,fs.getImageAndDimensions);try{if(e.type==="image/png"){const s=new DataView(await e.arrayBuffer());if(Fo.isPng(s,0)){const o=Fo.findChunk(s,"pHYs");if(o){const i=Fo.parsePhys(s,o.dataOffset);if(i.unit===1&&i.ppux===i.ppuy){const l=Math.max(i.ppux/2834.645669291339,1);return{w:Math.round(t/l),h:Math.round(r/l)}}}}}}catch(s){return console.error(s),{w:t,h:r}}return{w:t,h:r}}static async isAnimated(e){return e.type==="image/gif"?N4(await e.arrayBuffer()):e.type==="image/avif"?L4(await e.arrayBuffer()):e.type==="image/webp"?z4(await e.arrayBuffer()):e.type==="image/apng"?R4(await e.arrayBuffer()):!1}static isAnimatedImageType(e){return K_.includes(e||"")}static isStaticImageType(e){return U_.includes(e||"")}static isVectorImageType(e){return H_.includes(e||"")}static isImageType(e){return fd.includes(e||"")}static async usingObjectURL(e,t){const r=URL.createObjectURL(e);try{return await t(r)}finally{URL.revokeObjectURL(r)}}}function Ue(n,e,t){return n+(e-n)*t}function nh(n,e,t){return(t-n)/(e-n)}function Aa(n=""){let e=0,t=0,r=0,s=0;function o(){const i=e^e<<11;return e=t,t=r,r=s,s^=(s>>>19^i^i>>>8)>>>0,s/4294967296*2}for(let i=0;i<n.length+64;i++)e^=n.charCodeAt(i)|0,o();return o}function xo(n,e,t,r=!1){const[s,o]=e,[i,a]=t,l=i+(n-s)/(o-s)*(a-i);return r?i<a?Math.max(Math.min(l,a),i):Math.max(Math.min(l,i),a):l}function gn(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function un(n,e){if(gn(n,e))return n[e]}function Au(n){return Object.keys(n)}function Et(n){return Object.values(n)}function $s(n){return Object.entries(n)}function W_(n){return Object.fromEntries(n)}function Du(n,e){const t={};let r=!1;for(const s in n){if(!Object.prototype.hasOwnProperty.call(n,s))continue;const o=n[s];e(s,o)?t[s]=o:r=!0}return r?t:n}function Ka(n,e){const t={};for(const r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=e(r,n[r]));return t}function V_(n,e){if(n===e)return!0;const t=Object.keys(n);if(t.length!==Object.keys(e).length)return!1;for(const r of t)if(!gn(e,r)||!Object.is(n[r],e[r]))return!1;return!0}function H4(n,e){const t=[];for(const r in n)Object.is(n[r],e[r])||t.push(r);return t}function U4(n,e,t=1e-6){return v4(n,e,(r,s)=>{if(typeof r=="number"&&typeof s=="number")return Math.abs(r-s)<t})}const ru={Good:"#40C057",Mid:"#FFC078",Poor:"#E03131"},K4=ru.Good;class G_{constructor(){E(this,"startTime",0);E(this,"name","");E(this,"frames",0);E(this,"started",!1);E(this,"frame",null);E(this,"recordFrame",()=>{this.frames++,this.started&&(this.frame=requestAnimationFrame(this.recordFrame))})}start(e){this.name=e,this.frames=0,this.started=!0,this.frame!==null&&cancelAnimationFrame(this.frame),this.frame=requestAnimationFrame(this.recordFrame),this.startTime=performance.now()}stop(){this.started=!1,this.frame!==null&&cancelAnimationFrame(this.frame);const e=(performance.now()-this.startTime)/1e3,t=e===0?0:Math.floor(this.frames/e),r=t>55?ru.Good:t>30?ru.Mid:ru.Poor,s=r===ru.Mid?"black":"white",o=this.name[0].toUpperCase()+this.name.slice(1);console.debug(`%cPerf%c ${o} %c${t}%c fps`,`color: white; background: ${K4};padding: 2px;border-radius: 3px;`,"font-weight: normal",`font-weight: bold; padding: 2px; background: ${r};color: ${s};`,"font-weight: normal")}isStarted(){return this.started}}const Y_="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function _c(n,e,t){const r=t[0];if(e!=null&&n>=e)throw new Error(n+" >= "+e);if(n.slice(-1)===r||e&&e.slice(-1)===r)throw new Error("trailing zero");if(e){let i=0;for(;(n[i]||r)===e[i];)i++;if(i>0)return e.slice(0,i)+_c(n.slice(i),e.slice(i),t)}const s=n?t.indexOf(n[0]):0,o=e!=null?t.indexOf(e[0]):t.length;if(o-s>1){const i=Math.round(.5*(s+o));return t[i]}else return e&&e.length>1?e.slice(0,1):t[s]+_c(n.slice(1),null,t)}function X_(n){if(n.length!==q_(n[0]))throw new Error("invalid integer part of order key: "+n)}function q_(n){if(n>="a"&&n<="z")return n.charCodeAt(0)-97+2;if(n>="A"&&n<="Z")return 90-n.charCodeAt(0)+2;throw new Error("invalid order key head: "+n)}function su(n){const e=q_(n[0]);if(e>n.length)throw new Error("invalid order key: "+n);return n.slice(0,e)}function FP(n,e){if(n==="A"+e[0].repeat(26))throw new Error("invalid order key: "+n);const t=su(n);if(n.slice(t.length).slice(-1)===e[0])throw new Error("invalid order key: "+n)}function BP(n,e){X_(n);const[t,...r]=n.split("");let s=!0;for(let o=r.length-1;s&&o>=0;o--){const i=e.indexOf(r[o])+1;i===e.length?r[o]=e[0]:(r[o]=e[i],s=!1)}if(s){if(t==="Z")return"a"+e[0];if(t==="z")return null;const o=String.fromCharCode(t.charCodeAt(0)+1);return o>"a"?r.push(e[0]):r.pop(),o+r.join("")}else return t+r.join("")}function W4(n,e){X_(n);const[t,...r]=n.split("");let s=!0;for(let o=r.length-1;s&&o>=0;o--){const i=e.indexOf(r[o])-1;i===-1?r[o]=e.slice(-1):(r[o]=e[i],s=!1)}if(s){if(t==="a")return"Z"+e.slice(-1);if(t==="A")return null;const o=String.fromCharCode(t.charCodeAt(0)-1);return o<"Z"?r.push(e.slice(-1)):r.pop(),o+r.join("")}else return t+r.join("")}function fa(n,e,t=Y_){if(n!=null&&FP(n,t),e!=null&&FP(e,t),n!=null&&e!=null&&n>=e)throw new Error(n+" >= "+e);if(n==null){if(e==null)return"a"+t[0];const l=su(e),c=e.slice(l.length);if(l==="A"+t[0].repeat(26))return l+_c("",c,t);if(l<e)return l;const u=W4(l,t);if(u==null)throw new Error("cannot decrement any more");return u}if(e==null){const l=su(n),c=n.slice(l.length),u=BP(l,t);return u??l+_c(c,null,t)}const r=su(n),s=n.slice(r.length),o=su(e),i=e.slice(o.length);if(r===o)return r+_c(s,i,t);const a=BP(r,t);if(a==null)throw new Error("cannot increment any more");return a<e?a:r+_c(s,null,t)}function wg(n,e,t,r=Y_){if(t===0)return[];if(t===1)return[fa(n,e,r)];if(e==null){let i=fa(n,e,r);const a=[i];for(let l=0;l<t-1;l++)i=fa(i,e,r),a.push(i);return a}if(n==null){let i=fa(n,e,r);const a=[i];for(let l=0;l<t-1;l++)i=fa(n,i,r),a.push(i);return a.reverse(),a}const s=Math.floor(t/2),o=fa(n,e,r);return[...wg(n,o,s,r),o,...wg(o,e,t-s-1,r)]}const V4=30,G4=()=>Math.random()<.5;function Z_(n,e){if(!Number.isInteger(e))throw new Error(`"${n}" must be an integer, got '${e}'`);if(e<0)throw new Error(`"${n}" must be greater than or equal to 0, got '${e}'`)}function J_(n,e,t){const{digits:r,jitterBits:s=V4,getRandomBit:o=G4}=t??{};Z_("jitterBits",s);let i=s,a=n,l=e,c=fa(n,e,r);for(;i>0;)(o()?1:0)===1?a=c:l=c,c=fa(a,l,r),i--;return c}function Y4(n,e,t,r){const{digits:s,jitterBits:o}=r??{};if(Z_("n",t),t===0)return[];if(o===0)return wg(n,e,t,s);const i=wg(n,e,t+1,s),a=[];for(let l=0;l<t;l++){const c=i[l],u=i[l+1];a.push(J_(c,u,r))}return a}const gd=Y4,fv="a0";function X4(n){try{J_(n,null)}catch{throw new Error("invalid index: "+n)}}function El(n,e,t){return gd(n??null,e??null,t)}function Sx(n,e){return gd(n??null,null,e)}function Xc(n,e){return gd(n??null,e??null,1)[0]}function Ns(n=null){return gd(n,null,1)[0]}function q4(n=null){return gd(null,n,1)[0]}function rh(n,e="a1"){return[e,...gd(e,null,n)]}function Tn(n,e){return n.index<e.index?-1:n.index>e.index?1:0}function Z4(n,e){return n.id>e.id?1:-1}function gv(n){try{return localStorage.getItem(n)}catch{return null}}function mv(n,e){try{localStorage.setItem(n,e)}catch{}}function J4(){try{localStorage.clear()}catch{}}function Q_(n){try{return sessionStorage.getItem(n)}catch{return null}}function yv(n,e){try{sessionStorage.setItem(n,e)}catch{}}function eM(n){try{sessionStorage.removeItem(n)}catch{}}function Q4(){try{sessionStorage.clear()}catch{}}const e6=.9,zP=n=>Math.floor(1e3/n)*e6;class t6{constructor(e=120){E(this,"targetFps");E(this,"targetTimePerFrame");E(this,"fpsQueue",[]);E(this,"frameRaf");E(this,"flushRaf");E(this,"lastFlushTime");this.targetFps=e,this.targetTimePerFrame=zP(e),this.lastFlushTime=-this.targetTimePerFrame}updateTargetFps(e){e!==this.targetFps&&(this.targetFps=e,this.targetTimePerFrame=zP(e),this.lastFlushTime=-this.targetTimePerFrame)}flush(){const e=this.fpsQueue.splice(0,this.fpsQueue.length);for(const t of e)t()}tick(e=!1){if(this.frameRaf)return;const t=Date.now();if(t-this.lastFlushTime<this.targetTimePerFrame){this.frameRaf=requestAnimationFrame(()=>{this.frameRaf=void 0,this.tick(!0)});return}if(e){if(this.flushRaf)return;this.lastFlushTime=t,this.flush()}else{if(this.flushRaf)return;this.flushRaf=requestAnimationFrame(()=>{this.flushRaf=void 0,this.lastFlushTime=Date.now(),this.flush()})}}fpsThrottle(e){const t=()=>{this.fpsQueue.includes(e)||(this.fpsQueue.push(e),this.tick())};return t.cancel=()=>{const r=this.fpsQueue.indexOf(e);r>-1&&this.fpsQueue.splice(r,1)},t}throttleToNextFrame(e){return this.fpsQueue.includes(e)||(this.fpsQueue.push(e),this.tick()),()=>{const t=this.fpsQueue.indexOf(e);t>-1&&this.fpsQueue.splice(t,1)}}}const n6=new t6(120);function Sv(n){return n6.throttleToNextFrame(n)}class r6{constructor(){E(this,"timeouts",new Map);E(this,"intervals",new Map);E(this,"rafs",new Map);this.setTimeout=this.setTimeout.bind(this),this.setInterval=this.setInterval.bind(this),this.requestAnimationFrame=this.requestAnimationFrame.bind(this),this.dispose=this.dispose.bind(this)}setTimeout(e,t,r,...s){const o=window.setTimeout(t,r,s),i=this.timeouts.get(e)??[];return this.timeouts.set(e,[...i,o]),o}setInterval(e,t,r,...s){const o=window.setInterval(t,r,s),i=this.intervals.get(e)??[];return this.intervals.set(e,[...i,o]),o}requestAnimationFrame(e,t){const r=window.requestAnimationFrame(t),s=this.rafs.get(e)??[];return this.rafs.set(e,[...s,r]),r}dispose(e){var t,r,s;(t=this.timeouts.get(e))==null||t.forEach(o=>clearTimeout(o)),(r=this.intervals.get(e))==null||r.forEach(o=>clearInterval(o)),(s=this.rafs.get(e))==null||s.forEach(o=>cancelAnimationFrame(o)),this.timeouts.delete(e),this.intervals.delete(e),this.rafs.delete(e)}disposeAll(){for(const e of this.timeouts.keys())this.dispose(e)}forContext(e){return{setTimeout:(t,r,...s)=>this.setTimeout(e,t,r,s),setInterval:(t,r,...s)=>this.setInterval(e,t,r,s),requestAnimationFrame:t=>this.requestAnimationFrame(e,t),dispose:()=>this.dispose(e)}}}const ze=(n,e)=>{try{return new URL(n,e)}catch{return}};function s6(n){return n!==void 0}function o6(){return typeof globalThis<"u"&&globalThis.structuredClone?[globalThis.structuredClone,!0]:typeof global<"u"&&global.structuredClone?[global.structuredClone,!0]:typeof window<"u"&&window.structuredClone?[window.structuredClone,!0]:[n=>n&&JSON.parse(JSON.stringify(n)),!1]}const tM=o6(),Ft=tM[0];tM[1];const nM=Object.getPrototypeOf(Ft({})),$P=new Set;function i6(n){$P.has(n)||($P.add(n),console.warn(`[tldraw] ${n}`))}Wi("@tldraw/utils","4.4.0","esm");function rM(n){return n&&typeof n=="object"&&"parents"in n}function sM(n){for(let e=0,t=n.parents.length;e<t;e++)if(n.parents[e].__unsafe__getWithoutCapture(!0),n.parents[e].lastChangedEpoch!==n.parentEpochs[e])return!0;return!1}function vg(n,e){if(n.children.remove(e)&&n.children.isEmpty&&rM(n))for(let t=0,r=n.parents.length;t<r;t++)vg(n.parents[t],n)}function xv(n,e){if(n.children.add(e)&&rM(n))for(let t=0,r=n.parents.length;t<r;t++)xv(n.parents[t],n)}function oM(n,e){return n===e||Object.is(n,e)||!!(n&&e&&typeof n.equals=="function"&&n.equals(e))}function Wa(n,e){const t=Symbol.for(`com.tldraw.state/${n}`),r=globalThis;return r[t]??(r[t]=e()),r[t]}const Yt=Wa("empty_array",()=>Object.freeze([])),HP=8;class Cg{constructor(){E(this,"arraySize",0);E(this,"array",Array(HP));E(this,"set",null)}get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw new Error("no set or array")}add(e){if(this.array)return this.array.indexOf(e)!==-1?!1:this.arraySize<HP?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0);if(this.set)return this.set.has(e)?!1:(this.set.add(e),!0);throw new Error("no set or array")}remove(e){if(this.array){const t=this.array.indexOf(e);return t===-1?!1:(this.array[t]=void 0,this.arraySize--,t!==this.arraySize&&(this.array[t]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw new Error("no set or array")}visit(e){if(this.array){for(let t=0;t<this.arraySize;t++){const r=this.array[t];typeof r<"u"&&e(r)}return}if(this.set){this.set.forEach(e);return}throw new Error("no set or array")}*[Symbol.iterator](){if(this.array)for(let e=0;e<this.arraySize;e++){const t=this.array[e];typeof t<"u"&&(yield t)}else if(this.set)yield*this.set;else throw new Error("no set or array")}has(e){return this.array?this.array.indexOf(e)!==-1:this.set.has(e)}clear(){this.set?this.set.clear():(this.arraySize=0,this.array=[])}size(){return this.set?this.set.size:this.arraySize}}const Zr=Symbol.for("com.tldraw.state/RESET_VALUE");class iM{constructor(e){E(this,"index",0);E(this,"buffer");this.capacity=e,this.buffer=new Array(e)}pushEntry(e,t,r){if(r!==void 0){if(r===Zr){this.clear();return}this.buffer[this.index]=[e,t,r],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){const{index:t,capacity:r,buffer:s}=this;for(let o=0;o<r;o++){const i=(t-1+r-o)%r,a=s[i];if(!a)return Zr;const[l,c]=a;if(o===0&&e>=c)return[];if(l<=e&&e<c){const u=o+1,d=new Array(u);for(let h=0;h<u;h++)d[h]=s[(i+h)%r][2];return d}}return Zr}}const wa=-1;class a6{constructor(e,t,r){E(this,"_isActivelyListening",!1);E(this,"lastTraversedEpoch",wa);E(this,"lastReactedEpoch",wa);E(this,"_scheduleCount",0);E(this,"__debug_ancestor_epochs__",null);E(this,"parentSet",new Cg);E(this,"parentEpochs",[]);E(this,"parents",[]);E(this,"_scheduleEffect");E(this,"maybeExecute",()=>{this._isActivelyListening&&this.execute()});this.name=e,this.runEffect=t,this._scheduleEffect=r==null?void 0:r.scheduleEffect}get isActivelyListening(){return this._isActivelyListening}get scheduleCount(){return this._scheduleCount}maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==Wr()){if(this.parents.length&&!sM(this)){this.lastReactedEpoch=Wr();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let e=0,t=this.parents.length;e<t;e++)xv(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)vg(this.parents[e],this)}execute(){try{hM(this);const e=Wr(),t=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=e,t}finally{pM()}}}const Wl=Wa("EffectScheduler",()=>a6);function Mr(n,e,t){const r=new Wl(n,e,t);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function l6(n,e,t){const r=new Wl(n,e,t);return{scheduler:r,start:s=>{const o=(s==null?void 0:s.force)??!1;r.attach(),o?r.scheduleEffect():r.maybeScheduleEffect()},stop:()=>{r.detach()}}}let c6=class{constructor(e,t){E(this,"asyncProcessCount",0);E(this,"initialAtomValues",new Map);this.parent=e,this.isSync=t}get isRoot(){return this.parent===null}commit(){if(ut.globalIsReacting)for(const e of this.initialAtomValues.keys())dM(e);else this.isRoot?cM(this.initialAtomValues.keys()):this.initialAtomValues.forEach((e,t)=>{this.parent.initialAtomValues.has(t)||this.parent.initialAtomValues.set(t,e)})}abort(){ut.globalEpoch++,this.initialAtomValues.forEach((e,t)=>{var r;t.set(e),(r=t.historyBuffer)==null||r.clear()}),this.commit()}};const ut=Wa("transactions",()=>({globalEpoch:wa+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null,reactionEpoch:wa+1}));function d6(){return ut.reactionEpoch}function Wr(){return ut.globalEpoch}function u6(){return ut.globalIsReacting}let bv;function aM(n){n.lastTraversedEpoch!==ut.globalEpoch&&(n.lastTraversedEpoch=ut.globalEpoch,n instanceof Wl?bv.add(n):n.children.visit(aM))}function lM(n,e){bv=n,aM(e)}function cM(n){var t;if(ut.globalIsReacting)throw new Error("flushChanges cannot be called during a reaction");const e=ut.currentTransaction;try{ut.currentTransaction=null,ut.globalIsReacting=!0,ut.reactionEpoch=ut.globalEpoch;const r=new Set;for(const o of n)o.children.visit(i=>lM(r,i));for(const o of r)o.maybeScheduleEffect();let s=0;for(;(t=ut.cleanupReactors)!=null&&t.size;){if(s++>1e3)throw new Error("Reaction update depth limit exceeded");const o=ut.cleanupReactors;ut.cleanupReactors=null;for(const i of o)i.maybeScheduleEffect()}}finally{ut.cleanupReactors=null,ut.globalIsReacting=!1,ut.currentTransaction=e,bv=void 0}}function h6(n,e){ut.currentTransaction?ut.currentTransaction.initialAtomValues.has(n)||ut.currentTransaction.initialAtomValues.set(n,e):ut.globalIsReacting?dM(n):cM([n])}function dM(n){const e=ut.cleanupReactors??(ut.cleanupReactors=new Set);n.children.visit(t=>lM(e,t))}function p6(){ut.globalEpoch++}function f6(n){const e=new c6(ut.currentTransaction,!0);ut.currentTransaction=e;try{let t,r=!1;try{t=n(()=>r=!0)}catch(s){throw e.abort(),s}if(ut.currentTransaction!==e)throw new Error("Transaction boundaries overlap");return r?e.abort():e.commit(),t}finally{ut.currentTransaction=e.parent}}function ms(n){return ut.currentTransaction?n():f6(n)}let UP=!1;function g6(){UP||(UP=!0,console.warn(`Using \`@computed\` as a decorator for getters is deprecated and will be removed in the near future. Please refactor to use \`@computed\` as a decorator for methods.
32
+
33
+ // Before
34
+ @computed
35
+ get foo() {
36
+ return 'foo'
37
+ }
38
+
39
+ // After
40
+ @computed
41
+ getFoo() {
42
+ return 'foo'
43
+ }
44
+ `))}const nr=Symbol.for("com.tldraw.state/UNINITIALIZED");function Ri(n){return n===nr}const Sw=Wa("WithDiff",()=>class{constructor(e,t){this.value=e,this.diff=t}});function ou(n,e){return new Sw(n,e)}class m6{constructor(e,t,r){E(this,"lastChangedEpoch",wa);E(this,"lastTraversedEpoch",wa);E(this,"__debug_ancestor_epochs__",null);E(this,"lastCheckedEpoch",wa);E(this,"parentSet",new Cg);E(this,"parents",[]);E(this,"parentEpochs",[]);E(this,"children",new Cg);E(this,"historyBuffer");E(this,"state",nr);E(this,"error",null);E(this,"computeDiff");E(this,"isEqual");this.name=e,this.derive=t,r!=null&&r.historyLength&&(this.historyBuffer=new iM(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??oM}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(e){var s;const t=this.lastChangedEpoch===wa,r=Wr();if(!t&&(this.lastCheckedEpoch===r||this.isActivelyListening&&u6()&&this.lastTraversedEpoch<d6()||!sM(this)))if(this.lastCheckedEpoch=r,this.error){if(e)return this.state;throw this.error.thrownValue}else return this.state;try{hM(this);const o=this.derive(this.state,this.lastCheckedEpoch),i=o instanceof Sw?o.value:o,a=this.state===nr;if(a||!this.isEqual(i,this.state)){if(this.historyBuffer&&!a){const l=o instanceof Sw?o.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,Wr(),l??((s=this.computeDiff)==null?void 0:s.call(this,this.state,i,this.lastCheckedEpoch,Wr()))??Zr)}this.lastChangedEpoch=Wr(),this.state=i}return this.error=null,this.lastCheckedEpoch=Wr(),this.state}catch(o){if(this.state!==nr&&(this.state=nr,this.lastChangedEpoch=Wr()),this.lastCheckedEpoch=Wr(),this.historyBuffer&&this.historyBuffer.clear(),this.error={thrownValue:o},!e)throw o;return this.state}finally{pM()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{Pg(this)}}getDiffSince(e){var t;return this.__unsafe__getWithoutCapture(!0),Pg(this),e>=this.lastChangedEpoch?Yt:((t=this.historyBuffer)==null?void 0:t.getChangesSince(e))??Zr}}const Dh=Wa("Computed",()=>m6);function y6(n={},e,t,r){const s=r.value,o=Symbol.for("__@tldraw/state__computed__"+t);return r.value=function(){let i=this[o];return i||(i=new Dh(t,s.bind(this),n),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[uM]=!0,r}function S6(n={},e,t,r){const s=r.get,o=Symbol.for("__@tldraw/state__computed__"+t);return r.get=function(){let i=this[o];return i||(i=new Dh(t,s.bind(this),n),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}function x6(n,e,t){be(t.kind==="method","@computed can only be used on methods");const r=Symbol.for("__@tldraw/state__computed__"+String(t.name)),s=function(){let o=this[r];return o||(o=new Dh(String(t.name),e.bind(this),n),Object.defineProperty(this,r,{enumerable:!1,configurable:!1,writable:!1,value:o})),o.get()};return s[uM]=!0,s}function KP(n={},e){if(e.length===2){const[t,r]=e;return x6(n,t,r)}else{const[t,r,s]=e;return s.get?(g6(),S6(n,t,r,s)):y6(n,t,r,s)}}const uM="@@__isComputedMethod__@@";function q(){if(arguments.length===1){const n=arguments[0];return(...e)=>KP(n,e)}else return typeof arguments[0]=="string"?new Dh(arguments[0],arguments[1],arguments[2]):KP(void 0,arguments)}function wv(n){return!!(n&&n instanceof Dh)}class b6{constructor(e,t){E(this,"offset",0);E(this,"maybeRemoved");this.below=e,this.child=t}}const Mt=Wa("capture",()=>({stack:null}));function gl(n){const e=Mt.stack;Mt.stack=null;try{return n()}finally{Mt.stack=e}}function hM(n){if(Mt.stack=new b6(Mt.stack,n),n.__debug_ancestor_epochs__){const e=n.__debug_ancestor_epochs__;n.__debug_ancestor_epochs__=null;for(const t of n.parents)t.__unsafe__getWithoutCapture(!0);w6(n,e)}n.parentSet.clear()}function pM(){const n=Mt.stack;if(Mt.stack=n.below,n.offset<n.child.parents.length){for(let e=n.offset;e<n.child.parents.length;e++){const t=n.child.parents[e];n.child.parentSet.has(t)||vg(t,n.child)}n.child.parents.length=n.offset,n.child.parentEpochs.length=n.offset}if(n.maybeRemoved)for(let e=0;e<n.maybeRemoved.length;e++){const t=n.maybeRemoved[e];n.child.parentSet.has(t)||vg(t,n.child)}n.child.__debug_ancestor_epochs__&&fM(n.child,n.child.__debug_ancestor_epochs__)}function Pg(n){if(Mt.stack){if(Mt.stack.child.parentSet.has(n))return;if(Mt.stack.child.parentSet.add(n),Mt.stack.child.isActivelyListening&&xv(n,Mt.stack.child),Mt.stack.offset<Mt.stack.child.parents.length){const t=Mt.stack.child.parents[Mt.stack.offset];t!==n&&(Mt.stack.maybeRemoved?Mt.stack.maybeRemoved.push(t):Mt.stack.maybeRemoved=[t])}Mt.stack.child.parents[Mt.stack.offset]=n,Mt.stack.child.parentEpochs[Mt.stack.offset]=n.lastChangedEpoch,Mt.stack.offset++}}function fM(n,e){for(let t=0;t<n.parents.length;t++){const r=n.parents[t],s=n.parentEpochs[t];e.set(r,s),wv(r)&&fM(r,e)}return e}function gM(n,e){const t={};for(let r=0;r<n.parents.length;r++){const s=n.parents[r];if(!e.has(s))continue;const o=e.get(s);s.lastChangedEpoch!==o&&(wv(s)?t[s.name]=gM(s,e):t[s.name]=null)}return t}function w6(n,e){const t=gM(n,e);if(Object.keys(t).length===0){console.log(`Effect(${n.name}) was executed manually.`);return}let r=wv(n)?`Computed(${n.name}) is recomputing because:`:`Effect(${n.name}) is executing because:`;function s(o,i){const a=`
45
+ `+" ".repeat(i)+"↳ ";for(const[l,c]of Object.entries(o))c?(r+=`${a}Computed(${l}) changed`,s(c,i+2)):r+=`${a}Atom(${l}) changed`}s(t,1),console.log(r)}class v6{constructor(e,t,r){E(this,"isEqual");E(this,"computeDiff");E(this,"lastChangedEpoch",Wr());E(this,"children",new Cg);E(this,"historyBuffer");this.name=e,this.current=t,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new iM(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(e){return this.current}get(){return Pg(this),this.current}set(e,t){var s,o;if(((s=this.isEqual)==null?void 0:s.call(this,this.current,e))??oM(this.current,e))return this.current;p6(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,Wr(),t??((o=this.computeDiff)==null?void 0:o.call(this,this.current,e,this.lastChangedEpoch,Wr()))??Zr),this.lastChangedEpoch=Wr();const r=this.current;return this.current=e,h6(this,r),e}update(e){return this.set(e(this.current))}getDiffSince(e){var t;return Pg(this),e>=this.lastChangedEpoch?Yt:((t=this.historyBuffer)==null?void 0:t.getChangesSince(e))??Zr}}const C6=Wa("Atom",()=>v6);function We(n,e,t){return new C6(n,e,t)}const mM=1,P6=Wa("apiVersion",()=>mM);if(P6!==mM)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");Wi("@tldraw/state","4.4.0","esm");function oy(n,e,t=[]){const r=_e.useRef(e);r.current=e;const[s,o,i]=_e.useMemo(()=>{let a=null;const l=d=>(a=d,()=>{a=null}),c=new Wl(`useStateTracking(${n})`,()=>{var d;return(d=r.current)==null?void 0:d.call(r)},{scheduleEffect(){a==null||a()}});return[c,l,()=>c.scheduleCount]},[n,...t]);return _e.useSyncExternalStore(o,i,i),_e.useEffect(()=>(s.attach(),s.maybeScheduleEffect(),()=>{s.detach()}),[s]),s.execute()}const WP={apply(n,e,t){return oy(n.displayName??n.name??"tracked(???)",()=>n.apply(e,t))}},T6=Symbol.for("react.memo"),I6=Symbol.for("react.forward_ref");function rn(n){let e=null;const t=n.$$typeof;return t===T6&&(n=n.type,e=n.compare),t===I6?x.memo(x.forwardRef(new Proxy(n.render,WP))):x.memo(new Proxy(n,WP),e)}function md(n,e,t){return x.useState(()=>{const r=typeof e=="function"?e():e;return We(`useAtom(${n})`,r,t)})[0]}function vv(){const n=arguments[0],e=arguments[1],t=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return x.useMemo(()=>q(`useComputed(${n})`,e,t),r)}function Va(n,e,t=Yt){x.useEffect(()=>{const r=new Wl(n,e);return r.attach(),r.execute(),()=>{r.detach()}},t)}function iy(n,e,t=[]){x.useEffect(()=>{let r;const s=new Wl(n,e,{scheduleEffect:o=>{r=Sv(o)}});return s.attach(),s.execute(),()=>{s.detach(),r==null||r()}},t)}function W(){const n=arguments,e=n.length===3?n[2]:[n[0]],t=n.length===3?n[0]:`useValue(${n[0].name})`,{$val:r,subscribe:s,getSnapshot:o}=x.useMemo(()=>{const i=n.length===1?n[0]:q(t,n[1]);return{$val:i,subscribe:a=>Mr(`useValue(${t})`,()=>{try{i.get()}catch{}a()}),getSnapshot:()=>i.lastChangedEpoch}},e);return x.useSyncExternalStore(s,o,o),r.__unsafe__getWithoutCapture()}Wi("@tldraw/state-react","4.4.0","esm");/*!
46
+ * This file was lovingly and delicately extracted from Immutable.js
47
+ * MIT License: https://github.com/immutable-js/immutable-js/blob/main/LICENSE
48
+ * Copyright (c) 2014-present, Lee Byron and other contributors.
49
+ */function Cv(n){return n>>>1&1073741824|n&3221225471}const E6=Object.prototype.valueOf;function kl(n){if(n==null)return VP(n);if(typeof n.hashCode=="function")return Cv(n.hashCode(n));const e=D6(n);if(e==null)return VP(e);switch(typeof e){case"boolean":return e?1108378657:1108378656;case"number":return k6(e);case"string":return _6(e);case"object":case"function":return A6(e);case"symbol":return M6(e);default:if(typeof e.toString=="function")return yM(e.toString());throw new Error("Value type "+typeof e+" cannot be hashed.")}}function VP(n){return n===null?1108378658:1108378659}function k6(n){if(n!==n||n===1/0)return 0;let e=n|0;for(e!==n&&(e^=n*4294967295);n>4294967295;)n/=4294967295,e^=n;return Cv(e)}function _6(n){let e=bx[n];return e===void 0&&(e=yM(n),wx===O6&&(wx=0,bx={}),bx[n]=e,wx++),e}function yM(n){let e=0;for(let t=0;t<n.length;t++)e=31*e+n.charCodeAt(t)|0;return Cv(e)}function M6(n){let e=YP[n];return e!==void 0||(e=SM(),YP[n]=e),e}function A6(n){let e=GP.get(n);return e!==void 0||(e=SM(),GP.set(n,e)),e}function D6(n){return n.valueOf!==E6&&typeof n.valueOf=="function"?n.valueOf(n):n}function SM(){const n=++xx;return xx&1073741824&&(xx=0),n}const GP=new WeakMap,YP=Object.create(null);let xx=0,bx={},wx=0;const O6=24e3,qc=5,Oh=1<<qc,Zc=Oh-1,Hi={};function XP(){return{value:!1}}function co(n){n&&(n.value=!0)}function Pv(n,e=0){return n.slice(e)}class xM{}class Tv{constructor(e){E(this,"_root");E(this,"size");E(this,"__ownerID");E(this,"__hash");E(this,"__altered");return e==null?Lc():e instanceof Tv?e:Lc().withMutations(t=>{for(const[r,s]of e)t.set(r,s)})}get(e,t){return this._root?this._root.get(0,void 0,e,t):t}set(e,t){return JP(this,e,t)}delete(e){return JP(this,e,Hi)}deleteAll(e){return this.withMutations(t=>{for(const r of e)t.delete(r)})}__ensureOwner(e){return e===this.__ownerID?this:e?kv(this.size,this._root,e,this.__hash):this.size===0?Lc():(this.__ownerID=e,this.__altered=!1,this)}withMutations(e){const t=this.asMutable();return e(t),t.wasAltered()?t.__ensureOwner(this.__ownerID):this}wasAltered(){return this.__altered}asMutable(){return this.__ownerID?this:this.__ensureOwner(new xM)}[Symbol.iterator](){return this.entries()[Symbol.iterator]()}entries(){return new vx(this,R6,!1)}keys(){return new vx(this,bM,!1)}values(){return new vx(this,wM,!1)}}class Iv{constructor(e,t){this.ownerID=e,this.entries=t}get(e,t,r,s){const o=this.entries;for(let i=0,a=o.length;i<a;i++)if(Object.is(r,o[i][0]))return o[i][1];return s}update(e,t,r,s,o,i,a){const l=o===Hi,c=this.entries;let u=0;const d=c.length;for(;u<d&&!Object.is(s,c[u][0]);u++);const h=u<d;if(h?c[u][1]===o:l)return this;if(co(a),(l||!h)&&co(i),l&&c.length===1)return;if(!h&&!l&&c.length>=H6)return N6(e,c,s,o);const f=e&&e===this.ownerID,g=f?c:Pv(c);return h?l?u===d-1?g.pop():g[u]=g.pop():g[u]=[s,o]:g.push([s,o]),f?(this.entries=g,this):new Iv(e,g)}}class ay{constructor(e,t,r){this.ownerID=e,this.bitmap=t,this.nodes=r}get(e,t,r,s){t===void 0&&(t=kl(r));const o=1<<((e===0?t:t>>>e)&Zc),i=this.bitmap;return(i&o)===0?s:this.nodes[eT(i&o-1)].get(e+qc,t,r,s)}update(e,t,r,s,o,i,a){r===void 0&&(r=kl(s));const l=(t===0?r:r>>>t)&Zc,c=1<<l,u=this.bitmap,d=(u&c)!==0;if(!d&&o===Hi)return this;const h=eT(u&c-1),f=this.nodes,g=d?f[h]:void 0,m=_v(g,e,t+qc,r,s,o,i,a);if(m===g)return this;if(!d&&m&&f.length>=U6)return B6(e,f,u,l,m);if(d&&!m&&f.length===2&&QP(f[h^1]))return f[h^1];if(d&&m&&f.length===1&&QP(m))return m;const y=e&&e===this.ownerID,S=d?m?u:u^c:u|c,b=d?m?vM(f,h,m,y):$6(f,h,y):z6(f,h,m,y);return y?(this.bitmap=S,this.nodes=b,this):new ay(e,S,b)}}class Ev{constructor(e,t,r){this.ownerID=e,this.count=t,this.nodes=r}get(e,t,r,s){t===void 0&&(t=kl(r));const o=(e===0?t:t>>>e)&Zc,i=this.nodes[o];return i?i.get(e+qc,t,r,s):s}update(e,t,r,s,o,i,a){r===void 0&&(r=kl(s));const l=(t===0?r:r>>>t)&Zc,c=o===Hi,u=this.nodes,d=u[l];if(c&&!d)return this;const h=_v(d,e,t+qc,r,s,o,i,a);if(h===d)return this;let f=this.count;if(!d)f++;else if(!h&&(f--,f<K6))return F6(e,u,f,l);const g=e&&e===this.ownerID,m=vM(u,l,h,g);return g?(this.count=f,this.nodes=m,this):new Ev(e,f,m)}}class ly{constructor(e,t,r){this.ownerID=e,this.keyHash=t,this.entries=r}get(e,t,r,s){const o=this.entries;for(let i=0,a=o.length;i<a;i++)if(Object.is(r,o[i][0]))return o[i][1];return s}update(e,t,r,s,o,i,a){r===void 0&&(r=kl(s));const l=o===Hi;if(r!==this.keyHash)return l?this:(co(a),co(i),Mv(this,e,t,r,[s,o]));const c=this.entries;let u=0;const d=c.length;for(;u<d&&!Object.is(s,c[u][0]);u++);const h=u<d;if(h?c[u][1]===o:l)return this;if(co(a),(l||!h)&&co(i),l&&d===2)return new Vl(e,this.keyHash,c[u^1]);const f=e&&e===this.ownerID,g=f?c:Pv(c);return h?l?u===d-1?g.pop():g[u]=g.pop():g[u]=[s,o]:g.push([s,o]),f?(this.entries=g,this):new ly(e,this.keyHash,g)}}class Vl{constructor(e,t,r){this.ownerID=e,this.keyHash=t,this.entry=r}get(e,t,r,s){return Object.is(r,this.entry[0])?this.entry[1]:s}update(e,t,r,s,o,i,a){const l=o===Hi,c=Object.is(s,this.entry[0]);if(c?o===this.entry[1]:l)return this;if(co(a),l){co(i);return}return c?e&&e===this.ownerID?(this.entry[1]=o,this):new Vl(e,this.keyHash,[s,o]):(co(i),Mv(this,e,t,kl(s),[s,o]))}}class vx{constructor(e,t,r){E(this,"_stack");this._type=t,this._reverse=r,this._stack=e._root&&qP(e._root)}[Symbol.iterator](){return this}next(){const e=this._type;let t=this._stack;for(;t;){const r=t.node,s=t.index++;let o;if(r.entry){if(s===0)return Cx(e,r.entry)}else if("entries"in r&&r.entries){if(o=r.entries.length-1,s<=o)return Cx(e,r.entries[this._reverse?o-s:s])}else if(o=r.nodes.length-1,s<=o){const i=r.nodes[this._reverse?o-s:s];if(i){if(i.entry)return Cx(e,i.entry);t=this._stack=qP(i,t)}continue}t=this._stack=this._stack.__prev}return j6()}}function Cx(n,e){return L6(n,e[0],e[1])}function qP(n,e){return{node:n,index:0,__prev:e}}const bM=0,wM=1,R6=2;function L6(n,e,t,r){const s=n===bM?e:n===wM?t:[e,t];return r?r.value=s:r={value:s,done:!1},r}function j6(){return{value:void 0,done:!0}}function kv(n,e,t,r){const s=Object.create(Tv.prototype);return s.size=n,s._root=e,s.__ownerID=t,s.__hash=r,s.__altered=!1,s}let ZP;function Lc(){return ZP||(ZP=kv(0))}function JP(n,e,t){let r,s;if(n._root){const o=XP(),i=XP();if(r=_v(n._root,n.__ownerID,0,void 0,e,t,o,i),!i.value)return n;s=n.size+(o.value?t===Hi?-1:1:0)}else{if(t===Hi)return n;s=1,r=new Iv(n.__ownerID,[[e,t]])}return n.__ownerID?(n.size=s,n._root=r,n.__hash=void 0,n.__altered=!0,n):r?kv(s,r):Lc()}function _v(n,e,t,r,s,o,i,a){return n?n.update(e,t,r,s,o,i,a):o===Hi?n:(co(a),co(i),new Vl(e,r,[s,o]))}function QP(n){return n.constructor===Vl||n.constructor===ly}function Mv(n,e,t,r,s){if(n.keyHash===r)return new ly(e,r,[n.entry,s]);const o=(t===0?n.keyHash:n.keyHash>>>t)&Zc,i=(t===0?r:r>>>t)&Zc;let a;const l=o===i?[Mv(n,e,t+qc,r,s)]:(a=new Vl(e,r,s),o<i?[n,a]:[a,n]);return new ay(e,1<<o|1<<i,l)}function N6(n,e,t,r){n||(n=new xM);let s=new Vl(n,kl(t),[t,r]);for(let o=0;o<e.length;o++){const i=e[o];s=s.update(n,0,void 0,i[0],i[1])}return s}function F6(n,e,t,r){let s=0,o=0;const i=new Array(t);for(let a=0,l=1,c=e.length;a<c;a++,l<<=1){const u=e[a];u!==void 0&&a!==r&&(s|=l,i[o++]=u)}return new ay(n,s,i)}function B6(n,e,t,r,s){let o=0;const i=new Array(Oh);for(let a=0;t!==0;a++,t>>>=1)i[a]=t&1?e[o++]:void 0;return i[r]=s,new Ev(n,o+1,i)}function eT(n){return n-=n>>1&1431655765,n=(n&858993459)+(n>>2&858993459),n=n+(n>>4)&252645135,n+=n>>8,n+=n>>16,n&127}function vM(n,e,t,r){const s=r?n:Pv(n);return s[e]=t,s}function z6(n,e,t,r){const s=n.length+1;if(r&&e+1===s)return n[e]=t,n;const o=new Array(s);let i=0;for(let a=0;a<s;a++)a===e?(o[a]=t,i=-1):o[a]=n[a+i];return o}function $6(n,e,t){const r=n.length-1;if(t&&e===r)return n.pop(),n;const s=new Array(r);let o=0;for(let i=0;i<r;i++)i===e&&(o=1),s[i]=n[i+o];return s}const H6=Oh/4,U6=Oh/2,K6=Oh/4;var A_,D_;class Tg{constructor(e,t){E(this,"atoms");E(this,A_,"AtomMap");this.name=e;let r=Lc();t&&(r=r.withMutations(s=>{for(const[o,i]of t)s.set(o,We(`${e}:${String(o)}`,i))})),this.atoms=We(`${e}:atoms`,r)}getAtom(e){const t=this.atoms.__unsafe__getWithoutCapture().get(e);if(!t){this.atoms.get();return}return t}get(e){var r;const t=(r=this.getAtom(e))==null?void 0:r.get();return be(t!==nr),t}__unsafe__getWithoutCapture(e){const t=this.atoms.__unsafe__getWithoutCapture().get(e);if(!t)return;const r=t.__unsafe__getWithoutCapture();return be(r!==nr),r}has(e){const t=this.getAtom(e);return t?t.get()!==nr:!1}__unsafe__hasWithoutCapture(e){const t=this.atoms.__unsafe__getWithoutCapture().get(e);return t?(be(t.__unsafe__getWithoutCapture()!==nr),!0):!1}set(e,t){const r=this.atoms.__unsafe__getWithoutCapture().get(e);return r?r.set(t):this.atoms.update(s=>s.set(e,We(`${this.name}:${String(e)}`,t))),this}update(e,t){const r=this.atoms.__unsafe__getWithoutCapture().get(e);if(!r)throw new Error(`AtomMap: key ${e} not found`);const s=r.__unsafe__getWithoutCapture();be(s!==nr),r.set(t(s))}delete(e){const t=this.atoms.__unsafe__getWithoutCapture().get(e);return t?(ms(()=>{t.set(nr),this.atoms.update(r=>r.delete(e))}),!0):!1}deleteMany(e){return ms(()=>{const t=[],r=this.atoms.get().withMutations(s=>{for(const o of e){const i=s.get(o);if(!i)continue;const a=i.get();be(a!==nr),t.push([o,a]),s.delete(o),i.set(nr)}});return t.length&&this.atoms.set(r),t})}clear(){return ms(()=>{for(const e of this.atoms.__unsafe__getWithoutCapture().values())e.set(nr);this.atoms.set(Lc())})}*entries(){for(const[e,t]of this.atoms.get()){const r=t.get();be(r!==nr),yield[e,r]}}*keys(){for(const e of this.atoms.get().keys())yield e}*values(){for(const e of this.atoms.get().values()){const t=e.get();be(t!==nr),yield t}}get size(){return this.atoms.get().size}forEach(e,t){for(const[r,s]of this.entries())e.call(t,s,r,this)}[(D_=Symbol.iterator,A_=Symbol.toStringTag,D_)](){return this.entries()}}var O_,R_;class tT{constructor(e,t){E(this,"map");E(this,O_,"AtomSet");this.name=e;const r=t?Array.from(t,s=>[s,s]):void 0;this.map=new Tg(e,r)}add(e){return this.map.set(e,e),this}clear(){this.map.clear()}delete(e){return this.map.delete(e)}forEach(e,t){for(const r of this)e.call(t,r,r,this)}has(e){return this.map.has(e)}get size(){return this.map.size}entries(){return this.map.entries()}keys(){return this.map.keys()}values(){return this.map.keys()}[(R_=Symbol.iterator,O_=Symbol.toStringTag,R_)](){return this.map.keys()}}let Ig=!1;try{Ig=!1}catch{}try{Ig=Ig||!1||void 0||!1||!1}catch{}function W6(){return Ig}function jc(n){if(!W6())return n;const e=Object.getPrototypeOf(n);if(e&&!(Array.isArray(n)||e===Object.prototype||e===null||e===nM))throw console.error("cannot include non-js data in a record",n),new Error("cannot include non-js data in a record");if(Object.isFrozen(n))return n;const t=Object.getOwnPropertyNames(n);for(const r of t){const s=n[r];s&&typeof s=="object"&&jc(s)}return Object.freeze(n)}class Rf{constructor(e){E(this,"nextValue");E(this,"diff");this.previousValue=e}get(){var r,s,o,i;const e=((s=(r=this.diff)==null?void 0:r.removed)==null?void 0:s.size)??0,t=((i=(o=this.diff)==null?void 0:o.added)==null?void 0:i.size)??0;if(!(e===0&&t===0))return{value:this.nextValue,diff:this.diff}}_add(e,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(e),this.diff??(this.diff={}),t?(r=this.diff.removed)==null||r.delete(e):((s=this.diff).added??(s.added=new Set),this.diff.added.add(e))}add(e){var s,o,i;const t=this.previousValue.has(e);if(t)return((o=(s=this.diff)==null?void 0:s.removed)==null?void 0:o.has(e))?this._add(e,t):void 0;(i=this.nextValue)!=null&&i.has(e)||this._add(e,t)}_remove(e,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(e),this.diff??(this.diff={}),t?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(e)):(s=this.diff.added)==null||s.delete(e)}remove(e){var s,o,i,a;const t=this.previousValue.has(e);if(!t)return((o=(s=this.diff)==null?void 0:s.added)==null?void 0:o.has(e))?this._remove(e,t):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(e)||this._remove(e,t)}}function V6(n){const e=[];for(let t=n.length-1;t>=0;t--){const r=n[t];if("id"in r)e.unshift(r);else{const s=r.dependsOn,o=e[0];o&&(e[0]={...o,dependsOn:s.concat(o.dependsOn??[])})}}return e}function Nc({sequence:n,sequenceId:e,retroactive:t=!0}){const r={sequenceId:e,retroactive:t,sequence:V6(n)};return CM(r),r}function ns(n,e){return Object.fromEntries($s(e).map(([t,r])=>[t,`${n}/${r}`]))}function vs(n){const e=n.sequenceId;return Nc({sequenceId:e,retroactive:n.retroactive??!0,sequence:n.sequence.map(t=>"id"in t?{...t,scope:"record",filter:r=>{var s,o;return r.typeName===n.recordType&&(((s=t.filter)==null?void 0:s.call(t,r))??!0)&&(((o=n.filter)==null?void 0:o.call(n,r))??!0)}}:t)})}function G6(n){if(n.length===0)return[];const e=new Map(n.map(l=>[l.id,l])),t=new Map,r=new Map,s=new Map;for(const l of n)r.set(l.id,0),t.set(l.id,new Set),s.set(l.id,new Set);for(const l of n){const{version:c,sequenceId:u}=Eg(l.id),d=`${u}/${c-1}`;if(e.has(d)&&(t.get(d).add(l.id),r.set(l.id,r.get(l.id)+1)),l.dependsOn)for(const h of l.dependsOn)e.has(h)&&(t.get(h).add(l.id),s.get(l.id).add(h),r.set(l.id,r.get(l.id)+1))}const o=n.filter(l=>r.get(l.id)===0),i=[],a=new Set;for(;o.length>0;){let l,c=-1/0;for(const d of o){let h=0;for(const f of t.get(d.id)||[])a.has(f)||(h+=1,s.get(f).has(d.id)&&(h+=100));(h>c||h===c&&d.id.localeCompare((l==null?void 0:l.id)??"")<0)&&(l=d,c=h)}const u=l;o.splice(o.indexOf(u),1),i.push(u),a.add(u.id);for(const d of t.get(u.id)||[])a.has(d)||(r.set(d,r.get(d)-1),r.get(d)===0&&o.push(e.get(d)))}if(i.length!==n.length){const l=n.filter(c=>!a.has(c.id));be(!1,`Circular dependency in migrations: ${l[0].id}`)}return i}function Eg(n){const[e,t]=n.split("/");return{sequenceId:e,version:parseInt(t)}}function nT(n,e){e&&be(n.startsWith(e+"/"),`Every migration in sequence '${e}' must have an id starting with '${e}/'. Got invalid id: '${n}'`),be(n.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${n}'`)}function CM(n){if(be(!n.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${n.sequenceId}`),be(n.sequenceId.length,"sequenceId must be a non-empty string"),n.sequence.length===0)return;nT(n.sequence[0].id,n.sequenceId);let e=Eg(n.sequence[0].id).version;be(e===1,`Expected the first migrationId to be '${n.sequenceId}/1' but got '${n.sequence[0].id}'`);for(let t=1;t<n.sequence.length;t++){const r=n.sequence[t].id;nT(r,n.sequenceId);const s=Eg(r).version;be(s===e+1,`Migration id numbers must increase in increments of 1, expected ${n.sequenceId}/${e+1} but got '${n.sequence[t].id}'`),e=s}}var ca=(n=>(n.IncompatibleSubtype="incompatible-subtype",n.UnknownType="unknown-type",n.TargetVersionTooNew="target-version-too-new",n.TargetVersionTooOld="target-version-too-old",n.MigrationError="migration-error",n.UnrecognizedSubtype="unrecognized-subtype",n))(ca||{});function kg(){return{added:{},updated:{},removed:{}}}function xw(n){const e={added:n.removed,removed:n.added,updated:{}};for(const[t,r]of Object.values(n.updated))e.updated[t.id]=[r,t];return e}function PM(n){return Object.keys(n.added).length===0&&Object.keys(n.updated).length===0&&Object.keys(n.removed).length===0}function Av(n,e){const t=e!=null&&e.mutateFirstDiff?n[0]:{added:{},removed:{},updated:{}};return Ou(t,n),t}function Ou(n,e){for(const t of e){for(const[r,s]of $s(t.added))if(n.removed[r]){const o=n.removed[r];delete n.removed[r],o!==s&&(n.updated[r]=[o,s])}else n.added[r]=s;for(const[r,[s,o]]of $s(t.updated)){if(n.added[r]){n.added[r]=o,delete n.updated[r],delete n.removed[r];continue}if(n.updated[r]){n.updated[r]=[n.updated[r][0],o],delete n.removed[r];continue}n.updated[r]=t.updated[r],delete n.removed[r]}for(const[r,s]of $s(t.removed))n.added[r]?delete n.added[r]:n.updated[r]?(n.removed[r]=n.updated[r][0],delete n.updated[r]):n.removed[r]=s}}class cy{constructor(e,t){E(this,"createDefaultProperties");E(this,"validator");E(this,"ephemeralKeys");E(this,"ephemeralKeySet");E(this,"scope");this.typeName=e,this.createDefaultProperties=t.createDefaultProperties,this.validator=t.validator??{validate:s=>s},this.scope=t.scope??"document",this.ephemeralKeys=t.ephemeralKeys;const r=new Set;if(t.ephemeralKeys)for(const[s,o]of $s(t.ephemeralKeys))o&&r.add(s);this.ephemeralKeySet=r}create(e){const t={...this.createDefaultProperties(),id:"id"in e?e.id:this.createId()};for(const[r,s]of Object.entries(e))s!==void 0&&(t[r]=s);return t.typeName=this.typeName,t}clone(e){return{...Ft(e),id:this.createId()}}createId(e){return this.typeName+":"+(e??at())}parseId(e){if(!this.isId(e))throw new Error(`ID "${e}" is not a valid ID for type "${this.typeName}"`);return e.slice(this.typeName.length+1)}isInstance(e){return(e==null?void 0:e.typeName)===this.typeName}isId(e){if(!e)return!1;for(let t=0;t<this.typeName.length;t++)if(e[t]!==this.typeName[t])return!1;return e[this.typeName.length]===":"}withDefaultProperties(e){return new cy(this.typeName,{createDefaultProperties:e,validator:this.validator,scope:this.scope,ephemeralKeys:this.ephemeralKeys})}validate(e,t){return t&&this.validator.validateUsingKnownGoodVersion?this.validator.validateUsingKnownGoodVersion(t,e):this.validator.validate(e)}}function qo(n,e){return new cy(n,{createDefaultProperties:()=>({}),validator:e.validator,scope:e.scope,ephemeralKeys:e.ephemeralKeys})}function Y6(n){if(n.length===0)return new Set;const e=n[0],t=n.slice(1),r=new Set;for(const s of e)t.every(o=>o.has(s))&&r.add(s);return r}function X6(n,e){const t={};for(const r of e)n.has(r)||(t.added??(t.added=new Set),t.added.add(r));for(const r of n)e.has(r)||(t.removed??(t.removed=new Set),t.removed.add(r));return t.added||t.removed?t:void 0}function TM(n){return typeof n!="object"||n===null?!1:"eq"in n||"neq"in n||"gt"in n}function IM(n,e=""){const t=[];for(const[r,s]of Object.entries(n)){const o=e?`${e}\\${r}`:r;TM(s)?t.push({path:o,matcher:s}):typeof s=="object"&&s!==null&&t.push(...IM(s,o))}return t}function bw(n,e){for(const[t,r]of Object.entries(n)){const s=e[t];if(TM(r)){if("eq"in r&&s!==r.eq||"neq"in r&&s===r.neq||"gt"in r&&(typeof s!="number"||s<=r.gt))return!1;continue}if(typeof s!="object"||s===null||!bw(r,s))return!1}return!0}function rT(n,e,t){const r=IM(t),s=Object.fromEntries(r.map(({path:o})=>[o,new Set]));for(const{path:o,matcher:i}of r){const a=n.index(e,o);if("eq"in i){const l=a.get().get(i.eq);if(l)for(const c of l)s[o].add(c)}else if("neq"in i){for(const[l,c]of a.get())if(l!==i.neq)for(const u of c)s[o].add(u)}else if("gt"in i){for(const[l,c]of a.get())if(typeof l=="number"&&l>i.gt)for(const u of c)s[o].add(u)}if(s[o].size===0)return new Set}return Y6(Object.values(s))}class q6{constructor(e,t){E(this,"indexCache",new Map);E(this,"historyCache",new Map);this.recordMap=e,this.history=t}getAllIdsForType(e){const t=new Set;for(const r of this.recordMap.values())r.typeName===e&&t.add(r.id);return t}getRecordById(e,t){const r=this.recordMap.get(t);if(r&&r.typeName===e)return r}getNestedValue(e,t){let r=e;for(const s of t){if(r==null||typeof r!="object")return;r=r[s]}return r}filterHistory(e){if(this.historyCache.has(e))return this.historyCache.get(e);const t=q("filterHistory:"+e,(r,s)=>{if(Ri(r))return this.history.get();const o=this.history.getDiffSince(s);if(o===Zr)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const u of o){for(const d of Et(u.added))if(d.typeName===e)if(i.removed[d.id]){const h=i.removed[d.id];delete i.removed[d.id],l--,h!==d&&(i.updated[d.id]=[h,d],c++)}else i.added[d.id]=d,a++;for(const[d,h]of Et(u.updated))h.typeName===e&&(i.added[h.id]?i.added[h.id]=h:i.updated[h.id]?i.updated[h.id]=[i.updated[h.id][0],h]:(i.updated[h.id]=[d,h],c++));for(const d of Et(u.removed))d.typeName===e&&(i.added[d.id]?(delete i.added[d.id],a--):i.updated[d.id]?(i.removed[d.id]=i.updated[d.id][0],delete i.updated[d.id],c--,l++):(i.removed[d.id]=d,l++))}return a||l||c?ou(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(e,t),t}index(e,t){const r=e+":"+t;if(this.indexCache.has(r))return this.indexCache.get(r);const s=this.__uncached_createIndex(e,t);return this.indexCache.set(r,s),s}__uncached_createIndex(e,t){const r=this.filterHistory(e),s=t.split("\\"),o=s.length>1?a=>this.getNestedValue(a,s):a=>a[t],i=()=>{r.get();const a=new Map;for(const l of this.recordMap.values())if(l.typeName===e){const c=o(l);c!==void 0&&(a.has(c)||a.set(c,new Set),a.get(c).add(l.id))}return a};return q("index:"+e+":"+t,(a,l)=>{if(Ri(a))return i();const c=r.getDiffSince(l);if(c===Zr)return i();const u=new Map,d=(m,y)=>{let S=u.get(m);S||(S=new Rf(a.get(m)??new Set)),S.add(y),u.set(m,S)},h=(m,y)=>{let S=u.get(m);S||(S=new Rf(a.get(m)??new Set)),S.remove(y),u.set(m,S)};for(const m of c){for(const y of Et(m.added))if(y.typeName===e){const S=o(y);S!==void 0&&d(S,y.id)}for(const[y,S]of Et(m.updated))if(S.typeName===e){const b=o(y),w=o(S);b!==w&&(b!==void 0&&h(b,S.id),w!==void 0&&d(w,S.id))}for(const y of Et(m.removed))if(y.typeName===e){const S=o(y);S!==void 0&&h(S,y.id)}}let f,g;for(const[m,y]of u){const S=y.get();S&&(f||(f=new Map(a)),g||(g=new Map),S.value.size===0?f.delete(m):f.set(m,S.value),g.set(m,S.diff))}return f&&g?ou(f,g):a},{historyLength:100})}record(e,t=()=>({}),r="record:"+e+(t?":"+t.toString():"")){const s=this.ids(e,t,r);return q(r,()=>{for(const o of s.get())return this.recordMap.get(o)})}records(e,t=()=>({}),r="records:"+e+(t?":"+t.toString():"")){const s=this.ids(e,t,"ids:"+r);return q(r,()=>Array.from(s.get(),o=>this.recordMap.get(o)),{isEqual:bg})}ids(e,t=()=>({}),r="ids:"+e+(t?":"+t.toString():"")){const s=this.filterHistory(e),o=()=>{s.get();const l=t();return Object.keys(l).length===0?this.getAllIdsForType(e):rT(this,e,l)},i=l=>{const c=o(),u=X6(l,c);return u?ou(c,u):l},a=q("ids_query:"+r,t,{isEqual:So});return q("query:"+r,(l,c)=>{const u=a.get();if(Ri(l))return o();if(c<a.lastChangedEpoch)return i(l);const d=s.getDiffSince(c);if(d===Zr)return i(l);const h=new Rf(l);for(const g of d){for(const m of Et(g.added))m.typeName===e&&bw(u,m)&&h.add(m.id);for(const[m,y]of Et(g.updated))y.typeName===e&&(bw(u,y)?h.add(y.id):h.remove(y.id));for(const m of Et(g.removed))m.typeName===e&&h.remove(m.id)}const f=h.get();return f?ou(f.value,f.diff):l},{historyLength:50})}exec(e,t){const r=rT(this,e,t);return r.size===0?Yt:Array.from(r,s=>this.recordMap.get(s))}}class Z6{constructor(e){E(this,"_beforeCreateHandlers",{});E(this,"_afterCreateHandlers",{});E(this,"_beforeChangeHandlers",{});E(this,"_afterChangeHandlers",{});E(this,"_beforeDeleteHandlers",{});E(this,"_afterDeleteHandlers",{});E(this,"_operationCompleteHandlers",[]);E(this,"_isEnabled",!0);this.store=e}isEnabled(){return this._isEnabled}setIsEnabled(e){this._isEnabled=e}handleBeforeCreate(e,t){if(!this._isEnabled)return e;const r=this._beforeCreateHandlers[e.typeName];if(r){let s=e;for(const o of r)s=o(s,t);return s}return e}handleAfterCreate(e,t){if(!this._isEnabled)return;const r=this._afterCreateHandlers[e.typeName];if(r)for(const s of r)s(e,t)}handleBeforeChange(e,t,r){if(!this._isEnabled)return t;const s=this._beforeChangeHandlers[t.typeName];if(s){let o=t;for(const i of s)o=i(e,o,r);return o}return t}handleAfterChange(e,t,r){if(!this._isEnabled)return;const s=this._afterChangeHandlers[t.typeName];if(s)for(const o of s)o(e,t,r)}handleBeforeDelete(e,t){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[e.typeName];if(r){for(const s of r)if(s(e,t)===!1)return!1}return!0}handleAfterDelete(e,t){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[e.typeName];if(r)for(const s of r)s(e,t)}handleOperationComplete(e){if(this._isEnabled)for(const t of this._operationCompleteHandlers)t(e)}register(e){const t=[];for(const[r,s]of Object.entries(e))s!=null&&s.beforeCreate&&t.push(this.registerBeforeCreateHandler(r,s.beforeCreate)),s!=null&&s.afterCreate&&t.push(this.registerAfterCreateHandler(r,s.afterCreate)),s!=null&&s.beforeChange&&t.push(this.registerBeforeChangeHandler(r,s.beforeChange)),s!=null&&s.afterChange&&t.push(this.registerAfterChangeHandler(r,s.afterChange)),s!=null&&s.beforeDelete&&t.push(this.registerBeforeDeleteHandler(r,s.beforeDelete)),s!=null&&s.afterDelete&&t.push(this.registerAfterDeleteHandler(r,s.afterDelete));return()=>{for(const r of t)r()}}registerBeforeCreateHandler(e,t){return this._beforeCreateHandlers[e]||(this._beforeCreateHandlers[e]=[]),this._beforeCreateHandlers[e].push(t),()=>ll(this._beforeCreateHandlers[e],t)}registerAfterCreateHandler(e,t){return this._afterCreateHandlers[e]||(this._afterCreateHandlers[e]=[]),this._afterCreateHandlers[e].push(t),()=>ll(this._afterCreateHandlers[e],t)}registerBeforeChangeHandler(e,t){return this._beforeChangeHandlers[e]||(this._beforeChangeHandlers[e]=[]),this._beforeChangeHandlers[e].push(t),()=>ll(this._beforeChangeHandlers[e],t)}registerAfterChangeHandler(e,t){return this._afterChangeHandlers[e]||(this._afterChangeHandlers[e]=[]),this._afterChangeHandlers[e].push(t),()=>ll(this._afterChangeHandlers[e],t)}registerBeforeDeleteHandler(e,t){return this._beforeDeleteHandlers[e]||(this._beforeDeleteHandlers[e]=[]),this._beforeDeleteHandlers[e].push(t),()=>ll(this._beforeDeleteHandlers[e],t)}registerAfterDeleteHandler(e,t){return this._afterDeleteHandlers[e]||(this._afterDeleteHandlers[e]=[]),this._afterDeleteHandlers[e].push(t),()=>ll(this._afterDeleteHandlers[e],t)}registerOperationCompleteHandler(e){return this._operationCompleteHandlers.push(e),()=>ll(this._operationCompleteHandlers,e)}}function ll(n,e){const t=n.indexOf(e);t>=0&&n.splice(t,1)}class Dv{constructor(e){E(this,"id");E(this,"records");E(this,"history",We("history",0,{historyLength:1e3}));E(this,"query");E(this,"listeners",new Set);E(this,"historyAccumulator",new Q6);E(this,"historyReactor");E(this,"schema");E(this,"props");E(this,"scopedTypes");E(this,"sideEffects",new Z6(this));E(this,"isMergingRemoteChanges",!1);E(this,"_integrityChecker");E(this,"_isPossiblyCorrupted",!1);E(this,"pendingAfterEvents",null);E(this,"_isInAtomicOp",!1);const{initialData:t,schema:r,id:s}=e;this.id=s??at(),this.schema=r,this.props=e.props,t?this.records=new Tg("store",$s(t).map(([o,i])=>[o,jc(this.schema.validateRecord(this,i,"initialize",null))])):this.records=new Tg("store"),this.query=new q6(this.records,this.history),this.historyReactor=l6("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:o=>this.cancelHistoryReactor=Sv(o)}),this.scopedTypes={document:new Set(Et(this.schema.types).filter(o=>o.scope==="document").map(o=>o.typeName)),session:new Set(Et(this.schema.types).filter(o=>o.scope==="session").map(o=>o.typeName)),presence:new Set(Et(this.schema.types).filter(o=>o.scope==="presence").map(o=>o.typeName))}}cancelHistoryReactor(){}_flushHistory(){if(this.historyAccumulator.hasChanges()){const e=this.historyAccumulator.flush();for(const{changes:t,source:r}of e){let s=null,o=null,i=null;for(const{onHistory:a,filters:l}of this.listeners)if(!(l.source!=="all"&&l.source!==r))if(l.scope!=="all")if(l.scope==="document"){if(o??(o=this.filterChangesByScope(t,"document")),!o)continue;a({changes:o,source:r})}else if(l.scope==="session"){if(s??(s=this.filterChangesByScope(t,"session")),!s)continue;a({changes:s,source:r})}else{if(i??(i=this.filterChangesByScope(t,"presence")),!i)continue;a({changes:i,source:r})}else a({changes:t,source:r})}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(e,t){const r={added:Du(e.added,(s,o)=>this.scopedTypes[t].has(o.typeName)),updated:Du(e.updated,(s,o)=>this.scopedTypes[t].has(o[1].typeName)),removed:Du(e.removed,(s,o)=>this.scopedTypes[t].has(o.typeName))};return Object.keys(r.added).length===0&&Object.keys(r.updated).length===0&&Object.keys(r.removed).length===0?null:r}updateHistory(e){this.historyAccumulator.add({changes:e,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,e)}validate(e){this.allRecords().forEach(t=>this.schema.validateRecord(this,t,e,null))}put(e,t){this.atomic(()=>{const r={},s={};let o,i=!1;const a=this.isMergingRemoteChanges?"remote":"user";for(let l=0,c=e.length;l<c;l++){o=e[l];const u=this.records.__unsafe__getWithoutCapture(o.id);if(u){if(o=this.sideEffects.handleBeforeChange(u,o,a),this.schema.validateRecord(this,o,t??"updateRecord",u)===u)continue;o=jc(o),this.records.set(o.id,o),i=!0,r[o.id]=[u,o],this.addDiffForAfterEvent(u,o)}else o=this.sideEffects.handleBeforeCreate(o,a),i=!0,o=this.schema.validateRecord(this,o,t??"createRecord",null),o=jc(o),s[o.id]=o,this.addDiffForAfterEvent(null,o),this.records.set(o.id,o)}i&&this.updateHistory({added:s,updated:r,removed:{}})})}remove(e){this.atomic(()=>{const t=new Set(e),r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const i of e){const a=this.records.__unsafe__getWithoutCapture(i);a&&this.sideEffects.handleBeforeDelete(a,r)===!1&&t.delete(i)}const s=this.records.deleteMany(t);if(s.length===0)return;const o={};for(const[i,a]of s)o[i]=a,this.addDiffForAfterEvent(a,null);this.updateHistory({added:{},updated:{},removed:o})})}get(e){return this.records.get(e)}unsafeGetWithoutCapture(e){return this.records.__unsafe__getWithoutCapture(e)}serialize(e="document"){const t={};for(const[r,s]of this.records)(e==="all"||this.scopedTypes[e].has(s.typeName))&&(t[r]=s);return t}getStoreSnapshot(e="document"){return{store:this.serialize(e),schema:this.schema.serialize()}}migrateSnapshot(e){const t=this.schema.migrateStoreSnapshot(e);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);return{store:t.value,schema:this.schema.serialize()}}loadStoreSnapshot(e){const t=this.schema.migrateStoreSnapshot(e);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);const r=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(t.value)),this.ensureStoreIsUsable()})}finally{this.sideEffects.setIsEnabled(r)}}allRecords(){return Array.from(this.records.values())}clear(){this.remove(Array.from(this.records.keys()))}update(e,t){const r=this.unsafeGetWithoutCapture(e);if(!r){console.error(`Record ${e} not found. This is probably an error`);return}this.put([t(r)])}has(e){return this.records.has(e)}listen(e,t){this._flushHistory();const r={onHistory:e,filters:{source:(t==null?void 0:t.source)??"all",scope:(t==null?void 0:t.scope)??"all"}};return this.historyReactor.scheduler.isActivelyListening||(this.historyReactor.start(),this.historyReactor.scheduler.execute()),this.listeners.add(r),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}}mergeRemoteChanges(e){if(this.isMergingRemoteChanges)return e();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.atomic(e,!0,!0)}finally{this.ensureStoreIsUsable()}}extractingChanges(e){const t=[],r=this.historyAccumulator.addInterceptor(s=>t.push(s.changes));try{return ms(e),Av(t)}finally{r()}}applyDiff(e,{runCallbacks:t=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const s=Et(e.added);for(const[i,a]of Et(e.updated)){const l=this.schema.getType(a.typeName);if(r&&l.ephemeralKeySet.size){const c=this.get(a.id);if(!c){s.push(a);continue}let u=null;for(const[d,h]of Object.entries(a))l.ephemeralKeySet.has(d)||Object.is(h,un(c,d))||(u||(u={...c}),u[d]=h);u&&s.push(u)}else s.push(a)}const o=Au(e.removed);s.length&&this.put(s),o.length&&this.remove(o)},t)}createCache(e){const t=new Vn;return{get:r=>{const s=this.records.getAtom(r);if(s)return t.get(s,()=>e(r,s)).get()}}}createComputedCache(e,t,r){return this.createCache((s,o)=>{const i=r!=null&&r.areRecordsEqual?q(`${e}:${s}:isEqual`,()=>o.get(),{isEqual:r.areRecordsEqual}):o;return q(e+":"+s,()=>t(i.get()),{isEqual:r==null?void 0:r.areResultsEqual})})}ensureStoreIsUsable(){this.atomic(()=>{var e;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(e=this._integrityChecker)==null||e.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(e,t){if(be(this.pendingAfterEvents,"must be in event operation"),e===t||(e&&t&&be(e.id===t.id),!e&&!t))return;const r=(e||t).id,s=this.pendingAfterEvents.get(r);s?s.after=t:this.pendingAfterEvents.set(r,{before:e,after:t})}flushAtomicCallbacks(e){let t=0,r=e?"remote":"user";for(;this.pendingAfterEvents;){const s=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(t++,t>100)throw new Error("Maximum store update depth exceeded, bailing out");for(const{before:o,after:i}of s.values())o&&i&&o!==i&&!So(o,i)?this.sideEffects.handleAfterChange(o,i,r):o&&!i?this.sideEffects.handleAfterDelete(o,r):!o&&i&&this.sideEffects.handleAfterCreate(i,r);this.pendingAfterEvents?r="user":this.sideEffects.handleOperationComplete(r)}}}atomic(e,t=!0,r=!1){return ms(()=>{if(this._isInAtomicOp){this.pendingAfterEvents||(this.pendingAfterEvents=new Map);const o=this.sideEffects.isEnabled();be(!r,"cannot call mergeRemoteChanges while in atomic operation");try{return o&&!t&&this.sideEffects.setIsEnabled(!1),e()}finally{this.sideEffects.setIsEnabled(o)}}this.pendingAfterEvents=new Map;const s=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(t??s),this._isInAtomicOp=!0,r&&(this.isMergingRemoteChanges=!0);try{const o=e();return this.isMergingRemoteChanges=!1,this.flushAtomicCallbacks(r),o}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(s),this._isInAtomicOp=!1,this.isMergingRemoteChanges=!1}})}addHistoryInterceptor(e){return this.historyAccumulator.addInterceptor(t=>e(t,this.isMergingRemoteChanges?"remote":"user"))}}function J6(n){if(n.length===0)return[];const e=[];let t=[n[0]],r;for(let s=1,o=n.length;s<o;s++)r=n[s],t[0].source!==r.source&&(e.push(t),t=[]),t.push(r);return e.push(t),jc(e.map(s=>({source:s[0].source,changes:Av(s.map(o=>o.changes))})))}class Q6{constructor(){E(this,"_history",[]);E(this,"_interceptors",new Set)}addInterceptor(e){return this._interceptors.add(e),()=>{this._interceptors.delete(e)}}add(e){this._history.push(e);for(const t of this._interceptors)t(e)}flush(){const e=J6(this._history);return this._history=[],e}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function Rh(n,e,t){const r=new Vn;return{get(s,o){return r.get(s,()=>(s instanceof Dv?s:s.store).createComputedCache(n,l=>e(s,l),t)).get(o)}}}function eH(n){if(n.schemaVersion>2||n.schemaVersion<1)return zs.err("Bad schema version");if(n.schemaVersion===2)return zs.ok(n);const e={schemaVersion:2,sequences:{"com.tldraw.store":n.storeVersion}};for(const[t,r]of Object.entries(n.recordVersions))if(e.sequences[`com.tldraw.${t}`]=r.version,"subTypeKey"in r)for(const[s,o]of Object.entries(r.subTypeVersions))e.sequences[`com.tldraw.${t}.${s}`]=o;return zs.ok(e)}class Ov{constructor(e,t){E(this,"migrations",{});E(this,"sortedMigrations");E(this,"migrationCache",new WeakMap);var s;this.types=e,this.options=t;for(const o of t.migrations??[])be(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),CM(o),this.migrations[o.sequenceId]=o;const r=Object.values(this.migrations).flatMap(o=>o.sequence);this.sortedMigrations=G6(r);for(const o of this.sortedMigrations)if((s=o.dependsOn)!=null&&s.length)for(const i of o.dependsOn){const a=r.find(l=>l.id===i);be(a,`Migration '${o.id}' depends on missing migration '${i}'`)}}static create(e,t){return new Ov(e,t??{})}validateRecord(e,t,r,s){try{const o=un(this.types,t.typeName);if(!o)throw new Error(`Missing definition for record type ${t.typeName}`);return o.validate(t,s??void 0)}catch(o){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:e,record:t,phase:r,recordBefore:s,error:o});throw o}}getMigrationsSince(e){const t=this.migrationCache.get(e);if(t)return t;const r=eH(e);if(!r.ok)return this.migrationCache.set(e,r),r;const s=r.value,o=new Set(Object.keys(s.sequences).filter(l=>this.migrations[l]));for(const l in this.migrations)s.sequences[l]===void 0&&this.migrations[l].retroactive&&o.add(l);if(o.size===0){const l=zs.ok([]);return this.migrationCache.set(e,l),l}const i=new Set;for(const l of o){const c=s.sequences[l];if(typeof c!="number"&&this.migrations[l].retroactive||c===0){for(const h of this.migrations[l].sequence)i.add(h.id);continue}const u=`${l}/${c}`,d=this.migrations[l].sequence.findIndex(h=>h.id===u);if(d===-1){const h=zs.err("Incompatible schema?");return this.migrationCache.set(e,h),h}for(const h of this.migrations[l].sequence.slice(d+1))i.add(h.id)}const a=zs.ok(this.sortedMigrations.filter(({id:l})=>i.has(l)));return this.migrationCache.set(e,a),a}migratePersistedRecord(e,t,r="up"){const s=this.getMigrationsSince(t);if(!s.ok)return console.error("Error migrating record",s.error),{type:"error",reason:ca.MigrationError};let o=s.value;if(o.length===0)return{type:"success",value:e};if(!o.every(i=>i.scope==="record"))return{type:"error",reason:r==="down"?ca.TargetVersionTooOld:ca.TargetVersionTooNew};if(r==="down"){if(!o.every(i=>i.scope==="record"&&i.down))return{type:"error",reason:ca.TargetVersionTooOld};o=o.slice().reverse()}e=Ft(e);try{for(const i of o){if(i.scope==="store")throw new Error;if(i.scope==="storage")throw new Error;if(!(i.filter?i.filter(e):!0))continue;const l=i[r](e);l&&(e=Ft(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:ca.MigrationError}}return{type:"success",value:e}}migrateStorage(e){const t=e.getSchema();be(t,"Schema is missing.");const r=this.getMigrationsSince(t);if(!r.ok)throw console.error("Error migrating store",r.error),new Error(r.error);const s=r.value;if(s.length!==0){e.setSchema(this.serialize());for(const o of s)if(o.scope==="record"){const i=[];for(const[a,l]of e.entries()){if(!(o.filter?o.filter(l):!0))continue;const u=Ft(l),d=o.up(u)??u;So(d,l)||i.push([a,d])}for(const[a,l]of i)e.set(a,l)}else if(o.scope==="store"){const i=Object.fromEntries(e.entries());let a=Ft(i);a=o.up(a)??a;for(const[l,c]of Object.entries(a))c&&(So(c,i[l])||e.set(l,c));for(const l of Object.keys(i))a[l]||e.delete(l)}else o.scope==="storage"?o.up(e):it(o);for(const[o,i]of e.entries())this.getType(i.typeName).scope!=="document"&&e.delete(o)}}migrateStoreSnapshot(e,t){const r=this.getMigrationsSince(e.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:ca.MigrationError};if(r.value.length===0)return{type:"success",value:e.store};const o=Object.assign(new Map($s(e.store).map(jc)),{getSchema:()=>e.schema,setSchema:i=>{}});try{if(this.migrateStorage(o),t!=null&&t.mutateInputStore){for(const[i,a]of o.entries())e.store[i]=a;for(const i of Object.keys(e.store))o.has(i)||delete e.store[i];return{type:"success",value:e.store}}else return{type:"success",value:Object.fromEntries(o.entries())}}catch(i){return console.error("Error migrating store",i),{type:"error",reason:ca.MigrationError}}}createIntegrityChecker(e){var t,r;return((r=(t=this.options).createIntegrityChecker)==null?void 0:r.call(t,e))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e,sequence:t})=>[e,t.length?Eg(t.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e})=>[e,0]))}}getType(e){const t=un(this.types,e);return be(t,"record type does not exists"),t}}Wi("@tldraw/store","4.4.0","esm");function tH(n){if(!n.length)return null;let e="";for(const t of n)typeof t=="number"?e+=`.${t}`:t.startsWith("(")?e.endsWith(")")?e=`${e.slice(0,-1)}, ${t.slice(1)}`:e+=t:e+=`.${t}`;return e=e.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),e.startsWith(".")?e.slice(1):e}class ue extends Error{constructor(t,r=[]){const s=tH(r),o=t.split(`
50
+ `).map((i,a)=>a===0?i:` ${i}`).join(`
51
+ `);super(r?`At ${s}: ${o}`:o);E(this,"name","ValidationError");this.rawMessage=t,this.path=r}}function Fc(n,e){try{return e()}catch(t){throw t instanceof ue?new ue(t.rawMessage,[n,...t.path]):new ue(t.toString(),[n])}}function Or(n){if(n===null)return"null";if(Array.isArray(n))return"an array";const e=typeof n;switch(e){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${e}`;case"object":return`an ${e}`;case"undefined":return"undefined";default:it(e)}}class kt{constructor(e,t,r=!1){this.validationFn=e,this.validateUsingKnownGoodVersionFn=t,this.skipSameValueCheck=r}validate(e){return this.validationFn(e)}validateUsingKnownGoodVersion(e,t){return Object.is(e,t)?e:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(e,t):this.validate(t)}isValid(e){try{return this.validate(e),!0}catch{return!1}}nullable(){return lH(this)}optional(){return _M(this)}refine(e){return new kt(t=>e(this.validate(t)),(t,r)=>{const s=this.validateUsingKnownGoodVersion(t,r);return Object.is(t,s)?t:e(s)},!0)}check(e,t){return typeof e=="string"?this.refine(r=>(Fc(`(check ${e})`,()=>t(r)),r)):this.refine(r=>(e(r),r))}}class nH extends kt{constructor(e){super(t=>{const r=sT.validate(t);for(let s=0;s<r.length;s++)try{e.validate(r[s])}catch(o){throw o instanceof ue?new ue(o.rawMessage,[s,...o.path]):new ue(o.toString(),[s])}return r},(t,r)=>{if(Object.is(t,r))return t;if(!e.validateUsingKnownGoodVersion)return this.validate(r);const s=sT.validate(r);let o=t.length!==s.length;for(let i=0;i<s.length;i++){const a=s[i];if(i>=t.length){o=!0;try{e.validate(a)}catch(l){throw l instanceof ue?new ue(l.rawMessage,[i,...l.path]):new ue(l.toString(),[i])}continue}if(!Object.is(t[i],a))try{const l=e.validateUsingKnownGoodVersion(t[i],a);Object.is(l,t[i])||(o=!0)}catch(l){throw l instanceof ue?new ue(l.rawMessage,[i,...l.path]):new ue(l.toString(),[i])}}return o?r:t}),this.itemValidator=e}nonEmpty(){return this.check(e=>{if(e.length===0)throw new ue("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(e=>{if(e.length<=1)throw new ue("Expected an array with length greater than 1")})}}class _g extends kt{constructor(e,t=!1){super(r=>{if(typeof r!="object"||r===null)throw new ue(`Expected object, got ${Or(r)}`);for(const s in e){if(!gn(e,s))continue;const o=e[s];try{o.validate(un(r,s))}catch(i){throw i instanceof ue?new ue(i.rawMessage,[s,...i.path]):new ue(i.toString(),[s])}}if(!t){for(const s of Object.keys(r))if(!gn(e,s))throw new ue("Unexpected property",[s])}return r},(r,s)=>{if(Object.is(r,s))return r;if(typeof s!="object"||s===null)throw new ue(`Expected object, got ${Or(s)}`);let o=!1;for(const i in e){if(!gn(e,i))continue;const a=e[i],l=un(r,i),c=un(s,i);if(!Object.is(l,c))try{const u=a,d=u.validateUsingKnownGoodVersion?u.validateUsingKnownGoodVersion(l,c):u.validate(c);Object.is(d,l)||(o=!0)}catch(u){throw u instanceof ue?new ue(u.rawMessage,[i,...u.path]):new ue(u.toString(),[i])}}if(!t){for(const i of Object.keys(s))if(!gn(e,i))throw new ue("Unexpected property",[i])}for(const i of Object.keys(r))if(!gn(s,i)){o=!0;break}return o?s:r}),this.config=e,this.shouldAllowUnknownProperties=t}allowUnknownProperties(){return new _g(this.config,!0)}extend(e){return new _g({...this.config,...e})}}class dy extends kt{constructor(e,t,r,s){super(o=>{this.expectObject(o);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(o);return i===void 0?this.unknownValueValidation(o,a):Fc(`(${e} = ${a})`,()=>i.validate(o))},(o,i)=>{this.expectObject(i),this.expectObject(o);const{matchingSchema:a,variant:l}=this.getMatchingSchemaAndVariant(i);return a===void 0?this.unknownValueValidation(i,l):un(o,e)!==un(i,e)?Fc(`(${e} = ${l})`,()=>a.validate(i)):Fc(`(${e} = ${l})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(o,i):a.validate(i))}),this.key=e,this.config=t,this.unknownValueValidation=r,this.useNumberKeys=s}expectObject(e){if(typeof e!="object"||e===null)throw new ue(`Expected an object, got ${Or(e)}`,[])}getMatchingSchemaAndVariant(e){const t=un(e,this.key);if(!this.useNumberKeys&&typeof t!="string")throw new ue(`Expected a string for key "${this.key}", got ${Or(t)}`);if(this.useNumberKeys){const s=Number(t);if(s-s!==0)throw new ue(`Expected a number for key "${this.key}", got "${t}"`)}return{matchingSchema:gn(this.config,t)?this.config[t]:void 0,variant:t}}validateUnknownVariants(e){return new dy(this.key,this.config,e,this.useNumberKeys)}}class rH extends kt{constructor(e,t){super(r=>{if(typeof r!="object"||r===null)throw new ue(`Expected object, got ${Or(r)}`);for(const s in r)if(gn(r,s))try{e.validate(s),t.validate(r[s])}catch(o){throw o instanceof ue?new ue(o.rawMessage,[s,...o.path]):new ue(o.toString(),[s])}return r},(r,s)=>{if(typeof s!="object"||s===null)throw new ue(`Expected object, got ${Or(s)}`);const o=s;let i=!1,a=0;for(const l in o){if(!gn(o,l))continue;a++;const c=o[l];if(!gn(r,l)){i=!0;try{e.validate(l),t.validate(c)}catch(d){throw d instanceof ue?new ue(d.rawMessage,[l,...d.path]):new ue(d.toString(),[l])}continue}const u=r[l];if(!Object.is(u,c))try{const d=t.validateUsingKnownGoodVersion?t.validateUsingKnownGoodVersion(u,c):t.validate(c);Object.is(d,u)||(i=!0)}catch(d){throw d instanceof ue?new ue(d.rawMessage,[l,...d.path]):new ue(d.toString(),[l])}}if(!i){let l=0;for(const c in r)gn(r,c)&&l++;l!==a&&(i=!0)}return i?s:r}),this.keyValidator=e,this.valueValidator=t}}function EM(n){return new kt(e=>{if(typeof e!==n)throw new ue(`Expected ${n}, got ${Or(e)}`);return e})}const sH=new kt(n=>n),kM=new kt(n=>n),Ke=EM("string"),Be=new kt(n=>{if(Number.isFinite(n))return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):new ue(`Expected a finite number, got ${n}`)}),Mg=new kt(n=>{if(Number.isFinite(n)&&n>=0)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):n<0?new ue(`Expected a positive number, got ${n}`):new ue(`Expected a finite number, got ${n}`)}),en=new kt(n=>{if(Number.isFinite(n)&&n>0)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):n<=0?new ue(`Expected a non-zero positive number, got ${n}`):new ue(`Expected a finite number, got ${n}`)}),Ag=new kt(n=>{if(Number.isFinite(n)&&n!==0)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):n===0?new ue("Expected a non-zero number, got 0"):new ue(`Expected a finite number, got ${n}`)}),oH=new kt(n=>{if(Number.isFinite(n)&&n>=0&&n<=1)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):new ue(`Expected a number between 0 and 1, got ${n}`)}),Lf=new kt(n=>{if(Number.isInteger(n)&&n>=0)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):n-n!==0?new ue(`Expected a finite number, got ${n}`):n<0?new ue(`Expected a positive integer, got ${n}`):new ue(`Expected an integer, got ${n}`)}),iH=new kt(n=>{if(Number.isInteger(n)&&n>0)return n;throw typeof n!="number"?new ue(`Expected number, got ${Or(n)}`):n!==n?new ue("Expected a number, got NaN"):n-n!==0?new ue(`Expected a finite number, got ${n}`):n<=0?new ue(`Expected a non-zero positive integer, got ${n}`):new ue(`Expected an integer, got ${n}`)}),Ve=EM("boolean");function lr(n){return new kt(e=>{if(e!==n)throw new ue(`Expected ${n}, got ${JSON.stringify(e)}`);return n})}const sT=new kt(n=>{if(!Array.isArray(n))throw new ue(`Expected an array, got ${Or(n)}`);return n});function Bn(n){return new nH(n)}function tt(n){return new _g(n)}function ww(n){return typeof n=="object"&&n!==null&&(Object.getPrototypeOf(n)===Object.prototype||Object.getPrototypeOf(n)===null||Object.getPrototypeOf(n)===nM)}function vw(n){return n===null||typeof n=="number"||typeof n=="string"||typeof n=="boolean"?!0:Array.isArray(n)?n.every(vw):ww(n)?Object.values(n).every(vw):!1}const zn=new kt(n=>{if(vw(n))return n;throw new ue(`Expected json serializable value, got ${typeof n}`)},(n,e)=>{if(Array.isArray(n)&&Array.isArray(e)){let t=n.length!==e.length;for(let r=0;r<e.length;r++){if(r>=n.length){t=!0,zn.validate(e[r]);continue}const s=n[r],o=e[r];if(Object.is(s,o))continue;const i=zn.validateUsingKnownGoodVersion(s,o);Object.is(i,s)||(t=!0)}return t?e:n}else if(ww(n)&&ww(e)){let t=!1;for(const r of Object.keys(e)){if(!gn(n,r)){t=!0,zn.validate(e[r]);continue}const s=n[r],o=e[r];if(Object.is(s,o))continue;const i=zn.validateUsingKnownGoodVersion(s,o);Object.is(i,s)||(t=!0)}for(const r of Object.keys(n))if(!gn(e,r)){t=!0;break}return t?e:n}else return zn.validate(e)});function Dg(n,e){return new rH(n,e)}function Rv(n,e){return new dy(n,e,(t,r)=>{throw new ue(`Expected one of ${Object.keys(e).map(s=>JSON.stringify(s)).join(" or ")}, got ${JSON.stringify(r)}`,[n])},!1)}function aH(n,e){return new dy(n,e,(t,r)=>{throw new ue(`Expected one of ${Object.keys(e).map(s=>JSON.stringify(s)).join(" or ")}, got ${JSON.stringify(r)}`,[n])},!0)}function Zo(n,e){return new kt(t=>Fc(n,()=>e.validate(t)),(t,r)=>Fc(n,()=>e.validateUsingKnownGoodVersion?e.validateUsingKnownGoodVersion(t,r):e.validate(r)))}function uy(n){return new kt(e=>{if(!n.has(e)){const t=Array.from(n,r=>JSON.stringify(r)).join(" or ");throw new ue(`Expected ${t}, got ${e}`)}return e})}function _M(n){return new kt(e=>{if(e!==void 0)return n.validate(e)},(e,t)=>{if(t!==void 0)return n.validateUsingKnownGoodVersion&&e!==void 0?n.validateUsingKnownGoodVersion(e,t):n.validate(t)},n instanceof kt&&n.skipSameValueCheck)}function lH(n){return new kt(e=>e===null?null:n.validate(e),(e,t)=>t===null?null:n.validateUsingKnownGoodVersion&&e!==null?n.validateUsingKnownGoodVersion(e,t):n.validate(t),n instanceof kt&&n.skipSameValueCheck)}function Da(...n){return uy(new Set(n))}function Lv(n){try{return new URL(n)}catch{if(n.startsWith("/")||n.startsWith("./"))try{return new URL(n,"http://example.com")}catch{throw new ue(`Expected a valid url, got ${JSON.stringify(n)}`)}throw new ue(`Expected a valid url, got ${JSON.stringify(n)}`)}}const cH=new Set(["http:","https:","mailto:"]),bs=Ke.check(n=>{if(n==="")return;const e=Lv(n);if(!cH.has(e.protocol.toLowerCase()))throw new ue(`Expected a valid url, got ${JSON.stringify(n)} (invalid protocol)`)}),dH=new Set(["http:","https:","data:","asset:"]),_l=Ke.check(n=>{if(n==="")return;const e=Lv(n);if(!dH.has(e.protocol.toLowerCase()))throw new ue(`Expected a valid url, got ${JSON.stringify(n)} (invalid protocol)`)});Ke.check(n=>{if(n==="")return;if(!Lv(n).protocol.toLowerCase().match(/^https?:$/))throw new ue(`Expected a valid url, got ${JSON.stringify(n)} (invalid protocol)`)});const jv=Ke.refine(n=>{try{return X4(n),n}catch{throw new ue(`Expected an index key, got ${JSON.stringify(n)}`)}});Wi("@tldraw/validate","4.4.0","esm");function ys(n){return Ke.refine(e=>{if(!e.startsWith(`${n}:`))throw new Error(`${n} ID must start with "${n}:"`);return e})}const hy=ys("asset");function Nv(n,e){return tt({id:hy,typeName:lr("asset"),type:lr(n),props:e,meta:zn})}const Jc=tt({x:Be,y:Be,z:Be.optional()}),Ru=tt({x:Be,y:Be,w:Be,h:Be}),MM=oH,uH=Ke.refine(n=>{if(!n.startsWith("page:")&&!n.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return n}),Rs=ys("shape");function hH(n,e,t){return tt({id:Rs,typeName:lr("shape"),x:Be,y:Be,rotation:Be,index:jv,parentId:uH,type:lr(n),isLocked:Ve,opacity:MM,props:e?tt(e):zn,meta:t?tt(t):zn})}const pH=ys("binding");function fH(n,e,t){return tt({id:pH,typeName:lr("binding"),type:lr(n),fromId:Rs,toId:Rs,props:e?tt(e):zn,meta:t?tt(t):zn})}ns("com.tldraw.binding",{});vs({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function wl(n){return`binding:${at()}`}function gH(n,e){return Ka(e,(t,r)=>`com.tldraw.binding.${n}/${r}`)}function mH(n){return qo("binding",{scope:"document",validator:Zo("binding",Rv("type",Ka(n,(e,{props:t,meta:r})=>fH(e,t,r))))}).withDefaultProperties(()=>({meta:{}}))}const Lh=tt({type:Ke,content:Bn(sH),attrs:kM.optional()});function Kn(n){return{type:"doc",content:n.split(`
52
+ `).map(r=>r?{type:"paragraph",content:[{type:"text",text:r}]}:{type:"paragraph"})}}class Mn{constructor(e,t,r){this.id=e,this.defaultValue=t,this.type=r}static define(e,t){const{defaultValue:r,type:s=kM}=t;return new Mn(e,r,s)}static defineEnum(e,t){const{defaultValue:r,values:s}=t;return new yH(e,r,s)}setDefaultValue(e){this.defaultValue=e}validate(e){return this.type.validate(e)}validateUsingKnownGoodVersion(e,t){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(e,t):this.validate(t)}}class yH extends Mn{constructor(e,t,r){super(e,t,Da(...r)),this.values=r}}const Op=ns("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),SH=vs({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:Op.AddIsLocked,up:n=>{n.isLocked=!1},down:n=>{delete n.isLocked}},{id:Op.HoistOpacity,up:n=>{n.opacity=Number(n.props.opacity??"1"),delete n.props.opacity},down:n=>{const e=n.opacity;delete n.opacity,n.props.opacity=e<.175?"0.1":e<.375?"0.25":e<.625?"0.5":e<.875?"0.75":"1"}},{id:Op.AddMeta,up:n=>{n.meta={}}},{id:Op.AddWhite,up:n=>{},down:n=>{n.props.color==="white"&&(n.props.color="black")}}]});function Di(n){return n?n.typeName==="shape":!1}function Pr(n){return n?n.startsWith("shape:"):!1}function St(n){return`shape:${n??at()}`}function AM(n){const e=new Map;for(const[t,r]of Object.entries(n))if(r instanceof Mn){if(e.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);e.set(r,t)}return e}function Vs(n,e){return Ka(e,(t,r)=>`com.tldraw.shape.${n}/${r}`)}function xH(n){return qo("shape",{scope:"document",validator:Zo("shape",Rv("type",Ka(n,(e,{props:t,meta:r})=>hH(e,t,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function oT(n,e){const t=[];for(const[r,{migrations:s}]of Object.entries(e)){const o=`com.tldraw.${n}.${r}`;s?"sequenceId"in s?(be(o===s.sequenceId,`sequenceId mismatch for ${r} ${cy} migrations. Expected '${o}', got '${s.sequenceId}'`),t.push(s)):"sequence"in s?t.push(Nc({sequenceId:o,retroactive:!0,sequence:s.sequence.map(i=>"id"in i?DM(n,r,i):i)})):t.push(Nc({sequenceId:o,retroactive:!0,sequence:Object.keys(s.migrators).map(i=>Number(i)).sort((i,a)=>i-a).map(i=>({id:`${o}/${i}`,scope:"record",filter:a=>a.typeName===n&&a.type===r,up:a=>{const l=s.migrators[i].up(a);if(l)return l},down:a=>{const l=s.migrators[i].down(a);if(l)return l}}))})):t.push(Nc({sequenceId:o,retroactive:!0,sequence:[]}))}return t}function DM(n,e,t){return{id:t.id,dependsOn:t.dependsOn,scope:"record",filter:r=>r.typeName===n&&r.type===e,up:r=>{const s=t.up(r.props);s&&(r.props=s)},down:typeof t.down=="function"?r=>{const s=t.down(r.props);s&&(r.props=s)}:void 0}}const Fv=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Og={lightMode:{id:"light",text:"#000000",background:"#f9fafb",solid:"#fcfffe",black:{solid:"#1d1d1d",fill:"#1d1d1d",linedFill:"#363636",frameHeadingStroke:"#717171",frameHeadingFill:"#ffffff",frameStroke:"#717171",frameFill:"#ffffff",frameText:"#000000",noteFill:"#FCE19C",noteText:"#000000",semi:"#e8e8e8",pattern:"#494949",highlightSrgb:"#fddd00",highlightP3:"color(display-p3 0.972 0.8205 0.05)"},blue:{solid:"#4465e9",fill:"#4465e9",linedFill:"#6580ec",frameHeadingStroke:"#6681ec",frameHeadingFill:"#f9fafe",frameStroke:"#6681ec",frameFill:"#f9fafe",frameText:"#000000",noteFill:"#8AA3FF",noteText:"#000000",semi:"#dce1f8",pattern:"#6681ee",highlightSrgb:"#10acff",highlightP3:"color(display-p3 0.308 0.6632 0.9996)"},green:{solid:"#099268",fill:"#099268",linedFill:"#0bad7c",frameHeadingStroke:"#37a684",frameHeadingFill:"#f8fcfa",frameStroke:"#37a684",frameFill:"#f8fcfa",frameText:"#000000",noteFill:"#6FC896",noteText:"#000000",semi:"#d3e9e3",pattern:"#39a785",highlightSrgb:"#00ffc8",highlightP3:"color(display-p3 0.2536 0.984 0.7981)"},grey:{solid:"#9fa8b2",fill:"#9fa8b2",linedFill:"#bbc1c9",frameHeadingStroke:"#aaaaab",frameHeadingFill:"#fbfcfc",frameStroke:"#aaaaab",frameFill:"#fcfcfd",frameText:"#000000",noteFill:"#C0CAD3",noteText:"#000000",semi:"#eceef0",pattern:"#bcc3c9",highlightSrgb:"#cbe7f1",highlightP3:"color(display-p3 0.8163 0.9023 0.9416)"},"light-blue":{solid:"#4ba1f1",fill:"#4ba1f1",linedFill:"#7abaf5",frameHeadingStroke:"#6cb2f3",frameHeadingFill:"#f8fbfe",frameStroke:"#6cb2f3",frameFill:"#fafcff",frameText:"#000000",noteFill:"#9BC4FD",noteText:"#000000",semi:"#ddedfa",pattern:"#6fbbf8",highlightSrgb:"#00f4ff",highlightP3:"color(display-p3 0.1512 0.9414 0.9996)"},"light-green":{solid:"#4cb05e",fill:"#4cb05e",linedFill:"#7ec88c",frameHeadingStroke:"#6dbe7c",frameHeadingFill:"#f8fcf9",frameStroke:"#6dbe7c",frameFill:"#fafdfa",frameText:"#000000",noteFill:"#98D08A",noteText:"#000000",semi:"#dbf0e0",pattern:"#65cb78",highlightSrgb:"#65f641",highlightP3:"color(display-p3 0.563 0.9495 0.3857)"},"light-red":{solid:"#f87777",fill:"#f87777",linedFill:"#f99a9a",frameHeadingStroke:"#f89090",frameHeadingFill:"#fffafa",frameStroke:"#f89090",frameFill:"#fffbfb",frameText:"#000000",noteFill:"#F7A5A1",noteText:"#000000",semi:"#f4dadb",pattern:"#fe9e9e",highlightSrgb:"#ff7fa3",highlightP3:"color(display-p3 0.9988 0.5301 0.6397)"},"light-violet":{solid:"#e085f4",fill:"#e085f4",linedFill:"#e9abf7",frameHeadingStroke:"#e59bf5",frameHeadingFill:"#fefaff",frameStroke:"#e59bf5",frameFill:"#fefbff",frameText:"#000000",noteFill:"#DFB0F9",noteText:"#000000",semi:"#f5eafa",pattern:"#e9acf8",highlightSrgb:"#ff88ff",highlightP3:"color(display-p3 0.9676 0.5652 0.9999)"},orange:{solid:"#e16919",fill:"#e16919",linedFill:"#ea8643",frameHeadingStroke:"#e68544",frameHeadingFill:"#fef9f6",frameStroke:"#e68544",frameFill:"#fef9f6",frameText:"#000000",noteFill:"#FAA475",noteText:"#000000",semi:"#f8e2d4",pattern:"#f78438",highlightSrgb:"#ffa500",highlightP3:"color(display-p3 0.9988 0.6905 0.266)"},red:{solid:"#e03131",fill:"#e03131",linedFill:"#e75f5f",frameHeadingStroke:"#e55757",frameHeadingFill:"#fef7f7",frameStroke:"#e55757",frameFill:"#fef9f9",frameText:"#000000",noteFill:"#FC8282",noteText:"#000000",semi:"#f4dadb",pattern:"#e55959",highlightSrgb:"#ff636e",highlightP3:"color(display-p3 0.9992 0.4376 0.45)"},violet:{solid:"#ae3ec9",fill:"#ae3ec9",linedFill:"#be68d4",frameHeadingStroke:"#bc62d3",frameHeadingFill:"#fcf7fd",frameStroke:"#bc62d3",frameFill:"#fdf9fd",frameText:"#000000",noteFill:"#DB91FD",noteText:"#000000",semi:"#ecdcf2",pattern:"#bd63d3",highlightSrgb:"#c77cff",highlightP3:"color(display-p3 0.7469 0.5089 0.9995)"},yellow:{solid:"#f1ac4b",fill:"#f1ac4b",linedFill:"#f5c27a",frameHeadingStroke:"#f3bb6c",frameHeadingFill:"#fefcf8",frameStroke:"#f3bb6c",frameFill:"#fffdfa",frameText:"#000000",noteFill:"#FED49A",noteText:"#000000",semi:"#f9f0e6",pattern:"#fecb92",highlightSrgb:"#fddd00",highlightP3:"color(display-p3 0.972 0.8705 0.05)"},white:{solid:"#FFFFFF",fill:"#FFFFFF",linedFill:"#ffffff",semi:"#f5f5f5",pattern:"#f9f9f9",frameHeadingStroke:"#7d7d7d",frameHeadingFill:"#ffffff",frameStroke:"#7d7d7d",frameFill:"#ffffff",frameText:"#000000",noteFill:"#FFFFFF",noteText:"#000000",highlightSrgb:"#ffffff",highlightP3:"color(display-p3 1 1 1)"}},darkMode:{id:"dark",text:"hsl(210, 17%, 98%)",background:"hsl(240, 5%, 6.5%)",solid:"#010403",black:{solid:"#f2f2f2",fill:"#f2f2f2",linedFill:"#ffffff",frameHeadingStroke:"#5c5c5c",frameHeadingFill:"#252525",frameStroke:"#5c5c5c",frameFill:"#0c0c0c",frameText:"#f2f2f2",noteFill:"#2c2c2c",noteText:"#f2f2f2",semi:"#2c3036",pattern:"#989898",highlightSrgb:"#d2b700",highlightP3:"color(display-p3 0.8078 0.6225 0.0312)"},blue:{solid:"#4f72fc",fill:"#4f72fc",linedFill:"#3c5cdd",frameHeadingStroke:"#384994",frameHeadingFill:"#1C2036",frameStroke:"#384994",frameFill:"#11141f",frameText:"#f2f2f2",noteFill:"#2A3F98",noteText:"#f2f2f2",semi:"#262d40",pattern:"#3a4b9e",highlightSrgb:"#0079d2",highlightP3:"color(display-p3 0.0032 0.4655 0.7991)"},green:{solid:"#099268",fill:"#099268",linedFill:"#087856",frameHeadingStroke:"#10513C",frameHeadingFill:"#14241f",frameStroke:"#10513C",frameFill:"#0E1614",frameText:"#f2f2f2",noteFill:"#014429",noteText:"#f2f2f2",semi:"#253231",pattern:"#366a53",highlightSrgb:"#009774",highlightP3:"color(display-p3 0.0085 0.582 0.4604)"},grey:{solid:"#9398b0",fill:"#9398b0",linedFill:"#8388a5",frameHeadingStroke:"#42474D",frameHeadingFill:"#23262A",frameStroke:"#42474D",frameFill:"#151719",frameText:"#f2f2f2",noteFill:"#56595F",noteText:"#f2f2f2",semi:"#33373c",pattern:"#7c8187",highlightSrgb:"#9cb4cb",highlightP3:"color(display-p3 0.6299 0.7012 0.7856)"},"light-blue":{solid:"#4dabf7",fill:"#4dabf7",linedFill:"#2793ec",frameHeadingStroke:"#075797",frameHeadingFill:"#142839",frameStroke:"#075797",frameFill:"#0B1823",frameText:"#f2f2f2",noteFill:"#1F5495",noteText:"#f2f2f2",semi:"#2a3642",pattern:"#4d7aa9",highlightSrgb:"#00bdc8",highlightP3:"color(display-p3 0.0023 0.7259 0.7735)"},"light-green":{solid:"#40c057",fill:"#40c057",linedFill:"#37a44b",frameHeadingStroke:"#1C5427",frameHeadingFill:"#18251A",frameStroke:"#1C5427",frameFill:"#0F1911",frameText:"#f2f2f2",noteFill:"#21581D",noteText:"#f2f2f2",semi:"#2a3830",pattern:"#4e874e",highlightSrgb:"#00a000",highlightP3:"color(display-p3 0.2711 0.6172 0.0195)"},"light-red":{solid:"#ff8787",fill:"#ff8787",linedFill:"#ff6666",frameHeadingStroke:"#6f3232",frameHeadingFill:"#341818",frameStroke:"#6f3232",frameFill:"#181212",frameText:"#f2f2f2",noteFill:"#7a3333",noteText:"#f2f2f2",semi:"#3c2b2b",pattern:"#a56767",highlightSrgb:"#db005b",highlightP3:"color(display-p3 0.7849 0.0585 0.3589)"},"light-violet":{solid:"#e599f7",fill:"#e599f7",linedFill:"#dc71f4",frameHeadingStroke:"#6c367a",frameHeadingFill:"#2D2230",frameStroke:"#6c367a",frameFill:"#1C151E",frameText:"#f2f2f2",noteFill:"#762F8E",noteText:"#f2f2f2",semi:"#383442",pattern:"#9770a9",highlightSrgb:"#c400c7",highlightP3:"color(display-p3 0.7024 0.0403 0.753)"},orange:{solid:"#f76707",fill:"#f76707",linedFill:"#f54900",frameHeadingStroke:"#773a0e",frameHeadingFill:"#2f1d13",frameStroke:"#773a0e",frameFill:"#1c1512",frameText:"#f2f2f2",noteFill:"#7c3905",noteText:"#f2f2f2",semi:"#3b2e27",pattern:"#9f552d",highlightSrgb:"#d07a00",highlightP3:"color(display-p3 0.7699 0.4937 0.0085)"},red:{solid:"#e03131",fill:"#e03131",linedFill:"#c31d1d",frameHeadingStroke:"#701e1e",frameHeadingFill:"#301616",frameStroke:"#701e1e",frameFill:"#1b1313",frameText:"#f2f2f2",noteFill:"#7e201f",noteText:"#f2f2f2",semi:"#382726",pattern:"#8f3734",highlightSrgb:"#de002c",highlightP3:"color(display-p3 0.7978 0.0509 0.2035)"},violet:{solid:"#ae3ec9",fill:"#ae3ec9",linedFill:"#8f2fa7",frameHeadingStroke:"#6d1583",frameHeadingFill:"#27152e",frameStroke:"#6d1583",frameFill:"#1b0f21",frameText:"#f2f2f2",noteFill:"#5f1c70",noteText:"#f2f2f2",semi:"#342938",pattern:"#763a8b",highlightSrgb:"#9e00ee",highlightP3:"color(display-p3 0.5651 0.0079 0.8986)"},yellow:{solid:"#ffc034",fill:"#ffc034",linedFill:"#ffae00",frameHeadingStroke:"#684e12",frameHeadingFill:"#2a2113",frameStroke:"#684e12",frameFill:"#1e1911",frameText:"#f2f2f2",noteFill:"#8a5e1c",noteText:"#f2f2f2",semi:"#3b352b",pattern:"#fecb92",highlightSrgb:"#d2b700",highlightP3:"color(display-p3 0.8078 0.7225 0.0312)"},white:{solid:"#f3f3f3",fill:"#f3f3f3",linedFill:"#f3f3f3",semi:"#f5f5f5",pattern:"#f9f9f9",frameHeadingStroke:"#ffffff",frameHeadingFill:"#ffffff",frameStroke:"#ffffff",frameFill:"#ffffff",frameText:"#000000",noteFill:"#eaeaea",noteText:"#1d1d1d",highlightSrgb:"#ffffff",highlightP3:"color(display-p3 1 1 1)"}}};function Ga(n){return n.isDarkMode?Og.darkMode:Og.lightMode}const Rr=Mn.defineEnum("tldraw:color",{defaultValue:"black",values:Fv}),Bv=Mn.defineEnum("tldraw:labelColor",{defaultValue:"black",values:Fv}),bH=new Set(Fv);function wH(n){return bH.has(n)}function st(n,e,t){return wH(e)?n[e][t]:e}const Ml=Mn.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),Li=Mn.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill","lined-fill"]}),Oa=Mn.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),vH={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},Vo=Mn.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),CH=["arc","elbow"],Rg=Mn.defineEnum("tldraw:arrowKind",{defaultValue:"arc",values:CH}),OM=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],Cw=Mn.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:OM}),Pw=Mn.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:OM}),RM={kind:Rg,labelColor:Bv,color:Rr,fill:Li,dash:Ml,size:Vo,arrowheadStart:Cw,arrowheadEnd:Pw,font:Oa,start:Jc,end:Jc,bend:Be,richText:Lh,labelPosition:Be,scale:en,elbowMidPoint:Be},Ti=Vs("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5,AddElbow:6,AddRichText:7,AddRichTextAttrs:8});function cl(n){return DM("shape","arrow",n)}const LM=Nc({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[cl({id:Ti.AddLabelColor,up:n=>{n.labelColor="black"},down:"retired"}),cl({id:Ti.AddIsPrecise,up:({start:n,end:e})=>{n.type==="binding"&&(n.isPrecise=!(n.normalizedAnchor.x===.5&&n.normalizedAnchor.y===.5)),e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5))},down:({start:n,end:e})=>{n.type==="binding"&&(n.isPrecise||(n.normalizedAnchor={x:.5,y:.5}),delete n.isPrecise),e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise)}}),cl({id:Ti.AddLabelPosition,up:n=>{n.labelPosition=.5},down:n=>{delete n.labelPosition}}),{id:Ti.ExtractBindings,scope:"storage",up:n=>{const e=[];for(const t of n.values()){if(t.typeName!=="shape"||t.type!=="arrow")continue;const r=t,s=Ft(r),{start:o,end:i}=r.props;if(o.type==="binding"){const a=wl(),l={typeName:"binding",id:a,type:"arrow",fromId:r.id,toId:o.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:o.normalizedAnchor,isExact:o.isExact,isPrecise:o.isPrecise}};e.push([a,l]),s.props.start={x:0,y:0}}else delete s.props.start.type;if(i.type==="binding"){const a=wl(),l={typeName:"binding",id:a,type:"arrow",fromId:r.id,toId:i.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:i.normalizedAnchor,isExact:i.isExact,isPrecise:i.isPrecise}};e.push([a,l]),s.props.end={x:0,y:0}}else delete s.props.end.type;e.push([r.id,s])}for(const[t,r]of e)n.set(t,r)}},cl({id:Ti.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}}),cl({id:Ti.AddElbow,up:n=>{n.kind="arc",n.elbowMidPoint=.5},down:n=>{delete n.kind,delete n.elbowMidPoint}}),cl({id:Ti.AddRichText,up:n=>{n.richText=Kn(n.text),delete n.text}}),cl({id:Ti.AddRichTextAttrs,up:n=>{},down:n=>{n.richText&&"attrs"in n.richText&&delete n.richText.attrs}})]}),PH=Da("center","edge-point","edge","none"),jM={terminal:Da("start","end"),normalizedAnchor:Jc,isExact:Ve,isPrecise:Ve,snap:PH},TH=gH("arrow",{AddSnap:1}),NM={sequence:[{dependsOn:[Ti.ExtractBindings]},{id:TH.AddSnap,up:n=>{n.snap="none"},down:n=>{delete n.snap}}]},IH=Zo("camera",tt({typeName:lr("camera"),id:ys("camera"),x:Be,y:Be,z:Be,meta:zn})),EH=ns("com.tldraw.camera",{AddMeta:1}),kH=vs({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:EH.AddMeta,up:n=>{n.meta={}}}]}),zo=qo("camera",{validator:IH,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),_H=new Set(["none","default","pointer","cross","grab","rotate","grabbing","resize-edge","resize-corner","text","move","ew-resize","ns-resize","nesw-resize","nwse-resize","nesw-rotate","nwse-rotate","swne-rotate","senw-rotate","zoom-in","zoom-out"]),FM=uy(_H),MH=tt({type:FM,rotation:Be}),AH=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),DH=uy(AH),OH=new Set(["starting","paused","active","complete","stopping"]),BM=tt({id:Ke,points:Bn(Jc),size:Mg,color:DH,opacity:Be,state:uy(OH),delay:Be,shrink:Be,taper:Ve}),sh=ys("page"),RH=Zo("page",tt({typeName:lr("page"),id:sh,name:Ke,index:jv,meta:zn})),LH=ns("com.tldraw.page",{AddMeta:1}),jH=vs({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:LH.AddMeta,up:n=>{n.meta={}}}]}),Ar=qo("page",{validator:RH,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function On(n){return Ar.isId(n)}const NH={id:!1,typeName:!1,currentPageId:!1,opacityForNextShape:!1,stylesForNextShape:!1,followingUserId:!1,highlightedUserIds:!1,brush:!1,cursor:!1,scribbles:!1,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!1,chatMessage:!1,isChatting:!1,isPenMode:!1,isGridMode:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!1,openMenus:!1,isChangingStyle:!1,isReadonly:!0,meta:!1,duplicateProps:!1,cameraState:!1};function zM(n){return n?Du(n,e=>NH[e]):null}ys("instance");function FH(n){const e={};for(const[r,s]of n)e[r]=_M(s);const t=Zo("instance",tt({typeName:lr("instance"),id:ys("instance"),currentPageId:sh,followingUserId:Ke.nullable(),brush:Ru.nullable(),opacityForNextShape:MM,stylesForNextShape:tt(e),cursor:MH,scribbles:Bn(BM),isFocusMode:Ve,isDebugMode:Ve,isToolLocked:Ve,exportBackground:Ve,screenBounds:Ru,insets:Bn(Ve),zoomBrush:Ru.nullable(),isPenMode:Ve,isGridMode:Ve,chatMessage:Ke,isChatting:Ve,highlightedUserIds:Bn(Ke),isFocused:Ve,devicePixelRatio:Be,isCoarsePointer:Ve,isHoveringCanvas:Ve.nullable(),openMenus:Bn(Ke),isChangingStyle:Ve,isReadonly:Ve,meta:zn,duplicateProps:tt({shapeIds:Bn(ys("shape")),offset:tt({x:Be,y:Be})}).nullable(),cameraState:Da("idle","moving")}));return qo("instance",{validator:t,scope:"session",ephemeralKeys:{currentPageId:!1,meta:!1,followingUserId:!0,opacityForNextShape:!0,stylesForNextShape:!0,brush:!0,cursor:!0,scribbles:!0,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!0,isPenMode:!0,isGridMode:!0,chatMessage:!0,isChatting:!0,highlightedUserIds:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!0,openMenus:!0,isChangingStyle:!0,isReadonly:!0,duplicateProps:!0,cameraState:!0}}).withDefaultProperties(()=>({followingUserId:null,opacityForNextShape:1,stylesForNextShape:{},brush:null,scribbles:[],cursor:{type:"default",rotation:0},isFocusMode:!1,exportBackground:!1,isDebugMode:!1,isToolLocked:!1,screenBounds:{x:0,y:0,w:1080,h:720},insets:[!1,!1,!1,!1],zoomBrush:null,isGridMode:!1,isPenMode:!1,chatMessage:"",isChatting:!1,highlightedUserIds:[],isFocused:!1,devicePixelRatio:typeof window>"u"?1:window.devicePixelRatio,isCoarsePointer:!1,isHoveringCanvas:null,openMenus:[],isChangingStyle:!1,isReadonly:!1,meta:{},duplicateProps:null,cameraState:"idle"}))}const Pt=ns("com.tldraw.instance",{AddTransparentExportBgs:1,RemoveDialog:2,AddToolLockMode:3,RemoveExtraPropsForNextShape:4,AddLabelColor:5,AddFollowingUserId:6,RemoveAlignJustify:7,AddZoom:8,AddVerticalAlign:9,AddScribbleDelay:10,RemoveUserId:11,AddIsPenModeAndIsGridMode:12,HoistOpacity:13,AddChat:14,AddHighlightedUserIds:15,ReplacePropsForNextShapeWithStylesForNextShape:16,AddMeta:17,RemoveCursorColor:18,AddLonelyProperties:19,ReadOnlyReadonly:20,AddHoveringCanvas:21,AddScribbles:22,AddInset:23,AddDuplicateProps:24,RemoveCanMoveCamera:25,AddCameraState:26}),BH=vs({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:Pt.AddTransparentExportBgs,up:n=>({...n,exportBackground:!0})},{id:Pt.RemoveDialog,up:({dialog:n,...e})=>e},{id:Pt.AddToolLockMode,up:n=>({...n,isToolLocked:!1})},{id:Pt.RemoveExtraPropsForNextShape,up:({propsForNextShape:n,...e})=>({...e,propsForNextShape:Object.fromEntries(Object.entries(n).filter(([t])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(t)))})},{id:Pt.AddLabelColor,up:({propsForNextShape:n,...e})=>({...e,propsForNextShape:{...n,labelColor:"black"}})},{id:Pt.AddFollowingUserId,up:n=>({...n,followingUserId:null})},{id:Pt.RemoveAlignJustify,up:n=>{let e=n.propsForNextShape.align;return e==="justify"&&(e="start"),{...n,propsForNextShape:{...n.propsForNextShape,align:e}}}},{id:Pt.AddZoom,up:n=>({...n,zoomBrush:null})},{id:Pt.AddVerticalAlign,up:n=>({...n,propsForNextShape:{...n.propsForNextShape,verticalAlign:"middle"}})},{id:Pt.AddScribbleDelay,up:n=>n.scribble!==null?{...n,scribble:{...n.scribble,delay:0}}:{...n}},{id:Pt.RemoveUserId,up:({userId:n,...e})=>e},{id:Pt.AddIsPenModeAndIsGridMode,up:n=>({...n,isPenMode:!1,isGridMode:!1})},{id:Pt.HoistOpacity,up:({propsForNextShape:{opacity:n,...e},...t})=>({...t,opacityForNextShape:Number(n??"1"),propsForNextShape:e})},{id:Pt.AddChat,up:n=>({...n,chatMessage:"",isChatting:!1})},{id:Pt.AddHighlightedUserIds,up:n=>({...n,highlightedUserIds:[]})},{id:Pt.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:n,...e})=>({...e,stylesForNextShape:{}})},{id:Pt.AddMeta,up:n=>({...n,meta:{}})},{id:Pt.RemoveCursorColor,up:n=>{const{color:e,...t}=n.cursor;return{...n,cursor:t}}},{id:Pt.AddLonelyProperties,up:n=>({...n,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:Pt.ReadOnlyReadonly,up:({isReadOnly:n,...e})=>({...e,isReadonly:n})},{id:Pt.AddHoveringCanvas,up:n=>({...n,isHoveringCanvas:null})},{id:Pt.AddScribbles,up:({scribble:n,...e})=>({...e,scribbles:[]})},{id:Pt.AddInset,up:n=>({...n,insets:[!1,!1,!1,!1]}),down:({insets:n,...e})=>({...e})},{id:Pt.AddDuplicateProps,up:n=>({...n,duplicateProps:null}),down:({duplicateProps:n,...e})=>({...e})},{id:Pt.RemoveCanMoveCamera,up:({canMoveCamera:n,...e})=>({...e}),down:n=>({...n,canMoveCamera:!0})},{id:Pt.AddCameraState,up:n=>({...n,cameraState:"idle"}),down:({cameraState:n,...e})=>e}]}),Er="instance:instance",zH=Zo("instance_page_state",tt({typeName:lr("instance_page_state"),id:ys("instance_page_state"),pageId:sh,selectedShapeIds:Bn(Rs),hintingShapeIds:Bn(Rs),erasingShapeIds:Bn(Rs),hoveredShapeId:Rs.nullable(),editingShapeId:Rs.nullable(),croppingShapeId:Rs.nullable(),focusedGroupId:Rs.nullable(),meta:zn})),Od=ns("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),$H=vs({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:Od.AddCroppingId,up(n){n.croppingShapeId=null}},{id:Od.RemoveInstanceIdAndCameraId,up(n){delete n.instanceId,delete n.cameraId}},{id:Od.AddMeta,up:n=>{n.meta={}}},{id:Od.RenameProperties,up:n=>{},down:n=>{}},{id:Od.RenamePropertiesAgain,up:n=>{n.selectedShapeIds=n.selectedIds,delete n.selectedIds,n.hintingShapeIds=n.hintingIds,delete n.hintingIds,n.erasingShapeIds=n.erasingIds,delete n.erasingIds,n.hoveredShapeId=n.hoveredId,delete n.hoveredId,n.editingShapeId=n.editingId,delete n.editingId,n.croppingShapeId=n.croppingShapeId??n.croppingId??null,delete n.croppingId,n.focusedGroupId=n.focusLayerId,delete n.focusLayerId},down:n=>{n.selectedIds=n.selectedShapeIds,delete n.selectedShapeIds,n.hintingIds=n.hintingShapeIds,delete n.hintingShapeIds,n.erasingIds=n.erasingShapeIds,delete n.erasingShapeIds,n.hoveredId=n.hoveredShapeId,delete n.hoveredShapeId,n.editingId=n.editingShapeId,delete n.editingShapeId,n.croppingId=n.croppingShapeId,delete n.croppingShapeId,n.focusLayerId=n.focusedGroupId,delete n.focusedGroupId}}]}),uo=qo("instance_page_state",{validator:zH,scope:"session",ephemeralKeys:{pageId:!1,selectedShapeIds:!1,editingShapeId:!1,croppingShapeId:!1,meta:!1,hintingShapeIds:!0,erasingShapeIds:!0,hoveredShapeId:!0,focusedGroupId:!0}}).withDefaultProperties(()=>({editingShapeId:null,croppingShapeId:null,selectedShapeIds:[],hoveredShapeId:null,erasingShapeIds:[],hintingShapeIds:[],focusedGroupId:null,meta:{}})),HH=Zo("pointer",tt({typeName:lr("pointer"),id:ys("pointer"),x:Be,y:Be,lastActivityTimestamp:Be,meta:zn})),UH=ns("com.tldraw.pointer",{AddMeta:1}),KH=vs({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:UH.AddMeta,up:n=>{n.meta={}}}]}),zv=qo("pointer",{validator:HH,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),Lg=zv.createId("pointer"),WH=Zo("instance_presence",tt({typeName:lr("instance_presence"),id:ys("instance_presence"),userId:Ke,userName:Ke,lastActivityTimestamp:Be.nullable(),followingUserId:Ke.nullable(),cursor:tt({x:Be,y:Be,type:FM,rotation:Be}).nullable(),color:Ke,camera:tt({x:Be,y:Be,z:Be}).nullable(),screenBounds:Ru.nullable(),selectedShapeIds:Bn(ys("shape")),currentPageId:ys("page"),brush:Ru.nullable(),scribbles:Bn(BM),chatMessage:Ke,meta:zn})),rc=ns("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),VH=vs({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:rc.AddScribbleDelay,up:n=>{n.scribble!==null&&(n.scribble.delay=0)}},{id:rc.RemoveInstanceId,up:n=>{delete n.instanceId}},{id:rc.AddChatMessage,up:n=>{n.chatMessage=""}},{id:rc.AddMeta,up:n=>{n.meta={}}},{id:rc.RenameSelectedShapeIds,up:n=>{}},{id:rc.NullableCameraCursor,up:n=>{},down:n=>{n.camera===null&&(n.camera={x:0,y:0,z:1}),n.lastActivityTimestamp===null&&(n.lastActivityTimestamp=0),n.cursor===null&&(n.cursor={type:"default",x:0,y:0,rotation:0}),n.screenBounds===null&&(n.screenBounds={x:0,y:0,w:1,h:1})}}]}),GH=qo("instance_presence",{validator:WH,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}})),YH=Zo("document",tt({typeName:lr("document"),id:lr("document:document"),gridSize:Be,name:Ke,meta:zn})),iT=ns("com.tldraw.document",{AddName:1,AddMeta:2}),XH=vs({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:iT.AddName,up:n=>{n.name=""},down:n=>{delete n.name}},{id:iT.AddMeta,up:n=>{n.meta={}}}]}),$v=qo("document",{validator:YH,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),Tw=$v.createId("document");function aT(n){n.typeName==="asset"&&("src"in n&&(n.src="<redacted>"),"src"in n.props&&(n.props.src="<redacted>"))}function qH({error:n,phase:e,record:t,recordBefore:r}){throw pv(n,{tags:{origin:"store.validateRecord",storePhase:e,isExistingValidationIssue:e==="initialize"},extras:{recordBefore:r?aT(Ft(r)):void 0,recordAfter:aT(Ft(t))}}),n}function ZH(){return[Ar.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function JH(n){const e=n.query.ids("page"),t=n.query.records("instance_page_state"),r=()=>{if(!n.has(Tw))return n.put([$v.create({id:Tw,name:n.props.defaultName})]),r();if(!n.has(Lg))return n.put([zv.create({id:Lg})]),r();const s=e.get();if(s.size===0)return n.put(ZH()),r();const o=()=>[...s].map(u=>n.get(u)).sort(Tn)[0].id,i=n.get(Er);if(i){if(!s.has(i.currentPageId))return n.put([{...i,currentPageId:o()}]),r()}else return n.put([n.schema.types.instance.create({id:Er,currentPageId:o(),exportBackground:!0})]),r();const a=new Set,l=new Set;for(const u of s){const d=uo.createId(u);n.get(d)||a.add(d);const f=zo.createId(u);n.has(f)||l.add(f)}a.size>0&&n.put([...a].map(u=>uo.create({id:u,pageId:uo.parseId(u)}))),l.size>0&&n.put([...l].map(u=>zo.create({id:u})));const c=t.get();for(const u of c){if(!s.has(u.pageId)){n.remove([u.id]);continue}if(u.croppingShapeId&&!n.has(u.croppingShapeId))return n.put([{...u,croppingShapeId:null}]),r();if(u.focusedGroupId&&!n.has(u.focusedGroupId))return n.put([{...u,focusedGroupId:null}]),r();if(u.hoveredShapeId&&!n.has(u.hoveredShapeId))return n.put([{...u,hoveredShapeId:null}]),r();const d=u.selectedShapeIds.filter(g=>n.has(g));if(d.length!==u.selectedShapeIds.length)return n.put([{...u,selectedShapeIds:d}]),r();const h=u.hintingShapeIds.filter(g=>n.has(g));if(h.length!==u.hintingShapeIds.length)return n.put([{...u,hintingShapeIds:h}]),r();const f=u.erasingShapeIds.filter(g=>n.has(g));if(f.length!==u.erasingShapeIds.length)return n.put([{...u,erasingShapeIds:f}]),r()}};return r}const QH=Nv("bookmark",tt({title:Ke,description:Ke,image:Ke,favicon:Ke,src:_l.nullable()})),lT=ns("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),eU=vs({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:n=>n.type==="bookmark",sequence:[{id:lT.MakeUrlsValid,up:n=>{_l.isValid(n.props.src)||(n.props.src="")},down:n=>{}},{id:lT.AddFavicon,up:n=>{_l.isValid(n.props.favicon)||(n.props.favicon="")},down:n=>{delete n.props.favicon}}]}),tU=Nv("image",tt({w:Be,h:Be,name:Ke,isAnimated:Ve,mimeType:Ke.nullable(),src:_l.nullable(),fileSize:en.optional()})),Rd=ns("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),nU=vs({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:n=>n.type==="image",sequence:[{id:Rd.AddIsAnimated,up:n=>{n.props.isAnimated=!1},down:n=>{delete n.props.isAnimated}},{id:Rd.RenameWidthHeight,up:n=>{n.props.w=n.props.width,n.props.h=n.props.height,delete n.props.width,delete n.props.height},down:n=>{n.props.width=n.props.w,n.props.height=n.props.h,delete n.props.w,delete n.props.h}},{id:Rd.MakeUrlsValid,up:n=>{_l.isValid(n.props.src)||(n.props.src="")},down:n=>{}},{id:Rd.AddFileSize,up:n=>{n.props.fileSize=-1},down:n=>{delete n.props.fileSize}},{id:Rd.MakeFileSizeOptional,up:n=>{n.props.fileSize===-1&&(n.props.fileSize=void 0)},down:n=>{n.props.fileSize===void 0&&(n.props.fileSize=-1)}}]}),rU=Nv("video",tt({w:Be,h:Be,name:Ke,isAnimated:Ve,mimeType:Ke.nullable(),src:_l.nullable(),fileSize:Be.optional()})),Ld=ns("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),sU=vs({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:n=>n.type==="video",sequence:[{id:Ld.AddIsAnimated,up:n=>{n.props.isAnimated=!1},down:n=>{delete n.props.isAnimated}},{id:Ld.RenameWidthHeight,up:n=>{n.props.w=n.props.width,n.props.h=n.props.height,delete n.props.width,delete n.props.height},down:n=>{n.props.width=n.props.w,n.props.height=n.props.h,delete n.props.w,delete n.props.h}},{id:Ld.MakeUrlsValid,up:n=>{_l.isValid(n.props.src)||(n.props.src="")},down:n=>{}},{id:Ld.AddFileSize,up:n=>{n.props.fileSize=-1},down:n=>{delete n.props.fileSize}},{id:Ld.MakeFileSizeOptional,up:n=>{n.props.fileSize===-1&&(n.props.fileSize=void 0)},down:n=>{n.props.fileSize===void 0&&(n.props.fileSize=-1)}}]}),oU=Zo("asset",Rv("type",{image:tU,video:rU,bookmark:QH})),iU=ns("com.tldraw.asset",{AddMeta:1}),aU=vs({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:iU.AddMeta,up:n=>{n.meta={}}}]}),Gl=qo("asset",{validator:oU,scope:"document"}).withDefaultProperties(()=>({meta:{}})),$M={w:en,h:en,assetId:hy.nullable(),url:bs},cT=Vs("bookmark",{NullAssetId:1,MakeUrlsValid:2}),HM={sequence:[{id:cT.NullAssetId,up:n=>{n.assetId===void 0&&(n.assetId=null)},down:"retired"},{id:cT.MakeUrlsValid,up:n=>{bs.isValid(n.url)||(n.url="")},down:n=>{}}]},Px=16,iu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",au=new Uint8Array(128);for(let n=0;n<64;n++)au[iu.charCodeAt(n)]=n;const UM=new Float64Array(31);for(let n=0;n<31;n++)UM[n]=Math.pow(2,n-15);const dT=Math.pow(2,-14)/1024,KM=new Float64Array(1024);for(let n=0;n<1024;n++)KM[n]=1+n/1024;function lU(n,e){return n.getFloat16(e,!0)}function cU(n,e){return mU(n.getUint16(e,!0))}const Si=typeof DataView.prototype.getFloat16=="function"?lU:cU;function dU(n,e,t){n.setFloat16(e,t,!0)}function uU(n,e,t){n.setUint16(e,yU(t),!0)}const xi=typeof DataView.prototype.setFloat16=="function"?dU:uU;function hU(n){return Uint8Array.fromBase64(n)}function pU(n){const e=Math.floor(n.length*3/4),t=new Uint8Array(e);let r=0;for(let s=0;s<n.length;s+=4){const o=au[n.charCodeAt(s)],i=au[n.charCodeAt(s+1)],a=au[n.charCodeAt(s+2)],l=au[n.charCodeAt(s+3)],c=o<<18|i<<12|a<<6|l;t[r++]=c>>16&255,t[r++]=c>>8&255,t[r++]=c&255}return t}function fU(n){return n.toBase64()}function gU(n){be(n.length%3===0,"Uint8Array length must be a multiple of 3");let e="";for(let t=0;t<n.length;t+=3){const r=n[t],s=n[t+1],o=n[t+2],i=r<<16|s<<8|o;e+=iu[i>>18&63]+iu[i>>12&63]+iu[i>>6&63]+iu[i&63]}return e}const Tx=typeof Uint8Array.prototype.toBase64=="function"?fU:gU,Rp=typeof Uint8Array.fromBase64=="function"?hU:pU;function mU(n){const e=n>>15,t=n>>10&31,r=n&1023;if(t===0)return e?-r*dT:r*dT;if(t===31)return r?NaN:e?-1/0:1/0;const s=UM[t]*KM[r];return e?-s:s}function yU(n){if(n===0)return Object.is(n,-0)?32768:0;if(!Number.isFinite(n))return Number.isNaN(n)?32256:n>0?31744:64512;const e=n<0?1:0;n=Math.abs(n);const t=Math.floor(Math.log2(n));let r=t+15;if(r>=31)return e<<15|31744;if(r<=0){const i=Math.round(n*Math.pow(2,14)*1024);return e<<15|i&1023}const s=n/Math.pow(2,t)-1;let o=Math.round(s*1024);return o>=1024&&(o=0,r++,r>=31)?e<<15|31744:e<<15|r<<10|o}class ot{static _legacyEncodePoint(e,t,r){const s=new Uint8Array(6),o=new DataView(s.buffer);return xi(o,0,e),xi(o,2,t),xi(o,4,r),Tx(s)}static _legacyEncodePoints(e){if(e.length===0)return"";const t=new Uint8Array(e.length*6),r=new DataView(t.buffer);for(let s=0;s<e.length;s++){const o=e[s],i=s*6;xi(r,i,o.x),xi(r,i+2,o.y),xi(r,i+4,o.z??.5)}return Tx(t)}static _legacyDecodePoints(e){const t=Rp(e),r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=[];for(let o=0;o<t.length;o+=6)s.push({x:Si(r,o),y:Si(r,o+2),z:Si(r,o+4)});return s}static encodePoints(e){if(e.length===0)return"";const t=12,r=(e.length-1)*6,s=t+r,o=new Uint8Array(s),i=new DataView(o.buffer),a=e[0];i.setFloat32(0,a.x,!0),i.setFloat32(4,a.y,!0),i.setFloat32(8,a.z??.5,!0);let l=a.x,c=a.y,u=a.z??.5;for(let d=1;d<e.length;d++){const h=e[d],f=h.z??.5,g=t+(d-1)*6;xi(i,g,h.x-l),xi(i,g+2,h.y-c),xi(i,g+4,f-u),l=h.x,c=h.y,u=f}return Tx(o)}static decodePoints(e){if(e.length===0)return[];const t=Rp(e),r=new DataView(t.buffer,t.byteOffset,t.byteLength),s=[];let o=r.getFloat32(0,!0),i=r.getFloat32(4,!0),a=r.getFloat32(8,!0);s.push({x:o,y:i,z:a});const l=12;for(let c=l;c<t.length;c+=6)o+=Si(r,c),i+=Si(r,c+2),a+=Si(r,c+4),s.push({x:o,y:i,z:a});return s}static decodeFirstPoint(e){if(e.length<Px)return null;const t=Rp(e.slice(0,Px)),r=new DataView(t.buffer,t.byteOffset,t.byteLength);return{x:r.getFloat32(0,!0),y:r.getFloat32(4,!0),z:r.getFloat32(8,!0)}}static decodeLastPoint(e){if(e.length<Px)return null;const t=Rp(e),r=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=r.getFloat32(0,!0),o=r.getFloat32(4,!0),i=r.getFloat32(8,!0);const a=12;for(let l=a;l<t.length;l+=6)s+=Si(r,l),o+=Si(r,l+2),i+=Si(r,l+4);return{x:s,y:o,z:i}}}const WM=tt({type:Da("free","straight"),path:Ke}),VM={color:Rr,fill:Li,dash:Ml,size:Vo,segments:Bn(WM),isComplete:Ve,isClosed:Ve,isPen:Ve,scale:en,scaleX:Ag,scaleY:Ag},Lp=Vs("draw",{AddInPen:1,AddScale:2,Base64:3,LegacyPointsConversion:4}),GM={sequence:[{id:Lp.AddInPen,up:n=>{const{points:e}=n.segments[0];if(e.length===0){n.isPen=!1;return}let t=!(e[0].z===0||e[0].z===.5);e[1]&&(t=t&&!(e[1].z===0||e[1].z===.5)),n.isPen=t},down:"retired"},{id:Lp.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}},{id:Lp.Base64,up:n=>{n.segments=n.segments.map(e=>{if(e.path!==void 0)return e;const{points:t,...r}=e,s=Array.isArray(t)?t:ot._legacyDecodePoints(t);return{...r,path:ot.encodePoints(s)}}),n.scaleX=n.scaleX??1,n.scaleY=n.scaleY??1},down:n=>{n.segments=n.segments.map(e=>{const{path:t,...r}=e;return{...r,points:ot.decodePoints(t)}}),delete n.scaleX,delete n.scaleY}},{id:Lp.LegacyPointsConversion,up:n=>{n.segments=n.segments.map(e=>{if(e.path!==void 0)return e;const{points:t,...r}=e,s=Array.isArray(t)?t:ot._legacyDecodePoints(t);return{...r,path:ot.encodePoints(s)}})},down:n=>{}}]},SU=/(^\/r\/[^/]+\/?$)/,xU=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(SU))return n}},{hostnames:["figma.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/?$/)){const t=e.searchParams.get("url");if(t)return t}}},{hostnames:["google.*"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom"),[s,o]=e.searchParams.get("center").split(",");return`https://www.google.com/maps/@${s},${o},${r}z`}}},{hostnames:["val.town"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(t)return`https://www.val.town/v/${t[1]}`}},{hostnames:["codesandbox.io"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(t)return`https://codesandbox.io/s/${t[1]}`}},{hostnames:["codepen.io"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,t=n.match(e);if(t){const[r,s,o]=t;return`https://codepen.io/${s}/pen/${o}`}}},{hostnames:["scratch.mit.edu"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,t=n.match(e);if(t){const[r,s]=t;return`https://scratch.mit.edu/projects/${s}`}}},{hostnames:["*.youtube.com","youtube.com","youtu.be"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{hostnames:["calendar.google.*"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n),t=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&t){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const s of r)e.searchParams.delete(s);return e.searchParams.set("cid",t),e.href}}},{hostnames:["docs.google.*"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const t=Array.from(e.searchParams.keys());for(const r of t)e.searchParams.delete(r);return e.href}}},{hostnames:["gist.github.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return n.split("/").pop()?n:void 0}},{hostnames:["replit.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{hostnames:["felt.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{hostnames:["open.spotify.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{hostnames:["vimeo.com","player.vimeo.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="player.vimeo.com"){const t=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(t)return"https://vimeo.com/"+t[1]}}},{hostnames:["observablehq.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{hostnames:["desmos.com"],canEditWhileLocked:!0,fromEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return n.replace("?embed","")}}],YM={w:en,h:en,url:Ke},jp=Vs("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),XM={sequence:[{id:jp.GenOriginalUrlInEmbed,up:n=>{try{const e=n.url,t=new URL(e).host.replace("www.","");let r;for(const s of xU)if(s.hostnames.includes(t))try{r=s.fromEmbedUrl(e)}catch(o){console.warn(o)}n.tmpOldUrl=n.url,n.url=r??""}catch{n.url="",n.tmpOldUrl=n.url}},down:"retired"},{id:jp.RemoveDoesResize,up:n=>{delete n.doesResize},down:"retired"},{id:jp.RemoveTmpOldUrl,up:n=>{delete n.tmpOldUrl},down:"retired"},{id:jp.RemovePermissionOverrides,up:n=>{delete n.overridePermissions},down:"retired"}]},qM={w:en,h:en,name:Ke,color:Da(...Rr.values)},bU=Vs("frame",{AddColorProp:1}),ZM={sequence:[{id:bU.AddColorProp,up:n=>{n.color="black"},down:n=>{delete n.color}}]},jg=Mn.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),Ng=Mn.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),$o=Mn.defineEnum("tldraw:geo",{defaultValue:"rectangle",values:["cloud","rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","rhombus-2","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","x-box","check-box","heart"]}),JM={geo:$o,dash:Ml,url:bs,w:en,h:en,growY:Mg,scale:en,labelColor:Bv,color:Rr,fill:Li,size:Vo,font:Oa,align:jg,verticalAlign:Ng,richText:Lh},so=Vs("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9,AddRichText:10,AddRichTextAttrs:11}),QM={sequence:[{id:so.AddUrlProp,up:n=>{n.url=""},down:"retired"},{id:so.AddLabelColor,up:n=>{n.labelColor="black"},down:"retired"},{id:so.RemoveJustify,up:n=>{n.align==="justify"&&(n.align="start")},down:"retired"},{id:so.AddCheckBox,up:n=>{},down:"retired"},{id:so.AddVerticalAlign,up:n=>{n.verticalAlign="middle"},down:"retired"},{id:so.MigrateLegacyAlign,up:n=>{let e;switch(n.align){case"start":e="start-legacy";break;case"end":e="end-legacy";break;default:e="middle-legacy";break}n.align=e},down:"retired"},{id:so.AddCloud,up:n=>{},down:"retired"},{id:so.MakeUrlsValid,up:n=>{bs.isValid(n.url)||(n.url="")},down:n=>{}},{id:so.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}},{id:so.AddRichText,up:n=>{n.richText=Kn(n.text),delete n.text}},{id:so.AddRichTextAttrs,up:n=>{},down:n=>{n.richText&&"attrs"in n.richText&&delete n.richText.attrs}}]},eA={},tA={sequence:[]},nA={color:Rr,size:Vo,segments:Bn(WM),isComplete:Ve,isPen:Ve,scale:en,scaleX:Ag,scaleY:Ag},Ix=Vs("highlight",{AddScale:1,Base64:2,LegacyPointsConversion:3}),rA={sequence:[{id:Ix.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}},{id:Ix.Base64,up:n=>{n.segments=n.segments.map(e=>{if(e.path!==void 0)return e;const{points:t,...r}=e,s=Array.isArray(t)?t:ot._legacyDecodePoints(t);return{...r,path:ot.encodePoints(s)}}),n.scaleX=n.scaleX??1,n.scaleY=n.scaleY??1},down:n=>{n.segments=n.segments.map(e=>{const{path:t,...r}=e;return{...r,points:ot.decodePoints(t)}}),delete n.scaleX,delete n.scaleY}},{id:Ix.LegacyPointsConversion,up:n=>{n.segments=n.segments.map(e=>{if(e.path!==void 0)return e;const{points:t,...r}=e,s=Array.isArray(t)?t:ot._legacyDecodePoints(t);return{...r,path:ot.encodePoints(s)}})},down:n=>{}}]},wU=tt({topLeft:Jc,bottomRight:Jc,isCircle:Ve.optional()}),sA={w:en,h:en,playing:Ve,url:bs,assetId:hy.nullable(),crop:wU.nullable(),flipX:Ve,flipY:Ve,altText:Ke},jd=Vs("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4,AddAltText:5}),oA={sequence:[{id:jd.AddUrlProp,up:n=>{n.url=""},down:"retired"},{id:jd.AddCropProp,up:n=>{n.crop=null},down:n=>{delete n.crop}},{id:jd.MakeUrlsValid,up:n=>{bs.isValid(n.url)||(n.url="")},down:n=>{}},{id:jd.AddFlipProps,up:n=>{n.flipX=!1,n.flipY=!1},down:n=>{delete n.flipX,delete n.flipY}},{id:jd.AddAltText,up:n=>{n.altText=""},down:n=>{delete n.altText}}]},Iw=Mn.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),vU=tt({id:Ke,index:jv,x:Be,y:Be}),iA={color:Rr,dash:Ml,size:Vo,spline:Iw,points:Dg(Ke,vU),scale:en},Nd=Vs("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),aA={sequence:[{id:Nd.AddSnapHandles,up:n=>{for(const e of Object.values(n.handles))e.canSnap=!0},down:"retired"},{id:Nd.RemoveExtraHandleProps,up:n=>{n.handles=W_(Object.values(n.handles).map(e=>[e.index,{x:e.x,y:e.y}]))},down:n=>{const e=Object.entries(n.handles).map(([t,r])=>({index:t,...r})).sort(Tn);n.handles=Object.fromEntries(e.map((t,r)=>{const s=r===0?"start":r===e.length-1?"end":`handle:${t.index}`;return[s,{id:s,type:"vertex",canBind:!1,canSnap:!0,index:t.index,x:t.x,y:t.y}]}))}},{id:Nd.HandlesToPoints,up:n=>{const e=Object.entries(n.handles).map(([t,{x:r,y:s}])=>({x:r,y:s,index:t})).sort(Tn);n.points=e.map(({x:t,y:r})=>({x:t,y:r})),delete n.handles},down:n=>{const e=rh(n.points.length);n.handles=Object.fromEntries(n.points.map((t,r)=>[e[r],{x:t.x,y:t.y}])),delete n.points}},{id:Nd.PointIndexIds,up:n=>{const e=rh(n.points.length);n.points=Object.fromEntries(n.points.map((t,r)=>{const s=e[r];return[s,{id:s,index:s,x:t.x,y:t.y}]}))},down:n=>{const e=Object.values(n.points).sort(Tn);n.points=e.map(({x:t,y:r})=>({x:t,y:r}))}},{id:Nd.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}}]},lA={color:Rr,labelColor:Bv,size:Vo,font:Oa,fontSizeAdjustment:Mg,align:jg,verticalAlign:Ng,growY:Mg,url:bs,richText:Lh,scale:en},_o=Vs("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7,AddLabelColor:8,AddRichText:9,AddRichTextAttrs:10}),cA={sequence:[{id:_o.AddUrlProp,up:n=>{n.url=""},down:"retired"},{id:_o.RemoveJustify,up:n=>{n.align==="justify"&&(n.align="start")},down:"retired"},{id:_o.MigrateLegacyAlign,up:n=>{switch(n.align){case"start":n.align="start-legacy";return;case"end":n.align="end-legacy";return;default:n.align="middle-legacy";return}},down:"retired"},{id:_o.AddVerticalAlign,up:n=>{n.verticalAlign="middle"},down:"retired"},{id:_o.MakeUrlsValid,up:n=>{bs.isValid(n.url)||(n.url="")},down:n=>{}},{id:_o.AddFontSizeAdjustment,up:n=>{n.fontSizeAdjustment=0},down:n=>{delete n.fontSizeAdjustment}},{id:_o.AddScale,up:n=>{n.scale=1},down:n=>{delete n.scale}},{id:_o.AddLabelColor,up:n=>{n.labelColor="black"},down:n=>{delete n.labelColor}},{id:_o.AddRichText,up:n=>{n.richText=Kn(n.text),delete n.text}},{id:_o.AddRichTextAttrs,up:n=>{},down:n=>{n.richText&&"attrs"in n.richText&&delete n.richText.attrs}}]},Ew=Mn.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]}),dA={color:Rr,size:Vo,font:Oa,textAlign:Ew,w:en,richText:Lh,scale:en,autoSize:Ve},Np=Vs("text",{RemoveJustify:1,AddTextAlign:2,AddRichText:3,AddRichTextAttrs:4}),uA={sequence:[{id:Np.RemoveJustify,up:n=>{n.align==="justify"&&(n.align="start")},down:"retired"},{id:Np.AddTextAlign,up:n=>{n.textAlign=n.align,delete n.align},down:n=>{n.align=n.textAlign,delete n.textAlign}},{id:Np.AddRichText,up:n=>{n.richText=Kn(n.text),delete n.text}},{id:Np.AddRichTextAttrs,up:n=>{},down:n=>{n.richText&&"attrs"in n.richText&&delete n.richText.attrs}}]},hA={w:en,h:en,time:Be,playing:Ve,autoplay:Ve,url:bs,assetId:hy.nullable(),altText:Ke},Fp=Vs("video",{AddUrlProp:1,MakeUrlsValid:2,AddAltText:3,AddAutoplay:4}),pA={sequence:[{id:Fp.AddUrlProp,up:n=>{n.url=""},down:"retired"},{id:Fp.MakeUrlsValid,up:n=>{bs.isValid(n.url)||(n.url="")},down:n=>{}},{id:Fp.AddAltText,up:n=>{n.altText=""},down:n=>{delete n.altText}},{id:Fp.AddAutoplay,up:n=>{n.autoplay=!0},down:n=>{delete n.autoplay}}]},Fd=ns("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4,FixIndexKeys:5}),CU=Nc({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:Fd.RemoveCodeAndIconShapeTypes,scope:"storage",up:n=>{for(const[e,t]of n.entries())t.typeName==="shape"&&"type"in t&&(t.type==="icon"||t.type==="code")&&n.delete(e)}},{id:Fd.AddInstancePresenceType,scope:"storage",up(n){}},{id:Fd.RemoveTLUserAndPresenceAndAddPointer,scope:"storage",up:n=>{for(const[e,t]of n.entries())t.typeName.match(/^(user|user_presence)$/)&&n.delete(e)}},{id:Fd.RemoveUserDocument,scope:"storage",up:n=>{for(const[e,t]of n.entries())t.typeName.match("user_document")&&n.delete(e)}},{id:Fd.FixIndexKeys,scope:"record",up:n=>{if(["shape","page"].includes(n.typeName)&&"index"in n){const e=n;if(e.index.endsWith("0")&&e.index!=="a0"&&(e.index=e.index.slice(0,-1)+hT(3)),n.typeName==="shape"&&e.type==="line"){const t=e;for(const[r,s]of $s(t.props.points))s.index.endsWith("0")&&s.index!=="a0"&&(s.index=s.index.slice(0,-1)+hT(3))}}},down:()=>{}}]}),uT="123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",PU=()=>uT.charAt(Math.floor(Math.random()*uT.length)),hT=n=>Array.from({length:n},PU).join(""),TU={arrow:{migrations:LM,props:RM},bookmark:{migrations:HM,props:$M},draw:{migrations:GM,props:VM},embed:{migrations:XM,props:YM},frame:{migrations:ZM,props:qM},geo:{migrations:QM,props:JM},group:{migrations:tA,props:eA},highlight:{migrations:rA,props:nA},image:{migrations:oA,props:sA},line:{migrations:aA,props:iA},note:{migrations:cA,props:lA},text:{migrations:uA,props:dA},video:{migrations:pA,props:hA}},IU={arrow:{migrations:NM,props:jM}};function EU({shapes:n=TU,bindings:e=IU,migrations:t}={}){const r=new Map;for(const a of Et(n))for(const l of AM(a.props??{}).keys()){if(r.has(l.id)&&r.get(l.id)!==l)throw new Error(`Multiple StyleProp instances with the same id: ${l.id}`);r.set(l.id,l)}const s=xH(n),o=mH(e),i=FH(r);return Ov.create({asset:Gl,binding:o,camera:zo,document:$v,instance:i,instance_page_state:uo,page:Ar,instance_presence:GH,pointer:zv,shape:s},{migrations:[CU,aU,kH,XH,BH,$H,jH,VH,KH,SH,eU,nU,sU,...oT("shape",n),...oT("binding",e),...t??[]],onValidationFailure:qH,createIntegrityChecker:JH})}const oh=[{locale:"id",label:"Bahasa Indonesia"},{locale:"ms",label:"Bahasa Melayu"},{locale:"ca",label:"Català"},{locale:"cs",label:"Čeština"},{locale:"da",label:"Danish"},{locale:"de",label:"Deutsch"},{locale:"en",label:"English"},{locale:"es",label:"Español"},{locale:"tl",label:"Filipino"},{locale:"fr",label:"Français"},{locale:"gl",label:"Galego"},{locale:"hr",label:"Hrvatski"},{locale:"it",label:"Italiano"},{locale:"hu",label:"Magyar"},{locale:"nl",label:"Nederlands"},{locale:"no",label:"Norwegian"},{locale:"pl",label:"Polski"},{locale:"pt-br",label:"Português - Brasil"},{locale:"pt-pt",label:"Português - Europeu"},{locale:"ro",label:"Română"},{locale:"sl",label:"Slovenščina"},{locale:"so",label:"Somali"},{locale:"fi",label:"Suomi"},{locale:"sv",label:"Svenska"},{locale:"vi",label:"Tiếng Việt"},{locale:"tr",label:"Türkçe"},{locale:"el",label:"Ελληνικά"},{locale:"ru",label:"Русский"},{locale:"uk",label:"Українська"},{locale:"he",label:"עברית"},{locale:"ur",label:"اردو"},{locale:"ar",label:"عربي"},{locale:"fa",label:"فارسی"},{locale:"ne",label:"नेपाली"},{locale:"mr",label:"मराठी"},{locale:"hi-in",label:"हिन्दी"},{locale:"bn",label:"বাংলা"},{locale:"pa",label:"ਪੰਜਾਬੀ"},{locale:"gu-in",label:"ગુજરાતી"},{locale:"ta",label:"தமிழ்"},{locale:"te",label:"తెలుగు"},{locale:"kn",label:"ಕನ್ನಡ"},{locale:"ml",label:"മലയാളം"},{locale:"th",label:"ภาษาไทย"},{locale:"km-kh",label:"ភាសាខ្មែរ"},{locale:"ko-kr",label:"한국어"},{locale:"ja",label:"日本語"},{locale:"zh-cn",label:"简体中文"},{locale:"zh-tw",label:"繁體中文 (台灣)"}];function kU(){const n=typeof window<"u"&&window.navigator?window.navigator.languages??["en"]:["en"];return _U(n)}function _U(n){for(const e of n){const t=MU(e);if(t)return t}return"en"}const pT={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function MU(n){const e=oh.find(s=>s.locale===n.toLowerCase());if(e)return e.locale;const[t,r]=n.split(/[-_]/).map(s=>s.toLowerCase());if(r){const s=oh.find(o=>o.locale===t);if(s)return s.locale}return t in pT?pT[t]:null}Wi("@tldraw/tlschema","4.4.0","esm");function AU(){return p.jsx("div",{className:"tl-background"})}function jh(n,e,t,r,s,o){x.useLayoutEffect(()=>{const i=n.current;if(!i||e===void 0)return;let a=`translate(${e}px, ${t}px)`;r!==void 0&&(a+=` scale(${r})`),s!==void 0&&(a+=` rotate(${s}rad)`),o&&(a+=` translate(${o.x}px, ${o.y}px)`),i.style.transform=a})}const ar={linear:n=>n,easeInQuad:n=>n*n,easeOutQuad:n=>n*(2-n),easeInOutQuad:n=>n<.5?2*n*n:-1+(4-2*n)*n,easeInCubic:n=>n*n*n,easeOutCubic:n=>--n*n*n+1,easeInOutCubic:n=>n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1,easeInQuart:n=>n*n*n*n,easeOutQuart:n=>1- --n*n*n*n,easeInOutQuart:n=>n<.5?8*n*n*n*n:1-8*--n*n*n*n,easeInQuint:n=>n*n*n*n*n,easeOutQuint:n=>1+--n*n*n*n*n,easeInOutQuint:n=>n<.5?16*n*n*n*n*n:1+16*--n*n*n*n*n,easeInSine:n=>1-Math.cos(n*Math.PI/2),easeOutSine:n=>Math.sin(n*Math.PI/2),easeInOutSine:n=>-(Math.cos(Math.PI*n)-1)/2,easeInExpo:n=>n<=0?0:Math.pow(2,10*n-10),easeOutExpo:n=>n>=1?1:1-Math.pow(2,-10*n),easeInOutExpo:n=>n<=0?0:n>=1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2};class C{constructor(e=0,t=0,r=1){this.x=e,this.y=t,this.z=r}get pressure(){return this.z}set(e=this.x,t=this.y,r=this.z){return this.x=e,this.y=t,this.z=r,this}setTo({x:e=0,y:t=0,z:r=1}){return this.x=e,this.y=t,this.z=r,this}rot(e){if(e===0)return this;const{x:t,y:r}=this,s=Math.sin(e),o=Math.cos(e);return this.x=t*o-r*s,this.y=t*s+r*o,this}rotWith(e,t){if(t===0)return this;const r=this.x-e.x,s=this.y-e.y,o=Math.sin(t),i=Math.cos(t);return this.x=e.x+(r*i-s*o),this.y=e.y+(r*o+s*i),this}clone(){const{x:e,y:t,z:r}=this;return new C(e,t,r)}sub(e){return this.x-=e.x,this.y-=e.y,this}subXY(e,t){return this.x-=e,this.y-=t,this}subScalar(e){return this.x-=e,this.y-=e,this}add(e){return this.x+=e.x,this.y+=e.y,this}addXY(e,t){return this.x+=e,this.y+=t,this}addScalar(e){return this.x+=e,this.y+=e,this}clamp(e,t){return this.x=Math.max(this.x,e),this.y=Math.max(this.y,e),t!==void 0&&(this.x=Math.min(this.x,t),this.y=Math.min(this.y,t)),this}div(e){return this.x/=e,this.y/=e,this}divV(e){return this.x/=e.x,this.y/=e.y,this}mul(e){return this.x*=e,this.y*=e,this}mulV(e){return this.x*=e.x,this.y*=e.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(e,t){const r=C.Tan(e,this);return this.add(r.mul(t))}neg(){return this.x*=-1,this.y*=-1,this}cross(e){return this.x=this.y*e.z-this.z*e.y,this.y=this.z*e.x-this.x*e.z,this}dpr(e){return C.Dpr(this,e)}cpr(e){return C.Cpr(this,e)}len2(){return C.Len2(this)}len(){return C.Len(this)}pry(e){return C.Pry(this,e)}per(){const{x:e,y:t}=this;return this.x=t,this.y=-e,this}uni(){const e=this.len();return e===0?this:(this.x/=e,this.y/=e,this)}tan(e){return this.sub(e).uni()}dist(e){return C.Dist(this,e)}distanceToLineSegment(e,t){return C.DistanceToLineSegment(e,t,this)}slope(e){return C.Slope(this,e)}snapToGrid(e){return this.x=Math.round(this.x/e)*e,this.y=Math.round(this.y/e)*e,this}angle(e){return C.Angle(this,e)}toAngle(){return C.ToAngle(this)}lrp(e,t){return this.x=this.x+(e.x-this.x)*t,this.y=this.y+(e.y-this.y)*t,this}equals(e){return C.Equals(this,e)}equalsXY(e,t){return C.EqualsXY(this,e,t)}toFixed(){return this.x=Ai(this.x),this.y=Ai(this.y),this}toString(){return C.ToString(C.ToFixed(this))}toJson(){return C.ToJson(this)}toArray(){return C.ToArray(this)}static Add(e,t){return new C(e.x+t.x,e.y+t.y)}static AddXY(e,t,r){return new C(e.x+t,e.y+r)}static Sub(e,t){return new C(e.x-t.x,e.y-t.y)}static SubXY(e,t,r){return new C(e.x-t,e.y-r)}static AddScalar(e,t){return new C(e.x+t,e.y+t)}static SubScalar(e,t){return new C(e.x-t,e.y-t)}static Div(e,t){return new C(e.x/t,e.y/t)}static Mul(e,t){return new C(e.x*t,e.y*t)}static DivV(e,t){return new C(e.x/t.x,e.y/t.y)}static MulV(e,t){return new C(e.x*t.x,e.y*t.y)}static Neg(e){return new C(-e.x,-e.y)}static Per(e){return new C(e.y,-e.x)}static Abs(e){return new C(Math.abs(e.x),Math.abs(e.y))}static Dist(e,t){return((e.y-t.y)**2+(e.x-t.x)**2)**.5}static ManhattanDist(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}static DistMin(e,t,r){return(e.x-t.x)*(e.x-t.x)+(e.y-t.y)*(e.y-t.y)<r**2}static Dist2(e,t){return(e.x-t.x)*(e.x-t.x)+(e.y-t.y)*(e.y-t.y)}static Dpr(e,t){return e.x*t.x+e.y*t.y}static Cross(e,t){return new C(e.y*t.z-e.z*t.y,e.z*t.x-e.x*t.z)}static Cpr(e,t){return e.x*t.y-t.x*e.y}static Len2(e){return e.x*e.x+e.y*e.y}static Len(e){return(e.x*e.x+e.y*e.y)**.5}static Pry(e,t){return C.Dpr(e,t)/C.Len(t)}static Uni(e){const t=C.Len(e);return new C(t===0?0:e.x/t,t===0?0:e.y/t)}static Tan(e,t){return C.Uni(C.Sub(e,t))}static Min(e,t){return new C(Math.min(e.x,t.x),Math.min(e.y,t.y))}static Max(e,t){return new C(Math.max(e.x,t.x),Math.max(e.y,t.y))}static From({x:e,y:t,z:r=1}){return new C(e,t,r)}static FromArray(e){return new C(e[0],e[1])}static Rot(e,t=0){const r=Math.sin(t),s=Math.cos(t);return new C(e.x*s-e.y*r,e.x*r+e.y*s)}static RotWith(e,t,r){const s=e.x-t.x,o=e.y-t.y,i=Math.sin(r),a=Math.cos(r);return new C(t.x+(s*a-o*i),t.y+(s*i+o*a))}static NearestPointOnLineThroughPoint(e,t,r){return C.Mul(t,C.Sub(r,e).pry(t)).add(e)}static NearestPointOnLineSegment(e,t,r,s=!0){if(C.Equals(e,r)||C.Equals(t,r))return C.From(r);const o=C.Tan(t,e),i=C.Add(e,C.Mul(o,C.Sub(r,e).pry(o)));if(s){if(i.x<Math.min(e.x,t.x))return C.Cast(e.x<t.x?e:t);if(i.x>Math.max(e.x,t.x))return C.Cast(e.x>t.x?e:t);if(i.y<Math.min(e.y,t.y))return C.Cast(e.y<t.y?e:t);if(i.y>Math.max(e.y,t.y))return C.Cast(e.y>t.y?e:t)}return i}static DistanceToLineThroughPoint(e,t,r){return C.Dist(r,C.NearestPointOnLineThroughPoint(e,t,r))}static DistanceToLineSegment(e,t,r,s=!0){return C.Dist(r,C.NearestPointOnLineSegment(e,t,r,s))}static Snap(e,t=1){return new C(Math.round(e.x/t)*t,Math.round(e.y/t)*t)}static Cast(e){return e instanceof C?e:C.From(e)}static Slope(e,t){return e.x===t.y?NaN:(e.y-t.y)/(e.x-t.x)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static AngleBetween(e,t){const r=e.x*t.x+e.y*t.y,s=Math.sqrt((Math.pow(e.x,2)+Math.pow(e.y,2))*(Math.pow(t.x,2)+Math.pow(t.y,2)));return(e.x*t.y-e.y*t.x<0?-1:1)*Math.acos(Fe(r/s,-1,1))}static Lrp(e,t,r){return C.Sub(t,e).mul(r).add(e)}static Med(e,t){return new C((e.x+t.x)/2,(e.y+t.y)/2)}static Equals(e,t){return Math.abs(e.x-t.x)<1e-4&&Math.abs(e.y-t.y)<1e-4}static EqualsXY(e,t,r){return e.x===t&&e.y===r}static Clockwise(e,t,r){return(r.x-e.x)*(t.y-e.y)-(t.x-e.x)*(r.y-e.y)<0}static Rescale(e,t){const r=C.Len(e);return new C(t*e.x/r,t*e.y/r)}static ScaleWithOrigin(e,t,r){return C.Sub(e,r).mul(t).add(r)}static ToFixed(e){return new C(Ai(e.x),Ai(e.y))}static ToInt(e){return new C(parseInt(e.x.toFixed(0)),parseInt(e.y.toFixed(0)),parseInt((e.z??0).toFixed(0)))}static ToCss(e){return`${e.x},${e.y}`}static Nudge(e,t,r){return C.Add(e,C.Tan(t,e).mul(r))}static ToString(e){return`${e.x}, ${e.y}`}static ToAngle(e){let t=Math.atan2(e.y,e.x);return t<0&&(t+=Math.PI*2),t}static FromAngle(e,t=1){return new C(Math.cos(e)*t,Math.sin(e)*t)}static ToArray(e){return[e.x,e.y,e.z]}static ToJson(e){const{x:t,y:r,z:s}=e;return{x:t,y:r,z:s}}static Average(e){const t=e.length,r=new C(0,0);if(t===0)return r;for(let s=0;s<t;s++)r.add(e[s]);return r.div(t)}static Clamp(e,t,r){return r===void 0?new C(Math.min(Math.max(e.x,t)),Math.min(Math.max(e.y,t))):new C(Math.min(Math.max(e.x,t),r),Math.min(Math.max(e.y,t),r))}static PointsBetween(e,t,r=6){const s=[];for(let o=0;o<r;o++){const i=ar.easeInQuad(o/(r-1)),a=C.Lrp(e,t,i);a.z=Math.min(1,.5+Math.abs(.5-DU(i))*.65),s.push(a)}return s}static SnapToGrid(e,t=8){return new C(Math.round(e.x/t)*t,Math.round(e.y/t)*t)}}const DU=n=>n<.5?2*n*n:-1+(4-2*n)*n;function jn(n){return`${$(n.x)},${$(n.y)} `}function Vr(n,e){return`${$((n.x+e.x)/2)},${$((n.y+e.y)/2)} `}const ht=Math.PI,Bt=ht/2,vt=ht*2,OU=Math.sin;function Fe(n,e,t){return Math.max(e,typeof t<"u"?Math.min(n,t):n)}function Bp(n,e=1e10){return n?Math.round(n*e)/e:0}function tn(n,e,t=1e-6){return Math.abs(n-e)<=t}function va(n,e,t=1e-6){return n<e||tn(n,e,t)}function RU(n,e){const t=Math.pow(n-e,2)/Math.pow(n+e,2);return ht*(n+e)*(1+3*t/(10+Math.sqrt(4-3*t)))}function Fg(n){return n=n%vt,n<0?n=n+vt:n===0&&(n=0),n}function Hv(n,e){return n=Fg(n),e=Fg(e),n>e&&(e+=vt),e-n}function LU(n,e){return vt-Hv(n,e)}function jf(n,e){const t=(e-n)%vt;return 2*t%vt-t}function kw(n){return(vt+n)%vt}function Bg(n,e){const t=vt/e;let r=Math.floor((kw(n)+t/2)/t)*t%vt;return r<ht&&(r+=vt),r>ht&&(r-=vt),r}function fA(n,e){return n===e||tn(n%(Math.PI/2)-e%(Math.PI/2),0)}function jU(n){return n*ht/180}function NU(n){return n*180/ht}function Uv(n,e,t){return new C(n.x,n.y).add(C.FromAngle(t,e))}function Ex(n,e,t){const r=n/2,s=e/2,o=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let g=0;g<t;g++){const m=vt/t,y=-Bt+g*m,S=r+r*Math.cos(y),b=s+s*Math.sin(y);S<i&&(i=S),b<l&&(l=b),S>a&&(a=S),b>c&&(c=b),o.push(new C(S,b))}const u=a-i,d=c-l,h=n-u,f=e-d;if(h!==0||f!==0)for(let g=0;g<o.length;g++){const m=o[g];m.x=(m.x-i)/u*n,m.y=(m.y-l)/d*e}return o}function Bd(n,e,t,r){return n<r&&t<e}function io(n,e,t,r){const s=Math.max(n,t),o=Math.min(e,r);return s<=o?[s,o]:null}function fT(n,e,t){return(e.x-n.x)*(t.y-n.y)-(t.x-n.x)*(e.y-n.y)}function kr(n,e){let t=0,r,s;for(let o=0;o<e.length;o++){if(r=e[o],r.x===n.x&&r.y===n.y||(s=e[(o+1)%e.length],C.Dist(n,r)+C.Dist(n,s)===C.Dist(r,s)))return!0;r.y<=n.y?s.y>n.y&&fT(r,s,n)>0&&(t+=1):s.y<=n.y&&fT(r,s,n)<0&&(t-=1)}return t!==0}function $(n){return Math.round(n*1e4)/1e4}function Ai(n){return Math.round(n*100)/100}const gT=n=>Math.abs(n)<Number.MAX_SAFE_INTEGER;function mT(n,e,t,r){let s;if(Math.abs(n)>ht){s=jf(e,r);const o=jf(r,t);return Math.abs(s)<Math.abs(o)?s/n:(n-o)/n}else{s=jf(e,r);const o=s/n;return Math.sign(s)!==Math.sign(n)?Math.abs(o)>.5?1:0:o}}function FU(n,e,t,r){const s=2*((e-n)%vt)%vt-(e-n)%vt;return r?(vt-Math.abs(s))*(t?1:-1):s}function gA(n,e,t){const r=-2*(n.x*(e.y-t.y)-n.y*(e.x-t.x)+e.x*t.y-t.x*e.y),s=((n.x*n.x+n.y*n.y)*(t.y-e.y)+(e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y))/r,o=((n.x*n.x+n.y*n.y)*(e.x-t.x)+(e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x))/r;return!Number.isFinite(s)||!Number.isFinite(o)?null:new C(s,o)}const kx=({brush:n,color:e,opacity:t,className:r})=>{const s=x.useRef(null);jh(s,n.x,n.y);const o=$(Math.max(1,n.w)),i=$(Math.max(1,n.h));return p.jsx("svg",{className:"tl-overlays__item",ref:s,"aria-hidden":"true",children:e?p.jsxs("g",{className:"tl-brush",opacity:t,children:[p.jsx("rect",{width:o,height:i,fill:e,opacity:.75}),p.jsx("rect",{width:o,height:i,fill:"none",stroke:e,opacity:.1})]}):p.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:o,height:i})})};var _x={exports:{}};/*!
53
+ Copyright (c) 2018 Jed Watson.
54
+ Licensed under the MIT License (MIT), see
55
+ http://jedwatson.github.io/classnames
56
+ */var yT;function BU(){return yT||(yT=1,(function(n){(function(){var e={}.hasOwnProperty;function t(){for(var o="",i=0;i<arguments.length;i++){var a=arguments[i];a&&(o=s(o,r(a)))}return o}function r(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return t.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var i="";for(var a in o)e.call(o,a)&&o[a]&&(i=s(i,a));return i}function s(o,i){return i?o?o+" "+i:o+i:o}n.exports?(t.default=t,n.exports=t):window.classNames=t})()})(_x)),_x.exports}var zU=BU();const xe=Ua(zU),dt={isSafari:!1,isIos:!1,isChromeForIos:!1,isFirefox:!1,isAndroid:!1,isDarwin:!1,hasCanvasSupport:!1};let mA=!1;typeof window<"u"&&("navigator"in window&&(dt.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),dt.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),dt.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),dt.isFirefox=/firefox/i.test(navigator.userAgent),dt.isAndroid=/android/i.test(navigator.userAgent),dt.isDarwin=window.navigator.userAgent.toLowerCase().indexOf("mac")>-1),dt.hasCanvasSupport="Promise"in window&&"HTMLCanvasElement"in window,mA=dt.isFirefox&&!dt.isAndroid&&!dt.isIos);const Lu=We("tlenvReactive",{isCoarsePointer:!1});if(typeof window<"u"&&!mA){const n=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),e=()=>Lu.__unsafe__getWithoutCapture().isCoarsePointer;if(n){const t=()=>{const r=n.matches;r!==e()&&Lu.update(s=>({...s,isCoarsePointer:r}))};t(),n.addEventListener("change",t)}window.addEventListener("pointerdown",t=>{const r=t.pointerType!=="mouse";r!==e()&&Lu.update(s=>({...s,isCoarsePointer:r}))},{capture:!0})}const _w={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.05,.1,.25,.5,1,2,4,8]},Mx={duration:0,easing:ar.easeInOutCubic},yA={CAMERA_MOVE:-10},$U=["top","right","bottom","left"],ST=0,Kv=2,zp=1,xT=5;var Ax={};const HU={},SA=tr("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),Dt={logPreventDefaults:tr("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:tr("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:tr("logElementRemoves",{defaults:{all:!1}}),debugSvg:tr("debugSvg",{defaults:{all:!1}}),showFps:tr("showFps",{defaults:{all:!1}}),measurePerformance:tr("measurePerformance",{defaults:{all:!1}}),throwToBlob:tr("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:tr("reconnectOnPing",{defaults:{all:!1}}),debugCursors:tr("debugCursors",{defaults:{all:!1}}),forceSrgb:tr("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:tr("debugGeometry",{defaults:{all:!1}}),hideShapes:tr("hideShapes",{defaults:{all:!1}}),editOnType:tr("editOnType",{defaults:{all:!1}}),a11y:tr("a11y",{defaults:{all:!1}}),debugElbowArrows:tr("debugElbowArrows",{defaults:{all:!1}})};if(typeof Element<"u"){const n=Element.prototype.removeChild;Mr("element removal logging",()=>{Dt.logElementRemoves.get()?Element.prototype.removeChild=function(e){return console.warn("[tldraw] removing child:",e),n.call(this,e)}:Element.prototype.removeChild=n})}function tr(n,{defaults:e,shouldStoreForSession:t=!0}){return UU({name:n,defaults:e,shouldStoreForSession:t})}function UU(n){const e=WU(n),t=n.shouldStoreForSession?KU(n.name):null,r=We(`debug:${n.name}`,t??e);return typeof window<"u"&&(n.shouldStoreForSession&&Mr(`debug:${n.name}`,()=>{const s=r.get();s===e?eM(`tldraw_debug:${n.name}`):yv(`tldraw_debug:${n.name}`,JSON.stringify(s))}),Object.defineProperty(window,`tldraw${n.name.replace(/^[a-z]/,s=>s.toUpperCase())}`,{get(){return r.get()},set(s){r.set(s)},configurable:!0})),Object.assign(r,n,{reset:()=>r.set(e)})}function KU(n){try{return JSON.parse(Q_(`tldraw_debug:${n}`)??"null")}catch{return null}}function Dx(n){try{return n()}catch{return null}}function WU(n){switch(Dx(()=>Ax.TLDRAW_ENV)??Dx(()=>Ax.VERCEL_PUBLIC_TLDRAW_ENV)??Dx(()=>Ax.NEXT_PUBLIC_TLDRAW_ENV)??"production"){case"production":return n.defaults.production??n.defaults.all;case"preview":case"staging":return n.defaults.staging??n.defaults.all;default:return n.defaults.development??n.defaults.all}}function zg(n){if(n.nodeType===Node.ELEMENT_NODE)return n;if(n.parentElement)return zg(n.parentElement);throw Error("Could not find a parent element of an HTML type!")}function je(n){n.preventDefault(),Dt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",n)}function Nh(n,e){if(n.setPointerCapture(e.pointerId),Dt.logPointerCaptures.get()){const t=SA.get();t.set(n,(t.get(n)??0)+1),console.warn("setPointerCapture called on element:",n,e)}}function Fh(n,e){if(n.hasPointerCapture(e.pointerId)&&(n.releasePointerCapture(e.pointerId),Dt.logPointerCaptures.get())){const t=SA.get();t.get(n)===1?t.delete(n):t.has(n)?t.set(n,t.get(n)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",n,e)}}const Cn=(n,e,t)=>{n&&n.style.setProperty(e,t)};function xA(n=!1){const{activeElement:e}=document,t=n?["input","textarea"]:["input","select","button","textarea"];return!!(e&&(e.isContentEditable||t.indexOf(e.tagName.toLowerCase())>-1||e.classList.contains("tlui-slider__thumb")))}const Jt=n=>dt.isDarwin?n.metaKey:n.ctrlKey||n.metaKey;function $n(n,e){return n.markEventAsHandled(e),{point:{x:e.clientX,y:e.clientY,z:e.pressure},shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.metaKey||e.ctrlKey,metaKey:e.metaKey,accelKey:Jt(e),pointerId:e.pointerId,button:e.button,isPen:e.pointerType==="pen"}}function Wv(n,e){return py(`${n}_${e}`)}function Yl(n){return py(`${x.useId()}${n??""}`)}function fo(n){const e=Pn(x.useContext(bA));return py(`${e}_${n}`)}function py(n){return n.replace(/:/g,"_")}const bA=x.createContext(null);function VU({children:n}){const e=Yl();return p.jsx(bA.Provider,{value:e,children:n})}const Vv=x.createContext(null);function K(){const n=_e.useContext(Vv);if(!n)throw new Error("useEditor must be used inside of the <Tldraw /> or <TldrawEditor /> components");return n}function Xt(){return _e.useContext(Vv)}function Gv({editor:n,children:e}){return p.jsx(Vv.Provider,{value:n,children:p.jsx(VU,{children:e})})}function fy(){const n=K(),e=n.getContainer().ownerDocument,t=W("current tool",()=>n.getCurrentTool(),[n]),r=x.useMemo(function(){function o(g){if(!n.wasEventAlreadyHandled(g)){if(g.button===Kv){n.dispatch({type:"pointer",target:"canvas",name:"right_click",...$n(n,g)});return}g.button!==0&&g.button!==1&&g.button!==5||(Nh(g.currentTarget,g),n.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...$n(n,g)}))}}function i(g){n.wasEventAlreadyHandled(g)||g.button!==0&&g.button!==1&&g.button!==2&&g.button!==5||(Fh(g.currentTarget,g),n.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...$n(n,g)}))}function a(g){if(n.wasEventAlreadyHandled(g)||n.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const m=g.pointerType==="mouse"||g.pointerType==="pen";n.updateInstanceState({isHoveringCanvas:m?!0:null})}function l(g){if(n.wasEventAlreadyHandled(g)||n.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const m=g.pointerType==="mouse"||g.pointerType==="pen";n.updateInstanceState({isHoveringCanvas:m?!1:null})}function c(g){n.wasEventAlreadyHandled(g)||(n.markEventAsHandled(g),je(g))}function u(g){var y;if(n.wasEventAlreadyHandled(g)||(n.markEventAsHandled(g),!(g.target instanceof HTMLElement)))return;const m=(y=n.getEditingShape())==null?void 0:y.id;!(m&&g.target.closest(`[data-shape-id="${m}"]`))&&g.target.tagName!=="A"&&g.target.tagName!=="TEXTAREA"&&!g.target.isContentEditable&&je(g)}function d(g){n.wasEventAlreadyHandled(g)||je(g)}async function h(g){var y,S;if(n.wasEventAlreadyHandled(g))return;if(je(g),g.stopPropagation(),(S=(y=g.dataTransfer)==null?void 0:y.files)!=null&&S.length){const b=Array.from(g.dataTransfer.files);await n.putExternalContent({type:"files",files:b,point:n.screenToPage({x:g.clientX,y:g.clientY})});return}const m=g.dataTransfer.getData("url");if(m){await n.putExternalContent({type:"url",url:m,point:n.screenToPage({x:g.clientX,y:g.clientY})});return}}function f(g){n.wasEventAlreadyHandled(g)||g.stopPropagation()}return{onPointerDown:o,onPointerUp:i,onPointerEnter:a,onPointerLeave:l,onDragOver:d,onDrop:h,onTouchStart:c,onTouchEnd:u,onClick:f}},[n]);return x.useEffect(()=>{let s,o;function i(a){if(n.wasEventAlreadyHandled(a)||(n.markEventAsHandled(a),a.clientX===s&&a.clientY===o))return;s=a.clientX,o=a.clientY;const l=!dt.isIos&&t.useCoalescedEvents&&a.getCoalescedEvents?a.getCoalescedEvents():[a];for(const c of l)n.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...$n(n,c)})}return e.body.addEventListener("pointermove",i),()=>{e.body.removeEventListener("pointermove",i)}},[n,t,e]),r}function GU(){const n=K();iy("coarse pointer change",()=>{const e=Lu.get().isCoarsePointer,t=gl(()=>n.getInstanceState().isCoarsePointer);e!==t&&n.updateInstanceState({isCoarsePointer:e})},[n])}const wA=x.createContext(null);function vA({container:n,children:e}){return p.jsx(wA.Provider,{value:n,children:e})}function sn(){return Pn(x.useContext(wA),"useContainer used outside of <Tldraw />")}function YU(){const n=K(),e=sn(),t=W("isEditing",()=>n.getEditingShapeId(),[n]),r=W("isFocused",()=>n.getIsFocused(),[n]);x.useEffect(()=>{if(!e)return;function s(o){if(o.isSpecialRedispatchedEvent)return;je(o),o.stopPropagation();const i=e.querySelector(".tl-canvas");if(!i)return;const a=new DragEvent(o.type,o);a.isSpecialRedispatchedEvent=!0,i.dispatchEvent(a)}return e.addEventListener("dragover",s),e.addEventListener("drop",s),()=>{e.removeEventListener("dragover",s),e.removeEventListener("drop",s)}},[e]),x.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;let s=null;const o=()=>{s!=null&&s();const i=`(resolution: ${window.devicePixelRatio}dppx)`,a=matchMedia(i),l=c=>{c.type==="change"&&o()};a.addEventListener?a.addEventListener("change",o):a.addListener&&a.addListener(l),s=()=>{a.removeEventListener?a.removeEventListener("change",o):a.removeListener&&a.removeListener(l)},n.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return o(),()=>{s==null||s()}},[n]),x.useEffect(()=>{if(!r)return;const s=l=>{if(l.altKey&&(n.isIn("zoom")||!n.getPath().endsWith(".idle"))&&!zd(n)&&je(l),n.wasEventAlreadyHandled(l))return;n.markEventAsHandled(l);const c=!!n.getSelectedShapeIds().length;switch(l.key){case"=":case"-":case"0":{if(l.metaKey||l.ctrlKey){je(l);return}break}case"Tab":{if(zd(n))return;c&&!t&&je(l);break}case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{if(zd(n))return;c&&(l.metaKey||l.ctrlKey)&&je(l);break}case",":return;case"Escape":{if((n.getEditingShape()||n.getSelectedShapeIds().length>0)&&je(l),n.menus.getOpenMenus().length>0)return;n.inputs.keys.has("Escape")||(n.inputs.keys.add("Escape"),n.cancel(),e.focus());return}default:if(zd(n))return}const u={type:"keyboard",name:l.repeat?"key_repeat":"key_down",key:l.key,code:l.code,shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:Jt(l)};n.dispatch(u)},o=l=>{if(n.wasEventAlreadyHandled(l)||(n.markEventAsHandled(l),zd(n))||l.key===",")return;const c={type:"keyboard",name:"key_up",key:l.key,code:l.code,shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:Jt(l)};n.dispatch(c)};function i(l){var c,u;if(e.contains(l.target)){const d=l.touches[0].pageX,h=l.touches[0].radiusX||0;(d-h<10||d+h>n.getViewportScreenBounds().width-10)&&(((c=l.target)==null?void 0:c.tagName)==="BUTTON"&&((u=l.target)==null||u.click()),je(l))}}const a=l=>{e.contains(l.target)&&(l.ctrlKey||l.metaKey)&&je(l)};return e.addEventListener("touchstart",i,{passive:!1}),e.addEventListener("wheel",a,{passive:!1}),document.addEventListener("gesturestart",je),document.addEventListener("gesturechange",je),document.addEventListener("gestureend",je),e.addEventListener("keydown",s),e.addEventListener("keyup",o),()=>{e.removeEventListener("touchstart",i),e.removeEventListener("wheel",a),document.removeEventListener("gesturestart",je),document.removeEventListener("gesturechange",je),document.removeEventListener("gestureend",je),e.removeEventListener("keydown",s),e.removeEventListener("keyup",o)}},[n,e,r,t])}function zd(n){return n.menus.hasOpenMenus()||xA()}function XU({className:n,zoom:e,point:t,color:r,viewport:s,opacity:o=1}){const i=x.useRef(null);jh(i,Fe(t.x,s.minX+5/e,s.maxX-5/e),Fe(t.y,s.minY+5/e,s.maxY-5/e),1/e,C.Angle(s.center,t));const a=fo("cursor_hint");return p.jsxs("svg",{ref:i,className:xe("tl-overlays__item",n),"aria-hidden":"true",children:[p.jsx("use",{href:`#${a}`,color:r,strokeWidth:3,stroke:"var(--tl-color-background)"}),p.jsx("use",{href:`#${a}`,color:r,opacity:o})]})}const bT=x.memo(function({className:e,zoom:t,point:r,color:s,name:o,chatMessage:i}){const a=x.useRef(null);jh(a,r==null?void 0:r.x,r==null?void 0:r.y,1/t);const l=fo("cursor");return r?p.jsxs("div",{ref:a,className:xe("tl-overlays__item",e),children:[p.jsx("svg",{className:"tl-cursor","aria-hidden":"true",children:p.jsx("use",{href:`#${l}`,color:s})}),i?p.jsxs(p.Fragment,{children:[o&&p.jsx("div",{className:"tl-nametag-title",style:{color:s},children:o}),p.jsx("div",{className:"tl-nametag-chat",style:{backgroundColor:s},children:i})]}):o&&p.jsx("div",{className:"tl-nametag",style:{backgroundColor:s},children:o})]}):null}),Bh={openWindow(n,e,t=!1){return window.open(n,e,t?"noopener":"noopener noreferrer")},refreshPage(){window.location.reload()},async hardReset(){var n;return await((n=window.__tldraw__hardReset)==null?void 0:n.call(window))}};function CA(){Bh.hardReset()}function qU(){Bh.refreshPage()}const ZU={error:null};class Yv extends x.Component{constructor(){super(...arguments);E(this,"state",ZU)}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t){var r,s;(s=(r=this.props).onError)==null||s.call(r,t)}render(){const{error:t}=this.state;if(t!==null){const{fallback:r}=this.props;return p.jsx(r,{error:t})}return this.props.children}}function ih({children:n,fallback:e,...t}){return e===null?n:p.jsx(Yv,{fallback:e,...t,children:n})}const JU="https://github.com/tldraw/tldraw/issues/new",PA=({error:n,editor:e})=>{const t=x.useRef(null),[r,s]=x.useState(!1),[o,i]=x.useState(!1),[a,l]=x.useState(!1);let c=null;try{c=xt().Canvas??null}catch{}const u=n instanceof Error?n.message:String(n),d=n instanceof Error?n.stack:null,h=W("isDarkMode",()=>{try{if(e)return e.user.getIsDarkMode()}catch{}return null},[e]),[f,g]=x.useState(null);x.useLayoutEffect(()=>{var P;h!==null&&g(h);let w=(P=t.current)==null?void 0:P.parentElement,v=!1;for(;w;){if(w.classList.contains("tl-theme__dark")||w.classList.contains("tl-theme__light")){v=!0;break}w=w.parentElement}if(v){g(null);return}typeof window<"u"&&window.matchMedia&&g(window.matchMedia("(prefers-color-scheme: dark)").matches)},[h]),x.useEffect(()=>{if(o){const w=e==null?void 0:e.timers.setTimeout(()=>{i(!1)},2e3);return()=>clearTimeout(w)}},[o,e]);const m=()=>{const w=document.createElement("textarea");w.value=d??u,document.body.appendChild(w),w.select(),document.execCommand("copy"),w.remove(),i(!0)},y=()=>{qU()},S=async()=>{CA()},b=new URL(JU);return b.searchParams.set("title",u),b.searchParams.set("labels","bug"),b.searchParams.set("body",`Hey, I ran into an error while using tldraw:
57
+
58
+ \`\`\`js
59
+ ${d??u}
60
+ \`\`\`
61
+
62
+ My browser: ${navigator.userAgent}`),p.jsxs("div",{ref:t,className:xe("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[p.jsx("div",{className:"tl-error-boundary__overlay"}),e&&p.jsx(Yv,{onError:eh,fallback:()=>null,children:p.jsx(Gv,{editor:e,children:p.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:c?p.jsx(c,{}):null})})}),p.jsx("div",{className:xe("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?p.jsxs(p.Fragment,{children:[p.jsx("h2",{children:"Are you sure?"}),p.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),p.jsxs("div",{className:"tl-error-boundary__content__actions",children:[p.jsx("button",{className:"tlui-button",onClick:()=>l(!1),children:"Cancel"}),p.jsx("button",{className:"tlui-button tl-error-boundary__reset",onClick:S,children:"Reset data"})]})]}):p.jsxs(p.Fragment,{children:[p.jsx("h2",{children:"Something went wrong"}),p.jsx("p",{children:"Please refresh your browser."}),p.jsx("p",{children:"If the issue continues after refreshing, you may need to reset the tldraw data stored on your device."}),p.jsxs("p",{children:[p.jsx("strong",{children:"Note:"})," Resetting will erase your current project and any unsaved work."]}),!1,r&&p.jsxs(p.Fragment,{children:["Message:",p.jsx("h4",{children:p.jsx("code",{children:u})}),"Stack trace:",p.jsxs("div",{className:"tl-error-boundary__content__error",children:[p.jsx("pre",{children:p.jsx("code",{children:d??u})}),p.jsx("button",{className:"tlui-button",onClick:m,children:o?"Copied!":"Copy"})]})]}),p.jsxs("div",{className:"tl-error-boundary__content__actions",children:[p.jsx("button",{className:"tlui-button",onClick:()=>s(!r),children:r?"Hide details":"Show details"}),p.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[p.jsx("button",{className:"tlui-button tl-error-boundary__reset",onClick:()=>l(!0),children:"Reset data"}),p.jsx("button",{className:"tlui-button tl-error-boundary__refresh",onClick:y,children:"Refresh Page"})]})]})]})})]})};function QU({x:n,y:e,z:t,size:r}){const s=Yl("grid"),o=K(),{gridSteps:i}=o.options;return p.jsxs("svg",{className:"tl-grid",version:"1.1",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[p.jsx("defs",{children:i.map(({min:a,mid:l,step:c},u)=>{const d=c*r*t,h=.5+n*t,f=.5+e*t,g=h>0?h%d:d+h%d,m=f>0?f%d:d+f%d,y=t<l?xo(t,[a,l],[0,1]):1;return p.jsx("pattern",{id:Wv(s,`${c}`),width:d,height:d,patternUnits:"userSpaceOnUse",children:p.jsx("circle",{className:"tl-grid-dot",cx:g,cy:m,r:1,opacity:y})},u)})}),i.map(({step:a},l)=>p.jsx("rect",{width:"100%",height:"100%",fill:`url(#${s}_${a})`},l))]})}function e8({handle:n,isCoarse:e,className:t,zoom:r}){const s=K(),o=(e?s.options.coarseHandleRadius:s.options.handleRadius)/r;if(n.type==="clone"){const a=3/r,l=`M0,${-a} A${a},${a} 0 0,1 0,${a}`,c=$U.indexOf(n.id);return p.jsxs("g",{className:xe(`tl-handle tl-handle__${n.type}`,t),children:[p.jsx("circle",{className:"tl-handle__bg",r:o}),p.jsx("path",{className:"tl-handle__fg",d:l,transform:`rotate(${-90+90*c})`})]})}const i=(n.type==="create"&&e?3:4)/Math.max(r,.25);return p.jsxs("g",{className:xe(`tl-handle tl-handle__${n.type}`,t),children:[p.jsx("circle",{className:"tl-handle__bg",r:o}),p.jsx("circle",{className:"tl-handle__fg",r:i})]})}const t8=({children:n})=>p.jsx("svg",{className:"tl-user-handles tl-overlays__item","aria-hidden":"true",children:n}),Xv="4.4.0",wT={major:"2025-09-18T14:39:22.803Z",minor:"2026-02-18T12:03:50.380Z"};function TA(n,e){const t=x.useRef(n);return e(n,t.current)?t.current:(t.current=n,n)}const n8=(n,e)=>(n??(n=null),e??(e=null),n===e?!0:!n||!e?!1:bg(n,e));function Sa(n){return TA(n,n8)}const r8=(n,e)=>(n??(n=null),e??(e=null),n===e?!0:!n||!e?!1:V_(n,e));function yd(n){return TA(n,r8)}const IA="TLDRAW_USER_DATA_v3",EA=tt({id:Ke,name:Ke.nullable().optional(),color:Ke.nullable().optional(),locale:Ke.nullable().optional(),animationSpeed:Be.nullable().optional(),areKeyboardShortcutsEnabled:Ve.nullable().optional(),edgeScrollSpeed:Be.nullable().optional(),colorScheme:Da("light","dark","system").optional(),isSnapMode:Ve.nullable().optional(),isWrapMode:Ve.nullable().optional(),isDynamicSizeMode:Ve.nullable().optional(),isPasteAtCursorMode:Ve.nullable().optional(),enhancedA11yMode:Ve.nullable().optional(),inputMode:Da("trackpad","mouse").nullable().optional(),isZoomDirectionInverted:Ve.nullable().optional()}),Hr={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5,AddDynamicSizeMode:6,AllowSystemColorScheme:7,AddPasteAtCursor:8,AddKeyboardShortcuts:9,AddShowUiLabels:10,AddPointerPeripheral:11,RenameShowUiLabelsToEnhancedA11yMode:12,AddZoomDirectionInverted:13},qv=Math.max(...Object.values(Hr));function s8(n){n.version<Hr.AddAnimationSpeed&&(n.user.animationSpeed=1),n.version<Hr.AddIsSnapMode&&(n.user.isSnapMode=!1),n.version<Hr.MakeFieldsNullable,n.version<Hr.AddEdgeScrollSpeed&&(n.user.edgeScrollSpeed=1),n.version<Hr.AddExcalidrawSelectMode&&(n.user.isWrapMode=!1),n.version<Hr.AllowSystemColorScheme&&(n.user.isDarkMode===!0?n.user.colorScheme="dark":n.user.isDarkMode===!1&&(n.user.colorScheme="light"),delete n.user.isDarkMode),n.version<Hr.AddDynamicSizeMode&&(n.user.isDynamicSizeMode=!1),n.version<Hr.AddPasteAtCursor&&(n.user.isPasteAtCursorMode=!1),n.version<Hr.AddKeyboardShortcuts&&(n.user.areKeyboardShortcutsEnabled=!0),n.version<Hr.AddShowUiLabels&&(n.user.showUiLabels=!1),n.version<Hr.RenameShowUiLabelsToEnhancedA11yMode&&(n.user.enhancedA11yMode=n.user.showUiLabels,delete n.user.showUiLabels),n.version<Hr.AddPointerPeripheral&&(n.user.inputMode=null),n.version<Hr.AddZoomDirectionInverted&&(n.user.isZoomDirectionInverted=!1),n.version=qv}const Mw=["#FF802B","#EC5E41","#F2555A","#F04F88","#E34BA9","#BD54C6","#9D5BD2","#7B66DC","#02B1CC","#11B3A3","#39B178","#55B467"];function kA(){return Mw[Math.floor(Math.random()*Mw.length)]}function o8(){var n,e;return typeof window<"u"&&window.matchMedia?((e=(n=window.matchMedia)==null?void 0:n.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1:!1}const Cr=Object.freeze({name:"",locale:kU(),color:kA(),edgeScrollSpeed:1,animationSpeed:o8()?0:1,areKeyboardShortcutsEnabled:!0,isSnapMode:!1,isWrapMode:!1,isDynamicSizeMode:!1,isPasteAtCursorMode:!1,enhancedA11yMode:!1,colorScheme:"light",inputMode:null,isZoomDirectionInverted:!1});function Ox(){return{id:at(),color:kA()}}function _A(n){if(n===null||typeof n!="object"||!("version"in n)||!("user"in n)||typeof n.version!="number")return Ox();const e=Ft(n);s8(e);try{return EA.validate(e.user)}catch{return Ox()}}function i8(){const n=JSON.parse(gv(IA)||"null")??null;return _A(n)}const gy=We("globalUserData",null);function a8(){mv(IA,JSON.stringify({version:qv,user:gy.get()}))}function MA(n){EA.validate(n),gy.set(n),a8(),l8()}const Bc=typeof BroadcastChannel<"u"?new BroadcastChannel("tldraw-user-sync"):null;Bc==null||Bc.addEventListener("message",n=>{const e=n.data;(e==null?void 0:e.type)===DA&&(e==null?void 0:e.origin)!==AA()&&gy.set(_A(e.data))});let Rx=null;function AA(){return Rx===null&&(Rx=at()),Rx}const DA="tldraw-user-preferences-change";function l8(){Bc==null||Bc.postMessage({type:DA,origin:AA(),data:{user:OA(),version:qv}})}function OA(){let n=gy.get();return n||(n=i8(),MA(n)),n}const c8=q("defaultLocalStorageUserPrefs",()=>OA());function RA(n={}){return{userPreferences:n.userPreferences??c8,setUserPreferences:n.setUserPreferences??MA}}var Lx={exports:{}},vT;function d8(){return vT||(vT=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,d||l,h),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function i(l,c){--l._eventsCount===0?l._events=new r:delete l._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,d;if(this._eventsCount===0)return c;for(d in u=this._events)e.call(u,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=t?t+c:c,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,g=new Array(f);h<f;h++)g[h]=d[h].fn;return g},a.prototype.listenerCount=function(c){var u=t?t+c:c,d=this._events[u];return d?d.fn?1:d.length:0},a.prototype.emit=function(c,u,d,h,f,g){var m=t?t+c:c;if(!this._events[m])return!1;var y=this._events[m],S=arguments.length,b,w;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),S){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,u),!0;case 3:return y.fn.call(y.context,u,d),!0;case 4:return y.fn.call(y.context,u,d,h),!0;case 5:return y.fn.call(y.context,u,d,h,f),!0;case 6:return y.fn.call(y.context,u,d,h,f,g),!0}for(w=1,b=new Array(S-1);w<S;w++)b[w-1]=arguments[w];y.fn.apply(y.context,b)}else{var v=y.length,P;for(w=0;w<v;w++)switch(y[w].once&&this.removeListener(c,y[w].fn,void 0,!0),S){case 1:y[w].fn.call(y[w].context);break;case 2:y[w].fn.call(y[w].context,u);break;case 3:y[w].fn.call(y[w].context,u,d);break;case 4:y[w].fn.call(y[w].context,u,d,h);break;default:if(!b)for(P=1,b=new Array(S-1);P<S;P++)b[P-1]=arguments[P];y[w].fn.apply(y[w].context,b)}}return!0},a.prototype.on=function(c,u,d){return o(this,c,u,d,!1)},a.prototype.once=function(c,u,d){return o(this,c,u,d,!0)},a.prototype.removeListener=function(c,u,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!u)return i(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!h||g.once)&&(!d||g.context===d)&&i(this,f);else{for(var m=0,y=[],S=g.length;m<S;m++)(g[m].fn!==u||h&&!g[m].once||d&&g[m].context!==d)&&y.push(g[m]);y.length?this._events[f]=y.length===1?y[0]:y:i(this,f)}return this},a.prototype.removeAllListeners=function(c){var u;return c?(u=t?t+c:c,this._events[u]&&i(this,u)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,n.exports=a})(Lx)),Lx.exports}var u8=d8();const h8=Ua(u8),zc="TLDRAW_TAB_ID_v2",ji=globalThis.window;function p8(){return ji?["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(ji.navigator.platform)||dt.isDarwin&&"ontouchend"in document:!1}const $g=ji?ji[zc]??Q_(zc)??"TLDRAW_INSTANCE_STATE_V1_"+at():"<error>";ji&&(ji[zc]=$g,p8()?yv(zc,$g):eM(zc));ji==null||ji.addEventListener("beforeunload",()=>{yv(zc,$g)});const LA={Initial:0},my=Math.max(...Object.values(LA));function f8(n){n.version<LA.Initial,n.version=my}const jA=tt({version:Be,currentPageId:sh.optional(),isFocusMode:Ve.optional(),exportBackground:Ve.optional(),isDebugMode:Ve.optional(),isToolLocked:Ve.optional(),isGridMode:Ve.optional(),pageStates:Bn(tt({pageId:sh,camera:tt({x:Be,y:Be,z:Be}).optional(),selectedShapeIds:Bn(Rs).optional(),focusedGroupId:Rs.nullable().optional()})).optional()});function g8(n){if(!n||typeof n!="object")return console.warn("Invalid instance state"),null;if(!("version"in n)||typeof n.version!="number")return console.warn("No version in instance state"),null;n.version!==my&&(n=Ft(n),f8(n));try{return jA.validate(n)}catch(e){return console.warn(e),null}}function Zv(n){const e=n.query.ids("page");return q("sessionStateSnapshot",()=>{const t=n.get(Er);if(!t)return null;const r=[...e.get()];return{version:my,currentPageId:t.currentPageId,exportBackground:t.exportBackground,isFocusMode:t.isFocusMode,isDebugMode:t.isDebugMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,pageStates:r.map(s=>{const o=n.get(uo.createId(s)),i=n.get(zo.createId(s));return{pageId:s,camera:{x:(i==null?void 0:i.x)??0,y:(i==null?void 0:i.y)??0,z:(i==null?void 0:i.z)??1},selectedShapeIds:(o==null?void 0:o.selectedShapeIds)??[],focusedGroupId:(o==null?void 0:o.focusedGroupId)??null}})}},{isEqual:So})}function Aw(n,e,t){const r=g8(e);if(!r)return;const s=zM(n.get(Er)),o=t!=null&&t.forceOverwrite?r:s,i=t!=null&&t.forceOverwrite?s:r,a=n.schema.types.instance.create({id:Er,...s,currentPageId:r.currentPageId,isDebugMode:(o==null?void 0:o.isDebugMode)??(i==null?void 0:i.isDebugMode),isFocusMode:(o==null?void 0:o.isFocusMode)??(i==null?void 0:i.isFocusMode),isToolLocked:(o==null?void 0:o.isToolLocked)??(i==null?void 0:i.isToolLocked),isGridMode:(o==null?void 0:o.isGridMode)??(i==null?void 0:i.isGridMode),exportBackground:(o==null?void 0:o.exportBackground)??(i==null?void 0:i.exportBackground)});n.atomic(()=>{var l,c,u;for(const d of r.pageStates??[]){if(!n.has(d.pageId))continue;const h=zo.createId(d.pageId),f=uo.createId(d.pageId),g=n.get(h),m=n.get(f);n.put([zo.create({id:h,x:((l=d.camera)==null?void 0:l.x)??(g==null?void 0:g.x),y:((c=d.camera)==null?void 0:c.y)??(g==null?void 0:g.y),z:((u=d.camera)==null?void 0:u.z)??(g==null?void 0:g.z)}),uo.create({id:f,pageId:d.pageId,selectedShapeIds:d.selectedShapeIds??(m==null?void 0:m.selectedShapeIds),focusedGroupId:d.focusedGroupId??(m==null?void 0:m.focusedGroupId)})])}n.put([a]),n.ensureStoreIsUsable()})}function m8(n){var s;const e=[];for(const o of Object.values(n))(s=o.typeName)!=null&&s.match(/^(instance.*|pointer|camera)$/)&&e.push(o);const t=e.filter(o=>o.typeName==="instance"&&o.id!==Er)[0];if(!t)return null;const r={version:my,currentPageId:t.currentPageId,exportBackground:!!t.exportBackground,isFocusMode:!!t.isFocusMode,isDebugMode:!!t.isDebugMode,isToolLocked:!!t.isToolLocked,isGridMode:!1,pageStates:e.filter(o=>o.typeName==="instance_page_state"&&o.instanceId===t.id).map(o=>{const i=n[o.cameraId]??{x:0,y:0,z:1};return{pageId:o.pageId,camera:{x:i.x,y:i.y,z:i.z},selectedShapeIds:o.selectedShapeIds,focusedGroupId:o.focusedGroupId}})};try{return jA.validate(r),r}catch{return null}}function NA(n,e,t){let r={};if("store"in e){const i=n.schema.migrateStoreSnapshot(e);if(i.type!=="success")throw new Error("Failed to migrate store snapshot: "+i.reason);r.document={schema:n.schema.serialize(),store:Du(i.value,(a,{typeName:l})=>n.scopedTypes.document.has(l))}}else r=e;const s=zM(n.get(Er)),o=FA.get(n,Zv).get();n.atomic(()=>{r.document&&n.loadStoreSnapshot(r.document),s&&n.update(Er,i=>({...i,...s})),o&&Aw(n,o),r.session&&Aw(n,r.session,{forceOverwrite:t==null?void 0:t.forceOverwriteSessionState})})}const FA=new Vn;function y8(n){const t=FA.get(n,Zv).get();if(!t)throw new Error("Session state is not ready yet");return{document:n.getStoreSnapshot(),session:t}}function BA(n){const e=[],t=new Set;for(const r of n){if(t.has(r.type))throw new Error(`Binding type "${r.type}" is defined more than once`);e.push(r),t.add(r.type)}return e}function Ra({children:n,className:e="",...t}){return p.jsx("svg",{...t,className:xe("tl-svg-container",e),"aria-hidden":"true",children:n})}class J{constructor(e=0,t=0,r=0,s=0){E(this,"x",0);E(this,"y",0);E(this,"w",0);E(this,"h",0);this.x=e,this.y=t,this.w=r,this.h=s}get point(){return new C(this.x,this.y)}set point(e){this.x=e.x,this.y=e.y}get minX(){return this.x}set minX(e){this.x=e}get left(){return this.x}get midX(){return this.x+this.w/2}get maxX(){return this.x+this.w}get right(){return this.x+this.w}get minY(){return this.y}set minY(e){this.y=e}get top(){return this.y}get midY(){return this.y+this.h/2}get maxY(){return this.y+this.h}get bottom(){return this.y+this.h}get width(){return this.w}set width(e){this.w=e}get height(){return this.h}set height(e){this.h=e}get aspectRatio(){return this.width/this.height}get center(){return new C(this.x+this.w/2,this.y+this.h/2)}set center(e){this.x=e.x-this.w/2,this.y=e.y-this.h/2}get corners(){return[new C(this.x,this.y),new C(this.x+this.w,this.y),new C(this.x+this.w,this.y+this.h),new C(this.x,this.y+this.h)]}get cornersAndCenter(){return[new C(this.x,this.y),new C(this.x+this.w,this.y),new C(this.x+this.w,this.y+this.h),new C(this.x,this.y+this.h),new C(this.x+this.w/2,this.y+this.h/2)]}get sides(){const{corners:e}=this;return[[e[0],e[1]],[e[1],e[2]],[e[2],e[3]],[e[3],e[0]]]}get size(){return new C(this.w,this.h)}isValid(){return Number.isFinite(this.x)&&Number.isFinite(this.y)&&Number.isFinite(this.w)&&Number.isFinite(this.h)}toFixed(){return this.x=Bp(this.x),this.y=Bp(this.y),this.w=Bp(this.w),this.h=Bp(this.h),this}setTo(e){return this.x=e.x,this.y=e.y,this.w=e.w,this.h=e.h,this}set(e=0,t=0,r=0,s=0){return this.x=e,this.y=t,this.w=r,this.h=s,this}expand(e){const t=Math.min(this.x,e.x),r=Math.min(this.y,e.y),s=Math.max(this.x+this.w,e.x+e.w),o=Math.max(this.y+this.h,e.y+e.h);return this.x=t,this.y=r,this.w=s-t,this.h=o-r,this}expandBy(e){return this.x-=e,this.y-=e,this.w+=e*2,this.h+=e*2,this}scale(e){return this.x/=e,this.y/=e,this.w/=e,this.h/=e,this}clone(){const{x:e,y:t,w:r,h:s}=this;return new J(e,t,r,s)}translate(e){return this.x+=e.x,this.y+=e.y,this}snapToGrid(e){const t=Math.round(this.x/e)*e,r=Math.round(this.y/e)*e,s=Math.round((this.x+this.w)/e)*e,o=Math.round((this.y+this.h)/e)*e;this.minX=t,this.minY=r,this.width=Math.max(1,s-t),this.height=Math.max(1,o-r)}collides(e){return J.Collides(this,e)}contains(e){return J.Contains(this,e)}includes(e){return J.Includes(this,e)}containsPoint(e,t=0){return J.ContainsPoint(this,e,t)}getHandlePoint(e){switch(e){case"top_left":return new C(this.x,this.y);case"top_right":return new C(this.x+this.w,this.y);case"bottom_left":return new C(this.x,this.y+this.h);case"bottom_right":return new C(this.x+this.w,this.y+this.h);case"top":return new C(this.x+this.w/2,this.y);case"right":return new C(this.x+this.w,this.y+this.h/2);case"bottom":return new C(this.x+this.w/2,this.y+this.h);case"left":return new C(this.x,this.y+this.h/2)}}toJson(){return{x:this.x,y:this.y,w:this.w,h:this.h}}resize(e,t,r){const{minX:s,minY:o,maxX:i,maxY:a}=this;let{minX:l,minY:c,maxX:u,maxY:d}=this;switch(e){case"left":case"top_left":case"bottom_left":{l+=t;break}case"right":case"top_right":case"bottom_right":{u+=t;break}}switch(e){case"top":case"top_left":case"top_right":{c+=r;break}case"bottom":case"bottom_left":case"bottom_right":{d+=r;break}}const h=(u-l)/(i-s),f=(d-c)/(a-o),g=h<0,m=f<0;if(g){const y=u;u=l,l=y}if(m){const y=d;d=c,c=y}this.minX=l,this.minY=c,this.width=Math.abs(u-l),this.height=Math.abs(d-c)}union(e){const t=Math.min(this.x,e.x),r=Math.min(this.y,e.y),s=Math.max(this.x+this.w,e.x+e.w),o=Math.max(this.y+this.h,e.y+e.h);return this.x=t,this.y=r,this.width=s-t,this.height=o-r,this}static From(e){return new J(e.x,e.y,e.w,e.h)}static FromCenter(e,t){return new J(e.x-t.x/2,e.y-t.y/2,t.x,t.y)}static FromPoints(e){if(e.length===0)return new J;let t=1/0,r=1/0,s=-1/0,o=-1/0,i;for(let a=0,l=e.length;a<l;a++)i=e[a],t=Math.min(i.x,t),r=Math.min(i.y,r),s=Math.max(i.x,s),o=Math.max(i.y,o);return new J(t,r,s-t,o-r)}static Expand(e,t){const r=Math.min(t.minX,e.minX),s=Math.min(t.minY,e.minY),o=Math.max(t.maxX,e.maxX),i=Math.max(t.maxY,e.maxY);return new J(r,s,o-r,i-s)}static ExpandBy(e,t){return new J(e.minX-t,e.minY-t,e.width+t*2,e.height+t*2)}static Collides(e,t){return!(e.maxX<t.minX||e.minX>t.maxX||e.maxY<t.minY||e.minY>t.maxY)}static Contains(e,t){return e.minX<t.minX&&e.minY<t.minY&&e.maxY>t.maxY&&e.maxX>t.maxX}static ContainsApproximately(e,t,r){return va(e.minX,t.minX,r)&&va(e.minY,t.minY,r)&&va(t.maxX,e.maxX,r)&&va(t.maxY,e.maxY,r)}static Includes(e,t){return J.Collides(e,t)||J.Contains(e,t)}static ContainsPoint(e,t,r=0){return!(t.x<e.minX-r||t.y<e.minY-r||t.x>e.maxX+r||t.y>e.maxY+r)}static Common(e){let t=1/0,r=1/0,s=-1/0,o=-1/0;for(let i=0;i<e.length;i++){const a=e[i];t=Math.min(t,a.minX),r=Math.min(r,a.minY),s=Math.max(s,a.maxX),o=Math.max(o,a.maxY)}return new J(t,r,s-t,o-r)}static Sides(e,t=0){const{corners:r}=e;return[[r[0],r[1]],[r[1],r[2]],[r[2],r[3]],[r[3],r[0]]]}static Resize(e,t,r,s,o=!1){const{minX:i,minY:a,maxX:l,maxY:c}=e;let{minX:u,minY:d,maxX:h,maxY:f}=e;switch(t){case"left":case"top_left":case"bottom_left":{u+=r;break}case"right":case"top_right":case"bottom_right":{h+=r;break}}switch(t){case"top":case"top_left":case"top_right":{d+=s;break}case"bottom":case"bottom_left":case"bottom_right":{f+=s;break}}const g=(h-u)/(l-i),m=(f-d)/(c-a),y=g<0,S=m<0;if(o){const w=(l-i)/(c-a),v=Math.abs(h-u),P=Math.abs(f-d),T=v*(m<0?1:-1)*(1/w),I=P*(g<0?1:-1)*w,k=w<v/P;switch(t){case"top_left":{k?d=f+T:u=h+I;break}case"top_right":{k?d=f+T:h=u-I;break}case"bottom_right":{k?f=d-T:h=u-I;break}case"bottom_left":{k?f=d-T:u=h+I;break}case"bottom":case"top":{const A=(u+h)/2,R=P*w;u=A-R/2,h=A+R/2;break}case"left":case"right":{const A=(d+f)/2,R=v/w;d=A-R/2,f=A+R/2;break}}}if(y){const w=h;h=u,u=w}if(S){const w=f;f=d,d=w}const b=new J(u,d,Math.abs(h-u),Math.abs(f-d));return{box:b,scaleX:+(b.width/e.width*(g>0?1:-1)).toFixed(5),scaleY:+(b.height/e.height*(m>0?1:-1)).toFixed(5)}}equals(e){return J.Equals(this,e)}static Equals(e,t){return t.x===e.x&&t.y===e.y&&t.w===e.w&&t.h===e.h}zeroFix(){return this.w=Math.max(1,this.w),this.h=Math.max(1,this.h),this}static ZeroFix(e){return new J(e.x,e.y,Math.max(1,e.w),Math.max(1,e.h))}}function S8(n){switch(n){case"top":return"bottom";case"bottom":return"top";case"top_left":return"bottom_left";case"top_right":return"bottom_right";case"bottom_left":return"top_left";case"bottom_right":return"top_right";default:return n}}function x8(n){switch(n){case"left":return"right";case"right":return"left";case"top_left":return"top_right";case"top_right":return"top_left";case"bottom_left":return"bottom_right";case"bottom_right":return"bottom_left";default:return n}}function b8(n){return n==="top_left"||n==="top_right"||n==="bottom_right"||n==="bottom_left"}class Q{constructor(e,t,r,s,o,i){E(this,"a",1);E(this,"b",0);E(this,"c",0);E(this,"d",1);E(this,"e",0);E(this,"f",0);this.a=e,this.b=t,this.c=r,this.d=s,this.e=o,this.f=i}equals(e){return this===e||this.a===e.a&&this.b===e.b&&this.c===e.c&&this.d===e.d&&this.e===e.e&&this.f===e.f}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this}multiply(e){const t=e,{a:r,b:s,c:o,d:i,e:a,f:l}=this;return this.a=r*t.a+o*t.b,this.c=r*t.c+o*t.d,this.e=r*t.e+o*t.f+a,this.b=s*t.a+i*t.b,this.d=s*t.c+i*t.d,this.f=s*t.e+i*t.f+l,this}rotate(e,t,r){return e===0?this:t===void 0?this.multiply(Q.Rotate(e)):this.translate(t,r).multiply(Q.Rotate(e)).translate(-t,-r)}translate(e,t){return this.multiply(Q.Translate(e,t))}scale(e,t){return this.multiply(Q.Scale(e,t))}invert(){const{a:e,b:t,c:r,d:s,e:o,f:i}=this,a=e*s-t*r;return this.a=s/a,this.b=t/-a,this.c=r/-a,this.d=e/a,this.e=(s*o-r*i)/-a,this.f=(t*o-e*i)/a,this}applyToPoint(e){return Q.applyToPoint(this,e)}applyToPoints(e){return Q.applyToPoints(this,e)}rotation(){return Q.Rotation(this)}point(){return Q.Point(this)}decomposed(){return Q.Decompose(this)}toCssString(){return Q.toCssString(this)}setTo(e){return Object.assign(this,e),this}decompose(){return Q.Decompose(this)}clone(){return new Q(this.a,this.b,this.c,this.d,this.e,this.f)}static Identity(){return new Q(1,0,0,1,0,0)}static Translate(e,t){return new Q(1,0,0,1,e,t)}static Rotate(e,t,r){if(e===0)return Q.Identity();const s=Math.cos(e),o=Math.sin(e),i=new Q(s,o,-o,s,0,0);return t===void 0?i:Q.Compose(Q.Translate(t,r),i,Q.Translate(-t,-r))}static Scale(e,t,r,s){const o=new Q(e,0,0,t,0,0);return r===void 0?o:Q.Translate(r,s).multiply(o).translate(-r,-s)}static Multiply(e,t){return{a:e.a*t.a+e.c*t.b,c:e.a*t.c+e.c*t.d,e:e.a*t.e+e.c*t.f+e.e,b:e.b*t.a+e.d*t.b,d:e.b*t.c+e.d*t.d,f:e.b*t.e+e.d*t.f+e.f}}static Inverse(e){const t=e.a*e.d-e.b*e.c;return{a:e.d/t,b:e.b/-t,c:e.c/-t,d:e.a/t,e:(e.d*e.e-e.c*e.f)/-t,f:(e.b*e.e-e.a*e.f)/t}}static Absolute(e){const t=e.a*e.d-e.b*e.c;return{a:e.d/t,b:e.b/-t,c:e.c/-t,d:e.a/t,e:(e.d*e.e-e.c*e.f)/t,f:(e.b*e.e-e.a*e.f)/-t}}static Compose(...e){const t=Q.Identity();for(let r=0,s=e.length;r<s;r++)t.multiply(e[r]);return t}static Point(e){return new C(e.e,e.f)}static Rotation(e){let t;if(e.a!==0||e.c!==0){const r=(e.a*e.a+e.c*e.c)**.5;t=Math.acos(e.a/r)*(e.c>0?-1:1)}else if(e.b!==0||e.d!==0){const r=(e.b*e.b+e.d*e.d)**.5;t=Bt+Math.acos(e.b/r)*(e.d>0?-1:1)}else t=0;return kw(t)}static Decompose(e){let t,r,s;if(e.a!==0||e.c!==0){const o=(e.a*e.a+e.c*e.c)**.5;t=o,r=(e.a*e.d-e.b*e.c)/o,s=Math.acos(e.a/o)*(e.c>0?-1:1)}else if(e.b!==0||e.d!==0){const o=(e.b*e.b+e.d*e.d)**.5;t=(e.a*e.d-e.b*e.c)/o,r=o,s=Bt+Math.acos(e.b/o)*(e.d>0?-1:1)}else t=0,r=0,s=0;return{x:e.e,y:e.f,scaleX:t,scaleY:r,rotation:kw(s)}}static Smooth(e,t=1e10){return e.a=Math.round(e.a*t)/t,e.b=Math.round(e.b*t)/t,e.c=Math.round(e.c*t)/t,e.d=Math.round(e.d*t)/t,e.e=Math.round(e.e*t)/t,e.f=Math.round(e.f*t)/t,e}static toCssString(e){return`matrix(${$(e.a)}, ${$(e.b)}, ${$(e.c)}, ${$(e.d)}, ${$(e.e)}, ${$(e.f)})`}static applyToPoint(e,t){return new C(e.a*t.x+e.c*t.y+e.e,e.b*t.x+e.d*t.y+e.f,t.z)}static applyToXY(e,t,r){return[e.a*t+e.c*r+e.e,e.b*t+e.d*r+e.f]}static applyToPoints(e,t){return t.map(r=>new C(e.a*r.x+e.c*r.y+e.e,e.b*r.x+e.d*r.y+e.f,r.z))}static applyToBounds(e,t){return new J(e.e+t.minX,e.f+t.minY,t.width,t.height)}static From(e){return new Q(e.a,e.b,e.c,e.d,e.e,e.f)}static Cast(e){return e instanceof Q?e:Q.From(e)}}function yy(n,e,t,r,s=1e-10){const o=n.x-t.x,i=n.y-t.y,a=r.x-t.x,l=r.y-t.y,c=e.x-n.x,u=e.y-n.y,d=a*i-l*o,h=c*i-u*o,f=l*c-a*u;if(tn(d,0,s)||tn(h,0,s)||tn(f,0,s))return null;if(f!==0){const g=d/f,m=h/f;if(va(0,g,s)&&va(g,1,s)&&va(0,m,s)&&va(m,1,s))return C.AddXY(n,g*c,g*u)}return null}function zh(n,e,t,r){const s=(e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y),o=2*((e.x-n.x)*(n.x-t.x)+(e.y-n.y)*(n.y-t.y)),i=t.x*t.x+t.y*t.y+n.x*n.x+n.y*n.y-2*(t.x*n.x+t.y*n.y)-r*r,a=o*o-4*s*i;if(a<0||a===0)return null;const l=Math.sqrt(a),c=(-o+l)/(2*s),u=(-o-l)/(2*s);if((c<0||c>1)&&(u<0||u>1))return null;const d=[];return 0<=c&&c<=1&&d.push(C.Lrp(n,e,c)),0<=u&&u<=1&&d.push(C.Lrp(n,e,u)),d.length===0?null:d}function w8(n,e,t){const r=[];let s;for(let o=0,i=t.length-1;o<i;o++)s=yy(n,e,t[o],t[o+1]),s&&r.push(s);return r.length===0?null:r}function zA(n,e,t){const r=[];let s;for(let o=1,i=t.length;o<i+1;o++)s=yy(n,e,t[o-1],t[o%t.length]),s&&r.push(s);return r.length===0?null:r}function v8(n,e,t,r){let s=t.x-n.x,o=t.y-n.y;const i=Math.sqrt(s*s+o*o),a=(i*i-r*r+e*e)/(2*i),l=Math.sqrt(e*e-a*a);return s/=i,o/=i,[new C(n.x+s*a-o*l,n.y+o*a+s*l),new C(n.x+s*a+o*l,n.y+o*a-s*l)]}function C8(n,e,t){const r=[];let s,o,i;for(let a=0,l=t.length;a<l;a++)s=t[a],o=t[(a+1)%t.length],i=zh(s,o,n,e),i&&r.push(...i);return r.length===0?null:r}function P8(n,e,t){const r=[];let s,o,i;for(let a=1,l=t.length;a<l;a++)s=t[a-1],o=t[a],i=zh(s,o,n,e),i&&r.push(...i);return r.length===0?null:r}function $p(n,e,t){return(t.y-n.y)*(e.x-n.x)>(e.y-n.y)*(t.x-n.x)}function Jv(n,e,t,r){return $p(n,t,r)!==$p(e,t,r)&&$p(n,e,t)!==$p(n,e,r)}function Hg(n,e){const t=new Map;let r,s,o,i;for(let a=0,l=n.length;a<l;a++)if(r=n[a],kr(r,e)){const c=Nf(r);t.has(c)||t.set(c,r)}for(let a=0,l=e.length;a<l;a++)if(r=e[a],kr(r,n)){const c=Nf(r);t.has(c)||t.set(c,r)}for(let a=0,l=n.length;a<l;a++){r=n[a],s=n[(a+1)%n.length];for(let c=0,u=e.length;c<u;c++){o=e[c],i=e[(c+1)%e.length];const d=yy(r,s,o,i);if(d!==null){const h=Nf(d);t.has(h)||t.set(h,d)}}}return t.size===0?null:T8([...t.values()])}function CT(n,e,t,r){const s=new Map;for(let o=0,i=t?n.length:n.length-1;o<i;o++){const a=n[o],l=n[(o+1)%n.length];for(let c=0,u=r?e.length:e.length-1;c<u;c++){const d=e[c],h=e[(c+1)%e.length],f=yy(a,l,d,h);if(f!==null){const g=Nf(f);s.has(g)||s.set(g,f)}}}return[...s.values()]}function Nf(n){return`${n.x},${n.y}`}function T8(n){const e=C.Average(n);return n.sort((t,r)=>C.Angle(e,t)-C.Angle(e,r))}function $A(n,e){let t,r,s,o;for(let i=0,a=n.length;i<a;i++){t=n[i],r=n[(i+1)%a];for(let l=0,c=e.length;l<c;l++)if(s=e[l],o=e[(l+1)%c],Jv(t,r,s,o))return!0}return!1}function I8(n,e){let t,r,s,o;for(let i=0,a=n.length;i<a;i++){t=n[i],r=n[(i+1)%a];for(let l=1,c=e.length;l<c;l++)if(s=e[l-1],o=e[l],Jv(t,r,s,o))return!0}return!1}const Ko={EXCLUDE_NON_STANDARD:{includeLabels:!1,includeInternal:!1},EXCLUDE_LABELS:{includeLabels:!1,includeInternal:!0}};class Ya{constructor(e){E(this,"isFilled",!1);E(this,"isClosed",!0);E(this,"isLabel",!1);E(this,"isEmptyLabel",!1);E(this,"isInternal",!1);E(this,"excludeFromShapeBounds",!1);E(this,"debugColor");E(this,"ignore");E(this,"_vertices");E(this,"_boundsVertices");E(this,"_bounds");E(this,"_area");E(this,"_length");const{isLabel:t=!1,isEmptyLabel:r=!1,isInternal:s=!1,excludeFromShapeBounds:o=!1}=e;this.isFilled=e.isFilled,this.isClosed=e.isClosed,this.debugColor=e.debugColor,this.ignore=e.ignore,this.isLabel=t,this.isEmptyLabel=r,this.isInternal=s,this.excludeFromShapeBounds=o}isExcludedByFilter(e){return e?!!(this.isLabel&&!e.includeLabels||this.isInternal&&!e.includeInternal):!1}hitTestPoint(e,t=0,r=!1,s){return this.isClosed&&(this.isFilled||r)&&kr(e,this.vertices)?!0:C.Dist2(e,this.nearestPoint(e))<=t*t}distanceToPoint(e,t=!1,r){return C.Dist(e,this.nearestPoint(e,r))*(this.isClosed&&(this.isFilled||t)&&kr(e,this.vertices)?-1:1)}distanceToLineSegment(e,t,r){if(C.Equals(e,t))return this.distanceToPoint(e,!1,r);const{vertices:s}=this;if(s.length===0)throw Error("nearest point not found");if(s.length===1)return C.Dist(e,s[0]);let o,i=1/0,a,l,c;const u=this.isClosed?s.length:s.length-1;for(let d=0;d<s.length;d++){if(l=s[d],d<u){const h=s[(d+1)%s.length];if(Jv(e,t,l,h))return 0}c=C.NearestPointOnLineSegment(e,t,l,!0),a=C.Dist2(l,c),a<i&&(i=a,o=c)}if(!o)throw Error("nearest point not found");return i=Math.sqrt(i),this.isClosed&&this.isFilled&&kr(o,this.vertices)?-i:i}hitTestLineSegment(e,t,r=0,s){return this.distanceToLineSegment(e,t,s)<=r}intersectLineSegment(e,t,r){return(this.isClosed?zA(e,t,this.vertices):w8(e,t,this.vertices))??[]}intersectCircle(e,t,r){return(this.isClosed?C8(e,t,this.vertices):P8(e,t,this.vertices))??[]}intersectPolygon(e,t){return CT(e,this.vertices,!0,this.isClosed)}intersectPolyline(e,t){return CT(e,this.vertices,!1,this.isClosed)}interpolateAlongEdge(e,t){const{vertices:r}=this;if(r.length===0)return new C(0,0);if(r.length===1||e<=0)return r[0];const s=e*this.length;let o=0;for(let i=0;i<(this.isClosed?r.length:r.length-1);i++){const a=r[i],l=r[(i+1)%r.length],c=C.Dist(a,l),u=o+c;if(u>=s)return C.Lrp(a,l,nh(o,u,s));o=u}return this.isClosed?r[0]:r[r.length-1]}uninterpolateAlongEdge(e,t){const{vertices:r,length:s}=this;let o=null,i=1/0,a=0;if(r.length===0||r.length===1)return 0;for(let c=0;c<(this.isClosed?r.length:r.length-1);c++){const u=r[c],d=r[(c+1)%r.length],h=C.NearestPointOnLineSegment(u,d,e,!0),f=C.Dist(h,e);f<i&&(i=f,o={start:u,end:d,nearestPoint:h,distanceToStart:a}),a+=C.Dist(u,d)}return be(o),(o.distanceToStart+C.Dist(o.start,o.nearestPoint))/s}isPointInBounds(e,t=0){const{bounds:r}=this;return!(e.x<r.minX-t||e.y<r.minY-t||e.x>r.maxX+t||e.y>r.maxY+t)}overlapsPolygon(e){const t=e.map(l=>C.From(l)),{vertices:r,center:s,isFilled:o,isEmptyLabel:i,isClosed:a}=this;if(i)return!1;if(r.some(l=>kr(l,t)))return!0;if(a){if(o&&(kr(s,t)||t.every(l=>kr(l,r)))||$A(t,r))return!0}else if(I8(t,r))return!0;return!1}transform(e,t){return new Qv(this,e,t)}get vertices(){return this._vertices||(this._vertices=this.getVertices(Ko.EXCLUDE_LABELS)),this._vertices}getBoundsVertices(){return this.excludeFromShapeBounds?[]:this.vertices}get boundsVertices(){return this._boundsVertices||(this._boundsVertices=this.getBoundsVertices()),this._boundsVertices}getBounds(){return J.FromPoints(this.boundsVertices)}get bounds(){return this._bounds||(this._bounds=this.getBounds()),this._bounds}get center(){return this.bounds.center}get area(){return this._area||(this._area=this.getArea()),this._area}getArea(){if(!this.isClosed)return 0;const{vertices:e}=this;let t=0;for(let r=0,s=e.length;r<s;r++){const o=e[r],i=e[(r+1)%s];t+=o.x*i.y-i.x*o.y}return t/2}toSimpleSvgPath(){let e="";const{vertices:t}=this,r=t.length;if(r===0)return e;e+=`M${t[0].x},${t[0].y}`;for(let s=1;s<r;s++)e+=`L${t[s].x},${t[s].y}`;return this.isClosed&&(e+="Z"),e}get length(){return this._length?this._length:(this._length=this.getLength(Ko.EXCLUDE_LABELS),this._length)}getLength(e){const t=this.getVertices(e??Ko.EXCLUDE_LABELS);if(t.length===0)return 0;let r=t[0],s=0;for(let o=1;o<t.length;o++){const i=t[o];s+=C.Dist(r,i),r=i}return this.isClosed&&(s+=C.Dist(t[t.length-1],t[0])),s}}class Qv extends Ya{constructor(t,r,s){super(t);E(this,"inverse");E(this,"decomposed");this.geometry=t,this.matrix=r,this.inverse=Q.Inverse(r),this.decomposed=Q.Decompose(r),s&&(s.isLabel!=null&&(this.isLabel=s.isLabel),s.isInternal!=null&&(this.isInternal=s.isInternal),s.debugColor!=null&&(this.debugColor=s.debugColor),s.ignore!=null&&(this.ignore=s.ignore)),be(tn(this.decomposed.scaleX,this.decomposed.scaleY),"non-uniform scaling is not yet supported")}getVertices(t){return this.geometry.getVertices(t).map(r=>Q.applyToPoint(this.matrix,r))}getBoundsVertices(){return this.geometry.getBoundsVertices().map(t=>Q.applyToPoint(this.matrix,t))}nearestPoint(t,r){return Q.applyToPoint(this.matrix,this.geometry.nearestPoint(Q.applyToPoint(this.inverse,t),r))}hitTestPoint(t,r=0,s,o){return this.geometry.hitTestPoint(Q.applyToPoint(this.inverse,t),r/this.decomposed.scaleX,s,o)}distanceToPoint(t,r=!1,s){return this.geometry.distanceToPoint(Q.applyToPoint(this.inverse,t),r,s)*this.decomposed.scaleX}distanceToLineSegment(t,r,s){return this.geometry.distanceToLineSegment(Q.applyToPoint(this.inverse,t),Q.applyToPoint(this.inverse,r),s)*this.decomposed.scaleX}hitTestLineSegment(t,r,s=0,o){return this.geometry.hitTestLineSegment(Q.applyToPoint(this.inverse,t),Q.applyToPoint(this.inverse,r),s/this.decomposed.scaleX,o)}intersectLineSegment(t,r,s){return Q.applyToPoints(this.matrix,this.geometry.intersectLineSegment(Q.applyToPoint(this.inverse,t),Q.applyToPoint(this.inverse,r),s))}intersectCircle(t,r,s){return Q.applyToPoints(this.matrix,this.geometry.intersectCircle(Q.applyToPoint(this.inverse,t),r/this.decomposed.scaleX,s))}intersectPolygon(t,r){return Q.applyToPoints(this.matrix,this.geometry.intersectPolygon(Q.applyToPoints(this.inverse,t),r))}intersectPolyline(t,r){return Q.applyToPoints(this.matrix,this.geometry.intersectPolyline(Q.applyToPoints(this.inverse,t),r))}transform(t,r){return new Qv(this.geometry,Q.Multiply(t,this.matrix),{isLabel:(r==null?void 0:r.isLabel)??this.isLabel,isInternal:(r==null?void 0:r.isInternal)??this.isInternal,debugColor:(r==null?void 0:r.debugColor)??this.debugColor,ignore:(r==null?void 0:r.ignore)??this.ignore})}getSvgPathData(){throw new Error("Cannot get SVG path data for transformed geometry.")}}class es extends Ya{constructor(t){super({...t,isClosed:!0,isFilled:!1});E(this,"children",[]);E(this,"ignoredChildren",[]);const r=s=>{for(const o of s)o instanceof es?r(o.children):o.ignore?this.ignoredChildren.push(o):this.children.push(o)};if(r(t.children),this.children.length===0)throw Error("Group2d must have at least one child")}getVertices(t){return this.isExcludedByFilter(t)?[]:this.children.filter(r=>!r.isExcludedByFilter(t)).flatMap(r=>r.getVertices(t))}nearestPoint(t,r){let s=1/0,o;const{children:i}=this;if(i.length===0)throw Error("no children");let a,l;for(const c of i)c.isExcludedByFilter(r)||(a=c.nearestPoint(t,r),l=C.Dist2(a,t),l<s&&(s=l,o=a));if(!o)throw Error("nearest point not found");return o}distanceToPoint(t,r=!1,s){let o=1/0;for(const i of this.children){if(i.isExcludedByFilter(s))continue;const a=i.distanceToPoint(t,r,s);a<o&&(o=a)}return o}hitTestPoint(t,r,s,o=Ko.EXCLUDE_LABELS){return!!this.children.filter(i=>!i.isExcludedByFilter(o)).find(i=>i.hitTestPoint(t,r,s))}hitTestLineSegment(t,r,s,o=Ko.EXCLUDE_LABELS){return!!this.children.filter(i=>!i.isExcludedByFilter(o)).find(i=>i.hitTestLineSegment(t,r,s))}intersectLineSegment(t,r,s){return this.children.flatMap(o=>o.isExcludedByFilter(s)?Yt:o.intersectLineSegment(t,r,s))}intersectCircle(t,r,s){return this.children.flatMap(o=>o.isExcludedByFilter(s)?Yt:o.intersectCircle(t,r,s))}getBoundsVertices(){return this.excludeFromShapeBounds?[]:this.children.flatMap(t=>t.getBoundsVertices())}intersectPolygon(t,r){return this.children.flatMap(s=>s.isExcludedByFilter(r)?Yt:s.intersectPolygon(t,r))}intersectPolyline(t,r){return this.children.flatMap(s=>s.isExcludedByFilter(r)?Yt:s.intersectPolyline(t,r))}interpolateAlongEdge(t,r){const s=this.getLength(r),o=t*s;let i=0;for(const a of this.children){if(a.isExcludedByFilter(r))continue;const l=a.length,c=i+l;if(c>=o)return a.interpolateAlongEdge(nh(i,c,o),r);i=c}return this.children[this.children.length-1].interpolateAlongEdge(1,r)}uninterpolateAlongEdge(t,r){const s=this.getLength(r);let o=null,i=1/0,a=0;for(const u of this.children){if(u.isExcludedByFilter(r))continue;const d=u.getLength(r),h=a+d,f=u.distanceToPoint(t,!1,r);f<i&&(i=f,o={startLength:a,endLength:h,child:u}),a=h}be(o);const l=o.child.uninterpolateAlongEdge(t,r);return Ue(o.startLength,o.endLength,l)/s}transform(t){return new es({children:this.children.map(r=>r.transform(t)),isLabel:this.isLabel,debugColor:this.debugColor,ignore:this.ignore})}getArea(){return this.children[0].area}toSimpleSvgPath(){let t="";for(const s of this.children)t+=s.toSimpleSvgPath();const r=J.FromPoints(this.boundsVertices).corners;for(let s=0,o=r.length;s<o;s++){const i=r[s],a=r[(s-1+o)%o],l=i.dist(a),c=r[(s+1)%o],u=i.dist(c),d=i.clone().lrp(a,4/l),h=i,f=i.clone().lrp(c,4/u);t+=`M${d.x},${d.y} L${h.x},${h.y} L${f.x},${f.y} `}return t}getLength(t){let r=0;for(const s of this.children)s.isExcludedByFilter(t)||(r+=s.length);return r}getSvgPathData(){return this.children.map((t,r)=>t.isLabel?"":t.getSvgPathData(r===0)).join(" ")}overlapsPolygon(t){return this.children.some(r=>r.overlapsPolygon(t))}}class Qc extends Ya{constructor(t){super({...t,isClosed:!1,isFilled:!1});E(this,"_start");E(this,"_end");E(this,"_d");E(this,"_u");E(this,"_ul");const{start:r,end:s}=t;this._start=r,this._end=s,this._d=r.clone().sub(s),this._u=this._d.clone().uni(),this._ul=this._u.len()}getLength(){return this._d.len()}getVertices(){return[this._start,this._end]}nearestPoint(t){const{_start:r,_end:s,_d:o,_u:i,_ul:a}=this;if(o.len()===0||a===0)return r;const l=C.Sub(t,r).dpr(i)/a,c=r.x+i.x*l;if(c<Math.min(r.x,s.x))return r.x<s.x?r:s;if(c>Math.max(r.x,s.x))return r.x>s.x?r:s;const u=r.y+i.y*l;return u<Math.min(r.y,s.y)?r.y<s.y?r:s:u>Math.max(r.y,s.y)?r.y>s.y?r:s:new C(c,u)}getSvgPathData(t=!0){const{_start:r,_end:s}=this;return`${t?`M${r.toFixed()}`:""} L${s.toFixed()}`}}class $h extends Ya{constructor(t){super({isClosed:!1,isFilled:!1,...t});E(this,"_points");E(this,"_segments");const{points:r}=t;if(this._points=r,r.length<2)throw new Error("Polyline2d: points must be an array of at least 2 points")}get segments(){if(!this._segments){this._segments=[];const{vertices:t}=this;for(let r=0,s=t.length-1;r<s;r++){const o=t[r],i=t[r+1];this._segments.push(new Qc({start:o,end:i}))}this.isClosed&&this._segments.push(new Qc({start:t[t.length-1],end:t[0]}))}return this._segments}getLength(){return this.segments.reduce((t,r)=>t+r.length,0)}getVertices(){return this._points}nearestPoint(t){const{segments:r}=this;let s=this._points[0],o=1/0,i,a;for(let l=0;l<r.length;l++)i=r[l].nearestPoint(t),a=C.Dist2(i,t),a<o&&(s=i,o=a);if(!s)throw Error("nearest point not found");return s}hitTestLineSegment(t,r,s=0){const{segments:o}=this;for(let i=0,a=o.length;i<a;i++)if(o[i].hitTestLineSegment(t,r,s))return!0;return!1}getSvgPathData(){const{vertices:t}=this;return t.length<2?"":t.reduce((r,s,o)=>o===0?`M ${s.x} ${s.y}`:`${r} L ${s.x} ${s.y}`,"")}}class ah extends $h{constructor(e){if(super({...e}),this.isClosed=!0,e.points.length<3)throw new Error("Polygon2d: points must be an array of at least 3 points")}}class bo extends ah{constructor(t){const{x:r=0,y:s=0,width:o,height:i}=t;super({...t,points:[new C(r,s),new C(r+o,s),new C(r+o,s+i),new C(r,s+i)]});E(this,"_x");E(this,"_y");E(this,"_w");E(this,"_h");this._x=r,this._y=s,this._w=o,this._h=i}getBounds(){return new J(this._x,this._y,this._w,this._h)}getSvgPathData(){const{_x:t,_y:r,_w:s,_h:o}=this;return this.negativeZeroFix(),`M${t},${r} h${s} v${o} h${-s}z`}negativeZeroFix(){this._x=Hp(this._x),this._y=Hp(this._y),this._w=Hp(this._w),this._h=Hp(this._h)}}function Hp(n){return Object.is(n,-0)?0:n}class go{constructor(e){E(this,"options",{});this.editor=e}static configure(e){return class extends this{constructor(){super(...arguments);E(this,"options",{...this.options,...e})}}}useLegacyIndicator(){return!0}getIndicatorPath(e){}getFontFaces(e){return Yt}canSnap(e){return!0}canTabTo(e){return!0}canScroll(e){return!1}canBind(e){return!0}canEdit(e,t){return!1}canResize(e){return!0}canResizeChildren(e){return!0}canEditInReadonly(e){return!1}canEditWhileLocked(e){return!1}canCrop(e){return!1}canBeLaidOut(e,t){return!0}canCull(e){return!0}providesBackgroundForChildren(e){return!1}hideResizeHandles(e){return!1}hideRotateHandle(e){return!1}hideSelectionBoundsBg(e){return!1}hideSelectionBoundsFg(e){return!1}isAspectRatioLocked(e){return!1}isExportBoundsContainer(e){return!1}canReceiveNewChildrenOfType(e,t){return!1}expandSelectionOutlinePx(e){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{}}getText(e){}getAriaDescriptor(e){}}E(go,"props"),E(go,"migrations"),E(go,"type");function HA(n,e,t={}){const{closed:r=!1,snap:s=1,start:o="outset",end:i="outset",lengthRatio:a=2,style:l="dashed",forceSolid:c=!1}=t;let u=0,d=0,h=1,f=0,g=0;if(c)return{strokeDasharray:"none",strokeDashoffset:"none"};switch(l){case"dashed":{h=1,u=Math.min(e*a,n/4);break}case"dotted":{h=100,u=e/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(o==="outset"?(n+=u/2,g+=u/2):o==="skip"&&(n-=u,g-=u),i==="outset"?n+=u/2:i==="skip"&&(n-=u)),d=Math.floor(n/u/(2*h)),d-=d%s,d<3&&l==="dashed"?n/e<4?(u=n,d=1,f=0):(u=n*(1/3),f=n*(1/3)):(u=n/d/(2*h),r?(g=u/2,f=(n-d*u)/d):f=(n-d*u)/Math.max(1,d-1)),{strokeDasharray:[u,f].join(" "),strokeDashoffset:g.toString()}}function PT({bounds:n,className:e}){const t=K(),r=W("zoom level",()=>t.getEfficientZoomLevel(),[t]);return p.jsx("g",{className:e,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:n.sides.map((s,o)=>{const{strokeDasharray:i,strokeDashoffset:a}=HA(s[0].dist(s[1]),1/r,{style:"dashed",lengthRatio:4});return p.jsx("line",{x1:s[0].x,y1:s[0].y,x2:s[1].x,y2:s[1].y,strokeDasharray:i,strokeDashoffset:a},o)})})}class Ff extends go{hideSelectionBoundsFg(){return!0}canBind(){return!1}canResize(){return!0}canResizeChildren(){return!0}getDefaultProps(){return{}}getGeometry(e){const t=this.editor.getSortedChildIdsForParent(e.id);return t.length===0?new bo({width:1,height:1,isFilled:!1}):new es({children:t.map(r=>{const s=this.editor.getShape(r);return this.editor.getShapeGeometry(r).transform(this.editor.getShapeLocalTransform(s),{isLabel:!1})})})}component(e){const t=this.editor.getErasingShapeIds().includes(e.id),{hintingShapeIds:r}=this.editor.getCurrentPageState(),s=r.length>0&&r.some(a=>a!==e.id&&this.editor.isShapeOfType(this.editor.getShape(a),"group")),o=this.editor.getCurrentPageState().focusedGroupId!==e.id;if(!t&&(o||s))return null;const i=this.editor.getShapeGeometry(e).bounds;return p.jsx(Ra,{children:p.jsx(PT,{className:"tl-group",bounds:i})})}indicator(e){const t=this.editor.getShapeGeometry(e).bounds;return p.jsx(PT,{className:"",bounds:t})}onChildrenChange(e){const t=this.editor.getSortedChildIdsForParent(e.id);if(t.length===0){this.editor.getCurrentPageState().focusedGroupId===e.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([e.id]);return}else if(t.length===1){this.editor.getCurrentPageState().focusedGroupId===e.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(t,e.parentId),this.editor.deleteShapes([e.id]);return}}}E(Ff,"type","group"),E(Ff,"props",eA),E(Ff,"migrations",tA);const UA=[Ff],E8=new Set(UA.map(n=>n.type));function KA(n){const e=[...UA],t=new Set;for(const r of n){if(E8.has(r.type))throw new Error(`Shape type "${r.type}" is a core shapes type and cannot be overridden`);if(t.has(r.type))throw new Error(`Shape type "${r.type}" is defined more than once`);e.push(r),t.add(r.type)}return e}var Vi=f4();const k8=Ua(Vi);function WA(n,e){const t=new Map;return async function(s){const o=t.get(s);if(o)return o;const i=(async()=>{try{const a=await $i(s,e);return be(a.ok),await n(a)}catch(a){return console.error(a),null}})();return t.set(s,i),i}}const Sy=WA(async n=>await ir.blobToDataUrl(await n.blob())),_8=/@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]+);/gi,M8=/@font-face\s*{([^}]+)}/gi,VA=/url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\)/gi,A8=/(?:^|;)\s*font-family\s*:\s*(?:([^'"][^;\n]+)|"([^"]+)"|'([^']+)')\s*(?:;|$)/gi;function D8(n){return Array.from(n.matchAll(_8),e=>({url:e[1]||e[2]||e[3]||e[4]||e[5],extras:e[6]}))}function GA(n,e){return Array.from(n.matchAll(M8),t=>{const r=t[1],s=Array.from(r.matchAll(VA),i=>{var l;const a=i[1]||i[2]||i[3];return{original:a,resolved:((l=ze(a,e))==null?void 0:l.href)??null}}),o=new Set(Array.from(r.matchAll(A8),i=>(i[1]||i[2]||i[3]).toLowerCase()));return{fontFace:r,urls:s,fontFamilies:o}})}function O8(n){const e=/\s*(?:([^'"][^;\n\s,]+)|"([^"]+)"|'([^']+)')\s*/gi,t=/\s*,\s*/gi,r=new Set;for(;;){const s=e.exec(n);if(!s)break;const o=s[1]||s[2]||s[3];if(r.add(o.toLowerCase()),t.lastIndex=e.lastIndex,!t.exec(n))break;e.lastIndex=t.lastIndex}return r}function YA(n){return!(n.startsWith("-")||n.startsWith("animation")||n.startsWith("transition")||n==="cursor"||n==="pointer-events"||n==="user-select"||n==="touch-action")}function R8(n,e){return{imports:D8(n),fontFaces:GA(n,e)}}function L8(n){return Array.from(n.matchAll(VA),e=>({original:e[0],url:e[1]||e[2]||e[3]})).filter(e=>!e.url.startsWith("#"))}var j8=Object.create,XA=Object.defineProperty,N8=Object.getOwnPropertyDescriptor,F8=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),qA=n=>{throw TypeError(n)},ZA=(n,e,t)=>e in n?XA(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,B8=n=>[,,,j8(null)],JA=["class","method","getter","setter","accessor","field","value","get","set"],QA=n=>n!==void 0&&typeof n!="function"?qA("Function expected"):n,z8=(n,e,t,r,s)=>({kind:JA[n],name:e,metadata:r,addInitializer:o=>t._?qA("Already initialized"):s.push(QA(o||null))}),$8=(n,e)=>ZA(e,F8("metadata"),n[3]),H8=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},U8=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=JA[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,N8(s,t)),S=r.length-1;S>=0;S--)l=z8(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,QA(i)&&(y[g]=i);return y&&XA(s,t,y),s},Up=(n,e,t)=>ZA(n,typeof e!="symbol"?e+"":e,t),e2,xy;const t2="tldraw-svg-export";e2=[Xr];class e1{constructor(){H8(xy,5,this),Up(this,"fontFacesPromise",null),Up(this,"foundFontNames",new Set),Up(this,"fontFacesToEmbed",new Set),Up(this,"pendingPromises",[])}startFindingCurrentDocumentFontFaces(){be(!this.fontFacesPromise,"FontEmbedder already started"),this.fontFacesPromise=K8()}onFontFamilyValue(e){be(this.fontFacesPromise,"FontEmbedder not started");const t=O8(e);for(const r of t){if(this.foundFontNames.has(r))return;this.foundFontNames.add(r),this.pendingPromises.push(this.fontFacesPromise.then(s=>{const o=s.filter(i=>i.fontFamilies.has(r));for(const i of o)if(!this.fontFacesToEmbed.has(i)){this.fontFacesToEmbed.add(i);for(const a of i.urls)!a.resolved||a.embedded||(a.embedded=Sy(a.resolved))}}))}}async createCss(){await Promise.all(this.pendingPromises);let e="";for(const t of this.fontFacesToEmbed){let r=`@font-face {${t.fontFace}}`;for(const s of t.urls){if(!s.embedded)continue;const o=await s.embedded;o&&(r=r.replace(s.original,o))}e+=r}return e}}xy=B8();U8(xy,1,"onFontFamilyValue",e2,e1);$8(xy,e1);async function K8(){var t;const n=[],e=Array.from(document.styleSheets).filter(r=>{var s;return!((s=r.ownerNode)!=null&&s.closest(`.${t2}`))});for(const r of e){let s;try{s=r.cssRules}catch{}if(s){for(const o of r.cssRules)if(o instanceof CSSFontFaceRule)n.push(GA(o.cssText,r.href??document.baseURI));else if(o instanceof CSSImportRule){const i=new URL(o.href,((t=o.parentStyleSheet)==null?void 0:t.href)??document.baseURI);n.push(Dw(i.href))}}else r.href&&n.push(Dw(r.href))}return Le(await Promise.all(n)).flat()}const Dw=WA(async n=>{const e=R8(await n.text(),n.url),t=await Promise.all(e.imports.map(({url:r})=>Dw(new URL(r,n.url).href)));return[...e.fontFaces,...Le(t).flat()]}),cs=(n,e,{currentColor:t})=>n==="currentColor"||n===t,Qe=(n,e,{parentStyles:t})=>t[e]===n,jt=n=>(e,t,{getStyle:r})=>{const s=r(`border-${n}-width`),o=r(`border-${n}-style`);return s==="0px"||o==="none"},n2={"border-block-end-color":cs,"border-block-start-color":cs,"border-bottom-color":cs,"border-inline-end-color":cs,"border-inline-start-color":cs,"border-left-color":cs,"border-right-color":cs,"border-top-color":cs,"caret-color":cs,"column-rule-color":cs,"outline-color":cs,"text-decoration":(n,e,{currentColor:t})=>n==="none solid currentColor"||n==="none solid "+t,"text-decoration-color":cs,"text-emphasis-color":cs,"border-collapse":Qe,"border-spacing":Qe,"caption-side":Qe,cursor:Qe,direction:Qe,"empty-cells":Qe,"font-family":Qe,"font-size":Qe,"font-style":Qe,"font-variant":Qe,"font-weight":Qe,"font-size-adjust":Qe,"font-stretch":Qe,font:Qe,"letter-spacing":Qe,"line-height":Qe,"list-style-image":Qe,"list-style-position":Qe,"list-style-type":Qe,"list-style":Qe,orphans:Qe,"overflow-wrap":Qe,quotes:Qe,"stroke-linecap":Qe,"stroke-linejoin":Qe,"tab-size":Qe,"text-align":Qe,"text-align-last":Qe,"text-indent":Qe,"text-justify":Qe,"text-shadow":Qe,"text-transform":Qe,visibility:Qe,"white-space":Qe,"white-space-collapse":Qe,widows:Qe,"word-break":Qe,"word-spacing":Qe,"word-wrap":Qe,"border-top":jt("top"),"border-right":jt("right"),"border-bottom":jt("bottom"),"border-left":jt("left"),"border-block-end":jt("block-end"),"border-block-start":jt("block-start"),"border-inline-end":jt("inline-end"),"border-inline-start":jt("inline-start"),"border-top-style":jt("top"),"border-right-style":jt("right"),"border-bottom-style":jt("bottom"),"border-left-style":jt("left"),"border-block-end-style":jt("block-end"),"border-block-start-style":jt("block-start"),"border-inline-end-style":jt("inline-end"),"border-inline-start-style":jt("inline-start"),"border-top-width":jt("top"),"border-right-width":jt("right"),"border-bottom-width":jt("bottom"),"border-left-width":jt("left"),"border-block-end-width":jt("block-end"),"border-block-start-width":jt("block-start"),"border-inline-end-width":jt("inline-end")};function r2(n){if(n.shadowRoot)return n.shadowRoot.childNodes;if(Y8(n)){const e=n.assignedNodes();if(e!=null&&e.length)return e}return n.childNodes}function*Ow(n){for(const e of r2(n))W8(e)&&(yield e)}function by(n){var e;return((e=n.ownerDocument)==null?void 0:e.defaultView)??globalThis}function W8(n){return n instanceof by(n).Element}function V8(n){return n instanceof by(n).ShadowRoot}function G8(n){return"getRootNode"in n&&V8(n.getRootNode())}function Y8(n){return G8(n)&&n instanceof by(n).HTMLSlotElement}function X8(n){return n.style}function t1(n,e){return by(n).getComputedStyle(n,e)}const ed={};class q8{constructor(e){E(this,"styles",new Map);E(this,"fonts",new e1);this.root=e}readRootElementStyles(e){this.readElementStyles(e,{shouldRespectDefaults:!1,shouldSkipInheritedParentStyles:!1});const t=Array.from(Ow(e));for(;t.length;){const r=t.pop();t.push(...Ow(r)),this.readElementStyles(r,{shouldRespectDefaults:!0,shouldSkipInheritedParentStyles:!0})}}readElementStyles(e,{shouldRespectDefaults:t=!0,shouldSkipInheritedParentStyles:r=!0}){var a;const s=t?e9(e.tagName.toLowerCase()):ed,o=Object.assign({},ed);if(r){let l=e.parentElement;for(;l;){const c=(a=this.styles.get(l))==null?void 0:a.self;for(const u in c)o[u]||(o[u]=c[u]);l=l.parentElement}}const i={self:Z8(e,{defaultStyles:s,parentStyles:o}),before:TT(e,"::before"),after:TT(e,"::after")};this.styles.set(e,i)}fetchResources(){const e=[];for(const t of this.styles.values())for(const r of Et(t))if(r)for(const[s,o]of Object.entries(r)){if(!o)continue;s==="font-family"&&this.fonts.onFontFamilyValue(o);const i=L8(o);i.length!==0&&e.push(...i.map(async({url:a,original:l})=>{const c=await Sy(a)??"data:";r[s]=o.replace(l,`url("${c}")`)}))}return Promise.all(e)}unwrapCustomElements(){const e=new Set,t=(r,s)=>{if(e.has(r))return;e.add(r);const o=r.shadowRoot;if(o){const i=document.createElement("div");this.styles.set(i,this.styles.get(r)),i.setAttribute("data-tl-custom-element",r.tagName),(s??r.parentElement).appendChild(i);for(const a of o.childNodes)a instanceof Element?t(a,i):i.appendChild(a.cloneNode(!0));r.remove()}else if(s){if(r.tagName.toLowerCase()==="style")return;const i=r.cloneNode(!1);this.styles.set(i,this.styles.get(r)),s.appendChild(i);for(const a of r2(r))a instanceof Element?t(a,i):i.appendChild(a.cloneNode(!0))}};for(const r of this.styles.keys())t(r,null)}embedStyles(){let e="";for(const[t,r]of this.styles){if(r.after||r.before){const o=`pseudo-${at()}`;t.classList.add(o),r.before&&(e+=`.${o}::before {${IT(r.before)}}
63
+ `),r.after&&(e+=`.${o}::after {${IT(r.after)}}
64
+ `)}const s=X8(t);for(const[o,i]of Object.entries(r.self))i&&s.setProperty(o,i);s.fontKerning==="auto"&&(s.fontKerning="normal")}return e}async getFontFaceCss(){return await this.fonts.createCss()}dispose(){Q8()}}function Z8(n,{defaultStyles:e,parentStyles:t}){return n.computedStyleMap?s2(n.computedStyleMap(),{defaultStyles:e,parentStyles:t}):n1(t1(n),{defaultStyles:e,parentStyles:t})}function TT(n,e){const t=t1(n,e),r=t.getPropertyValue("content");if(!(r===""||r==="none"))return n1(t,{defaultStyles:ed,parentStyles:ed})}function s2(n,{defaultStyles:e,parentStyles:t}){var i;const r={},o={currentColor:((i=n.get("color"))==null?void 0:i.toString())||"",parentStyles:t,defaultStyles:e,getStyle:a=>{var l;return((l=n.get(a))==null?void 0:l.toString())??""}};for(const a of n.keys()){if(!YA(a))continue;const l=n.get(a).toString();if(e[a]===l)continue;const c=un(n2,a);c&&c(l,a,o)||(r[a]=l)}return r}function n1(n,{defaultStyles:e,parentStyles:t}){const r={},o={currentColor:n.color,parentStyles:t,defaultStyles:e,getStyle:i=>n.getPropertyValue(i)};for(const i in n){if(!YA(i))continue;const a=n.getPropertyValue(i);if(e[i]===a)continue;const l=un(n2,i);l&&l(a,i,o)||(r[i]=a)}return r}function IT(n){let e="";for(const[t,r]of Object.entries(n))e+=`${t}: ${r};`;return e}let $c;const ET={};function J8(){if(!$c){const n=document.createElement("iframe");n.style.display="none",document.body.appendChild(n);const e=Pn(n.contentDocument,"frame must have a document"),t=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");t.appendChild(r),e.body.appendChild(t),$c={iframe:n,foreignObject:r,document:e}}return $c}function Q8(){$c&&(document.body.removeChild($c.iframe),$c=void 0)}const kT={defaultStyles:ed,parentStyles:ed};function e9(n){let e=ET[n];if(!e){const{foreignObject:t,document:r}=J8(),s=r.createElement(n);t.appendChild(s),e=s.computedStyleMap?s2(s.computedStyleMap(),kT):n1(t1(s),kT),t.removeChild(s),ET[n]=e}return e}function t9(n,e){Array.from(n.attributes).forEach(r=>{e.setAttribute(r.name,r.value)})}function _T(n,e){return n.replaceWith(e),e}async function ju(n,e){const t=document.createElement("img");e&&t9(e,t),t.setAttribute("src",n??"data:"),t.setAttribute("decoding","sync"),t.setAttribute("loading","eager");try{await t.decode()}catch{}return t}async function n9(n){try{const e=n.toDataURL();return await ju(e,n)}catch{return await ju(null,n)}}async function r9(n){try{const e=await fs.getVideoFrameAsDataUrl(n);return ju(e,n)}catch(e){console.error("Could not get video frame",e)}if(n.poster){const e=await Sy(n.poster);return ju(e,n)}return ju(null,n)}async function o2(n){if(n instanceof HTMLCanvasElement)return _T(n,await n9(n));if(n instanceof HTMLVideoElement)return _T(n,await r9(n));if(n instanceof HTMLImageElement){const e=n.currentSrc||n.src,t=await Sy(e);n.setAttribute("src",t??"data:"),n.setAttribute("decoding","sync"),n.setAttribute("loading","eager");try{await n.decode()}catch{}return n}else n instanceof HTMLInputElement?n.setAttribute("value",n.value):n instanceof HTMLTextAreaElement&&(n.textContent=n.value);await Promise.all(Array.from(Ow(n),e=>o2(e)))}const i2=x.createContext(null);function s9({children:n}){const e=x.useRef(new Map),t=x.useCallback((i,a,l,c)=>{const u=c?"none":"block";Cn(a,"display",u),Cn(l,"display",u),e.current.set(i,{container:a,bgContainer:l,isCulled:c})},[]),r=x.useCallback(i=>{e.current.delete(i)},[]),s=x.useCallback(i=>{for(const[a,l]of e.current){const c=i.has(a);if(c!==l.isCulled){const u=c?"none":"block";Cn(l.container,"display",u),Cn(l.bgContainer,"display",u),l.isCulled=c}}},[]),o=x.useMemo(()=>({register:t,unregister:r,updateCulling:s}),[t,r,s]);return p.jsx(i2.Provider,{value:o,children:n})}function a2(){const n=x.useContext(i2);if(!n)throw new Error("useShapeCulling must be used within ShapeCullingProvider");return n}const Rw=(n,e)=>n.props===e.props&&n.meta===e.meta,l2=x.memo(function({id:e,shape:t,util:r,index:s,backgroundIndex:o,opacity:i}){const a=K(),{ShapeErrorFallback:l,ShapeWrapper:c}=xt(),u=x.useRef(null),d=x.useRef(null);x.useEffect(()=>Mr("load fonts",()=>{const y=a.fonts.getShapeFontFaces(e);a.fonts.requestFonts(y)}),[a,e]);const h=x.useRef({transform:"",clipPath:"none",width:0,height:0,x:0,y:0});Va("set shape stuff",()=>{const y=a.getShape(e);if(!y)return;const S=h.current,b=a.getShapeClipPath(e)??"none";b!==S.clipPath&&(Cn(u.current,"clip-path",b),Cn(d.current,"clip-path",b),S.clipPath=b);const w=a.getShapePageTransform(e),v=Q.toCssString(w),P=a.getShapeGeometry(y).bounds;v!==S.transform&&(Cn(u.current,"transform",v),Cn(d.current,"transform",v),S.transform=v);const T=Math.max(P.width,1),I=Math.max(P.height,1);(T!==S.width||I!==S.height)&&(Cn(u.current,"width",T+"px"),Cn(u.current,"height",I+"px"),Cn(d.current,"width",T+"px"),Cn(d.current,"height",I+"px"),S.width=T,S.height=I)},[a]),x.useLayoutEffect(()=>{const y=u.current,S=d.current;Cn(y,"opacity",i),Cn(S,"opacity",i),Cn(y,"z-index",s),Cn(S,"z-index",o)},[i,s,o]);const{register:f,unregister:g}=a2();x.useLayoutEffect(()=>{const y=u.current;if(!y)return;const S=a.getCulledShapes().has(e);return f(e,y,d.current,S),()=>{g(e)}},[a,e,f,g]);const m=x.useCallback(y=>a.annotateError(y,{origin:"shape",willCrashApp:!1}),[a]);return!t||!c?null:p.jsxs(p.Fragment,{children:[r.backgroundComponent&&p.jsx(c,{ref:d,shape:t,isBackground:!0,children:p.jsx(ih,{fallback:l,onError:m,children:p.jsx(d2,{shape:t,util:r})})}),p.jsx(c,{ref:u,shape:t,isBackground:!1,children:p.jsx(ih,{fallback:l,onError:m,children:p.jsx(c2,{shape:t,util:r})})})]})}),c2=x.memo(function({shape:e,util:t}){return oy("InnerShape:"+e.type,()=>t.component(t.editor.store.unsafeGetWithoutCapture(e.id)),[t,e.id])},(n,e)=>Rw(n.shape,e.shape)&&n.util===e.util),d2=x.memo(function({shape:e,util:t}){return oy("InnerShape:"+e.type,()=>{var r;return(r=t.backgroundComponent)==null?void 0:r.call(t,t.editor.store.unsafeGetWithoutCapture(e.id))},[t,e.id])},(n,e)=>n.shape.props===e.shape.props&&n.shape.meta===e.shape.meta&&n.util===e.util);function No(n){const e=x.useRef(void 0);return x.useLayoutEffect(()=>{e.current=n}),x.useDebugValue(n),x.useCallback((...t)=>{const r=e.current;return be(r,"fn does not exist"),r(...t)},[])}const r1=x.createContext(null);function o9({context:n,editor:e,children:t}){const r=e.options.exportProvider;return p.jsx(Gv,{editor:e,children:p.jsx(vA,{container:e.getContainer(),children:p.jsx(r1.Provider,{value:n,children:p.jsx(r,{children:t})})})})}function Hh(){return x.useContext(r1)}function i9(){const n=x.useContext(r1),[e]=x.useState(hv);return x.useEffect(()=>(n==null||n.waitUntil(e),()=>{e.resolve()}),[e,n]),No(()=>{e.resolve()})}var a9=Object.create,u2=Object.defineProperty,l9=Object.getOwnPropertyDescriptor,c9=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),h2=n=>{throw TypeError(n)},p2=(n,e,t)=>e in n?u2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,d9=n=>[,,,a9(null)],f2=["class","method","getter","setter","accessor","field","value","get","set"],g2=n=>n!==void 0&&typeof n!="function"?h2("Function expected"):n,u9=(n,e,t,r,s)=>({kind:f2[n],name:e,metadata:r,addInitializer:o=>t._?h2("Already initialized"):s.push(g2(o||null))}),h9=(n,e)=>p2(e,c9("metadata"),n[3]),p9=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},f9=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=f2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,l9(s,t)),S=r.length-1;S>=0;S--)l=u9(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,g2(i)&&(y[g]=i);return y&&u2(s,t,y),s},MT=(n,e,t)=>p2(n,typeof e!="symbol"?e+"":e,t),m2,wy;m2=[Xr];class s1{constructor(e){this.maxDelayTimeMs=e,p9(wy,5,this),MT(this,"isResolved",!1),MT(this,"promisesToWaitFor",[])}waitUntil(e){if(this.isResolved)throw new Error("Cannot `waitUntil` - the export has already been resolved. Make sure to call `waitUntil` as soon as possible during an export - ie within the first react effect after rendering.");this.promisesToWaitFor.push(e.catch(t=>console.error("Error while waiting for export:",t)))}async resolvePromises(){let e=null;for(;this.promisesToWaitFor.length!==e;)e=this.promisesToWaitFor.length,await Promise.allSettled(this.promisesToWaitFor),await mw(0)}async resolve(){const e=mw(this.maxDelayTimeMs).then(()=>"timeout"),t=this.resolvePromises().then(()=>"resolved");await Promise.race([e,t])==="timeout"&&console.warn("[tldraw] Export delay timed out after ${this.maxDelayTimeMs}ms"),this.isResolved=!0}}wy=d9();f9(wy,1,"waitUntil",m2,s1);h9(wy,s1);function g9(n,e,t={}){var S,b;if(!window.document)throw Error("No document");const{scale:r=1,background:s=n.getInstanceState().exportBackground,padding:o=n.options.defaultSvgPadding,preserveAspectRatio:i}=t,a=t.darkMode??n.user.getIsDarkMode(),l=n.getShapeAndDescendantIds(e),c=n.getUnorderedRenderingShapes(!1).filter(({id:w})=>l.has(w)),u=e.length===1&&n.isShapeOfType(n.getShape(e[0]),"frame")?e[0]:null;let d=null;if(t.bounds?d=t.bounds.clone().expandBy(o):d=m9(n,c,o,u),!d)return;const h=d.width*r,f=d.height*r;try{(b=(S=document.body).focus)==null||b.call(S)}catch{}const g=new s1(n.options.maxExportDelayMs),m=hv();return g.waitUntil(m),{jsx:p.jsx(y9,{editor:n,preserveAspectRatio:i,scale:r,pixelRatio:t.pixelRatio??null,bbox:d,background:s,singleFrameShapeId:u,isDarkMode:a,renderingShapes:c,onMount:m.resolve,waitUntil:g.waitUntil}),width:h,height:f,exportDelay:g}}function m9(n,e,t,r){let s=!1,o=null;for(const{id:i}of e){const a=n.getShapeMaskedPageBounds(i);if(!a)continue;const l=n.getShape(i),c=n.getShapeUtil(l).isExportBoundsContainer(l);o?c&&J.ContainsApproximately(a,o)?(s=!0,o=a.clone()):(s&&!J.ContainsApproximately(o,a)&&(s=!1),o.union(a)):(s=c,o=a.clone())}return o?(!r&&!s&&o.expandBy(t),o):null}function y9({editor:n,preserveAspectRatio:e,scale:t,pixelRatio:r,bbox:s,background:o,singleFrameShapeId:i,isDarkMode:a,renderingShapes:l,onMount:c,waitUntil:u}){const d=Yl(),h=Ga({isDarkMode:a}),f=md("export state",{defsById:{},shapeElements:null}),{defsById:g,shapeElements:m}=W(f),y=No(v=>{f.update(P=>{if(gn(P.defsById,v.key))return P;const T=Promise.resolve(v.getElement());return u(T.then(I=>{f.update(k=>({...k,defsById:{...k.defsById,[v.key]:{pending:!1,element:I}}}))})),{...P,defsById:{...P.defsById,[v.key]:{pending:!0,element:T}}}})}),S=x.useMemo(()=>({isDarkMode:a,waitUntil:u,addExportDef:y,scale:t,pixelRatio:r,async resolveAssetUrl(v,P){const T=n.getAsset(v);return!T||T.type!=="image"&&T.type!=="video"?null:await n.resolveAssetUrl(v,{screenScale:t*(P/T.props.w),shouldResolveToOriginal:r===null,dpr:r??void 0})}}),[a,u,y,t,r,n]),b=x.useRef(!1);x.useLayoutEffect(()=>{if(b.current)throw new Error("SvgExport should only render once - do not use with react strict mode");b.current=!0,(async()=>{const v={},P=l.map(async({id:I,opacity:k,index:A,backgroundIndex:R})=>{var M,O;if(I===i)return[];const D=n.getShape(I);if(n.isShapeOfType(D,"group"))return[];const j=[],_=n.getShapeUtil(D);if(_.toSvg||_.toBackgroundSvg){const[N,B]=await Promise.all([(M=_.toSvg)==null?void 0:M.call(_,D,S),(O=_.toBackgroundSvg)==null?void 0:O.call(_,D,S)]),H=n.getShapePageTransform(D);let z=H.toCssString(),X=1;"scale"in D.props&&D.props.scale!==1&&(X=D.props.scale,z=`${z} scale(${D.props.scale}, ${D.props.scale})`);const G=n.getShapeMask(D.id),ae=G?Q.From(Q.Inverse(H)).applyToPoints(G):null,Ce=Wv(d,D.id);ae&&(v[Ce]={pending:!1,element:p.jsx("clipPath",{id:Ce,children:p.jsx("path",{d:`M${ae.map(({x:fe,y:oe})=>`${fe/X},${oe/X}`).join("L")}Z`})})}),N&&j.push({zIndex:A,element:p.jsx("g",{transform:z,opacity:k,clipPath:G?`url(#${Ce})`:void 0,children:N},`fg_${D.id}`)}),B&&j.push({zIndex:R,element:p.jsx("g",{transform:z,opacity:k,clipPath:G?`url(#${Ce})`:void 0,children:B},`bg_${D.id}`)})}else j.push({zIndex:A,element:p.jsx(AT,{shape:D,util:_,component:c2,className:"tl-shape",bbox:s,opacity:k},`fg_${D.id}`)}),_.backgroundComponent&&j.push({zIndex:R,element:p.jsx(AT,{shape:D,util:_,component:d2,className:"tl-shape tl-shape-background",bbox:s,opacity:k},`bg_${D.id}`)});return j}),T=(await Promise.all(P)).flat();Vi.flushSync(()=>{f.update(I=>({...I,shapeElements:T.sort((k,A)=>k.zIndex-A.zIndex).map(({element:k})=>k),defsById:{...I.defsById,...v}}))})})()},[s,n,S,d,l,i,f]),x.useEffect(()=>{const v=new Set;for(const{id:P}of l)for(const T of n.fonts.getShapeFontFaces(P))v.add(T);for(const P of v)y({key:at(),getElement:async()=>{const T=await n.fonts.toEmbeddedCssDeclaration(P);return p.jsx("style",{nonce:n.options.nonce,children:T})}})},[n,l,y]),x.useEffect(()=>{m!==null&&c()},[c,m]);let w=o?h.background:"transparent";if(i&&o){const v=n.getShapeUtil("frame");if(v!=null&&v.options.showColors){const P=n.getShape(i);w=st(h,P.props.color,"frameFill")}else w=h.solid}return p.jsx(o9,{editor:n,context:S,children:p.jsxs("svg",{preserveAspectRatio:e,direction:"ltr",width:s.width*t,height:s.height*t,viewBox:`${s.minX} ${s.minY} ${s.width} ${s.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:w},"data-color-mode":a?"dark":"light",className:`tl-container tl-theme__force-sRGB ${a?"tl-theme__dark":"tl-theme__light"}`,children:[p.jsx("defs",{children:Object.entries(g).map(([v,P])=>P.pending?null:p.jsx(x.Fragment,{children:P.element},v))}),m]})})}function AT({shape:n,util:e,className:t,component:r,bbox:s,opacity:o}){const i=K(),a=Q.Translate(-s.minX,-s.minY).multiply(i.getShapePageTransform(n.id)),l=i.getShapeGeometry(n.id).bounds,c=Math.max(l.width,1),u=Math.max(l.height,1);return p.jsx(Yv,{fallback:()=>null,children:p.jsx("foreignObject",{x:s.minX,y:s.minY,width:s.w,height:s.h,className:"tl-shape-foreign-object tl-export-embed-styles",children:p.jsx("div",{className:t,"data-shape-type":n.type,style:{clipPath:i.getShapeClipPath(n.id),transform:a.toCssString(),width:c,height:u,opacity:o},children:p.jsx(r,{shape:n,util:e})})})})}let S9=1;async function x9(n,e,t={}){const r=g9(n,e,t);if(!r)return;const s=n.getContainer(),o=document.createElement("div");o.className=t2,o.inert=!0,o.tabIndex=-1,Object.assign(o.style,{position:"absolute",top:"0px",left:"0px",width:r.width+"px",height:r.height+"px",pointerEvents:"none",opacity:0}),s.appendChild(o);const i=g4.createRoot(o,{identifierPrefix:`export_${S9++}_`});try{await Promise.resolve(),Vi.flushSync(()=>{i.render(r.jsx)}),await r.exportDelay.resolve();const a=o.firstElementChild;return be(a instanceof SVGSVGElement,"Expected an SVG element"),await b9(a),{svg:a,width:r.width,height:r.height}}finally{setTimeout(()=>{i.unmount(),s.removeChild(o)},0)}}async function b9(n){const e=[...n.querySelectorAll("foreignObject.tl-export-embed-styles > *")];if(!e.length)return;const t=new q8(n);try{t.fonts.startFindingCurrentDocumentFontFaces(),await Promise.all(e.map(o=>o2(o)));for(const o of e)t.readRootElementStyles(o);await t.fetchResources();const r=await t.getFontFaceCss();t.unwrapCustomElements();const s=t.embedStyles();if(r||s){const o=document.createElementNS("http://www.w3.org/2000/svg","style");o.textContent=`${r}
65
+ ${s}`,n.prepend(o)}}finally{t.dispose()}}let jx=null;function w9(){return jx||(jx={maxWidth:Nx("width"),maxHeight:Nx("height"),maxArea:Nx("area")}),jx}/*!
66
+ * Extracted from https://github.com/jhildenbiddle/canvas-size
67
+ * MIT License: https://github.com/jhildenbiddle/canvas-size/blob/master/LICENSE
68
+ * Copyright (c) John Hildenbiddle
69
+ */const DT=8192,v9=4096*4096,C9={area:[16384,14188,11402,11180,10836,8192,4096],height:[8388607,65535,32767,16384,8192,4096],width:[4194303,65535,32767,16384,8192,4096]};function Nx(n){const e=document.createElement("canvas");e.width=1,e.height=1;const t=e.getContext("2d");for(const r of C9[n]){const s=n==="height"?1:r,o=n==="width"?1:r,i=document.createElement("canvas");i.width=s,i.height=o,i.getContext("2d").fillRect(s-1,o-1,1,1),t.drawImage(i,s-1,o-1,1,1,0,0,1,1);const l=t.getImageData(0,0,1,1).data[3]!==0;if(i.width=0,i.height=0,l)return e.width=0,e.height=0,n==="area"?r*r:r}throw e.width=0,e.height=0,Error("Failed to determine maximum canvas dimension")}function P9(n,e){if(n<=DT&&e<=DT&&n*e<=v9)return[n,e];const{maxWidth:t,maxHeight:r,maxArea:s}=w9(),o=n/e;if(n>t&&(n=t,e=n/o),e>r&&(e=r,n=e*o),n*e>s){const i=Math.sqrt(s/(n*e));n*=i,e*=i}return[n,e]}async function T9(n,e){const{type:t,width:r,height:s,quality:o=1,pixelRatio:i=2}=e;let[a,l]=P9(r*i,s*i);a=Math.floor(a),l=Math.floor(l);const c=a/r,u=await ir.blobToDataUrl(new Blob([n],{type:"image/svg+xml"})),d=await new Promise(f=>{const g=th();g.crossOrigin="anonymous",g.onload=async()=>{dt.isSafari&&await mw(250);const m=document.createElement("canvas"),y=m.getContext("2d");m.width=a,m.height=l,y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="high",y.drawImage(g,0,0,a,l),URL.revokeObjectURL(u),f(m)},g.onerror=()=>{f(null)},g.src=u});if(!d)return null;const h=await new Promise(f=>d.toBlob(g=>{(!g||Dt.throwToBlob.get())&&f(null),f(g)},"image/"+t,o));if(!h)return null;if(t==="png"){const f=new DataView(await h.arrayBuffer());return Fo.setPhysChunk(f,c,{type:"image/"+t})}else return h}const Tr={menus:We("open menus",[]),getOpenMenus(n){return n?this.menus.get().filter(e=>e.endsWith("-"+n)):this.menus.get()},addOpenMenu(n,e=""){const t=e?`${n}-${e}`:n,r=new Set(this.menus.get());r.has(t)||(r.add(t),this.menus.set([...r]))},deleteOpenMenu(n,e=""){const t=e?`${n}-${e}`:n,r=new Set(this.menus.get());r.has(t)&&(r.delete(t),this.menus.set([...r]))},clearOpenMenus(n){this.menus.set(n?this.menus.get().filter(e=>!e.endsWith("-"+n)):[])},_hiddenMenus:[],hideOpenMenus(n){if(this._hiddenMenus=[...this.getOpenMenus(n)],this._hiddenMenus.length!==0)for(const e of this._hiddenMenus)this.deleteOpenMenu(e,n)},showOpenMenus(n){if(this._hiddenMenus.length!==0){for(const e of this._hiddenMenus)this.addOpenMenu(e,n);this._hiddenMenus=[]}},isMenuOpen(n,e){return this.getOpenMenus(e).includes(`${n}-${e}`)},hasOpenMenus(n){return this.getOpenMenus(n).length>0},hasAnyOpenMenus(){return this.getOpenMenus().length>0},forContext(n){return{getOpenMenus:()=>this.getOpenMenus(n),addOpenMenu:e=>this.addOpenMenu(e,n),deleteOpenMenu:e=>this.deleteOpenMenu(e,n),clearOpenMenus:()=>this.clearOpenMenus(n),isMenuOpen:e=>this.isMenuOpen(e,n),hasOpenMenus:()=>this.hasOpenMenus(n),hasAnyOpenMenus:()=>this.hasAnyOpenMenus()}}},Ug=new r6,I9={maxShapesPerPage:4e3,maxFilesAtOnce:100,maxPages:40,animationMediumMs:320,followChaseViewportSnap:2,doubleClickDurationMs:450,multiClickDurationMs:200,coarseDragDistanceSquared:36,dragDistanceSquared:16,uiDragDistanceSquared:16,uiCoarseDragDistanceSquared:625,defaultSvgPadding:32,cameraSlideFriction:.09,gridSteps:[{min:-1,mid:.15,step:64},{min:.05,mid:.375,step:16},{min:.15,mid:1,step:4},{min:.7,mid:2.5,step:1}],collaboratorInactiveTimeoutMs:6e4,collaboratorIdleTimeoutMs:3e3,collaboratorCheckIntervalMs:1200,cameraMovingTimeoutMs:64,hitTestMargin:8,edgeScrollDelay:200,edgeScrollEaseDuration:200,edgeScrollSpeed:25,edgeScrollDistance:8,coarsePointerWidth:12,coarseHandleRadius:20,handleRadius:12,longPressDurationMs:500,textShadowLod:.35,adjacentShapeMargin:10,flattenImageBoundsExpand:64,flattenImageBoundsPadding:16,laserDelayMs:1200,laserFadeoutMs:500,maxExportDelayMs:5e3,tooltipDelayMs:700,temporaryAssetPreviewLifetimeMs:18e4,actionShortcutsLocation:"swap",createTextOnCanvasDoubleClick:!0,exportProvider:x.Fragment,enableToolbarKeyboardShortcuts:!0,maxFontsToLoadBeforeRender:1/0,nonce:void 0,debouncedZoom:!0,debouncedZoomThreshold:500,spacebarPanning:!0,zoomToFitPadding:128,snapThreshold:8,camera:_w,text:{},deepLinks:void 0,quickZoomPreservesScreenBounds:!0};function OT(n,e){if(!e)return!1;switch(n.type){case"mixed":return e.type==="mixed";case"shared":return e.type==="shared"&&n.value===e.value;default:throw it(n)}}class E9{constructor(e){E(this,"map");this.map=new Map(e)}get(e){return this.map.get(e)}getAsKnownValue(e){const t=this.get(e);if(t&&t.type!=="mixed")return t.value}get size(){return this.map.size}equals(e){if(this.size!==e.size)return!1;const t=new Set;for(const[r,s]of this){if(!OT(s,e.get(r)))return!1;t.add(r)}for(const[r,s]of e)if(!t.has(r)&&!OT(s,this.get(r)))return!1;return!0}keys(){return this.map.keys()}values(){return this.map.values()}entries(){return this.map.entries()}[Symbol.iterator](){return this.map[Symbol.iterator]()}}class Lw extends E9{set(e,t){this.map.set(e,t)}applyValue(e,t){const r=this.get(e);if(!r){this.set(e,{type:"shared",value:t});return}switch(r.type){case"mixed":return;case"shared":r.value!==t&&this.set(e,{type:"mixed"});return;default:it(r,"type")}}}function k9(n,e,t){return $i(n).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],e,{type:t})})}const _9="https://cdn.tldraw.com";function ln(){return`${_9}/${Xv}`}function M9(n){switch(n.type){case"shapes":return`s${n.shapeIds.map(t=>Fx(t.slice(6))).join(".")}`;case"page":return"p"+Fx(Ar.parseId(n.pageId));case"viewport":{const{bounds:e,pageId:t}=n;let r=`v${Math.round(e.x)}.${Math.round(e.y)}.${Math.round(e.w)}.${Math.round(e.h)}`;return t&&(r+="."+Fx(Ar.parseId(t))),r}default:it(n)}}function A9(n){switch(n[0]){case"s":return{type:"shapes",shapeIds:n.slice(1).split(".").filter(Boolean).map(r=>St(decodeURIComponent(r)))};case"p":return{type:"page",pageId:Ar.createId(decodeURIComponent(n.slice(1)))};case"v":{const[t,r,s,o,i]=n.slice(1).split(".");return{type:"viewport",bounds:new J(Number(t),Number(r),Number(s),Number(o)),pageId:i?Ar.createId(decodeURIComponent(i)):void 0}}default:throw Error("Invalid deep link string")}}function Fx(n){return encodeURIComponent(n).replace(/\./g,"%2E")}function D9(n,e){var s;let t=n;const r=new Set(e);for(;r.has(t);)t=(s=/^.*(\d+)$/.exec(t))!=null&&s[1]?t.replace(/(\d+)(?=\D?)$/,o=>(+o+1).toString()):`${t} 1`;return t}function Kp(n,e,t,r){if(t.length===0)return[];const s=new Map;for(const i of Le(t.map(a=>n.getShape(a)))){const{parentId:a}=i;s.has(a)||s.set(a,{children:Le(n.getSortedChildIdsForParent(a).map(l=>n.getShape(l))),moving:new Set}),s.get(a).moving.add(i)}const o=[];switch(e){case"toBack":{s.forEach(({moving:i,children:a})=>O9(i,a,o));break}case"toFront":{s.forEach(({moving:i,children:a})=>R9(i,a,o));break}case"forward":{s.forEach(({moving:i,children:a})=>L9(n,i,a,o,r));break}case"backward":{s.forEach(({moving:i,children:a})=>j9(n,i,a,o,r));break}}return o}function O9(n,e,t){const r=e.length;if(n.size===r)return;let s,o;for(let i=0;i<r;i++){const a=e[i];if(n.has(a))s=a.index,n.delete(a);else{o=a.index;break}}if(n.size!==0){const i=El(s,o,n.size);t.push(...Array.from(n.values()).sort(Tn).map((a,l)=>({...a,index:i[l]})))}}function R9(n,e,t){const r=e.length;if(n.size===r)return;let s,o;for(let i=r-1;i>-1;i--){const a=e[i];if(n.has(a))o=a.index,n.delete(a);else{s=a.index;break}}if(n.size!==0){const i=El(s,o,n.size);t.push(...Array.from(n.values()).sort(Tn).map((a,l)=>({...a,index:i[l]})))}}function y2(n,e){const t=Le(Array.from(e).map(s=>{const o=n.getShapePageBounds(s);return o?{shape:s,bounds:o}:null}));return s=>{const o=n.getShapePageBounds(s);return o?t.some(i=>i.bounds.includes(o)):!1}}function L9(n,e,t,r,s){var l;const o=y2(n,e),i=t.length;if(e.size===i)return;let a={name:"skipping"};for(let c=0;c<i;c++){const u=e.has(t[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(s!=null&&s.considerAllShapes)&&!o(t[c]))continue;const{selectIndex:d}=a;El(t[c].index,(l=t[c+1])==null?void 0:l.index,c-d).forEach((h,f)=>{const g=t[d+f];e.has(g)&&r.push({...g,index:h})}),a={name:"skipping"};break}}}}function j9(n,e,t,r,s){var l;const o=y2(n,e),i=t.length;if(e.size===i)return;let a={name:"skipping"};for(let c=i-1;c>-1;c--){const u=e.has(t[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(s!=null&&s.considerAllShapes)&&!o(t[c]))continue;El((l=t[c-1])==null?void 0:l.index,t[c].index,a.selectIndex-c).forEach((d,h)=>{const f=t[c+h+1];e.has(f)&&r.push({...f,index:d})}),a={name:"skipping"};break}}}}function S2({editor:n,ids:e}){const t=Le(e.map(i=>n.getShape(i))),r=n.getShapesSharedRotation(e),s=n.getShapesRotatedPageBounds(e);if(!s)return null;const o=s.center.clone().rotWith(s.point,r);return{initialPageCenter:o,initialCursorAngle:o.angle(n.inputs.getOriginPagePoint()),initialShapesRotation:r,shapeSnapshots:t.map(i=>({shape:i,initialPagePoint:n.getShapePageTransform(i.id).point()}))}}function Bf({delta:n,editor:e,snapshot:t,stage:r,centerOverride:s}){const{initialPageCenter:o,shapeSnapshots:i}=t;e.updateShapes(i.map(({shape:l,initialPagePoint:c})=>{const u=Pr(l.parentId)?e.getShapePageTransform(l.parentId):Q.Identity(),d=C.RotWith(c,s??o,n),h=Q.applyToPoint(Q.Inverse(u),d),f=Fg(l.rotation+n);return{id:l.id,type:l.type,x:h.x,y:h.y,rotation:f}}));const a=[];i.forEach(({shape:l})=>{var h,f,g;const c=e.getShape(l.id);if(!c)return;const u=e.getShapeUtil(l);if(r==="start"||r==="one-off"){const m=(h=u.onRotateStart)==null?void 0:h.call(u,l);m&&a.push(m)}const d=(f=u.onRotate)==null?void 0:f.call(u,l,c);if(d&&a.push(d),r==="end"||r==="one-off"){const m=(g=u.onRotateEnd)==null?void 0:g.call(u,l,c);m&&a.push(m)}}),a.length>0&&e.updateShapes(a)}function RT(n){const e=n.get(),t=new Map;for(const r of e){const{fromId:s,toId:o}=r,i=t.get(s);i?i.push(r):t.set(s,[r]);const a=t.get(o);a?a.push(r):t.set(o,[r])}return t}const N9=n=>{const{store:e}=n,t=e.query.filterHistory("binding"),r=e.query.records("binding");return q("arrowBindingsIndex",(s,o)=>{if(Ri(s))return RT(r);const i=s,a=t.getDiffSince(o);if(a===Zr)return RT(r);let l;function c(h){l??(l=new Map(i));const f=l.get(h.fromId),g=f==null?void 0:f.filter(S=>S.id!==h.id);g!=null&&g.length?l.set(h.fromId,g):l.delete(h.fromId);const m=l.get(h.toId),y=m==null?void 0:m.filter(S=>S.id!==h.id);y!=null&&y.length?l.set(h.toId,y):l.delete(h.toId)}function u(h){l??(l=new Map(i));let f=l.get(h);return f?f===i.get(h)&&(f=f.slice(0),l.set(h,f)):(f=[],l.set(h,f)),f}function d(h){u(h.fromId).push(h),u(h.toId).push(h)}for(const h of a){for(const f of Et(h.added))d(f);for(const[f,g]of Et(h.updated))c(f),d(g);for(const f of Et(h.removed))c(f)}return l??i})};function F9(n){const e=new Set;return q("notVisibleShapes",function(t){const r=n.getCurrentPageShapes(),s=n.getViewportPageBounds(),o=n.getShapeIdsInsideBounds(s);let i;if(o.size===r.length)return Ri(t)||t.size>0?e:t;if(Ri(t)){const l=new Set;for(let c=0;c<r.length;c++)i=r[c],!o.has(i.id)&&n.getShapeUtil(i.type).canCull(i)&&l.add(i.id);return l}const a=[];for(let l=0;l<r.length;l++)i=r[l],!o.has(i.id)&&n.getShapeUtil(i.type).canCull(i)&&a.push(i.id);if(a.length===t.size){let l=!0;for(let c=0;c<a.length;c++)if(!t.has(a[c])){l=!1;break}if(l)return t}return new Set(a)})}function LT(n,e){const t={},r=n.get();return Array.from(r,o=>e.get(o)).sort(Tn).forEach(o=>{var i;t[i=o.parentId]??(t[i]=[]),t[o.parentId].push(o.id)}),t}const B9=n=>{const e=n.query.ids("shape"),t=n.query.filterHistory("shape");return q("parentsToChildrenWithIndexes",(r,s)=>{if(Ri(r))return LT(e,n);const o=t.getDiffSince(s);if(o===Zr)return LT(e,n);if(o.length===0)return r;let i=null;const a=u=>{i||(i={...r}),i[u]?i[u]===r[u]&&(i[u]=[...i[u]]):i[u]=[]},l=new Set;let c;for(let u=0,d=o.length;u<d;u++){c=o[u];for(const h of Object.values(c.added))Di(h)&&(a(h.parentId),i[h.parentId].push(h.id),l.add(i[h.parentId]));for(const[h,f]of Object.values(c.updated))if(Di(f)&&Di(h)){if(h.parentId!==f.parentId)a(h.parentId),a(f.parentId),i[h.parentId].splice(i[h.parentId].indexOf(f.id),1),i[f.parentId].push(f.id),l.add(i[f.parentId]);else if(h.index!==f.index){a(f.parentId);const g=i[f.parentId].indexOf(f.id);i[f.parentId][g]=f.id,l.add(i[f.parentId])}}for(const h of Object.values(c.removed))Di(h)&&(a(h.parentId),i[h.parentId].splice(i[h.parentId].indexOf(h.id),1))}for(const u of l){let d=0;for(let h=0;h<u.length;h++)n.get(u[h])&&(u[d++]=u[h]);u.length=d,u.sort((h,f)=>{const g=n.get(h),m=n.get(f);return Tn(g,m)})}return i??r})},Bx=(n,e,t)=>{for(;!On(t.parentId);){const r=n.get(t.parentId);if(!r)return!1;t=r}return t.parentId===e},z9=(n,e)=>{const t=n.query.ids("shape");let r=null;function s(){const o=e();return r=o,new Set([...t.get()].filter(i=>Bx(n,o,n.get(i))))}return q("_shapeIdsInCurrentPage",(o,i)=>{if(Ri(o))return s();const a=e();if(a!==r)return s();const l=n.history.getDiffSince(i);if(l===Zr)return s();const c=new Rf(o);for(const d of l){for(const h of Object.values(d.added))Di(h)&&Bx(n,a,h)&&c.add(h.id);for(const[h,f]of Object.values(d.updated))Di(f)&&(Bx(n,a,f)?c.add(f.id):c.remove(f.id));for(const h of Object.keys(d.removed))Pr(h)&&c.remove(h)}const u=c.get();return u?ou(u.value,u.diff):o})};var $9=Object.create,x2=Object.defineProperty,H9=Object.getOwnPropertyDescriptor,U9=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),b2=n=>{throw TypeError(n)},w2=(n,e,t)=>e in n?x2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,K9=n=>[,,,$9(null)],v2=["class","method","getter","setter","accessor","field","value","get","set"],C2=n=>n!==void 0&&typeof n!="function"?b2("Function expected"):n,W9=(n,e,t,r,s)=>({kind:v2[n],name:e,metadata:r,addInitializer:o=>t._?b2("Already initialized"):s.push(C2(o||null))}),V9=(n,e)=>w2(e,U9("metadata"),n[3]),G9=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},P2=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=v2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,H9(s,t)),S=r.length-1;S>=0;S--)l=W9(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,C2(i)&&(y[g]=i);return y&&x2(s,t,y),s},sc=(n,e,t)=>w2(n,typeof e!="symbol"?e+"":e,t),T2,I2,Uh;const Y9=40;I2=[Xr],T2=[Xr];class vy{constructor(e){this.editor=e,G9(Uh,5,this),sc(this,"_clickId",""),sc(this,"_clickTimeout"),sc(this,"_clickScreenPoint"),sc(this,"_previousScreenPoint"),sc(this,"_clickState","idle"),sc(this,"lastPointerInfo",{})}_getClickTimeout(e,t=at()){this._clickId=t,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===e&&this._clickId===t){switch(this._clickState){case"pendingTriple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"double_click",phase:"settle"});break}case"pendingQuadruple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"triple_click",phase:"settle"});break}case"pendingOverflow":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"settle"});break}}this._clickState="idle"}},e==="idle"||e==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)}get clickState(){return this._clickState}handlePointerEvent(e){switch(e.name){case"pointer_down":{if(!this._clickState)return e;switch(this._clickScreenPoint=C.From(e.point),this._previousScreenPoint&&C.Dist2(this._previousScreenPoint,this._clickScreenPoint)>Y9**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=e,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"quadruple_click",phase:"down"};case"idle":{this._clickState="pendingDouble";break}case"pendingOverflow":{this._clickState="overflow";break}}return this._clickTimeout=this._getClickTimeout(this._clickState),e}case"pointer_up":{if(!this._clickState)return e;switch(this._clickScreenPoint=C.From(e.point),this._clickState){case"pendingTriple":return{...this.lastPointerInfo,type:"click",name:"double_click",phase:"up"};case"pendingQuadruple":return{...this.lastPointerInfo,type:"click",name:"triple_click",phase:"up"};case"pendingOverflow":return{...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"up"}}return e}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&C.Dist2(this._clickScreenPoint,this.editor.inputs.getCurrentScreenPoint())>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),e}return e}cancelDoubleClickTimeout(){this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"}}Uh=K9();P2(Uh,1,"_getClickTimeout",I2,vy);P2(Uh,1,"cancelDoubleClickTimeout",T2,vy);V9(Uh,vy);class X9{constructor(e){E(this,"_isEdgeScrolling",!1);E(this,"_edgeScrollDuration",-1);this.editor=e}getIsEdgeScrolling(){return this._isEdgeScrolling}updateEdgeScrolling(e){const{editor:t}=this;if(t.getCameraOptions().isLocked)return;const r=this.getEdgeScroll();if(r.x===0&&r.y===0)this._isEdgeScrolling&&(this._isEdgeScrolling=!1,this._edgeScrollDuration=0);else if(this._isEdgeScrolling||(this._isEdgeScrolling=!0,this._edgeScrollDuration=0),this._edgeScrollDuration+=e,this._edgeScrollDuration>t.options.edgeScrollDelay){const s=t.options.edgeScrollEaseDuration>0?ar.easeInCubic(Math.min(1,this._edgeScrollDuration/(t.options.edgeScrollDelay+t.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*s,y:r.y*s})}}getEdgeProximityFactors(e,t,r,s,o){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=e-l,u=e+l,d=s?0:a,h=o?t:t-a;return c<d?Math.min(1,(d-c)/a):u>h?-Math.min(1,(u-h)/a):0}getEdgeScroll(){const{editor:e}=this,{x:t,y:r}=e.inputs.getCurrentScreenPoint(),s=e.getViewportScreenBounds(),{isCoarsePointer:o,insets:[i,a,l,c]}=e.getInstanceState(),u=this.getEdgeProximityFactors(t,s.w,o,c,a),d=this.getEdgeProximityFactors(r,s.h,o,i,l);return{x:u,y:d}}moveCameraWhenCloseToEdge(e){if(e.x===0&&e.y===0)return;const{editor:t}=this,r=t.getViewportScreenBounds(),s=r.w<1e3?.612:1,o=r.h<1e3?.612:1,i=t.getZoomLevel(),a=t.user.getEdgeScrollSpeed()*t.options.edgeScrollSpeed,l=a*e.x*s/i,c=a*e.y*o/i,{x:u,y:d,z:h}=t.getCamera();t.setCamera(new C(u+l,d+c,h))}}class q9{constructor(e,t){E(this,"disposeSideEffectListener");this.editor=e,this.disposeSideEffectListener=e.sideEffects.registerAfterChangeHandler("instance",(s,o)=>{s.isFocused!==o.isFocused&&this.updateContainerClass()});const r=e.getInstanceState().isFocused;t!==r&&e.updateInstanceState({isFocused:!!t}),this.updateContainerClass(),document.body.addEventListener("keydown",this.handleKeyDown.bind(this)),document.body.addEventListener("mousedown",this.handleMouseDown.bind(this))}updateContainerClass(){const e=this.editor.getContainer();this.editor.getInstanceState().isFocused?e.classList.add("tl-container__focused"):e.classList.remove("tl-container__focused"),e.classList.add("tl-container__no-focus-ring")}handleKeyDown(e){const t=this.editor.getContainer(),r=document.activeElement;this.editor.isIn("select.editing_shape")&&!(r!=null&&r.closest(".tlui-contextual-toolbar"))||r===t&&this.editor.getSelectedShapeIds().length>0||["Tab","ArrowUp","ArrowDown"].includes(e.key)&&t.classList.remove("tl-container__no-focus-ring")}handleMouseDown(){this.editor.getContainer().classList.add("tl-container__no-focus-ring")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var e;document.body.removeEventListener("keydown",this.handleKeyDown.bind(this)),document.body.removeEventListener("mousedown",this.handleMouseDown.bind(this)),(e=this.disposeSideEffectListener)==null||e.call(this)}}class Z9{constructor(e,t){E(this,"shapeFontFacesCache");E(this,"shapeFontLoadStateCache");E(this,"fontStates",new Tg("font states"));E(this,"fontsToLoad",new Set);this.editor=e,this.assetUrls=t,this.shapeFontFacesCache=e.store.createComputedCache("shape font faces",r=>this.editor.getShapeUtil(r).getFontFaces(r),{areResultsEqual:bg,areRecordsEqual:(r,s)=>r.props===s.props&&r.meta===s.meta}),this.shapeFontLoadStateCache=e.store.createCache(r=>{const s=q("font faces",()=>this.getShapeFontFaces(r));return q("font load state",()=>s.get().map(i=>this.getFontState(i)),{isEqual:bg})})}getShapeFontFaces(e){const t=typeof e=="string"?e:e.id;return this.shapeFontFacesCache.get(t)??Yt}trackFontsForShape(e){const t=typeof e=="string"?e:e.id;this.shapeFontLoadStateCache.get(t)}async loadRequiredFontsForCurrentPage(e=1/0){const t=new Set;for(const s of this.editor.getCurrentPageShapeIds())for(const o of this.getShapeFontFaces(this.editor.getShape(s)))t.add(o);if(t.size>e)return;const r=Array.from(t,s=>this.ensureFontIsLoaded(s));await Promise.all(r)}getFontState(e){return this.fontStates.get(e)??null}ensureFontIsLoaded(e){const t=this.getFontState(e);if(t)return t.loadingPromise;const r=this.findOrCreateFontFace(e),s={state:"loading",instance:r,loadingPromise:r.load().then(()=>{document.fonts.add(r),this.fontStates.update(e,o=>({...o,state:"ready"}))}).catch(o=>{console.error(o),this.fontStates.update(e,i=>({...i,state:"error"}))})};return this.fontStates.set(e,s),s.loadingPromise}requestFonts(e){this.fontsToLoad.size||queueMicrotask(()=>{if(this.editor.isDisposed)return;const t=this.fontsToLoad;this.fontsToLoad=new Set,ms(()=>{for(const r of t)this.ensureFontIsLoaded(r)})});for(const t of e)this.fontsToLoad.add(t)}findOrCreateFontFace(e){var s;for(const o of document.fonts)if(o.family===e.family&&$s(jT).every(([i,a])=>o[i]===(e[i]??a)))return o;const t=((s=this.assetUrls)==null?void 0:s[e.src.url])??e.src.url,r=new FontFace(e.family,`url(${JSON.stringify(t)})`,{...Ka(jT,o=>e[o]),display:"swap"});return document.fonts.add(r),r}async toEmbeddedCssDeclaration(e){var o;const t=((o=this.assetUrls)==null?void 0:o[e.src.url])??e.src.url,r=await ir.urlToDataUrl(t),s=Le([`url("${r}")`,e.src.format?`format(${e.src.format})`:null,e.src.tech?`tech(${e.src.tech})`:null]).join(" ");return Le(["@font-face {",` font-family: "${e.family}";`,e.ascentOverride?` ascent-override: ${e.ascentOverride};`:null,e.descentOverride?` descent-override: ${e.descentOverride};`:null,e.stretch?` font-stretch: ${e.stretch};`:null,e.style?` font-style: ${e.style};`:null,e.weight?` font-weight: ${e.weight};`:null,e.featureSettings?` font-feature-settings: ${e.featureSettings};`:null,e.lineGapOverride?` line-gap-override: ${e.lineGapOverride};`:null,e.unicodeRange?` unicode-range: ${e.unicodeRange};`:null,` src: ${s};`,"}"]).join(`
70
+ `)}}const jT={style:"normal",weight:"normal",stretch:"normal",unicodeRange:"U+0-10FFFF",featureSettings:"normal",ascentOverride:"normal",descentOverride:"normal",lineGapOverride:"normal"};class J9{constructor(e){E(this,"store");E(this,"dispose");E(this,"state","recording");E(this,"pendingDiff",new e7);E(this,"stacks",We("HistoryManager.stacks",{undos:$d(),redos:$d()},{isEqual:(e,t)=>e.undos===t.undos&&e.redos===t.redos}));E(this,"annotateError");E(this,"_isInBatch",!1);this.store=e.store,this.annotateError=e.annotateError??eh,this.dispose=this.store.addHistoryInterceptor((t,r)=>{if(r==="user")switch(this.state){case"recording":this.pendingDiff.apply(t.changes),this.stacks.update(({undos:s})=>({undos:s,redos:$d()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(t.changes);break;case"paused":break;default:it(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const e=this.pendingDiff.clear();this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"diff",diff:e}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}batch(e,t){const r=this.state;r!=="paused"&&(t!=null&&t.history)&&(this.state=Q9[t.history]);try{if(this._isInBatch)return ms(e),this;this._isInBatch=!0;try{ms(e)}catch(s){throw this.annotateError(s),s}finally{this._isInBatch=!1}return this}finally{this.state=r}}_undo({pushToRedoStack:e,toMark:t=void 0}){var s;const r=this.state;this.state="paused";try{let{undos:o,redos:i}=this.stacks.get();const a=this.pendingDiff.clear(),l=PM(a),c=xw(a);e&&!l&&(i=i.push({type:"diff",diff:a}));let u=!1;if(l)for(;((s=o.head)==null?void 0:s.type)==="stop";){const d=o.head;if(o=o.tail,e&&(i=i.push(d)),d.id===t){u=!0;break}}if(!u)e:for(;o.head;){const d=o.head;switch(o=o.tail,e&&(i=i.push(d)),d.type){case"diff":Ou(c,[xw(d.diff)]);break;case"stop":if(!t)break e;if(d.id===t){u=!0;break e}break;default:it(d)}}if(!u&&t)return this;this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:o,redos:i})}finally{this.state=r}return this}undo(){return this._undo({pushToRedoStack:!0}),this}redo(){var t;const e=this.state;this.state="paused";try{this.flushPendingDiff();let{undos:r,redos:s}=this.stacks.get();if(s.length===0)return this;for(;((t=s.head)==null?void 0:t.type)==="stop";)r=r.push(s.head),s=s.tail;const o=kg();for(;s.head;){const i=s.head;if(r=r.push(i),s=s.tail,i.type==="diff")Ou(o,[i.diff]);else break}this.store.applyDiff(o,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:s})}finally{this.state=e}return this}bail(){return this._undo({pushToRedoStack:!1}),this}bailToMark(e){return e&&this._undo({pushToRedoStack:!1,toMark:e}),this}squashToMark(e){var o;let t=this.stacks.get().undos;const r=[];for(;t.head&&!(t.head.type==="stop"&&t.head.id===e);)t.head.type==="diff"&&r.push(t.head.diff),t=t.tail;if(!t.head||((o=t.head)==null?void 0:o.id)!==e)return console.error("Could not find mark to squash to: ",e),this;if(r.length===0)return this;const s=kg();return Ou(s,r.reverse()),this.stacks.update(({redos:i})=>({undos:t.push({type:"diff",diff:s}),redos:i})),this}_mark(e){ms(()=>{this.flushPendingDiff(),this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"stop",id:e}),redos:r}))})}clear(){this.stacks.set({undos:$d(),redos:$d()}),this.pendingDiff.clear()}getMarkIdMatching(e){let t=this.stacks.get().undos;for(;t.head;){if(t.head.type==="stop"&&t.head.id.includes(e))return t.head.id;t=t.tail}return null}debug(){const{undos:e,redos:t}=this.stacks.get();return{undos:NT(e),redos:NT(t),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const Q9={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class e7{constructor(){E(this,"diff",kg());E(this,"isEmptyAtom",We("PendingDiff.isEmpty",!0))}clear(){const e=this.diff;return this.diff=kg(),this.isEmptyAtom.set(!0),e}isEmpty(){return this.isEmptyAtom.get()}apply(e){Ou(this.diff,[e]),this.isEmptyAtom.set(PM(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}function $d(){return n7}class t7{constructor(){E(this,"length",0);E(this,"head",null);E(this,"tail",this)}push(e){return new o1(e,this)}}const n7=new t7;class o1{constructor(e,t){E(this,"length");this.head=e,this.tail=t,this.length=t.length+1}push(e){return new o1(e,this)}}function NT(n){if(!n.length)return Yt;const e=[];for(;n.length;)e.push(n.head),n=n.tail;return e}var r7=Object.create,E2=Object.defineProperty,s7=Object.getOwnPropertyDescriptor,o7=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),k2=n=>{throw TypeError(n)},_2=(n,e,t)=>e in n?E2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,i7=n=>[,,,r7(null)],M2=["class","method","getter","setter","accessor","field","value","get","set"],A2=n=>n!==void 0&&typeof n!="function"?k2("Function expected"):n,a7=(n,e,t,r,s)=>({kind:M2[n],name:e,metadata:r,addInitializer:o=>t._?k2("Already initialized"):s.push(A2(o||null))}),l7=(n,e)=>_2(e,o7("metadata"),n[3]),c7=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},d7=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=M2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,s7(s,t)),S=r.length-1;S>=0;S--)l=a7(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,A2(i)&&(y[g]=i);return y&&E2(s,t,y),s},Zt=(n,e,t)=>_2(n,typeof e!="symbol"?e+"":e,t),D2,Cy;D2=[q];class i1{constructor(e){this.editor=e,c7(Cy,5,this),Zt(this,"_originPagePoint",We("originPagePoint",new C)),Zt(this,"_originScreenPoint",We("originScreenPoint",new C)),Zt(this,"_previousPagePoint",We("previousPagePoint",new C)),Zt(this,"_previousScreenPoint",We("previousScreenPoint",new C)),Zt(this,"_currentPagePoint",We("currentPagePoint",new C)),Zt(this,"_currentScreenPoint",We("currentScreenPoint",new C)),Zt(this,"_pointerVelocity",We("pointerVelocity",new C)),Zt(this,"keys",new tT("keys")),Zt(this,"buttons",new tT("buttons")),Zt(this,"_isPen",We("isPen",!1)),Zt(this,"_shiftKey",We("shiftKey",!1)),Zt(this,"_metaKey",We("metaKey",!1)),Zt(this,"_ctrlKey",We("ctrlKey",!1)),Zt(this,"_altKey",We("altKey",!1)),Zt(this,"_isDragging",We("isDragging",!1)),Zt(this,"_isPointing",We("isPointing",!1)),Zt(this,"_isPinching",We("isPinching",!1)),Zt(this,"_isEditing",We("isEditing",!1)),Zt(this,"_isPanning",We("isPanning",!1)),Zt(this,"_isSpacebarPanning",We("isSpacebarPanning",!1)),Zt(this,"_velocityPrevPoint",new C)}getOriginPagePoint(){return this._originPagePoint.get()}get originPagePoint(){return this.getOriginPagePoint()}getOriginScreenPoint(){return this._originScreenPoint.get()}get originScreenPoint(){return this.getOriginScreenPoint()}getPreviousPagePoint(){return this._previousPagePoint.get()}get previousPagePoint(){return this.getPreviousPagePoint()}getPreviousScreenPoint(){return this._previousScreenPoint.get()}get previousScreenPoint(){return this.getPreviousScreenPoint()}getCurrentPagePoint(){return this._currentPagePoint.get()}get currentPagePoint(){return this.getCurrentPagePoint()}getCurrentScreenPoint(){return this._currentScreenPoint.get()}get currentScreenPoint(){return this.getCurrentScreenPoint()}getPointerVelocity(){return this._pointerVelocity.get()}get pointerVelocity(){return this.getPointerVelocity()}setPointerVelocity(e){this._pointerVelocity.set(e)}getIsPen(){return this._isPen.get()}get isPen(){return this.getIsPen()}set isPen(e){this.setIsPen(e)}setIsPen(e){this._isPen.set(e)}getShiftKey(){return this._shiftKey.get()}get shiftKey(){return this.getShiftKey()}set shiftKey(e){this.setShiftKey(e)}setShiftKey(e){this._shiftKey.set(e)}getMetaKey(){return this._metaKey.get()}get metaKey(){return this.getMetaKey()}set metaKey(e){this.setMetaKey(e)}setMetaKey(e){this._metaKey.set(e)}getCtrlKey(){return this._ctrlKey.get()}get ctrlKey(){return this.getCtrlKey()}set ctrlKey(e){this.setCtrlKey(e)}setCtrlKey(e){this._ctrlKey.set(e)}getAltKey(){return this._altKey.get()}get altKey(){return this.getAltKey()}set altKey(e){this.setAltKey(e)}setAltKey(e){this._altKey.set(e)}getAccelKey(){return Jt({metaKey:this.getMetaKey(),ctrlKey:this.getCtrlKey()})}get accelKey(){return this.getAccelKey()}getIsDragging(){return this._isDragging.get()}get isDragging(){return this.getIsDragging()}set isDragging(e){this.setIsDragging(e)}setIsDragging(e){this._isDragging.set(e)}getIsPointing(){return this._isPointing.get()}get isPointing(){return this.getIsPointing()}set isPointing(e){this.setIsPointing(e)}setIsPointing(e){this._isPointing.set(e)}getIsPinching(){return this._isPinching.get()}get isPinching(){return this.getIsPinching()}set isPinching(e){this.setIsPinching(e)}setIsPinching(e){this._isPinching.set(e)}getIsEditing(){return this._isEditing.get()}get isEditing(){return this.getIsEditing()}set isEditing(e){this.setIsEditing(e)}setIsEditing(e){this._isEditing.set(e)}getIsPanning(){return this._isPanning.get()}get isPanning(){return this.getIsPanning()}set isPanning(e){this.setIsPanning(e)}setIsPanning(e){this._isPanning.set(e)}getIsSpacebarPanning(){return this._isSpacebarPanning.get()}get isSpacebarPanning(){return this.getIsSpacebarPanning()}set isSpacebarPanning(e){this.setIsSpacebarPanning(e)}setIsSpacebarPanning(e){this._isSpacebarPanning.set(e)}_getHasCollaborators(){return this.editor.getCollaborators().length>0}updatePointerVelocity(e){const t=this.getCurrentScreenPoint(),r=this.getPointerVelocity();if(e===0)return;const s=C.Sub(t,this._velocityPrevPoint);this._velocityPrevPoint=t.clone();const o=s.len(),i=o?s.div(o):new C(0,0),a=r.clone().lrp(i.mul(o/e),.5);Math.abs(a.x)<.01&&(a.x=0),Math.abs(a.y)<.01&&(a.y=0),r.equals(a)||this._pointerVelocity.set(a)}updateFromEvent(e){const t=this._currentScreenPoint.__unsafe__getWithoutCapture(),r=this._currentPagePoint.__unsafe__getWithoutCapture(),s=this._isPinching.__unsafe__getWithoutCapture(),{screenBounds:o}=this.editor.store.unsafeGetWithoutCapture(Er),{x:i,y:a,z:l}=gl(()=>this.editor.getCamera()),c=e.point.x-o.x,u=e.point.y-o.y,d=e.point.z??.5;this._previousScreenPoint.set(t),this._previousPagePoint.set(r),this._currentScreenPoint.set(new C(c,u));const h=c/l-i,f=u/l-a;isFinite(h)&&isFinite(f)&&this._currentPagePoint.set(new C(h,f,d)),this._isPen.set(e.type==="pointer"&&e.isPen),(e.name==="pointer_down"||s)&&(this._pointerVelocity.set(new C),this._originScreenPoint.set(this._currentScreenPoint.__unsafe__getWithoutCapture()),this._originPagePoint.set(this._currentPagePoint.__unsafe__getWithoutCapture())),this._getHasCollaborators()&&this.editor.run(()=>{var m;const g=this._currentPagePoint.__unsafe__getWithoutCapture();this.editor.store.put([{id:Lg,typeName:"pointer",x:g.x,y:g.y,lastActivityTimestamp:e.type==="pointer"&&e.pointerId===yA.CAMERA_MOVE?((m=this.editor.store.unsafeGetWithoutCapture(Lg))==null?void 0:m.lastActivityTimestamp)??Date.now():Date.now(),meta:{}}])},{history:"ignore"})}toJson(){return{originPagePoint:this._originPagePoint.get().toJson(),originScreenPoint:this._originScreenPoint.get().toJson(),previousPagePoint:this._previousPagePoint.get().toJson(),previousScreenPoint:this._previousScreenPoint.get().toJson(),currentPagePoint:this._currentPagePoint.get().toJson(),currentScreenPoint:this._currentScreenPoint.get().toJson(),pointerVelocity:this._pointerVelocity.get().toJson(),shiftKey:this._shiftKey.get(),metaKey:this._metaKey.get(),ctrlKey:this._ctrlKey.get(),altKey:this._altKey.get(),isPen:this._isPen.get(),isDragging:this._isDragging.get(),isPointing:this._isPointing.get(),isPinching:this._isPinching.get(),isEditing:this._isEditing.get(),isPanning:this._isPanning.get(),isSpacebarPanning:this._isSpacebarPanning.get(),keys:Array.from(this.keys.keys()),buttons:Array.from(this.buttons.keys())}}}Cy=i7();d7(Cy,1,"_getHasCollaborators",D2,i1);l7(Cy,i1);class u7{constructor(e){E(this,"sessions",new Map);this.editor=e}startSession(e={}){const t=e.id??at(),r={id:t,items:[],state:"active",options:{selfConsume:e.selfConsume??!0,idleTimeoutMs:e.idleTimeoutMs??0,fadeMode:e.fadeMode??"individual",fadeEasing:e.fadeEasing??(e.fadeMode==="grouped"?"ease-in":"linear"),fadeDurationMs:e.fadeDurationMs??this.editor.options.laserFadeoutMs},fadeElapsed:0,totalPointsAtFadeStart:0};return this.sessions.set(t,r),r.options.idleTimeoutMs>0&&this.resetIdleTimeout(r),t}addScribbleToSession(e,t,r=at()){const s=this.sessions.get(e);if(!s)throw Error(`Session ${e} not found`);const o={id:r,scribble:{id:r,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...t,state:"starting"},timeoutMs:0,delayRemaining:t.delay??0,prev:null,next:null};return s.items.push(o),s.options.idleTimeoutMs>0&&this.resetIdleTimeout(s),o}addPointToSession(e,t,r,s,o=.5){const i=this.sessions.get(e);if(!i)throw Error(`Session ${e} not found`);const a=i.items.find(c=>c.id===t);if(!a)throw Error(`Scribble ${t} not found in session ${e}`);const l={x:r,y:s,z:o};return(!a.prev||C.Dist(a.prev,l)>=1)&&(a.next=l),i.options.idleTimeoutMs>0&&this.resetIdleTimeout(i),a}extendSession(e){const t=this.sessions.get(e);t&&t.options.idleTimeoutMs>0&&this.resetIdleTimeout(t)}stopSession(e){const t=this.sessions.get(e);if(!(!t||t.state!=="active"))if(this.clearIdleTimeout(t),t.state="stopping",t.options.fadeMode==="grouped"){t.totalPointsAtFadeStart=t.items.reduce((r,s)=>r+s.scribble.points.length,0),t.fadeElapsed=0;for(const r of t.items)r.scribble.state="stopping"}else for(const r of t.items)r.delayRemaining=Math.min(r.delayRemaining,200),r.scribble.state="stopping"}clearSession(e){const t=this.sessions.get(e);if(t){this.clearIdleTimeout(t);for(const r of t.items)r.scribble.points.length=0;t.state="complete"}}isSessionActive(e){const t=this.sessions.get(e);return(t==null?void 0:t.state)==="active"}addScribble(e,t=at()){const r=this.startSession();return this.addScribbleToSession(r,e,t)}addPoint(e,t,r,s=.5){for(const o of this.sessions.values()){const i=o.items.find(a=>a.id===e);if(i){const a={x:t,y:r,z:s};return(!i.prev||C.Dist(i.prev,a)>=1)&&(i.next=a),o.options.idleTimeoutMs>0&&this.resetIdleTimeout(o),i}}throw Error(`Scribble with id ${e} not found`)}complete(e){for(const t of this.sessions.values()){const r=t.items.find(s=>s.id===e);if(r)return(r.scribble.state==="starting"||r.scribble.state==="active")&&(r.scribble.state="complete"),r}throw Error(`Scribble with id ${e} not found`)}stop(e){for(const t of this.sessions.values()){const r=t.items.find(s=>s.id===e);if(r)return r.delayRemaining=Math.min(r.delayRemaining,200),r.scribble.state="stopping",r}throw Error(`Scribble with id ${e} not found`)}reset(){for(const e of this.sessions.values())this.clearIdleTimeout(e);this.sessions.clear(),this.editor.updateInstanceState({scribbles:[]})}tick(e){const t=this.editor.getInstanceState().scribbles;this.sessions.size===0&&t.length===0||this.editor.run(()=>{for(const s of this.sessions.values())this.tickSession(s,e);for(const[s,o]of this.sessions)o.state==="complete"&&(this.clearIdleTimeout(o),this.sessions.delete(s));const r=[];for(const s of this.sessions.values())for(const o of s.items)o.scribble.points.length>0&&r.push({...o.scribble,points:[...o.scribble.points]});this.editor.updateInstanceState({scribbles:r})})}resetIdleTimeout(e){this.clearIdleTimeout(e),e.idleTimeoutHandle=this.editor.timers.setTimeout(()=>{this.stopSession(e.id)},e.options.idleTimeoutMs)}clearIdleTimeout(e){e.idleTimeoutHandle!==void 0&&(clearTimeout(e.idleTimeoutHandle),e.idleTimeoutHandle=void 0)}tickSession(e,t){if(e.state==="complete")return;e.state==="stopping"&&e.options.fadeMode==="grouped"?this.tickGroupedFade(e,t):this.tickSessionItems(e,t),!e.items.some(s=>s.scribble.points.length>0)&&(e.state==="stopping"||e.items.length===0)&&(e.state="complete")}tickSessionItems(e,t){for(const r of e.items)e.options.selfConsume||e.state==="stopping"||r.scribble.state==="stopping"?this.tickSelfConsumingItem(r,t):this.tickPersistentItem(r);if(e.options.fadeMode==="individual")for(let r=e.items.length-1;r>=0;r--)e.items[r].scribble.points.length===0&&e.items.splice(r,1)}tickPersistentItem(e){const{scribble:t}=e;if(t.state==="starting"){const{next:r,prev:s}=e;r&&r!==s&&(e.prev=r,t.points.push(r)),t.points.length>8&&(t.state="active");return}if(t.state==="active"){const{next:r,prev:s}=e;r&&r!==s&&(e.prev=r,t.points.push(r))}}tickSelfConsumingItem(e,t){const{scribble:r}=e;if(r.state==="starting"){const{next:l,prev:c}=e;l&&l!==c&&(e.prev=l,r.points.push(l)),r.points.length>8&&(r.state="active");return}e.delayRemaining>0&&(e.delayRemaining=Math.max(0,e.delayRemaining-t)),e.timeoutMs+=t,e.timeoutMs>=16&&(e.timeoutMs=0);const{delayRemaining:s,timeoutMs:o,prev:i,next:a}=e;switch(r.state){case"active":{a&&a!==i?(e.prev=a,r.points.push(a),s===0&&r.points.length>8&&r.points.shift()):o===0&&(r.points.length>1?r.points.shift():e.delayRemaining=r.delay);break}case"stopping":{if(s===0&&o===0){if(r.points.length<=1){r.points.length=0;return}r.shrink&&(r.size=Math.max(1,r.size*(1-r.shrink))),r.points.shift()}break}}}tickGroupedFade(e,t){e.fadeElapsed+=t;let r=0;for(const d of e.items)r+=d.scribble.points.length;if(r===0)return;if(e.fadeElapsed>=e.options.fadeDurationMs){for(const d of e.items)d.scribble.points.length=0;return}const s=e.fadeElapsed/e.options.fadeDurationMs,o=e.options.fadeEasing==="ease-in"?s*s:s,i=Math.floor(o*e.totalPointsAtFadeStart),a=e.totalPointsAtFadeStart-r,l=Math.max(1,i-a);let c=0,u=0;for(;c<l&&u<e.items.length;){const d=e.items[u];d.scribble.points.length>0?(d.scribble.points.shift(),c++):u++}}}var h7=Object.create,O2=Object.defineProperty,p7=Object.getOwnPropertyDescriptor,f7=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),R2=n=>{throw TypeError(n)},L2=(n,e,t)=>e in n?O2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,g7=n=>[,,,h7(null)],j2=["class","method","getter","setter","accessor","field","value","get","set"],N2=n=>n!==void 0&&typeof n!="function"?R2("Function expected"):n,m7=(n,e,t,r,s)=>({kind:j2[n],name:e,metadata:r,addInitializer:o=>t._?R2("Already initialized"):s.push(N2(o||null))}),y7=(n,e)=>L2(e,f7("metadata"),n[3]),S7=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},Py=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=j2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,p7(s,t)),S=r.length-1;S>=0;S--)l=m7(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,N2(i)&&(y[g]=i);return y&&O2(s,t,y),s},x7=(n,e,t)=>L2(n,e+"",t),F2,B2,z2,$2,Xl;const Oe=n=>Math.round(n*10**8)/10**8;function Ii(n,e,t,r,s){const o=n.filter(a=>(r==="forward"?a.startNode.id===e:a.endNode.id===e)&&Oe(a.length)===Oe(t)&&io(a.breadthIntersection[0],a.breadthIntersection[1],s[0],s[1]));if(o.length===0)return[];const i=new Set;return o.forEach(a=>{const l=r==="forward"?a.endNode.id:a.startNode.id;if(!i.has(l)){i.add(l);const c=Ii(n,l,t,r,io(a.breadthIntersection[0],a.breadthIntersection[1],s[0],s[1]));o.push(...c)}}),o}function b7(n){n.sort((e,t)=>t.gaps.length-e.gaps.length);for(let e=n.length-1;e>0;e--){const t=n[e];for(let r=e-1;r>=0;r--){const s=n[r];if(s.direction===t.direction&&t.gaps.every(o=>s.gaps.some(i=>Oe(o.startEdge[0].x)===Oe(i.startEdge[0].x)&&Oe(o.startEdge[0].y)===Oe(i.startEdge[0].y)&&Oe(o.startEdge[1].x)===Oe(i.startEdge[1].x)&&Oe(o.startEdge[1].y)===Oe(i.startEdge[1].y))&&s.gaps.some(i=>Oe(o.endEdge[0].x)===Oe(i.endEdge[0].x)&&Oe(o.endEdge[0].y)===Oe(i.endEdge[0].y)&&Oe(o.endEdge[1].x)===Oe(i.endEdge[1].x)&&Oe(o.endEdge[1].y)===Oe(i.endEdge[1].y)))){n.splice(e,1);break}}}}$2=[q],z2=[q],B2=[q],F2=[q];class Sd{constructor(e){this.manager=e,S7(Xl,5,this),x7(this,"editor"),this.editor=e.editor}getSnapPointsCache(){const{editor:e}=this;return e.store.createComputedCache("snapPoints",t=>{const r=e.getShapePageTransform(t.id);if(!r)return;const o=e.getShapeUtil(t).getBoundsSnapGeometry(t).points??e.getShapeGeometry(t).bounds.cornersAndCenter;if(!(!r||!o))return o.map((i,a)=>{const{x:l,y:c}=Q.applyToPoint(r,i);return{x:l,y:c,id:`${t.id}:${a}`}})})}getSnapPoints(e){return this.getSnapPointsCache().get(e)??[]}getSnappablePoints(){const e=this.getSnapPointsCache(),t=this.manager.getSnappableShapes(),r=[];for(const s of t){const o=e.get(s);o&&r.push(...o)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),e=>({id:e,pageBounds:Pn(this.editor.getShapePageBounds(e))}))}getVisibleGaps(){const e=[],t=[];let r,s;const o=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;a<o.length;a++){r=o[a];for(let l=a+1;l<o.length;l++)s=o[l],r.pageBounds.maxX<s.pageBounds.minX&&Bd(r.pageBounds.minY,r.pageBounds.maxY,s.pageBounds.minY,s.pageBounds.maxY)&&e.push({startNode:r,endNode:s,startEdge:[new C(r.pageBounds.maxX,r.pageBounds.minY),new C(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new C(s.pageBounds.minX,s.pageBounds.minY),new C(s.pageBounds.minX,s.pageBounds.maxY)],length:s.pageBounds.minX-r.pageBounds.maxX,breadthIntersection:io(r.pageBounds.minY,r.pageBounds.maxY,s.pageBounds.minY,s.pageBounds.maxY)})}const i=o.sort((a,l)=>a.pageBounds.minY-l.pageBounds.minY);for(let a=0;a<i.length;a++){r=i[a];for(let l=a+1;l<i.length;l++)s=i[l],r.pageBounds.maxY<s.pageBounds.minY&&Bd(r.pageBounds.minX,r.pageBounds.maxX,s.pageBounds.minX,s.pageBounds.maxX)&&t.push({startNode:r,endNode:s,startEdge:[new C(r.pageBounds.minX,r.pageBounds.maxY),new C(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new C(s.pageBounds.minX,s.pageBounds.minY),new C(s.pageBounds.maxX,s.pageBounds.minY)],length:s.pageBounds.minY-r.pageBounds.maxY,breadthIntersection:io(r.pageBounds.minX,r.pageBounds.maxX,s.pageBounds.minX,s.pageBounds.maxX)})}return{horizontal:e,vertical:t}}snapTranslateShapes({lockedAxis:e,initialSelectionPageBounds:t,initialSelectionSnapPoints:r,dragDelta:s}){var y,S;const o=this.manager.getSnapThreshold(),i=this.getSnappablePoints(),a=t.clone().translate(s),l=r.map(({x:b,y:w},v)=>({id:"selection:"+v,x:b+s.x,y:w+s.y})),c=i,u=[],d=[],h=new C(o,o);this.collectPointSnaps({minOffset:h,nearestSnapsX:u,nearestSnapsY:d,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d,minOffset:h});const f=new C(e==="x"?0:((y=u[0])==null?void 0:y.nudge)??0,e==="y"?0:((S=d[0])==null?void 0:S.nudge)??0);h.x=0,h.y=0,u.length=0,d.length=0,l.forEach(b=>{b.x+=f.x,b.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:h,nearestSnapsX:u,nearestSnapsY:d,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d,minOffset:h});const g=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:d}),m=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d});return this.manager.setIndicators([...m,...g]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:e,dragDelta:t,handle:r,isAspectRatioLocked:s,isResizingFromCenter:o}){var I,k;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=J.Resize(e,r,o?t.x*2:t.x,o?t.y*2:t.y,s);let u=r;l<0&&(u=x8(u)),c<0&&(u=S8(u)),o&&(a.center=e.center);const d=u==="top"||u==="bottom",h=u==="left"||u==="right",f=FT(u,a),g=this.getSnappablePoints(),m=[],y=[],S=new C(i,i);this.collectPointSnaps({minOffset:S,nearestSnapsX:m,nearestSnapsY:y,otherNodeSnapPoints:g,selectionSnapPoints:f});const b=new C(d?0:((I=m[0])==null?void 0:I.nudge)??0,h?0:((k=y[0])==null?void 0:k.nudge)??0);if(s&&b8(u)&&b.len()!==0){const A=m.length&&y.length?Math.abs(b.x)<Math.abs(b.y)?"x":"y":m.length?"x":"y",R=e.aspectRatio;A==="x"?(y.length=0,b.y=b.x/R,(u==="bottom_left"||u==="top_right")&&(b.y=-b.y)):(m.length=0,b.x=b.y*R,(u==="bottom_left"||u==="top_right")&&(b.x=-b.x))}const w=C.Add(t,b),{box:v}=J.Resize(e,r,o?w.x*2:w.x,o?w.y*2:w.y,s);o&&(v.center=e.center);const P=FT("any",v);m.length=0,y.length=0,S.x=0,S.y=0,this.collectPointSnaps({minOffset:S,nearestSnapsX:m,nearestSnapsY:y,otherNodeSnapPoints:g,selectionSnapPoints:P});const T=this.getPointSnapLines({nearestSnapsX:m,nearestSnapsY:y});return this.manager.setIndicators([...T]),{nudge:b}}collectPointSnaps({selectionSnapPoints:e,otherNodeSnapPoints:t,minOffset:r,nearestSnapsX:s,nearestSnapsY:o}){for(const i of e)for(const a of t){const l=C.Sub(i,a),c=Math.abs(l.x),u=Math.abs(l.y);Oe(c)<=Oe(r.x)&&(Oe(c)<Oe(r.x)&&(s.length=0),s.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.x-i.x}),r.x=c),Oe(u)<=Oe(r.y)&&(Oe(u)<Oe(r.y)&&(o.length=0),o.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.y-i.y}),r.y=u)}}collectGapSnaps({selectionPageBounds:e,minOffset:t,nearestSnapsX:r,nearestSnapsY:s}){const{horizontal:o,vertical:i}=this.getVisibleGaps();for(const a of o){if(!Bd(a.breadthIntersection[0],a.breadthIntersection[1],e.minY,e.maxY))continue;const c=a.startEdge[0].x+a.length/2-e.center.x;if(a.length>e.width&&Oe(Math.abs(c))<=Oe(t.x)){Oe(Math.abs(c))<Oe(t.x)&&(r.length=0),t.x=Math.abs(c);const S={type:"gap_center",gap:a,nudge:c},b=r.find(({type:v})=>v==="gap_center"),w=b&&io(a.breadthIntersection[0],a.breadthIntersection[1],b.gap.breadthIntersection[0],b.gap.breadthIntersection[1]);b&&b.gap.length>a.length&&w?r[r.indexOf(b)]=S:(!b||!w)&&r.push(S)}const d=a.startNode.pageBounds.minX-a.length,h=e.maxX,f=d-h;Oe(Math.abs(f))<=Oe(t.x)&&(Oe(Math.abs(f))<Oe(t.x)&&(r.length=0),t.x=Math.abs(f),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"left",nudge:f}));const g=a.endNode.pageBounds.maxX+a.length,m=e.minX,y=g-m;Oe(Math.abs(y))<=Oe(t.x)&&(Oe(Math.abs(y))<Oe(t.x)&&(r.length=0),t.x=Math.abs(y),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"right",nudge:y}))}for(const a of i){if(!Bd(a.breadthIntersection[0],a.breadthIntersection[1],e.minX,e.maxX))continue;const c=a.startEdge[0].y+a.length/2-e.center.y;if(a.length>e.height&&Oe(Math.abs(c))<=Oe(t.y)){Oe(Math.abs(c))<Oe(t.y)&&(s.length=0),t.y=Math.abs(c);const S={type:"gap_center",gap:a,nudge:c},b=s.find(({type:v})=>v==="gap_center"),w=b&&Bd(b.gap.breadthIntersection[0],b.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);b&&b.gap.length>a.length&&w?s[s.indexOf(b)]=S:(!b||!w)&&s.push(S);continue}const d=a.startNode.pageBounds.minY-a.length,h=e.maxY,f=d-h;Oe(Math.abs(f))<=Oe(t.y)&&(Oe(Math.abs(f))<Oe(t.y)&&(s.length=0),t.y=Math.abs(f),s.push({type:"gap_duplicate",gap:a,protrusionDirection:"top",nudge:f}));const g=a.endNode.pageBounds.maxY+a.length,m=e.minY,y=g-m;Oe(Math.abs(y))<=Oe(t.y)&&(Oe(Math.abs(y))<Oe(t.y)&&(s.length=0),t.y=Math.abs(y),s.push({type:"gap_duplicate",gap:a,protrusionDirection:"bottom",nudge:y}))}}getPointSnapLines({nearestSnapsX:e,nearestSnapsY:t}){const r={},s={};if(e.length>0){for(const o of e)if(o.type==="points"){const i=Oe(o.points.otherPoint.x);r[i]||(r[i]=[]),r[i].push(o.points)}}if(t.length>0){for(const o of t)if(o.type==="points"){const i=Oe(o.points.otherPoint.y);s[i]||(s[i]=[]),s[i].push(o.points)}}return Object.values(r).concat(Object.values(s)).map(o=>({id:at(),type:"points",points:ny(o.map(i=>C.From(i.otherPoint)).concat(o.map(i=>C.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:e,nearestSnapsX:t,nearestSnapsY:r}){const{vertical:s,horizontal:o}=this.getVisibleGaps(),i={top:e.sides[0],right:e.sides[1],bottom:[e.corners[3],e.corners[2]],left:[e.corners[0],e.corners[3]]},a=[];if(t.length>0)for(const l of t){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:d,endNode:h,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.width)/2,y=io(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:at(),gaps:[...Ii(o,d.id,m,"backward",y),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:g},...Ii(o,h.id,m,"forward",y)]});break}case"gap_duplicate":{const m=io(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:at(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(y=>y.clone().addXY(-d.pageBounds.width,0))},{startEdge:u,endEdge:g},...Ii(o,h.id,f,"forward",m)]:[...Ii(o,d.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(y=>y.clone().addXY(l.gap.endNode.pageBounds.width,0)),endEdge:i.left}]});break}}}if(r.length>0)for(const l of r){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:d,endNode:h,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.height)/2,y=io(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:at(),gaps:[...Ii(s,d.id,m,"backward",y),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:g},...Ii(s,l.gap.endNode.id,m,"forward",y)]});break}case"gap_duplicate":{const m=io(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:at(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(y=>y.clone().addXY(0,-d.pageBounds.height))},{startEdge:u,endEdge:g},...Ii(s,h.id,f,"forward",m)]:[...Ii(s,d.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(y=>y.clone().addXY(0,h.pageBounds.height)),endEdge:i.top}]})}break}}return b7(a),a}}Xl=g7();Py(Xl,1,"getSnapPointsCache",$2,Sd);Py(Xl,1,"getSnappablePoints",z2,Sd);Py(Xl,1,"getSnappableGapNodes",B2,Sd);Py(Xl,1,"getVisibleGaps",F2,Sd);y7(Xl,Sd);function FT(n,e){const{minX:t,maxX:r,minY:s,maxY:o}=e,i=[];switch(n){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:t,y:s})}switch(n){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:s})}switch(n){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:o})}switch(n){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:t,y:o})}return i}var w7=Object.create,H2=Object.defineProperty,v7=Object.getOwnPropertyDescriptor,C7=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),U2=n=>{throw TypeError(n)},K2=(n,e,t)=>e in n?H2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,P7=n=>[,,,w7(null)],W2=["class","method","getter","setter","accessor","field","value","get","set"],V2=n=>n!==void 0&&typeof n!="function"?U2("Function expected"):n,T7=(n,e,t,r,s)=>({kind:W2[n],name:e,metadata:r,addInitializer:o=>t._?U2("Already initialized"):s.push(V2(o||null))}),I7=(n,e)=>K2(e,C7("metadata"),n[3]),E7=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},k7=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=W2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,v7(s,t)),S=r.length-1;S>=0;S--)l=T7(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,V2(i)&&(y[g]=i);return y&&H2(s,t,y),s},_7=(n,e,t)=>K2(n,e+"",t),G2,Ty;const M7=()=>null,A7=()=>[];G2=[q];class a1{constructor(e){this.manager=e,E7(Ty,5,this),_7(this,"editor"),this.editor=e.editor}getSnapGeometryCache(){const{editor:e}=this;return e.store.createComputedCache("handle snap geometry",t=>{const r=e.getShapeUtil(t).getHandleSnapGeometry(t),s=r.getSelfSnapOutline?r.getSelfSnapOutline.bind(r):M7,o=r.getSelfSnapPoints?r.getSelfSnapPoints.bind(r):A7;return{outline:r.outline===void 0?e.getShapeGeometry(t):r.outline,points:r.points??[],getSelfSnapOutline:s,getSelfSnapPoints:o}})}*iterateSnapPointsInPageSpace(e,t){var s,o;const r=(s=this.getSnapGeometryCache().get(e))==null?void 0:s.getSelfSnapPoints(t);if(r&&r.length){const i=Pn(this.editor.getShapePageTransform(e));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.points;if(!a||!a.length)continue;const l=Pn(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(e,t){var s,o;const r=(s=this.getSnapGeometryCache().get(e))==null?void 0:s.getSelfSnapOutline(t);r&&(yield{shapeId:e,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:e,handle:t,handleInPageSpace:r}){const s=this.manager.getSnapThreshold();let o=s,i=null;for(const c of this.iterateSnapPointsInPageSpace(e,t))C.DistMin(r,c,o)&&(o=C.Dist(r,c),i=c);if(i)return i;let a=s,l=null;for(const{shapeId:c,outline:u}of this.iterateSnapOutlines(e,t)){const d=Pn(this.editor.getShapePageTransform(c)),h=this.editor.getPointInShapeSpace(c,r),f=u.nearestPoint(h),g=d.applyToPoint(f);C.DistMin(r,g,a)&&(a=C.Dist(r,g),l=g)}return l||null}getHandleSnapData({handle:e,currentShapeId:t}){const r=this.manager.getSnapThreshold(),o=Pn(this.editor.getShapePageTransform(t)).applyToPoint(e);let i=null,a=null,l=r,c=r;for(const f of this.iterateSnapPointsInPageSpace(t,e)){const g=Math.abs(o.x-f.x),m=Math.abs(o.y-f.y);g<l&&(l=g,i=f),m<c&&(c=m,a=f)}if(!i&&!a)return null;const u=new C(i?i.x-o.x:0,a?a.y-o.y:0),d=C.Add(o,u),h=[];if(i){const f=new C(i.x,d.y);h.push({id:at(),type:"points",points:[i,f]})}if(a){const f=new C(d.x,a.y);h.push({id:at(),type:"points",points:[a,f]})}return{snaps:h,nudge:u}}snapHandle({currentShapeId:e,handle:t}){const s=Pn(this.editor.getShapePageTransform(e)).applyToPoint(t),o=t.canSnap?"point":t.snapType;if(o==="point"){const i=this.getHandleSnapPosition({currentShapeId:e,handle:t,handleInPageSpace:s});return i?(this.manager.setIndicators([{id:at(),type:"points",points:[i]}]),{nudge:C.Sub(i,s)}):null}if(o==="align"){const i=this.getHandleSnapData({handle:t,currentShapeId:e});return i?(this.manager.setIndicators(i.snaps),{nudge:i.nudge}):null}return null}}Ty=P7();k7(Ty,1,"getSnapGeometryCache",G2,a1);I7(Ty,a1);var D7=Object.create,Y2=Object.defineProperty,O7=Object.getOwnPropertyDescriptor,R7=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),X2=n=>{throw TypeError(n)},q2=(n,e,t)=>e in n?Y2(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,L7=n=>[,,,D7(null)],Z2=["class","method","getter","setter","accessor","field","value","get","set"],J2=n=>n!==void 0&&typeof n!="function"?X2("Function expected"):n,j7=(n,e,t,r,s)=>({kind:Z2[n],name:e,metadata:r,addInitializer:o=>t._?X2("Already initialized"):s.push(J2(o||null))}),N7=(n,e)=>q2(e,R7("metadata"),n[3]),F7=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},l1=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=Z2[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,O7(s,t)),S=r.length-1;S>=0;S--)l=j7(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,J2(i)&&(y[g]=i);return y&&Y2(s,t,y),s},zx=(n,e,t)=>q2(n,typeof e!="symbol"?e+"":e,t),Q2,eD,tD,xd;tD=[q],eD=[q],Q2=[q];class Kh{constructor(e){this.editor=e,F7(xd,5,this),zx(this,"shapeBounds"),zx(this,"handles"),zx(this,"_snapIndicators",We("snapLines",void 0)),this.shapeBounds=new Sd(this),this.handles=new a1(this)}getIndicators(){return this._snapIndicators.get()??Yt}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(e){this._snapIndicators.set(e)}getSnapThreshold(){return this.editor.options.snapThreshold/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:e}=this,t=e.getViewportPageBounds(),r=e.getSelectedShapeIds(),s=new Set,o=i=>{if(Pr(i)){const l=e.getShape(i);l&&e.isShapeOfType(l,"frame")&&s.add(i)}const a=e.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=e.getShape(l);if(!c||!e.getShapeUtil(c).canSnap(c))continue;const d=e.getShapePageBounds(l);if(d&&t.includes(d)){if(e.isShapeOfType(c,"group")){o(l);continue}s.add(l)}}};return o(this.getCurrentCommonAncestor()??e.getCurrentPageId()),s}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}}xd=L7();l1(xd,1,"getSnapThreshold",tD,Kh);l1(xd,1,"getSnappableShapes",eD,Kh);l1(xd,1,"getCurrentCommonAncestor",Q2,Kh);N7(xd,Kh);function B7(n,e,t,r,s){nD(n,e,t||0,r||n.length-1,s||z7)}function nD(n,e,t,r,s){for(;r>t;){if(r-t>600){var o=r-t+1,i=e-t+1,a=Math.log(o),l=.5*Math.exp(2*a/3),c=.5*Math.sqrt(a*l*(o-l)/o)*(i-o/2<0?-1:1),u=Math.max(t,Math.floor(e-i*l/o+c)),d=Math.min(r,Math.floor(e+(o-i)*l/o+c));nD(n,e,u,d,s)}var h=n[e],f=t,g=r;for(Hd(n,t,e),s(n[r],h)>0&&Hd(n,t,r);f<g;){for(Hd(n,f,g),f++,g--;s(n[f],h)<0;)f++;for(;s(n[g],h)>0;)g--}s(n[t],h)===0?Hd(n,t,g):(g++,Hd(n,g,r)),g<=e&&(t=g+1),e<=g&&(r=g-1)}}function Hd(n,e,t){var r=n[e];n[e]=n[t],n[t]=r}function z7(n,e){return n<e?-1:n>e?1:0}class $7{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!Vp(e,t))return r;const s=this.toBBox,o=[];for(;t;){for(let i=0;i<t.children.length;i++){const a=t.children[i],l=t.leaf?s(a):a;Vp(e,l)&&(t.leaf?r.push(a):Hx(e,l)?this._all(a,r):o.push(a))}t=o.pop()}return r}collides(e){let t=this.data;if(!Vp(e,t))return!1;const r=[];for(;t;){for(let s=0;s<t.children.length;s++){const o=t.children[s],i=t.leaf?this.toBBox(o):o;if(Vp(e,i)){if(t.leaf||Hx(e,i))return!0;r.push(o)}}t=r.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let r=0;r<e.length;r++)this.insert(e[r]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=t;else if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const r=this.data;this.data=t,t=r}this._insert(t,this.data.height-t.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=vc([]),this}remove(e,t){if(!e)return this;let r=this.data;const s=this.toBBox(e),o=[],i=[];let a,l,c;for(;r||o.length;){if(r||(r=o.pop(),l=o[o.length-1],a=i.pop(),c=!0),r.leaf){const u=H7(e,r.children,t);if(u!==-1)return r.children.splice(u,1),o.push(r),this._condense(o),this}!c&&!r.leaf&&Hx(r,s)?(o.push(r),i.push(a),a=0,l=r,r=r.children[0]):l?(a++,r=l.children[a],c=!1):r=null}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,s){const o=r-t+1;let i=this._maxEntries,a;if(o<=i)return a=vc(e.slice(t,r+1)),oc(a,this.toBBox),a;s||(s=Math.ceil(Math.log(o)/Math.log(i)),i=Math.ceil(o/Math.pow(i,s-1))),a=vc([]),a.leaf=!1,a.height=s;const l=Math.ceil(o/i),c=l*Math.ceil(Math.sqrt(i));BT(e,t,r,c,this.compareMinX);for(let u=t;u<=r;u+=c){const d=Math.min(u+c-1,r);BT(e,u,d,l,this.compareMinY);for(let h=u;h<=d;h+=l){const f=Math.min(h+l-1,d);a.children.push(this._build(e,h,f,s-1))}}return oc(a,this.toBBox),a}_chooseSubtree(e,t,r,s){for(;s.push(t),!(t.leaf||s.length-1===r);){let o=1/0,i=1/0,a;for(let l=0;l<t.children.length;l++){const c=t.children[l],u=$x(c),d=W7(e,c)-u;d<i?(i=d,o=u<o?u:o,a=c):d===i&&u<o&&(o=u,a=c)}t=a||t.children[0]}return t}_insert(e,t,r){const s=r?e:this.toBBox(e),o=[],i=this._chooseSubtree(s,this.data,t,o);for(i.children.push(e),cu(i,s);t>=0&&o[t].children.length>this._maxEntries;)this._split(o,t),t--;this._adjustParentBBoxes(s,o,t)}_split(e,t){const r=e[t],s=r.children.length,o=this._minEntries;this._chooseSplitAxis(r,o,s);const i=this._chooseSplitIndex(r,o,s),a=vc(r.children.splice(i,r.children.length-i));a.height=r.height,a.leaf=r.leaf,oc(r,this.toBBox),oc(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(r,a)}_splitRoot(e,t){this.data=vc([e,t]),this.data.height=e.height+1,this.data.leaf=!1,oc(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let s,o=1/0,i=1/0;for(let a=t;a<=r-t;a++){const l=lu(e,0,a,this.toBBox),c=lu(e,a,r,this.toBBox),u=V7(l,c),d=$x(l)+$x(c);u<o?(o=u,s=a,i=d<i?d:i):u===o&&d<i&&(i=d,s=a)}return s||r-t}_chooseSplitAxis(e,t,r){const s=e.leaf?this.compareMinX:U7,o=e.leaf?this.compareMinY:K7,i=this._allDistMargin(e,t,r,s),a=this._allDistMargin(e,t,r,o);i<a&&e.children.sort(s)}_allDistMargin(e,t,r,s){e.children.sort(s);const o=this.toBBox,i=lu(e,0,t,o),a=lu(e,r-t,r,o);let l=Wp(i)+Wp(a);for(let c=t;c<r-t;c++){const u=e.children[c];cu(i,e.leaf?o(u):u),l+=Wp(i)}for(let c=r-t-1;c>=t;c--){const u=e.children[c];cu(a,e.leaf?o(u):u),l+=Wp(a)}return l}_adjustParentBBoxes(e,t,r){for(let s=r;s>=0;s--)cu(t[s],e)}_condense(e){for(let t=e.length-1,r;t>=0;t--)e[t].children.length===0?t>0?(r=e[t-1].children,r.splice(r.indexOf(e[t]),1)):this.clear():oc(e[t],this.toBBox)}}function H7(n,e,t){if(!t)return e.indexOf(n);for(let r=0;r<e.length;r++)if(t(n,e[r]))return r;return-1}function oc(n,e){lu(n,0,n.children.length,e,n)}function lu(n,e,t,r,s){s||(s=vc(null)),s.minX=1/0,s.minY=1/0,s.maxX=-1/0,s.maxY=-1/0;for(let o=e;o<t;o++){const i=n.children[o];cu(s,n.leaf?r(i):i)}return s}function cu(n,e){return n.minX=Math.min(n.minX,e.minX),n.minY=Math.min(n.minY,e.minY),n.maxX=Math.max(n.maxX,e.maxX),n.maxY=Math.max(n.maxY,e.maxY),n}function U7(n,e){return n.minX-e.minX}function K7(n,e){return n.minY-e.minY}function $x(n){return(n.maxX-n.minX)*(n.maxY-n.minY)}function Wp(n){return n.maxX-n.minX+(n.maxY-n.minY)}function W7(n,e){return(Math.max(e.maxX,n.maxX)-Math.min(e.minX,n.minX))*(Math.max(e.maxY,n.maxY)-Math.min(e.minY,n.minY))}function V7(n,e){const t=Math.max(n.minX,e.minX),r=Math.max(n.minY,e.minY),s=Math.min(n.maxX,e.maxX),o=Math.min(n.maxY,e.maxY);return Math.max(0,s-t)*Math.max(0,o-r)}function Hx(n,e){return n.minX<=e.minX&&n.minY<=e.minY&&e.maxX<=n.maxX&&e.maxY<=n.maxY}function Vp(n,e){return e.minX<=n.maxX&&e.minY<=n.maxY&&e.maxX>=n.minX&&e.maxY>=n.minY}function vc(n){return{children:n,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function BT(n,e,t,r,s){const o=[e,t];for(;o.length;){if(t=o.pop(),e=o.pop(),t-e<=r)continue;const i=e+Math.ceil((t-e)/r/2)*r;B7(n,i,e,t,s),o.push(e,i,i,t)}}class G7 extends $7{}class Y7{constructor(){E(this,"rBush");E(this,"elementsInTree");this.rBush=new G7,this.elementsInTree=new Map}search(e){const t=this.rBush.search({minX:e.minX,minY:e.minY,maxX:e.maxX,maxY:e.maxY});return new Set(t.map(r=>r.id))}upsert(e,t){const r=this.elementsInTree.get(e);r&&this.rBush.remove(r);const s={minX:t.minX,minY:t.minY,maxX:t.maxX,maxY:t.maxY,id:e};this.rBush.insert(s),this.elementsInTree.set(e,s)}remove(e){const t=this.elementsInTree.get(e);t&&(this.rBush.remove(t),this.elementsInTree.delete(e))}bulkLoad(e){this.rBush.load(e);for(const t of e)this.elementsInTree.set(t.id,t)}clear(){this.rBush.clear(),this.elementsInTree.clear()}has(e){return this.elementsInTree.has(e)}getSize(){return this.elementsInTree.size}getAllShapeIds(){return Array.from(this.elementsInTree.keys())}getBounds(e){const t=this.elementsInTree.get(e);if(t)return new J(t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY)}dispose(){this.clear()}}class X7{constructor(e){E(this,"rbush");E(this,"spatialIndexComputed");E(this,"lastPageId",null);this.editor=e,this.rbush=new Y7,this.spatialIndexComputed=this.createSpatialIndexComputed()}createSpatialIndexComputed(){const e=this.editor.store.query.filterHistory("shape");return q("spatialIndex",(t,r)=>{if(Ri(t))return this.buildFromScratch(r);const s=e.getDiffSince(r);if(s===Zr)return this.buildFromScratch(r);const o=this.editor.getCurrentPageId();return this.lastPageId!==o?this.buildFromScratch(r):(s.length===0||this.processIncrementalUpdate(s),r)})}buildFromScratch(e){this.rbush.clear(),this.lastPageId=this.editor.getCurrentPageId();const t=this.editor.getCurrentPageShapes(),r=[];for(const s of t){const o=this.editor.getShapePageBounds(s.id);o&&r.push({minX:o.minX,minY:o.minY,maxX:o.maxX,maxY:o.maxY,id:s.id})}return this.rbush.bulkLoad(r),e}processIncrementalUpdate(e){const t=new Set;for(const s of e){for(const o of Et(s.added))if(Di(o)&&this.editor.getAncestorPageId(o)===this.lastPageId){const i=this.editor.getShapePageBounds(o.id);i&&this.rbush.upsert(o.id,i),t.add(o.id)}for(const o of Et(s.removed))Di(o)&&(this.rbush.remove(o.id),t.add(o.id));for(const[,o]of Et(s.updated)){if(!Di(o))continue;if(t.add(o.id),this.editor.getAncestorPageId(o)===this.lastPageId){const a=this.editor.getShapePageBounds(o.id);a&&this.rbush.upsert(o.id,a)}else this.rbush.remove(o.id)}}const r=this.rbush.getAllShapeIds();for(const s of r){if(t.has(s))continue;const o=this.editor.getShapePageBounds(s),i=this.rbush.getBounds(s);this.areBoundsEqual(o,i)||(o?this.rbush.upsert(s,o):this.rbush.remove(s))}}areBoundsEqual(e,t){return!e&&!t?!0:!e||!t?!1:e.minX===t.minX&&e.minY===t.minY&&e.maxX===t.maxX&&e.maxY===t.maxY}getShapeIdsInsideBounds(e){return this.spatialIndexComputed.get(),this.rbush.search(e)}getShapeIdsAtPoint(e,t=0){return this.spatialIndexComputed.get(),this.rbush.search(new J(e.x-t,e.y-t,t*2,t*2))}dispose(){this.rbush.dispose(),this.lastPageId=null}}const q7=/\r?\n|\r/g;function zT(n){return n.replace(q7,`
71
+ `).split(`
72
+ `).map(e=>e||" ").join(`
73
+ `)}const Z7={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},J7=/\s/,$T=Object.freeze({"overflow-wrap":"break-word","word-break":"auto",width:null,height:null,"max-width":null,"min-width":null});class Q7{constructor(e){E(this,"elm");this.editor=e;const t=document.createElement("div");t.classList.add("tl-text"),t.classList.add("tl-text-measure"),t.setAttribute("dir","auto"),t.tabIndex=-1,this.editor.getContainer().appendChild(t),this.elm=t;for(const r of Au($T))t.style.setProperty(r,$T[r])}setElementStyles(e){const t={};for(const r of Au(e))if(typeof e[r]=="string"){const s=this.elm.style.getPropertyValue(r);if(s===e[r])continue;t[r]=s,this.elm.style.setProperty(r,e[r])}return()=>{for(const r of Au(t))this.elm.style.setProperty(r,t[r])}}dispose(){return this.elm.remove()}measureText(e,t){const r=document.createElement("div");return r.textContent=zT(e),this.measureHtml(r.innerHTML,t)}measureHtml(e,t){const{elm:r}=this,s={"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"font-size":t.fontSize+"px","line-height":t.lineHeight.toString(),padding:t.padding,"max-width":t.maxWidth?t.maxWidth+"px":void 0,"min-width":t.minWidth?t.minWidth+"px":void 0,"overflow-wrap":t.disableOverflowWrapBreaking?"normal":void 0,...t.otherStyles},o=this.setElementStyles(s);try{r.innerHTML=e;const i=t.measureScrollWidth?r.scrollWidth:0,a=r.getBoundingClientRect();return{x:0,y:0,w:a.width,h:a.height,scrollWidth:i}}finally{o()}}measureElementTextNodeSpans(e,{shouldTruncateToFirstLine:t=!1}={}){const r=[],s=e.getBoundingClientRect(),o=-s.left,i=-s.top,a=new Range,l=e.childNodes[0];let c=0,u=null,d=null,h=0,f=0,g=!1;for(const m of e.childNodes)if(m.nodeType===Node.TEXT_NODE)for(const y of m.textContent??""){a.setStart(l,c),a.setEnd(l,c+y.length);const S=a.getClientRects(),b=S[S.length-1],w=b.top+i,v=b.left+o,P=b.right+o,T=v<f,I=J7.test(y);if(I!==d||w!==h||!u){if(u){if(t&&w!==h){g=!0;break}r.push(u)}u={box:{x:v,y:w,w:b.width,h:b.height},text:y},f=v}else T&&(u.box.x=v),u.box.w=T?u.box.w+b.width:P-u.box.x,u.text+=y;y===`
74
+ `&&(f=0),d=I,h=w,c+=y.length}return u&&r.push(u),{spans:r,didTruncate:g}}measureTextSpans(e,t){if(e==="")return[];const{elm:r}=this,s=t.overflow==="truncate-ellipsis"||t.overflow==="truncate-clip",o=Math.ceil(t.width-t.padding*2),i={"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"font-size":t.fontSize+"px","line-height":t.lineHeight.toString(),width:`${o}px`,height:"min-content","text-align":Z7[t.textAlign],"overflow-wrap":s?"anywhere":void 0,"word-break":s?"break-all":void 0,...t.otherStyles},a=this.setElementStyles(i);try{const l=zT(e);r.textContent=l;const{spans:c,didTruncate:u}=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:s});if(t.overflow==="truncate-ellipsis"&&u){r.textContent="…";const d=Math.ceil(this.measureElementTextNodeSpans(r).spans[0].box.w);r.style.setProperty("width",`${o-d}px`),r.textContent=l;const h=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:!0}).spans,f=h[h.length-1];return h.push({text:"…",box:{x:Math.min(f.box.x+f.box.w,t.width-t.padding-d),y:f.box.y,w:d,h:f.box.h}}),h}return c}finally{a()}}}var eK=Object.create,rD=Object.defineProperty,tK=Object.getOwnPropertyDescriptor,nK=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),sD=n=>{throw TypeError(n)},oD=(n,e,t)=>e in n?rD(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,rK=n=>[,,,eK(null)],iD=["class","method","getter","setter","accessor","field","value","get","set"],aD=n=>n!==void 0&&typeof n!="function"?sD("Function expected"):n,sK=(n,e,t,r,s)=>({kind:iD[n],name:e,metadata:r,addInitializer:o=>t._?sD("Already initialized"):s.push(aD(o||null))}),oK=(n,e)=>oD(e,nK("metadata"),n[3]),iK=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},lD=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=iD[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,tK(s,t)),S=r.length-1;S>=0;S--)l=sK(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,aD(i)&&(y[g]=i);return y&&rD(s,t,y),s},Ux=(n,e,t)=>oD(n,typeof e!="symbol"?e+"":e,t),cD,dD,Wh;const HT=Sv;dD=[Xr],cD=[Xr];class Iy{constructor(e){this.editor=e,iK(Wh,5,this),Ux(this,"cancelRaf"),Ux(this,"isPaused",!0),Ux(this,"now",0),this.editor.disposables.add(this.dispose),this.start()}start(){var e;this.isPaused=!1,(e=this.cancelRaf)==null||e.call(this),this.cancelRaf=HT(this.tick),this.now=Date.now()}tick(){if(this.isPaused)return;const e=Date.now(),t=e-this.now;this.now=e,this.editor.inputs.updatePointerVelocity(t),this.editor.emit("frame",t),this.editor.emit("tick",t),this.cancelRaf=HT(this.tick)}dispose(){var e;this.isPaused=!0,(e=this.cancelRaf)==null||e.call(this)}}Wh=rK();lD(Wh,1,"tick",dD,Iy);lD(Wh,1,"dispose",cD,Iy);oK(Wh,Iy);var aK=Object.create,uD=Object.defineProperty,lK=Object.getOwnPropertyDescriptor,cK=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),hD=n=>{throw TypeError(n)},pD=(n,e,t)=>e in n?uD(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,dK=n=>[,,,aK(null)],fD=["class","method","getter","setter","accessor","field","value","get","set"],gD=n=>n!==void 0&&typeof n!="function"?hD("Function expected"):n,uK=(n,e,t,r,s)=>({kind:fD[n],name:e,metadata:r,addInitializer:o=>t._?hD("Already initialized"):s.push(gD(o||null))}),hK=(n,e)=>pD(e,cK("metadata"),n[3]),pK=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},hr=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=fD[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,lK(s,t)),S=r.length-1;S>=0;S--)l=uK(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,gD(i)&&(y[g]=i);return y&&uD(s,t,y),s},UT=(n,e,t)=>pD(n,typeof e!="symbol"?e+"":e,t),mD,yD,SD,xD,bD,wD,vD,CD,PD,TD,ID,ED,kD,_D,MD,AD,yn;AD=[q],MD=[q],_D=[q],kD=[q],ED=[q],ID=[q],TD=[q],PD=[q],CD=[q],vD=[q],wD=[q],bD=[q],xD=[q],SD=[q],yD=[q],mD=[q];class An{constructor(e,t){if(this.user=e,this.inferDarkMode=t,pK(yn,5,this),UT(this,"systemColorScheme",We("systemColorScheme","light")),UT(this,"disposables",new Set),typeof window>"u"||!window.matchMedia)return;const r=window.matchMedia("(prefers-color-scheme: dark)");r!=null&&r.matches&&this.systemColorScheme.set("dark");const s=o=>{o.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")};r==null||r.addEventListener("change",s),this.disposables.add(()=>r==null?void 0:r.removeEventListener("change",s))}dispose(){this.disposables.forEach(e=>e())}updateUserPreferences(e){this.user.setUserPreferences({...this.user.userPreferences.get(),...e})}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),areKeyboardShortcutsEnabled:this.getAreKeyboardShortcutsEnabled(),isSnapMode:this.getIsSnapMode(),colorScheme:this.user.userPreferences.get().colorScheme,isDarkMode:this.getIsDarkMode(),isWrapMode:this.getIsWrapMode(),isDynamicResizeMode:this.getIsDynamicResizeMode(),enhancedA11yMode:this.getEnhancedA11yMode(),inputMode:this.getInputMode(),isZoomDirectionInverted:this.getIsZoomDirectionInverted()}}getIsDarkMode(){switch(this.user.userPreferences.get().colorScheme){case"dark":return!0;case"light":return!1;case"system":return this.systemColorScheme.get()==="dark";default:return this.inferDarkMode?this.systemColorScheme.get()==="dark":!1}}getEdgeScrollSpeed(){return this.user.userPreferences.get().edgeScrollSpeed??Cr.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??Cr.animationSpeed}getAreKeyboardShortcutsEnabled(){return this.user.userPreferences.get().areKeyboardShortcutsEnabled??Cr.areKeyboardShortcutsEnabled}getId(){return this.user.userPreferences.get().id}getName(){var e;return((e=this.user.userPreferences.get().name)==null?void 0:e.trim())??Cr.name}getLocale(){return this.user.userPreferences.get().locale??Cr.locale}getColor(){return this.user.userPreferences.get().color??Cr.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??Cr.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??Cr.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??Cr.isDynamicSizeMode}getIsPasteAtCursorMode(){return this.user.userPreferences.get().isPasteAtCursorMode??Cr.isPasteAtCursorMode}getEnhancedA11yMode(){return this.user.userPreferences.get().enhancedA11yMode??Cr.enhancedA11yMode}getInputMode(){return this.user.userPreferences.get().inputMode??Cr.inputMode}getIsZoomDirectionInverted(){return this.user.userPreferences.get().isZoomDirectionInverted??Cr.isZoomDirectionInverted}}yn=dK();hr(yn,1,"getUserPreferences",AD,An);hr(yn,1,"getIsDarkMode",MD,An);hr(yn,1,"getEdgeScrollSpeed",_D,An);hr(yn,1,"getAnimationSpeed",kD,An);hr(yn,1,"getAreKeyboardShortcutsEnabled",ED,An);hr(yn,1,"getId",ID,An);hr(yn,1,"getName",TD,An);hr(yn,1,"getLocale",PD,An);hr(yn,1,"getColor",CD,An);hr(yn,1,"getIsSnapMode",vD,An);hr(yn,1,"getIsWrapMode",wD,An);hr(yn,1,"getIsDynamicResizeMode",bD,An);hr(yn,1,"getIsPasteAtCursorMode",xD,An);hr(yn,1,"getEnhancedA11yMode",SD,An);hr(yn,1,"getInputMode",yD,An);hr(yn,1,"getIsZoomDirectionInverted",mD,An);hK(yn,An);const fK={wheel:"onWheel",pointer_down:"onPointerDown",pointer_move:"onPointerMove",long_press:"onLongPress",pointer_up:"onPointerUp",right_click:"onRightClick",middle_click:"onMiddleClick",key_down:"onKeyDown",key_up:"onKeyUp",key_repeat:"onKeyRepeat",cancel:"onCancel",complete:"onComplete",interrupt:"onInterrupt",double_click:"onDoubleClick",triple_click:"onTripleClick",quadruple_click:"onQuadrupleClick",tick:"onTick"},gK=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class ve{constructor(e,t){E(this,"performanceTracker");E(this,"id");E(this,"type");E(this,"shapeType");E(this,"initial");E(this,"children");E(this,"isLockable");E(this,"useCoalescedEvents");E(this,"parent");E(this,"_path");E(this,"_current");E(this,"_isActive");E(this,"_currentToolIdMask",We("curent tool id mask",void 0));this.editor=e;const{id:r,children:s,initial:o,isLockable:i,useCoalescedEvents:a}=this.constructor;this.id=r,this._isActive=We("toolIsActive"+this.id,!1),this._current=We("toolState"+this.id,void 0),this._path=q("toolPath"+this.id,()=>{const l=this.getCurrent();return this.id+(l?`.${l.getPath()}`:"")}),this.parent=t??{},t?s&&o?(this.type="branch",this.initial=o,this.children=Object.fromEntries(s().map(l=>[l.id,new l(this.editor,this)])),this._current.set(this.children[this.initial])):this.type="leaf":(this.type="root",s&&o&&(this.initial=o,this.children=Object.fromEntries(s().map(l=>[l.id,new l(this.editor,this)])),this._current.set(this.children[this.initial]))),this.isLockable=i,this.useCoalescedEvents=a,this.performanceTracker=new G_}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}transition(e,t={}){var o;const r=e.split(".");let s=this;for(let i=0;i<r.length;i++){const a=r[i],l=s.getCurrent(),c=(o=s.children)==null?void 0:o[a];if(!c)throw Error(`${s.id} - no child state exists with the id ${a}.`);if((l==null?void 0:l.id)!==c.id&&(l==null||l.exit(t,a),s._current.set(c),c.enter(t,(l==null?void 0:l.id)||"initial"),!c.getIsActive()))break;s=c}return this}handleEvent(e){var s;const t=fK[e.name],r=this._current.__unsafe__getWithoutCapture();(s=this[t])==null||s.call(this,e),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(e)}enter(e,t){var r;if(Dt.measurePerformance.get()&&gK.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,e,t),this.children&&this.initial&&this.getIsActive()){const s=this.children[this.initial];this._current.set(s),s.enter(e,t)}}exit(e,t){var r,s;Dt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,e,t),this.getIsActive()||(s=this.getCurrent())==null||s.exit(e,t)}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(e){this._currentToolIdMask.set(e)}addChild(e){if(this.type==="leaf")throw new Error("StateNode.addChild: cannot add child to a leaf node");this.children||(this.children={});const t=new e(this.editor,this);if(this.children[t.id])throw new Error(`StateNode.addChild: a child with id '${t.id}' already exists`);return this.children[t.id]=t,this}}E(ve,"id"),E(ve,"initial"),E(ve,"children"),E(ve,"isLockable",!0),E(ve,"useCoalescedEvents",!1);class jw extends ve{static children(){return[]}}E(jw,"id","root"),E(jw,"initial","");var mK=Object.create,DD=Object.defineProperty,yK=Object.getOwnPropertyDescriptor,OD=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),RD=n=>{throw TypeError(n)},LD=(n,e,t)=>e in n?DD(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,SK=n=>[,,,mK((n==null?void 0:n[OD("metadata")])??null)],jD=["class","method","getter","setter","accessor","field","value","get","set"],ND=n=>n!==void 0&&typeof n!="function"?RD("Function expected"):n,xK=(n,e,t,r,s)=>({kind:jD[n],name:e,metadata:r,addInitializer:o=>t._?RD("Already initialized"):s.push(ND(o||null))}),bK=(n,e)=>LD(e,OD("metadata"),n[3]),wK=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},me=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=jD[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,yK(s,t)),S=r.length-1;S>=0;S--)l=xK(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,ND(i)&&(y[g]=i);return y&&DD(s,t,y),s},Ie=(n,e,t)=>LD(n,typeof e!="symbol"?e+"":e,t),FD,BD,zD,$D,HD,UD,KD,WD,VD,GD,YD,XD,qD,ZD,JD,QD,eO,tO,nO,rO,sO,oO,iO,aO,lO,cO,dO,uO,hO,pO,fO,gO,mO,yO,SO,xO,bO,wO,vO,CO,PO,TO,IO,EO,kO,_O,MO,AO,DO,OO,RO,LO,jO,NO,FO,BO,zO,$O,HO,UO,KO,WO,VO,GO,YO,XO,qO,ZO,JO,QO,eR,tR,nR,rR,Nw,pe;let he=class extends(Nw=h8,rR=[q],nR=[q],tR=[q],eR=[q],QO=[q],JO=[q],ZO=[q],qO=[q],XO=[q],YO=[q],GO=[q],VO=[q],WO=[q],KO=[q],UO=[q],HO=[q],$O=[q],zO=[q],BO=[q],FO=[q],NO=[q],jO=[q],LO=[q],RO=[q],OO=[q],DO=[q],AO=[q],MO=[q],_O=[q],kO=[q],EO=[q],IO=[q],TO=[q],PO=[q],CO=[q],vO=[q],wO=[q],bO=[q],xO=[q],SO=[q],yO=[q],mO=[q],gO=[q],fO=[q],pO=[q],hO=[q],uO=[q],dO=[q],cO=[q],lO=[q],aO=[q],iO=[q],oO=[q],sO=[q],rO=[q],nO=[q],tO=[q],eO=[q],QD=[q],JD=[q],ZD=[q],qD=[q],XD=[q],YD=[q],GD=[q],VD=[q],WD=[q({isEqual:(e,t)=>e.equals(t)})],KD=[q],UD=[q],HD=[q],$D=[Xr],zD=[Xr],BD=[Xr],FD=[Xr],Nw){constructor({store:e,user:t,shapeUtils:r,bindingUtils:s,tools:o,getContainer:i,cameraOptions:a,initialState:l,autoFocus:c,inferDarkMode:u,options:d,textOptions:h,getShapeVisibility:f,fontAssetUrls:g}){var j;super(),wK(pe,5,this),Ie(this,"id",at()),Ie(this,"_getShapeVisibility"),Ie(this,"options"),Ie(this,"contextId",at()),Ie(this,"store"),Ie(this,"root"),Ie(this,"disposables",new Set),Ie(this,"isDisposed",!1),Ie(this,"_tickManager"),Ie(this,"inputs"),Ie(this,"snaps"),Ie(this,"_spatialIndex"),Ie(this,"timers",Ug.forContext(this.contextId)),Ie(this,"user"),Ie(this,"textMeasure"),Ie(this,"fonts"),Ie(this,"scribbles"),Ie(this,"sideEffects"),Ie(this,"edgeScrollManager"),Ie(this,"focusManager"),Ie(this,"getContainer"),Ie(this,"shapeUtils"),Ie(this,"styleProps"),Ie(this,"bindingUtils"),Ie(this,"history"),Ie(this,"_shouldIgnoreShapeLock",!1),Ie(this,"_crashingError",null),Ie(this,"_isChangingStyleTimeout",-1),Ie(this,"menus",Tr.forContext(this.contextId)),Ie(this,"_currentRichTextEditor",We("rich text editor",null)),Ie(this,"_textOptions"),Ie(this,"_debouncedZoomLevel",We("debounced zoom level",1)),Ie(this,"_cameraOptions",We("camera options",_w)),Ie(this,"_viewportAnimation",null),Ie(this,"_willSetInitialBounds",!0),Ie(this,"_isLockedOnFollowingUser",We("isLockedOnFollowingUser",!1)),Ie(this,"_cameraStateTimeoutRemaining",0),Ie(this,"_currentPageShapeIds"),Ie(this,"_shapeGeometryCaches",{}),Ie(this,"_notVisibleShapes",F9(this)),Ie(this,"_culledShapesCache",null),Ie(this,"_parentIdsToChildIds"),Ie(this,"animatingShapes",new Map),Ie(this,"externalAssetContentHandlers",{file:null,url:null}),Ie(this,"temporaryAssetPreview",new Map),Ie(this,"externalContentHandlers",{text:null,files:null,"file-replace":null,embed:null,"svg-text":null,url:null,tldraw:null,excalidraw:null}),Ie(this,"_clickManager",new vy(this)),Ie(this,"_prevCursor","default"),Ie(this,"_shiftKeyTimeout",-1),Ie(this,"_altKeyTimeout",-1),Ie(this,"_ctrlKeyTimeout",-1),Ie(this,"_metaKeyTimeout",-1),Ie(this,"_restoreToolId","select"),Ie(this,"_didPinch",!1),Ie(this,"_selectedShapeIdsAtPointerDown",[]),Ie(this,"_longPressTimeout",-1),Ie(this,"capturedPointerId",null),Ie(this,"performanceTracker"),Ie(this,"performanceTrackerTimeout",-1),Ie(this,"handledEvents",new WeakSet),Ie(this,"_pendingEventsForNextTick",[]),this._getShapeVisibility=f;const m=h?{...d,text:(d==null?void 0:d.text)??h}:d;this.options={...I9,...m},this.store=e,this.history=new J9({store:e,annotateError:_=>{this.annotateError(_,{origin:"history.batch",willCrashApp:!0}),this.crash(_)}}),this.snaps=new Kh(this),this._spatialIndex=new X7(this),this.disposables.add(()=>this._spatialIndex.dispose()),this.disposables.add(this.timers.dispose),this._cameraOptions.set({..._w,...a,...m==null?void 0:m.camera}),this._textOptions=We("text options",(m==null?void 0:m.text)??null),this.user=new An(t??RA(),u??!1),this.disposables.add(()=>this.user.dispose()),this.getContainer=i,this.textMeasure=new Q7(this),this.disposables.add(()=>this.textMeasure.dispose()),this.fonts=new Z9(this,g),this._tickManager=new Iy(this),this.inputs=new i1(this);class y extends jw{}E(y,"initial",l??""),this.root=new y(this),this.root.children={},this.markEventAsHandled=this.markEventAsHandled.bind(this);const S=KA(r),b={},w={},v=new Map;for(const _ of S){const M=new _(this);b[_.type]=M;const O=AM(_.props??{});w[_.type]=O;for(const N of O.keys())if(!v.has(N.id))v.set(N.id,N);else if(v.get(N.id)!==N)throw Error(`Multiple style props with id "${N.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=b,this.styleProps=w;const P=BA(s),T={};for(const _ of P){const M=new _(this);T[_.type]=M}this.bindingUtils=T;for(const _ of[...o]){if(gn(this.root.children,_.id))throw Error(`Can't override tool with id "${_.id}"`);this.root.children[_.id]=new _(this,this.root)}this.scribbles=new u7(this);const I=(_,M)=>{let O=null;const N=_.selectedShapeIds.filter(z=>!M.has(z));N.length!==_.selectedShapeIds.length&&(O||(O={..._}),O.selectedShapeIds=N);const B=_.erasingShapeIds.filter(z=>!M.has(z));B.length!==_.erasingShapeIds.length&&(O||(O={..._}),O.erasingShapeIds=B),_.hoveredShapeId&&M.has(_.hoveredShapeId)&&(O||(O={..._}),O.hoveredShapeId=null),_.editingShapeId&&M.has(_.editingShapeId)&&(O||(O={..._}),O.editingShapeId=null);const H=_.hintingShapeIds.filter(z=>!M.has(z));return H.length!==_.hintingShapeIds.length&&(O||(O={..._}),O.hintingShapeIds=H),_.focusedGroupId&&M.has(_.focusedGroupId)&&(O||(O={..._}),O.focusedGroupId=null),O};this.sideEffects=this.store.sideEffects;let k=new Map;const A=new Set,R=new Set;let D=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var _,M,O,N;A.clear();for(const B of R){R.delete(B);const H=this.getShape(B);if(!H)continue;const z=this.getShapeUtil(H),X=(_=z.onChildrenChange)==null?void 0:_.call(z,H);X!=null&&X.length&&this.updateShapes(X)}if(D.size){const B=D;D=new Set;for(const H of B){const z=this.getBindingUtil(H);(M=z.onOperationComplete)==null||M.call(z)}}if(k.size){const B=k;k=new Map;for(const H of B.values())(N=(O=this.getBindingUtil(H.binding)).onAfterDelete)==null||N.call(O,H)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(_,M)=>{var O,N,B,H;for(const z of this.getBindingsInvolvingShape(M))D.add(z.type),z.fromId===M.id&&((N=(O=this.getBindingUtil(z)).onAfterChangeFromShape)==null||N.call(O,{binding:z,shapeBefore:_,shapeAfter:M,reason:"self"})),z.toId===M.id&&((H=(B=this.getBindingUtil(z)).onAfterChangeToShape)==null||H.call(B,{binding:z,shapeBefore:_,shapeAfter:M,reason:"self"}));if(_.parentId!==M.parentId){const z=X=>{var ae,Ce,fe,oe;const G=this.getShape(X);if(G)for(const Te of this.getBindingsInvolvingShape(G))D.add(Te.type),Te.fromId===G.id&&((Ce=(ae=this.getBindingUtil(Te)).onAfterChangeFromShape)==null||Ce.call(ae,{binding:Te,shapeBefore:G,shapeAfter:G,reason:"ancestry"})),Te.toId===G.id&&((oe=(fe=this.getBindingUtil(Te)).onAfterChangeToShape)==null||oe.call(fe,{binding:Te,shapeBefore:G,shapeAfter:G,reason:"ancestry"}))};z(M.id),this.visitDescendants(M.id,z)}if(_.parentId!==M.parentId&&On(M.parentId)){const z=new Set([_.id]);this.visitDescendants(_.id,X=>{z.add(X)});for(const X of this.getPageStates()){if(X.pageId===M.parentId)continue;const G=I(X,z);G&&this.store.put([G])}}_.parentId&&Pr(_.parentId)&&R.add(_.parentId),M.parentId!==_.parentId&&Pr(M.parentId)&&R.add(M.parentId)},beforeDelete:_=>{var B,H,z,X;if(A.has(_.id))return;_.parentId&&Pr(_.parentId)&&R.add(_.parentId),A.add(_.id);const M=[];for(const G of this.getBindingsInvolvingShape(_)){D.add(G.type),M.push(G.id);const ae=this.getBindingUtil(G);G.fromId===_.id?((B=ae.onBeforeIsolateToShape)==null||B.call(ae,{binding:G,removedShape:_}),(H=ae.onBeforeDeleteFromShape)==null||H.call(ae,{binding:G,shape:_})):((z=ae.onBeforeIsolateFromShape)==null||z.call(ae,{binding:G,removedShape:_}),(X=ae.onBeforeDeleteToShape)==null||X.call(ae,{binding:G,shape:_}))}M.length&&this.deleteBindings(M);const O=new Set([_.id]),N=Le(this.getPageStates().map(G=>I(G,O)));N.length&&this.store.put(N)}},binding:{beforeCreate:_=>{var O,N;const M=(N=(O=this.getBindingUtil(_)).onBeforeCreate)==null?void 0:N.call(O,{binding:_});return M||_},afterCreate:_=>{var M,O;D.add(_.type),(O=(M=this.getBindingUtil(_)).onAfterCreate)==null||O.call(M,{binding:_})},beforeChange:(_,M)=>{var N,B;const O=(B=(N=this.getBindingUtil(M)).onBeforeChange)==null?void 0:B.call(N,{bindingBefore:_,bindingAfter:M});return O||M},afterChange:(_,M)=>{var O,N;D.add(M.type),(N=(O=this.getBindingUtil(M)).onAfterChange)==null||N.call(O,{bindingBefore:_,bindingAfter:M})},beforeDelete:_=>{var M,O;(O=(M=this.getBindingUtil(_)).onBeforeDelete)==null||O.call(M,{binding:_})},afterDelete:_=>{var M,O;(O=(M=this.getBindingUtil(_)).onAfterDelete)==null||O.call(M,{binding:_}),D.add(_.type)}},page:{afterCreate:_=>{const M=zo.createId(_.id),O=uo.createId(_.id);this.store.has(M)||this.store.put([zo.create({id:M})]),this.store.has(O)||this.store.put([uo.create({id:O,pageId:_.id})])},afterDelete:(_,M)=>{var B,H;if(((B=this.getInstanceState())==null?void 0:B.currentPageId)===_.id){const z=(H=this.getPages().find(X=>X.id!==_.id))==null?void 0:H.id;z?this.store.put([{...this.getInstanceState(),currentPageId:z}]):M==="user"&&this.store.ensureStoreIsUsable()}const O=zo.createId(_.id),N=uo.createId(_.id);this.store.remove([O,N])}},instance:{afterChange:(_,M,O)=>{var N;if(!this.store.has(M.currentPageId)){const B=this.store.has(_.currentPageId)?_.currentPageId:(N=this.getPages()[0])==null?void 0:N.id;B?this.store.update(M.id,H=>({...H,currentPageId:B})):O==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(_,M)=>{if((_==null?void 0:_.selectedShapeIds)!==(M==null?void 0:M.selectedShapeIds)){const O=M.selectedShapeIds.filter(B=>{var z,X;let H=(z=this.getShape(B))==null?void 0:z.parentId;for(;Pr(H);){if(M.selectedShapeIds.includes(H))return!1;H=(X=this.getShape(H))==null?void 0:X.parentId}return!0});let N=null;if(O.length>0){const B=this.findCommonAncestor(Le(O.map(H=>this.getShape(H))),H=>this.isShapeOfType(H,"group"));B&&(N=B)}else M!=null&&M.focusedGroupId&&(N=M.focusedGroupId);(O.length!==M.selectedShapeIds.length||N!==M.focusedGroupId)&&this.store.put([{...M,selectedShapeIds:O,focusedGroupId:N??null}])}}}})),this._currentPageShapeIds=z9(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=B9(this.store),this.disposables.add(this.store.listen(_=>{this.emit("change",_)})),this.disposables.add(this.history.dispose),this.run(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})},{history:"ignore"}),l&&this.root.children[l]===void 0)throw Error(`No state found for initialState "${l}".`);if(this.root.enter(void 0,"initial"),this.edgeScrollManager=new X9(this),this.focusManager=new q9(this,c),this.disposables.add(this.focusManager.dispose.bind(this.focusManager)),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this.on("tick",this._flushEventsForTick),this.timers.requestAnimationFrame(()=>{this._tickManager.start()}),this.performanceTracker=new G_,(j=this.store.props.collaboration)!=null&&j.mode){const _=this.store.props.collaboration.mode;this.disposables.add(Mr("update collaboration mode",()=>{this.store.put([{...this.getInstanceState(),isReadonly:_.get()==="readonly"}])}))}}getIsShapeHiddenCache(){return this._getShapeVisibility?this.store.createComputedCache("isShapeHidden",e=>{const t=this._getShapeVisibility(e,this);return(Ar.isId(e.parentId)?!1:this.isShapeHidden(e.parentId))?t!=="visible":t==="hidden"}):null}isShapeHidden(e){return this._getShapeVisibility?!!this.getIsShapeHiddenCache().get(typeof e=="string"?e:e.id):!1}setTool(e,t){if(t??(t=this.root),gn(t.children,e.id))throw Error(`Can't override tool with id "${e.id}"`);t.children[e.id]=new e(this,t)}removeTool(e,t){t??(t=this.root),gn(t.children,e.id)&&delete t.children[e.id]}dispose(){this.disposables.forEach(e=>e()),this.disposables.clear(),this.store.dispose(),this.isDisposed=!0,this.emit("dispose")}getShapeUtil(e){const t=typeof e=="string"?e:e.type,r=un(this.shapeUtils,t);return be(r,`No shape util found for type "${t}"`),r}hasShapeUtil(e){const t=typeof e=="string"?e:e.type;return gn(this.shapeUtils,t)}getBindingUtil(e){const t=typeof e=="string"?e:e.type,r=un(this.bindingUtils,t);return be(r,`No binding util found for type "${t}"`),r}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}canUndo(){return this.history.getNumUndos()>0}getCanUndo(){return this.canUndo()}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}canRedo(){return this.history.getNumRedos()>0}getCanRedo(){return this.canRedo()}clearHistory(){return this.history.clear(),this}markHistoryStoppingPoint(e){const t=`[${e??"stop"}]_${at()}`;return this.history._mark(t),t}getMarkIdMatching(e){return this.history.getMarkIdMatching(e)}squashToMark(e){return this.history.squashToMark(e),this}bail(){return this.history.bail(),this}bailToMark(e){return this.history.bailToMark(e),this}run(e,t){const r=this._shouldIgnoreShapeLock;this._shouldIgnoreShapeLock=(t==null?void 0:t.ignoreShapeLock)??r;try{this.history.batch(e,t)}finally{this._shouldIgnoreShapeLock=r}return this}annotateError(e,{origin:t,willCrashApp:r,tags:s,extras:o}){const i=this.createErrorAnnotations(t,r);return pv(e,{tags:{...i.tags,...s},extras:{...i.extras,...o}}),r&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(e,t){try{const r=this.getEditingShapeId();return{tags:{origin:e,willCrashApp:t},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes().map(s=>{const{props:o,...i}=s,{text:a,richText:l,...c}=o;return{...i,props:c}}),selectionCount:this.getSelectedShapes().length,editingShape:r?this.getShape(r):void 0,inputs:this.inputs.toJson(),pageState:this.getCurrentPageState(),instanceState:this.getInstanceState(),collaboratorCount:this.getCollaboratorsOnCurrentPage().length}}}catch{return{tags:{origin:e,willCrashApp:t},extras:{}}}}getCrashingError(){return this._crashingError}crash(e){return this._crashingError=e,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:e}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(e){const t=e.split(".").reverse();let r=this.root;for(;t.length>0;){const s=t.pop();if(!s)return!0;const o=r.getCurrent();if((o==null?void 0:o.id)===s){if(t.length===0)return!0;r=o;continue}else return!1}return!1}isInAny(...e){return e.some(t=>this.isIn(t))}setCurrentTool(e,t={}){return this.root.transition(e,t),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const e=this.getCurrentTool();return e?e.getCurrentToolIdMask()??e.id:""}getStateDescendant(e){var s;const t=e.split(".").reverse();let r=this.root;for(;t.length>0;){const o=t.pop();if(!o)return r;const i=(s=r.children)==null?void 0:s[o];if(!i)return;r=i}return r}getDocumentSettings(){return this.store.get(Tw)}updateDocumentSettings(e){return this.run(()=>{this.store.put([{...this.getDocumentSettings(),...e}])},{history:"ignore"}),this}getInstanceState(){return this.store.get(Er)}updateInstanceState(e,t){return this._updateInstanceState(e,{history:"ignore",...t}),e.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),e.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},1e3))),this}_updateInstanceState(e,t){this.run(()=>{this.store.put([{...this.getInstanceState(),...e}])},t)}setCursor(e){return this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...e}}),this}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return uo.createId(this.getCurrentPageId())}updateCurrentPageState(e){return this._updateCurrentPageState(e),this}_updateCurrentPageState(e){this.store.update(e.id??this.getCurrentPageState().id,t=>({...t,...e}))}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){return Le(this.getSelectedShapeIds().map(e=>this.store.get(e)))}setSelectedShapes(e){return this.run(()=>{const t=e.map(o=>typeof o=="string"?o:o.id),{selectedShapeIds:r}=this.getCurrentPageState(),s=new Set(r);if(t.length===s.size&&t.every(o=>s.has(o)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:t}])},{history:"record-preserveRedoStack"})}isAncestorSelected(e){const t=typeof e=="string"?e:(e==null?void 0:e.id)??null,r=this.getShape(t);if(!r)return!1;const s=this.getSelectedShapeIds();return!!this.findShapeAncestor(r,o=>s.includes(o.id))}select(...e){const t=typeof e[0]=="string"?e:e.map(r=>r.id);return this.setSelectedShapes(t),this}deselect(...e){const t=typeof e[0]=="string"?e:e.map(s=>s.id),r=this.getSelectedShapeIds();return r.length>0&&t.length>0&&this.setSelectedShapes(r.filter(s=>!t.includes(s))),this}selectAll(){let e=null;const t=this.getSelectedShapeIds();if(t.length>0)for(const s of t){const o=this.getShape(s);if(o){if(e===null)e=o.parentId;else if(e!==o.parentId)return this}}e||(e=this.getCurrentPageId());const r=this.getSortedChildIdsForParent(e);return r.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(r)),this)}selectAdjacentShape(e){var u,d;const t=this.getSelectedShapeIds(),r=t[0]?(u=this.getShape(t[0]))==null?void 0:u.parentId:null,s=r&&t.every(h=>{var f;return((f=this.getShape(h))==null?void 0:f.parentId)===r})&&!On(r),o=s?this.getCurrentPageShapes().filter(h=>h.parentId===r):this.getCurrentPageShapes().filter(h=>On(h.parentId)),i=s?this._getShapesInReadingOrder(o):this.getCurrentPageShapesInReadingOrder(),a=t.length===1?t[0]:(d=i.find(h=>t.includes(h.id)))==null?void 0:d.id;let l;if(e==="next"||e==="prev"){const h=i.map(m=>m.id),g=((a?h.indexOf(a):-1)+(e==="next"?1:-1)+h.length)%h.length;l=h[g]}else{if(!a)return;l=this.getNearestAdjacentShape(o,a,e)}const c=this.getShape(l);c&&this._selectShapesAndZoom([c.id])}getCurrentPageShapesInReadingOrder(){const e=this.getCurrentPageShapes().filter(t=>On(t.parentId));return this._getShapesInReadingOrder(e)}_getShapesInReadingOrder(e){const s=e.filter(a=>this.getShapeUtil(a).canTabTo(a));if(s.length<=1)return s;const o=s.map(a=>({shape:a,center:this.getShapePageBounds(a).center}));o.sort((a,l)=>a.center.y-l.center.y);const i=[];for(const a of o){let l=-1;for(let c=i.length-1;c>=0;c--){const u=i[c],d=u[u.length-1];if(Math.abs(a.center.y-d.center.y)<100){l=c;break}}l===-1?i.push([a]):i[l].push(a)}for(const a of i)a.sort((l,c)=>l.center.x-c.center.x);for(const a of i)if(!(a.length<=2))for(let l=0;l<a.length-2;l++){const c=a[l],u=a[l+1],d=a[l+2],h=C.Dist2(c.center,u.center);C.Dist2(c.center,d.center)<h*.9&&Math.abs(C.Angle(c.center,d.center)*(180/Math.PI))<=20&&([a[l+1],a[l+2]]=[a[l+2],a[l+1]])}return i.flat().map(a=>a.shape)}getNearestAdjacentShape(e,t,r){const s={right:0,left:180,down:90,up:270},o=this.getShape(t);if(!o)return t;const i=e.filter(d=>this.getShapeUtil(d).canTabTo(d)&&d.id!==t);if(!i.length)return t;const a=this.getShapePageBounds(o).center,c=i.map(d=>({shape:d,center:this.getShapePageBounds(d).center})).filter(({center:d})=>{const h=d.x>a.x,f=d.y>a.y,g=d.x-a.x,m=d.y-a.y,y=Math.abs(m)<Math.abs(g)*2,S=Math.abs(g)<Math.abs(m)*2;if(r==="left"||r==="right")return y&&(r==="right"?h:!h);if(r==="up"||r==="down")return S&&(r==="down"?f:!f)});return c.length===0?t:F_(c,({center:d})=>{const h=C.Dist2(a,d),f=["left","right"].includes(r)?"x":"y",g=Math.abs(d[f]-a[f]),m=["left","right"].includes(r)?"y":"x",y=Math.abs(d[m]-a[m]),S=Math.abs(C.Angle(a,d)*(180/Math.PI)),b=Math.abs(S-s[r]);return h*1+y*2+(h-g)*1.5+b*.5}).shape.id}selectParentShape(){const e=this.getOnlySelectedShape();if(!e)return;const t=this.getShape(e.parentId);t&&this._selectShapesAndZoom([t.id])}selectFirstChildShape(){const e=this.getSelectedShapes();if(!e.length)return;const t=e[0],r=this.getSortedChildIdsForParent(t.id).map(o=>this.getShape(o)).filter(o=>o),s=this._getShapesInReadingOrder(r);s.length!==0&&this._selectShapesAndZoom([s[0].id])}_selectShapesAndZoom(e){this.setSelectedShapes(e),this.zoomToSelectionIfOffscreen(256,{animation:{duration:this.options.animationMediumMs},inset:0})}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var e;return((e=this.getOnlySelectedShape())==null?void 0:e.id)??null}getOnlySelectedShape(){const e=this.getSelectedShapes();return e.length===1?e[0]:null}getShapesPageBounds(e){const t=Le(e.map(r=>this.getShapePageBounds(r)));return t.length===0?null:J.Common(t)}getSelectionPageBounds(){return this.getShapesPageBounds(this.getSelectedShapeIds())}getSelectionScreenBounds(){const e=this.getSelectionPageBounds();if(!e)return;const{x:t,y:r}=this.pageToScreen(e.point),s=this.getZoomLevel();return new J(t,r,e.width*s,e.height*s)}getShapesSharedRotation(e){let t=!1,r=0;for(let s=0,o=e.length;s<o;s++){const i=this.getShapePageTransform(e[s]);if(i)if(t){if(i.rotation()!==r)return 0}else t=!0,r=i.rotation()}return r}getSelectionRotation(){return this.getShapesSharedRotation(this.getSelectedShapeIds())}getShapesRotatedPageBounds(e){if(e.length===0)return;const t=this.getShapesSharedRotation(e);if(t===0)return this.getShapesPageBounds(e)??void 0;if(e.length===1){const s=this.getShapeGeometry(e[0]).bounds.clone(),o=this.getShapePageTransform(e[0]);return s.point=o.applyToPoint(s.point),s}const r=J.FromPoints(e.flatMap(s=>{const o=this.getShapePageTransform(s);return o?o.applyToPoints(this.getShapeGeometry(s).bounds.corners):[]}).map(s=>s.rot(-t)));return r.point=r.point.rot(t),r}getSelectionRotatedPageBounds(){return this.getShapesRotatedPageBounds(this.getSelectedShapeIds())}getSelectionRotatedScreenBounds(){const e=this.getSelectionRotatedPageBounds();if(!e)return;const{x:t,y:r}=this.pageToScreen(e.point),s=this.getZoomLevel();return new J(t,r,e.width*s,e.height*s)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const e=this.getFocusedGroupId();return e?this.getShape(e):void 0}setFocusedGroup(e){const t=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(t!==null){const r=this.getShape(t);if(!r)throw Error(`Editor.setFocusedGroup: Shape with id ${t} does not exist`);if(!this.isShapeOfType(r,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${r.type}`)}return t===this.getFocusedGroupId()?this:this.run(()=>{this.store.update(this.getCurrentPageState().id,r=>({...r,focusedGroupId:t}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const e=this.getFocusedGroup();if(e){const t=this.findShapeAncestor(e,r=>this.isShapeOfType(r,"group"));this.setFocusedGroup((t==null?void 0:t.id)??null),this.select(e.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const e=this.getEditingShapeId();return e?this.getShape(e):void 0}canEditShape(e,t){const r=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(!r||r===this.getEditingShapeId())return!1;const s=this.getShape(r);if(!s)return!1;const o=this.getShapeUtil(s),i=t??{type:"unknown"};return!(!o.canEdit(s,i)||this.getIsReadonly()&&!o.canEditInReadonly(s)||this.isShapeOrAncestorLocked(s)&&!o.canEditWhileLocked(s))}setEditingShape(e){const t=typeof e=="string"?e:(e==null?void 0:e.id)??null;return t?this.canEditShape(t)?(this.run(()=>{var o,i,a,l;const r=this.getEditingShapeId();if(r){const c=this.getShape(r);c&&((i=(o=this.getShapeUtil(c)).onEditEnd)==null||i.call(o,c))}this._updateCurrentPageState({editingShapeId:null}),this._currentRichTextEditor.set(null),this.select(t),this._updateCurrentPageState({editingShapeId:t});const s=this.getShape(t);(l=(a=this.getShapeUtil(s)).onEditStart)==null||l.call(a,s)},{history:"ignore"}),this):this:(this.run(()=>{var s,o;const r=this.getEditingShapeId();if(r){const i=this.getShape(r);i&&((o=(s=this.getShapeUtil(i)).onEditEnd)==null||o.call(s,i))}this._updateCurrentPageState({editingShapeId:null}),this._currentRichTextEditor.set(null)},{history:"ignore"}),this)}getRichTextEditor(){return this._currentRichTextEditor.get()}setRichTextEditor(e){return this._currentRichTextEditor.set(e),this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const e=this.getHoveredShapeId();return e?this.getShape(e):void 0}setHoveredShape(e){const t=typeof e=="string"?e:(e==null?void 0:e.id)??null;return t===this.getHoveredShapeId()?this:(this.run(()=>{this.updateCurrentPageState({hoveredShapeId:t})},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const e=this.getHintingShapeIds();return Le(e.map(t=>this.getShape(t)))}setHintingShapes(e){const t=typeof e[0]=="string"?e:e.map(r=>r.id);return this.run(()=>{this._updateCurrentPageState({hintingShapeIds:ny(t)})},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const e=this.getErasingShapeIds();return Le(e.map(t=>this.getShape(t)))}setErasingShapes(e){const t=typeof e[0]=="string"?e:e.map(s=>s.id);t.sort();const r=this.getErasingShapeIds();return this.run(()=>{if(t.length===r.length){for(let s=0;s<t.length;s++)if(t[s]!==r[s]){this._updateCurrentPageState({erasingShapeIds:t});break}}else this._updateCurrentPageState({erasingShapeIds:t})},{history:"ignore"}),this}getCroppingShapeId(){return this.getCurrentPageState().croppingShapeId}canCropShape(e){if(!e)return!1;const t=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(!t)return!1;const r=this.getShape(t);return!(!r||!this.getShapeUtil(r).canCrop(r)||this.isShapeOrAncestorLocked(r))}setCroppingShape(e){const t=typeof e=="string"?e:(e==null?void 0:e.id)??null;return t!==this.getCroppingShapeId()&&this.run(()=>{t?this.canCropShape(t)&&this.updateCurrentPageState({croppingShapeId:t}):this.updateCurrentPageState({croppingShapeId:null})},{history:"ignore"}),this}getTextOptions(){return Pn(this._textOptions.get(),"Cannot use text without setting textOptions")}_unsafe_getCameraId(){return zo.createId(this.getCurrentPageId())}getCamera(){const e=this.store.get(this._unsafe_getCameraId());if(this._isLockedOnFollowingUser.get()){const t=this.getCameraForFollowing();if(t)return{...e,...t}}return e}_getFollowingPresence(e){const t=[this.user.getId()],r=this.getCollaborators();let s=null;for(;e&&!t.includes(e);)s=r.find(o=>o.userId===e)??null,e=(s==null?void 0:s.followingUserId)??null,s&&t.push(s.userId);return s}getViewportPageBoundsForFollowing(){const e=this._getFollowingPresence(this.getInstanceState().followingUserId);if(!(e!=null&&e.camera)||!(e!=null&&e.screenBounds))return null;const{w:t,h:r}=e.screenBounds,{x:s,y:o,z:i}=e.camera,a=new J(-s,-o,t/i,r/i),l=this.getViewportScreenBounds().clone(),c=l.width/l.height;return l.width=a.width,l.height=l.width/c,l.height<a.height&&(l.height=a.height,l.width=l.height*c),l.center=a.center,l}getCameraForFollowing(){const e=this.getViewportPageBoundsForFollowing();return e?{x:-e.x,y:-e.y,z:this.getViewportScreenBounds().w/e.width}:null}getZoomLevel(){return this.getCamera().z}getDebouncedZoomLevel(){return this.options.debouncedZoom?this.getCameraState()==="idle"?this.getZoomLevel():this._debouncedZoomLevel.get():this.getZoomLevel()}_getAboveDebouncedZoomThreshold(){return this.getCurrentPageShapeIds().size>this.options.debouncedZoomThreshold}getEfficientZoomLevel(){return this._getAboveDebouncedZoomThreshold()?this.getDebouncedZoomLevel():this.getZoomLevel()}getInitialZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.initialZoom==="default")return 1;const{zx:t,zy:r}=WT(this,e);switch(e.constraints.initialZoom){case"fit-min":return Math.max(t,r);case"fit-max":return Math.min(t,r);case"fit-x":return t;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(t,r));case"fit-max-100":return Math.min(1,Math.min(t,r));case"fit-x-100":return Math.min(1,t);case"fit-y-100":return Math.min(1,r);default:throw it(e.constraints.initialZoom)}}getBaseZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.baseZoom==="default")return 1;const{zx:t,zy:r}=WT(this,e);switch(e.constraints.baseZoom){case"fit-min":return Math.max(t,r);case"fit-max":return Math.min(t,r);case"fit-x":return t;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(t,r));case"fit-max-100":return Math.min(1,Math.min(t,r));case"fit-x-100":return Math.min(1,t);case"fit-y-100":return Math.min(1,r);default:throw it(e.constraints.baseZoom)}}getCameraOptions(){return this._cameraOptions.get()}setCameraOptions(e){var r;const t=Ft({...this._cameraOptions.__unsafe__getWithoutCapture(),...e});return((r=t.zoomSteps)==null?void 0:r.length)<1&&(t.zoomSteps=[1]),this._cameraOptions.set(t),this.setCamera(this.getCamera()),this}getConstrainedCamera(e,t){const r=this.getCamera();let{x:s,y:o,z:i=r.z}=e;if(!(t!=null&&t.force)){const a=this.getCameraOptions(),l=a.zoomSteps[0],c=gs(a.zoomSteps),u=this.getViewportScreenBounds();if(a.constraints){const{constraints:d}=a,h=Math.min(d.padding.y,u.w/2),f=Math.min(d.padding.x,u.h/2),g=J.From(a.constraints.bounds),m=(u.w-f*2)/g.w,y=(u.h-h*2)/g.h,S=this.getBaseZoom(),b=c*S,w=l*S;if(t!=null&&t.reset&&(i=this.getInitialZoom()),i<w||i>b){const{x:j,y:_,z:M}=r,O=-j+u.w/M/2,N=-_+u.h/M/2;i=Fe(i,w,b);const B=-j+u.w/i/2,H=-_+u.h/i/2;s=j+B-O,o=_+H-N}const v=f/i-g.x,P=h/i-g.y,T=(u.w-f*2)/i-g.w,I=(u.h-h*2)/i-g.h,k=v+T*d.origin.x,A=P+I*d.origin.y,R=typeof d.behavior=="string"?d.behavior:d.behavior.x,D=typeof d.behavior=="string"?d.behavior:d.behavior.y;if(t!=null&&t.reset)s=k,o=A;else{switch(R){case"fixed":{s=k;break}case"contain":{i<m?s=k:s=Fe(s,v+T,v);break}case"inside":{i<m?s=Fe(s,v,(u.w-f)/i-g.w):s=Fe(s,v+T,v);break}case"outside":{s=Fe(s,f/i-g.w,(u.w-f)/i);break}case"free":break;default:throw it(R)}switch(D){case"fixed":{o=A;break}case"contain":{i<y?o=A:o=Fe(o,P+I,P);break}case"inside":{i<y?o=Fe(o,P,(u.h-h)/i-g.h):o=Fe(o,P+I,P);break}case"outside":{o=Fe(o,h/i-g.h,(u.h-h)/i);break}case"free":break;default:throw it(D)}}}else if(i>c||i<l){const{x:d,y:h,z:f}=r;i=Fe(i,l,c),s=d+(-d+u.w/i/2)-(-d+u.w/f/2),o=h+(-h+u.h/i/2)-(-h+u.h/f/2)}}return{x:s,y:o,z:i}}_setCamera(e,t){const r=this.getCamera(),{x:s,y:o,z:i}=this.getConstrainedCamera(e,t);return r.x===s&&r.y===o&&r.z===i?this:(ms(()=>{const a={...r,x:s,y:o,z:i};this.run(()=>{this.store.put([a])},{history:"ignore"});const l=this.inputs.getCurrentScreenPoint(),c=this.inputs.getCurrentPagePoint();(l.x/i-s!==c.x||l.y/i-o!==c.y)&&this.updatePointer({immediate:t==null?void 0:t.immediate,pointerId:yA.CAMERA_MOVE}),this._tickCameraState()}),this)}setCamera(e,t){const{isLocked:r}=this._cameraOptions.__unsafe__getWithoutCapture();if(r&&!(t!=null&&t.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const s=C.Cast(e);Number.isFinite(s.x)||(s.x=0),Number.isFinite(s.y)||(s.y=0),(s.z===void 0||!Number.isFinite(s.z))&&(e.z=this.getZoomLevel());const o=this.getConstrainedCamera(s,t);if(t!=null&&t.animation){const{width:i,height:a}=this.getViewportScreenBounds();this._animateToViewport(new J(-o.x,-o.y,i/o.z,a/o.z),t)}else this._setCamera(o,{...t,force:!0});return this}centerOnPoint(e,t){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const{width:s,height:o}=this.getViewportPageBounds();return this.setCamera(new C(-(e.x-s/2),-(e.y-o/2),this.getCamera().z),t),this}zoomToFit(e){const t=[...this.getCurrentPageShapeIds()].filter(s=>!this.isShapeHidden(s));if(t.length<=0)return this;const r=J.Common(Le(t.map(s=>this.getShapePageBounds(s))));return this.zoomToBounds(r,e),this}resetZoom(e=this.getViewportScreenCenter(),t){const{isLocked:r,constraints:s}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const o=this.getCamera(),{x:i,y:a,z:l}=o,{x:c,y:u}=e;let d=1;if(s){const h=this.getInitialZoom();l!==h&&(d=h)}return this.setCamera(new C(i+(c/d-c)-(c/l-c),a+(u/d-u)-(u/l-u),d),t),this}zoomIn(e=this.getViewportScreenCenter(),t){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const{x:s,y:o,z:i}=this.getCamera(),{zoomSteps:a}=this.getCameraOptions();if(a!==null&&a.length>1){const l=this.getBaseZoom();let c=gs(a)*l;for(let u=1;u<a.length;u++){const d=a[u-1]*l,h=a[u]*l;if(!(h-i<=(h-d)/2)){c=h;break}}this.setCamera(new C(s+(e.x/c-e.x)-(e.x/i-e.x),o+(e.y/c-e.y)-(e.y/i-e.y),c),t)}return this}zoomOut(e=this.getViewportScreenCenter(),t){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const{zoomSteps:s}=this.getCameraOptions();if(s!==null&&s.length>1){const o=this.getBaseZoom(),{x:i,y:a,z:l}=this.getCamera();let c=s[0]*o;for(let u=s.length-1;u>0;u--){const d=s[u-1]*o,h=s[u]*o;if(!(h-l>=(h-d)/2)){c=d;break}}this.setCamera(new C(i+(e.x/c-e.x)-(e.x/l-e.x),a+(e.y/c-e.y)-(e.y/l-e.y),c),t)}return this}zoomToSelection(e){const{isLocked:t}=this.getCameraOptions();if(t&&!(e!=null&&e.force))return this;const r=this.getSelectionPageBounds();if(r){const s=this.getZoomLevel();Math.abs(s-1)<.01?this.zoomToBounds(r,e):this.zoomToBounds(r,{targetZoom:1,...e})}return this}zoomToSelectionIfOffscreen(e=16,t){const r=this.getSelectionPageBounds(),s=this.getViewportPageBounds();if(r&&!s.contains(r)){const o=r.clone().expandBy(e/this.getZoomLevel()).expand(s),i=s.clone().translate({x:(o.center.x-s.center.x)*2,y:(o.center.y-s.center.y)*2});this.zoomToBounds(i,t)}}zoomToBounds(e,t){const r=this._cameraOptions.__unsafe__getWithoutCapture();if(r.isLocked&&!(t!=null&&t.force))return this;const s=this.getViewportScreenBounds(),o=(t==null?void 0:t.inset)??Math.min(this.options.zoomToFitPadding,s.width*.28),i=this.getBaseZoom(),a=r.zoomSteps[0],l=gs(r.zoomSteps);let c=Fe(Math.min((s.width-o)/e.w,(s.height-o)/e.h),a*i,l*i);return(t==null?void 0:t.targetZoom)!==void 0&&(c=Math.min(t.targetZoom,c)),this.setCamera(new C(-e.x+(s.width-e.w*c)/2/c,-e.y+(s.height-e.h*c)/2/c,c),t),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(e){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=e;const{elapsed:t,easing:r,duration:s,start:o,end:i}=this._viewportAnimation;if(t>s){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new C(-i.x,-i.y,this.getViewportScreenBounds().width/i.width));return}const a=s-t,l=r(1-a/s),c=o.minX+(i.minX-o.minX)*l,u=o.minY+(i.minY-o.minY)*l,d=o.maxX+(i.maxX-o.maxX)*l;this._setCamera(new C(-c,-u,this.getViewportScreenBounds().width/(d-c)),{force:!0})}_animateToViewport(e,t={animation:Mx}){const{animation:r,...s}=t;if(!r)return;const{duration:o=0,easing:i=ar.easeInOutCubic}=r,a=this.user.getAnimationSpeed(),l=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),o===0||a===0?this._setCamera(new C(-e.x,-e.y,this.getViewportScreenBounds().width/e.width),{...s}):(this._viewportAnimation={elapsed:0,duration:o/a,easing:i,start:l.clone(),end:e.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(e={}){const{isLocked:t}=this.getCameraOptions();if(t&&!(e!=null&&e.force))return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:s,friction:o=this.options.cameraSlideFriction,direction:i,speedThreshold:a=.01}=e;let l=Math.min(s,1);const c=()=>{this.off("tick",u),this.off("stop-camera-animation",c)};this.once("stop-camera-animation",c);const u=d=>{const{x:h,y:f,z:g}=this.getCamera(),m=C.Mul(i,l*d/g);l*=1-o,l<a?c():this._setCamera(new C(h+m.x,f+m.y,g))};return this.on("tick",u),this}zoomToUser(e,t={animation:{duration:500}}){const r=this.getCollaborators().find(o=>o.userId===e);if(!r)return this;const s=r.cursor;return s?(this.run(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const o=r.currentPageId===this.getCurrentPageId();o||this.setCurrentPage(r.currentPageId),t&&t.animation&&!o&&(t.animation=void 0),this.centerOnPoint(s,t);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,e]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(e);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(e,t=!1){if(e instanceof J)e.width=Math.max(e.width,1),e.height=Math.max(e.height,1);else{const a=e.getBoundingClientRect();e=new J(a.left||a.x,a.top||a.y,Math.max(a.width,1),Math.max(a.height,1))}const r=[e.minY!==0,!tn(document.body.scrollWidth,e.maxX,1),!tn(document.body.scrollHeight,e.maxY,1),e.minX!==0],{_willSetInitialBounds:s}=this;this._willSetInitialBounds=!1;const{screenBounds:o,insets:i}=this.getInstanceState();if(e.equals(o)&&r.every((a,l)=>a===i[l]))return this;if(s)this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.emit("resize",e.toJson()),this.setCamera(this.getCamera());else if(t&&!this.getInstanceState().followingUserId){const a=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.emit("resize",e.toJson()),this.centerOnPoint(a)}else this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.emit("resize",e.toJson()),this._setCamera(C.From({...this.getCamera()}));return this}getViewportScreenBounds(){const{x:e,y:t,w:r,h:s}=this.getInstanceState().screenBounds;return new J(e,t,r,s)}getViewportScreenCenter(){const e=this.getViewportScreenBounds();return new C(e.w/2,e.h/2)}getViewportPageBounds(){const{w:e,h:t}=this.getViewportScreenBounds(),{x:r,y:s,z:o}=this.getCamera();return new J(-r,-s,e/o,t/o)}screenToPage(e){const{screenBounds:t}=this.store.unsafeGetWithoutCapture(Er),{x:r,y:s,z:o=1}=this.getCamera();return new C((e.x-t.x)/o-r,(e.y-t.y)/o-s,e.z??.5)}pageToScreen(e){const{screenBounds:t}=this.store.unsafeGetWithoutCapture(Er),{x:r,y:s,z:o=1}=this.getCamera();return new C((e.x+r)*o+t.x,(e.y+s)*o+t.y,e.z??.5)}pageToViewport(e){const{x:t,y:r,z:s=1}=this.getCamera();return new C((e.x+t)*s,(e.y+r)*s,e.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const e=this._getCollaboratorsQuery().get();return e.length?[...new Set(e.map(r=>r.userId))].sort().map(r=>k4(e.filter(o=>o.userId===r),o=>o.lastActivityTimestamp??0)):Yt}getCollaboratorsOnCurrentPage(){const e=this.getCurrentPageId();return this.getCollaborators().filter(t=>t.currentPageId===e)}startFollowingUser(e){if(this.stopFollowingUser(),this.user.getId()||console.warn("You should set the userId for the current instance before following a user"),!this._getFollowingPresence(e))return this;const s=q("latestLeaderPresence",()=>this._getFollowingPresence(e));return ms(()=>{this.updateInstanceState({followingUserId:e},{history:"ignore"});const o=Mr("update current page",()=>{const l=s.get();if(!l){this.stopFollowingUser();return}l.currentPageId!==this.getCurrentPageId()&&this.getPage(l.currentPageId)&&this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:l.currentPageId}]),this._isLockedOnFollowingUser.set(!0)},{history:"ignore"})}),i=()=>{o(),this._isLockedOnFollowingUser.set(!1),this.off("frame",a),this.off("stop-following",i)},a=()=>{if(!s.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const c=this.user.getAnimationSpeed();if(c===0){this._isLockedOnFollowingUser.set(!0);return}const u=this.getViewportPageBoundsForFollowing();if(!u){this.stopFollowingUser();return}const d=this.getViewportPageBounds(),h=Math.abs(u.minX-d.minX)+Math.abs(u.maxX-d.maxX),f=Math.abs(u.minY-d.minY)+Math.abs(u.maxY-d.maxY);if(h<this.options.followChaseViewportSnap&&f<this.options.followChaseViewportSnap){this._isLockedOnFollowingUser.set(!0);return}const g=Fe(c*.5,.1,.8),m=new J(Ue(d.minX,u.minX,g),Ue(d.minY,u.minY,g),Ue(d.width,u.width,g),Ue(d.height,u.height,g)),y=new C(-m.x,-m.y,this.getViewportScreenBounds().width/m.width);this.stopCameraAnimation(),this._setCamera(y)};this.once("stop-following",i),this.addListener("frame",a),a()}),this}stopFollowingUser(){return this.run(()=>{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")},{history:"ignore"}),this}getUnorderedRenderingShapes(e){const t=[];let r=this.options.maxShapesPerPage*2,s=this.options.maxShapesPerPage;const o=this.getErasingShapeIds(),i=(l,c,u)=>{const d=this.getShape(l);if(!d)return;if(this.isShapeHidden(d)){const y=u||o.includes(l);for(const S of this.getSortedChildIdsForParent(l))i(S,c,y);return}c*=d.opacity;let h=!1;const f=this.getShapeUtil(d);e&&(h=!u&&o.includes(l),h&&(c*=.32)),t.push({id:l,shape:d,util:f,index:r,backgroundIndex:s,opacity:c}),r+=1,s+=1;const g=this.getSortedChildIdsForParent(l);if(!g.length)return;let m=null;f.providesBackgroundForChildren(d)&&(m=s,s=r,r+=this.options.maxShapesPerPage);for(const y of g)i(y,c,u||h);m!==null&&(s=m)},a=e?[this.getCurrentPage()]:this.getPages();for(const l of a)for(const c of this.getSortedChildIdsForParent(l.id))i(c,1,!1);return t}_decayCameraStateTimeout(e){this._cameraStateTimeoutRemaining-=e,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._setCameraState("idle"))}_tickCameraState(){this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this.getInstanceState().cameraState==="idle"&&(this._setCameraState("moving"),this._debouncedZoomLevel.set(gl(()=>this.getCamera().z)),this.on("tick",this._decayCameraStateTimeout))}_setCameraState(e){this.updateInstanceState({cameraState:e},{history:"ignore"})}getCameraState(){return this.getInstanceState().cameraState}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(Z4)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return Array.from(this._getAllPagesQuery().get()).sort(Tn)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(e){return this.store.get(typeof e=="string"?e:e.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(e){const t=typeof e=="string"?e:e.id,r=this.store.query.exec("shape",{parentId:{eq:t}});return this.getShapeAndDescendantIds(r.map(s=>s.id))}setCurrentPage(e){const t=typeof e=="string"?e:e.id;return this.store.has(t)?(this.stopFollowingUser(),this.complete(),this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:t}]),this.setCamera(this.getCamera())},{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(e){return this.getIsReadonly()?this:this.getPage(e.id)?this.run(()=>this.store.update(e.id,r=>({...r,...e}))):this}createPage(e){return this.run(()=>{if(this.getIsReadonly()||this.getPages().length>=this.options.maxPages)return;const t=this.getPages(),r=D9(e.name??"Page 1",t.map(i=>i.name));let s=e.index;(!s||t.some(i=>i.index===s))&&(s=Ns(t[t.length-1].index));const o=Ar.create({meta:{},...e,name:r,index:s});this.store.put([o])}),this}deletePage(e){const t=typeof e=="string"?e:e.id;return this.run(()=>{if(this.getIsReadonly())return;const r=this.getPages();if(r.length===1)return;const s=this.getPage(t);if(!s)return;if(t===this.getCurrentPageId()){const i=r.findIndex(l=>l.id===t),a=r[i-1]??r[i+1];this.setCurrentPage(a.id)}const o=this.getSortedChildIdsForParent(s.id);this.deleteShapes(o),this.store.remove([s.id])},{ignoreShapeLock:!0}),this}duplicatePage(e,t=Ar.createId()){if(this.getPages().length>=this.options.maxPages)return this;const r=typeof e=="string"?e:e.id,s=this.getPage(r);if(!s)return this;const o={...this.getCamera()},i=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(s.id));return this.run(()=>{var c;const a=this.getPages(),l=Xc(s.index,(c=a[a.indexOf(s)+1])==null?void 0:c.index);if(this.createPage({name:s.name+" Copy",id:t,index:l}),this.setCurrentPage(t),this.setCamera(o),i)return this.putContentOntoCurrentPage(i)}),this}renamePage(e,t){const r=typeof e=="string"?e:e.id;return this.getIsReadonly()?this:(this.updatePage({id:r,name:t}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>this.store.put(e),{history:"ignore"}),this)}updateAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>{this.store.put(e.map(t=>({...this.store.get(t.id),...t})))},{history:"ignore"}),this)}deleteAssets(e){if(this.getIsReadonly())return this;const t=typeof e[0]=="string"?e:e.map(r=>r.id);return t.length<=0?this:(this.run(()=>{var r,s;(s=(r=this.store.props.assets).remove)==null||s.call(r,t),this.store.remove(t)},{history:"ignore"}),this)}getAsset(e){return this.store.get(typeof e=="string"?e:e.id)}async resolveAssetUrl(e,t){if(!e)return null;const r=this.getAsset(e);if(!r)return null;const{screenScale:s=1,shouldResolveToOriginal:o=!1,dpr:i=this.getInstanceState().devicePixelRatio}=t,l=(u=>Math.pow(2,Math.ceil(Math.log2(u))))(s),c="connection"in navigator?navigator.connection.effectiveType:null;return await this.store.props.assets.resolve(r,{screenScale:s||1,steppedScreenScale:l,dpr:i,networkEffectiveType:c,shouldResolveToOriginal:o})}async uploadAsset(e,t,r){return await this.store.props.assets.upload(e,t,r)}getShapeGeometry(e,t){const r=(t==null?void 0:t.context)??"none";return this._shapeGeometryCaches[r]||(this._shapeGeometryCaches[r]=this.store.createComputedCache("bounds",s=>(this.fonts.trackFontsForShape(s),this.getShapeUtil(s).getGeometry(s,t)),{areRecordsEqual:Rw})),this._shapeGeometryCaches[r].get(typeof e=="string"?e:e.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",e=>{var t,r;return(r=(t=this.getShapeUtil(e)).getHandles)==null?void 0:r.call(t,e)},{areRecordsEqual:Rw})}getShapeHandles(e){return this._getShapeHandlesCache().get(typeof e=="string"?e:e.id)}getShapeLocalTransform(e){const t=typeof e=="string"?e:e.id,r=this.getShape(t);if(!r)throw Error("Editor.getTransform: shape not found");return Q.Identity().translate(r.x,r.y).rotate(r.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",e=>{if(On(e.parentId))return this.getShapeLocalTransform(e);const t=this._getShapePageTransformCache().get(e.parentId)??Q.Identity();return Q.Compose(t,this.getShapeLocalTransform(e))})}getShapeParentTransform(e){const t=typeof e=="string"?e:e.id,r=this.getShape(t);return!r||On(r.parentId)?Q.Identity():this._getShapePageTransformCache().get(r.parentId)??Q.Identity()}getShapePageTransform(e){const t=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(t)??Q.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",e=>{const t=this.getShapePageTransform(e);if(t)return J.FromPoints(t.applyToPoints(this.getShapeGeometry(e).boundsVertices))})}getShapePageBounds(e){return this._getShapePageBoundsCache().get(typeof e=="string"?e:e.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",e=>{const t=this._getShapeMaskCache().get(e.id);if(!t)return;if(t.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const r=this._getShapePageTransformCache().get(e.id);return r?`polygon(${Q.applyToPoints(Q.Inverse(r),t).map(o=>`${o.x}px ${o.y}px`).join(",")})`:void 0})}getShapeClipPath(e){return this._getShapeClipPathCache().get(typeof e=="string"?e:e.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",e=>{var s,o;if(On(e.parentId))return;const t=[];for(const i of this.getShapeAncestors(e.id)){const a=this.getShapeUtil(i),l=(s=a.getClipPath)==null?void 0:s.call(a,i);if(!l||((o=a.shouldClipChild)==null?void 0:o.call(a,e))===!1)continue;const c=this.getShapePageTransform(i.id);t.push(c.applyToPoints(l))}return t.length===0?void 0:t.reduce((i,a)=>{const l=Hg(i,a);return l?l.map(C.Cast):[]})})}getShapeMask(e){return this._getShapeMaskCache().get(typeof e=="string"?e:e.id)}getShapeMaskedPageBounds(e){return typeof e!="string"&&(e=e.id),this._getShapeMaskedPageBoundsCache().get(e)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",e=>{const t=this._getShapePageBoundsCache().get(e.id);if(!t)return;const r=this._getShapeMaskCache().get(e.id);if(r){if(r.length===0)return;const{corners:s}=t;if(s.every((i,a)=>i&&C.Equals(i,r[a])))return t.clone();const o=Hg(r,s);return o?J.FromPoints(o):void 0}return t})}getShapeAncestors(e,t=[]){const r=typeof e=="string"?e:e.id,s=this.getShape(r);if(!s)return t;const o=s.parentId;if(On(o))return t.reverse(),t;const i=this.store.get(o);return i?(t.push(i),this.getShapeAncestors(i,t)):t}findShapeAncestor(e,t){const r=typeof e=="string"?e:e.id,s=this.getShape(r);if(!s)return;const o=s.parentId;if(On(o))return;const i=this.getShape(o);if(i)return t(i)?i:this.findShapeAncestor(i,t)}hasAncestor(e,t){const r=typeof e=="string"?e:e==null?void 0:e.id,s=r&&this.getShape(r);return s?s.parentId===t?!0:this.hasAncestor(this.getShapeParent(s),t):!1}findCommonAncestor(e,t){var l;if(e.length===0)return;const r=typeof e[0]=="string"?e:e.map(c=>c.id),s=Le(r.map(c=>this.getShape(c)));if(s.length===1){const c=s[0].parentId;return On(c)?void 0:t?(l=this.findShapeAncestor(s[0],t))==null?void 0:l.id:c}const[o,...i]=s;let a=this.getShapeParent(o);for(;a;){if(t&&!t(a)){a=this.getShapeParent(a);continue}if(i.every(c=>this.hasAncestor(c,a.id)))return a.id;a=this.getShapeParent(a)}}isShapeOrAncestorLocked(e){const t=e&&this.getShape(e);return t===void 0?!1:t.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(t))}getNotVisibleShapes(){return this._notVisibleShapes.get()}getCulledShapes(){const e=this.getNotVisibleShapes(),t=this.getSelectedShapeIds(),r=this.getEditingShapeId(),s=new Set(e);r&&s.delete(r),t.forEach(i=>{s.delete(i)});const o=this._culledShapesCache;if(o){if(o.size!==s.size)return this._culledShapesCache=s,s;for(const i of o)if(!s.has(i))return this._culledShapesCache=s,s;return o}return this._culledShapesCache=s,s}getCurrentPageBounds(){let e;return this.getCurrentPageShapeIdsSorted().forEach(t=>{if(this.isShapeHidden(t))return;const r=this.getShapeMaskedPageBounds(t);r&&(e?e=e.expand(r):e=r.clone())}),e}getSelectedShapeAtPoint(e){const t=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(r=>r.type!=="group"&&t.includes(r.id)).reverse().find(r=>this.isPointInShape(r,e,{hitInside:!0,margin:0}))}getShapeAtPoint(e,t={}){var v;const r=this.getZoomLevel(),s=this.getViewportPageBounds(),{filter:o,margin:i=0,hitLocked:a=!1,hitLabels:l=!1,hitInside:c=!1,hitFrameInside:u=!1}=t,[d,h]=Array.isArray(i)?i:[i,i];let f=1/0,g=null,m=1/0,y=null;const S=Math.max(d,h,this.options.hitTestMargin/r),b=this._spatialIndex.getShapeIdsAtPoint(e,S),w=(t.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(P=>{if(!b.has(P.id)&&!this.isShapeOfType(P,"frame")||P.isLocked&&!a||this.isShapeHidden(P)||this.isShapeOfType(P,"group"))return!1;const T=this.getShapeMask(P);return!(T&&!kr(e,T)||o&&!o(P))});for(let P=w.length-1;P>=0;P--){const T=w[P],I=this.getShapeGeometry(T),k=I instanceof es,A=this.getPointInShapeSpace(T,e);if(this.isShapeOfType(T,"frame")||(this.isShapeOfType(T,"note")||this.isShapeOfType(T,"arrow")||this.isShapeOfType(T,"geo")&&T.props.fill==="none")&&((v=this.getShapeUtil(T).getText(T))!=null&&v.trim())){for(const D of I.children)if(D.isLabel&&D.isPointInBounds(A))return T}if(this.isShapeOfType(T,"frame")){const D=I.distanceToPoint(A,u);if(u?D>0&&D<=h||D<=0&&D>-d:D>0&&D<=h)return y||T;if(I.hitTestPoint(A,0,!0))return y||g||(u?T:void 0);continue}let R;if(k){let D=1/0;for(const j of I.children){if(j.isLabel&&!l)continue;const _=j.distanceToPoint(A,c);_<D&&(D=_)}R=D}else h===0&&(I.bounds.w<1||I.bounds.h<1)||I.bounds.containsPoint(A,h)?R=I.distanceToPoint(A,c):R=1/0;if(I.isClosed){if(R<=h||c&&R<=0&&R>-d){if(I.isFilled||k&&I.children[0].isFilled)return y||T;if(this.getShapePageBounds(T).contains(s))continue;if(c?R>0&&R<=h||R<=0&&R>-d:Math.abs(R)<=Math.max(d,h))Math.abs(R)<m&&(m=Math.abs(R),y=T);else if(!y){const{area:D}=I;D<f&&(f=D,g=T)}}}else if(R<this.options.hitTestMargin/r)return T}return y||g||void 0}getShapesAtPoint(e,t={}){const r=t.margin??0,s=this._spatialIndex.getShapeIdsAtPoint(e,r);return this.getCurrentPageShapesSorted().filter(o=>this.isShapeHidden(o)||!s.has(o.id)&&!this.isShapeOfType(o,"frame")?!1:this.isPointInShape(o,e,t)).reverse()}getShapeIdsInsideBounds(e){return this._spatialIndex.getShapeIdsInsideBounds(e)}isPointInShape(e,t,r={}){const{hitInside:s=!1,margin:o=0}=r,i=typeof e=="string"?e:e.id,a=this.getShapeMask(i);return a&&!kr(t,a)?!1:this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(e,t),o,s)}getPointInShapeSpace(e,t){const r=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(r).clone().invert().applyToPoint(t)}getPointInParentSpace(e,t){const r=typeof e=="string"?e:e.id,s=this.getShape(r);if(!s)return new C(0,0);if(On(s.parentId))return C.From(t);const o=this.getShapePageTransform(s.parentId);return o?o.clone().invert().applyToPoint(t):C.From(t)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),e=>this.store.get(e))}getCurrentPageShapesSorted(){const e=[],t=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let r=0,s=t.length;r<s;r++)sR(this,t[r],e);return e}getCurrentPageRenderingShapesSorted(){const e=this.getCulledShapes();return this.getCurrentPageShapesSorted().filter(({id:t})=>!e.has(t)&&!this.isShapeHidden(t))}isShapeOfType(e,t){const r=typeof e=="string"?this.getShape(e):e;return r?r.type===t:!1}getShape(e){const t=typeof e=="string"?e:e.id;if(Pr(t))return this.store.get(t)}getShapeParent(e){const t=typeof e=="string"?e:e==null?void 0:e.id;if(!t)return;const r=this.getShape(t);if(!(r===void 0||!Pr(r.parentId)))return this.getShape(r.parentId)}getShapeNearestSibling(e,t){return t?t.parentId===e.parentId?t:this.findShapeAncestor(t,s=>s.parentId===e.parentId):void 0}isShapeInPage(e,t=this.getCurrentPageId()){const r=typeof e=="string"?e:e.id,s=this.getShape(r);if(!s)return!1;let o=!1;if(s.parentId===t)o=!0;else{let i=this.getShape(s.parentId);e:for(;i;){if(i.parentId===t){o=!0;break e}i=this.getShape(i.parentId)}}return o}getAncestorPageId(e){const t=typeof e=="string"?e:e==null?void 0:e.id,r=t&&this.getShape(t);if(r)return On(r.parentId)?r.parentId:this.getAncestorPageId(this.getShape(r.parentId))}reparentShapes(e,t,r){const s=typeof e[0]=="string"?e:e.map(h=>h.id);if(s.length===0)return this;const o=[],i=On(t)?Q.Identity():this.getShapePageTransform(t),a=i.rotation();let l=[];const c=Le(this.getSortedChildIdsForParent(t).map(h=>this.getShape(h)));if(r){const h=c.find(f=>f.index===r);if(h){const f=c[c.indexOf(h)+1];f?l=El(r,f.index,s.length):l=Sx(r,s.length)}else{const f=c.sort(Tn).find(g=>g.index>r);f?l=El(r,f.index,s.length):l=Sx(r,s.length)}}else{const h=c.length&&c[c.length-1];l=h?Sx(h.index,s.length):rh(s.length)}const u=i.clone().invert(),d=Le(s.map(h=>this.getShape(h))).sort(Tn);return this.run(()=>{for(let h=0;h<d.length;h++){const f=d[h],g=this.getShapePageTransform(f);if(!g)continue;const m=g.point();if(!m)continue;const y=u.applyToPoint(m),S=g.rotation()-a;if(f.id===t)throw Error("Attempted to reparent a shape to itself!");o.push({id:f.id,type:f.type,parentId:t,x:y.x,y:y.y,rotation:S,index:l[h]})}this.updateShapes(o)},{ignoreShapeLock:!0}),this}getHighestIndexForParent(e){const t=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[t];if(!r||r.length===0)return Ns(fv);const s=this.getShape(r[r.length-1]);return Ns(s.index)}getSortedChildIdsForParent(e){const t=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[t];return r||Yt}visitDescendants(e,t){const r=this.getSortedChildIdsForParent(e);for(const s of r)t(s)!==!1&&this.visitDescendants(s,t);return this}getShapeAndDescendantIds(e){const t=new Set;for(const r of e.map(s=>this.getShape(s)).sort(Tn))t.add(r.id),this.visitDescendants(r,s=>{t.add(s)});return t}getDraggingOverShape(e,t){const r=Le(t.map(o=>this.getShape(o))).filter(o=>!o.isLocked&&!this.isShapeHidden(o)),s=this.getShapesAtPoint(e,{hitInside:!0,margin:0}).filter(o=>!t.includes(o)&&!o.isLocked&&!this.isShapeHidden(o)&&!r.includes(o));for(const o of s){const i=this.getShapeUtil(o);if(i.onDragShapesOver||i.onDragShapesIn||i.onDragShapesOut||i.onDropShapesOver)return o}}getOutermostSelectableShape(e,t){const r=typeof e=="string"?e:e.id,s=this.getShape(r);let o=s,i=s;const a=this.getFocusedGroup();for(;i;){if(this.isShapeOfType(i,"group")&&(a==null?void 0:a.id)!==i.id&&!this.hasAncestor(a,i.id)&&((t==null?void 0:t(i))??!0))o=i;else if((a==null?void 0:a.id)===i.id)break;i=this.getShapeParent(i)}return o}_getBindingsIndexCache(){const e=N9(this);return this.store.createComputedCache("bindingsIndex",t=>e.get().get(t.id),{areRecordsEqual:()=>!0})}getBinding(e){return this.store.get(e)}getBindingsFromShape(e,t){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(s=>s.fromId===r&&s.type===t)}getBindingsToShape(e,t){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(s=>s.toId===r&&s.type===t)}getBindingsInvolvingShape(e,t){const r=typeof e=="string"?e:e.id,s=this._getBindingsIndexCache().get(r)??Yt;return t?s.filter(o=>o.type===t):s}createBindings(e){const t=[];for(const r of e){const s=this.getShape(r.fromId),o=this.getShape(r.toId);if(!s||!o||!this.canBindShapes({fromShape:s,toShape:o,binding:r}))continue;const a=this.getBindingUtil(r.type).getDefaultProps(),l=this.store.schema.types.binding.create({...r,id:r.id??wl(),props:{...a,...r.props}});t.push(l)}return this.store.put(t),this}createBinding(e){return this.createBindings([e])}updateBindings(e){const t=[];for(const r of e){if(!r)continue;const s=this.getBinding(r.id);if(!s)continue;const o=Mo(s,r);if(o===s)continue;const i=this.getShape(o.fromId),a=this.getShape(o.toId);!i||!a||this.canBindShapes({fromShape:i,toShape:a,binding:o})&&t.push(o)}return this.store.put(t),this}updateBinding(e){return this.updateBindings([e])}deleteBindings(e,{isolateShapes:t=!1}={}){const r=e.map(s=>typeof s=="string"?s:s.id);return t?this.store.atomic(()=>{var s,o;for(const i of r){const a=this.getBinding(i);if(!a)continue;const l=this.getBindingUtil(a);(s=l.onBeforeIsolateFromShape)==null||s.call(l,{binding:a,removedShape:this.getShape(a.toId)}),(o=l.onBeforeIsolateToShape)==null||o.call(l,{binding:a,removedShape:this.getShape(a.fromId)}),this.store.remove([i])}}):this.store.remove(r),this}deleteBinding(e,t){return this.deleteBindings([e],t)}canBindShapes({fromShape:e,toShape:t,binding:r}){const s=typeof e=="string"?e:e.type,o=typeof t=="string"?t:t.type,i=typeof r=="string"?r:r.type,a={fromShape:typeof e=="string"?{type:e}:e,toShape:typeof t=="string"?{type:t}:t,bindingType:i,fromShapeType:s,toShapeType:o};return s===o?this.getShapeUtil(s).canBind(a):this.getShapeUtil(s).canBind(a)&&this.getShapeUtil(o).canBind(a)}rotateShapesBy(e,t,r){const s=typeof e[0]=="string"?e:e.map(i=>i.id);if(s.length<=0)return this;const o=S2({editor:this,ids:s});return o?(Bf({delta:t,snapshot:o,editor:this,stage:"one-off",centerOverride:r==null?void 0:r.center}),this):this}getChangesToTranslateShape(e,t){var l,c,u;let r=e;const s=this.getShapeUtil(e),o=(l=s.onTranslateStart)==null?void 0:l.call(s,r);o&&(r=Mo(r,o)),r=Mo(r,{id:e.id,type:e.type,x:t.x,y:t.y});const i=(c=s.onTranslate)==null?void 0:c.call(s,e,r);i&&(r=Mo(r,i));const a=(u=s.onTranslateEnd)==null?void 0:u.call(s,e,r);return a&&(r=Mo(r,a)),r}nudgeShapes(e,t){const r=typeof e[0]=="string"?e:e.map(o=>o.id);if(r.length<=0)return this;const s=[];for(const o of r){const i=this.getShape(o),a=C.From(t),l=this.getShapeParentTransform(i);l&&a.rot(-l.rotation()),s.push(this.getChangesToTranslateShape(i,a.add(i)))}return this.updateShapes(s),this}duplicateShapes(e,t){return this.run(()=>{const r=typeof e[0]=="string"?e:e.map(h=>h.id),s=this._shouldIgnoreShapeLock?r:this._getUnlockedShapeIds(r);if(s.length<=0)return this;const o=new Set(s),i=this.getShapeAndDescendantIds(s),a=[...i].reverse(),l=new Map;for(const h of i)l.set(h,St());const{shapesToCreateWithOriginals:c,bindingsToCreate:u}=KT(this,i,h=>{const f=[];for(const m of h){const y=this.getBinding(m);if(!y)continue;const S=wl();f.push({...y,id:S,fromId:Pn(l.get(y.fromId)),toId:Pn(l.get(y.toId))})}const g=[];for(const m of a){const y=Pn(l.get(m)),S=this.getShape(m);if(!S)continue;let b=0,w=0;if(t&&o.has(m)){const v=this.getShapeParentTransform(S),P=new C(t.x,t.y).rot(-v.rotation());b=P.x,w=P.y}g.push({shape:{...S,id:y,x:S.x+b,y:S.y+w,index:"a1",parentId:l.get(S.parentId)??S.parentId},originalShape:S})}return{shapesToCreateWithOriginals:g,bindingsToCreate:f}});c.forEach(({shape:h,originalShape:f})=>{const g=f.parentId,m=this.getSortedChildIdsForParent(g),y=m.indexOf(f.id),S=m[y+1],b=S?this.getShape(S):void 0,w=Xc(f.index,b==null?void 0:b.index);h.index=w});const d=c.map(({shape:h})=>h);if(!this.canCreateShapes(d)){Gp(this);return}if(this.createShapes(d),this.createBindings(u),this.setSelectedShapes(Le(s.map(h=>{const f=l.get(h);return!f||!this.getShape(f)?null:f}))),t!==void 0){const h=this.getSelectionPageBounds(),f=this.getViewportPageBounds();h&&!f.contains(h)&&this.centerOnPoint(h.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(e,t){const r=typeof e[0]=="string"?e:e.map(a=>a.id);if(r.length===0)return this;if(this.getIsReadonly())return this;const s=this.getCurrentPageId();if(t===s)return this;if(!this.store.has(t))return this;const o=this.getContentFromCurrentPage(r);if(!o)return this;if(this.getPageShapeIds(t).size+o.shapes.length>this.options.maxShapesPerPage)return Gp(this,t),this;const i=this.getCamera().z;return this.run(()=>{this.deleteShapes(r),this.setCurrentPage(t),this.setFocusedGroup(null),this.selectNone(),this.putContentOntoCurrentPage(o,{select:!0,preserveIds:!0,preservePosition:!0}),this.setCamera({...this.getCamera(),z:i}),this.centerOnPoint(this.getSelectionRotatedPageBounds().center)}),this}toggleLock(e){const t=typeof e[0]=="string"?e:e.map(i=>i.id);if(this.getIsReadonly()||t.length===0)return this;let r=!0,s=!0;const o=[];for(const i of t){const a=this.getShape(i);a&&(o.push(a),a.isLocked?s=!1:r=!1)}return this.run(()=>{s?(this.updateShapes(o.map(i=>({id:i.id,type:i.type,isLocked:!0}))),this.setSelectedShapes([])):r?this.updateShapes(o.map(i=>({id:i.id,type:i.type,isLocked:!1}))):this.updateShapes(o.map(i=>({id:i.id,type:i.type,isLocked:!0})))}),this}sendToBack(e){const t=typeof e[0]=="string"?e:e.map(s=>s.id),r=Kp(this,"toBack",t,{considerAllShapes:!0});return r&&this.updateShapes(r),this}sendBackward(e,t={}){const r=typeof e[0]=="string"?e:e.map(o=>o.id),s=Kp(this,"backward",r,t);return s&&this.updateShapes(s),this}bringForward(e,t={}){const r=typeof e[0]=="string"?e:e.map(o=>o.id),s=Kp(this,"forward",r,t);return s&&this.updateShapes(s),this}bringToFront(e){const t=typeof e[0]=="string"?e:e.map(s=>s.id),r=Kp(this,"toFront",t);return r&&this.updateShapes(r),this}collectShapesViaArrowBindings(e){const{initialShapes:t,resultShapes:r,resultBounds:s,bindings:o,visited:i}=e;for(const a of o)for(const l of[a.fromId,a.toId])if(!i.has(l)){const c=t.find(u=>u.id===l);if(c&&!i.has(c.id)){i.add(c.id);const u=this.getShapePageBounds(c);if(!u)continue;r.push(c),s.push(u),this.collectShapesViaArrowBindings({...e,bindings:this.getBindingsInvolvingShape(c,"arrow")})}}}flipShapes(e,t){if(this.getIsReadonly())return this;const r=typeof e[0]=="string"?e:e.map(l=>l.id),s=Le(r.map(l=>this.getShape(l)));for(const l of s)if(this.isShapeOfType(l,"group")){const c=Le(this.getSortedChildIdsForParent(l.id).map(u=>this.getShape(u)));s.push(...c)}const o=[],i=[];for(const l of s){const c=this.getShapeUtil(l);if(!c.canBeLaidOut(l,{type:"flip",shapes:s}))continue;const u=this.getShapePageBounds(l),d=this.getShapeGeometry(l).bounds,h=this.getShapePageTransform(l.id);u&&d&&h&&(o.push({shape:l,localBounds:d,pageTransform:h,isAspectRatioLocked:c.isAspectRatioLocked(l)}),i.push(u))}if(!o.length)return this;const a=J.Common(i).center;return this.run(()=>{for(const{shape:l,localBounds:c,pageTransform:u,isAspectRatioLocked:d}of o)this.resizeShape(l.id,{x:t==="horizontal"?-1:1,y:t==="vertical"?-1:1},{initialBounds:c,initialPageTransform:u,initialShape:l,isAspectRatioLocked:d,mode:"scale_shape",scaleOrigin:a,scaleAxisRotation:0})}),this}stackShapes(e,t,r){var S,b;const s=r??this.options.adjacentShapeMargin,o=typeof e[0]=="string"?e:e.map(w=>w.id);if(this.getIsReadonly())return this;const i=Le(o.map(w=>this.getShape(w))),a=[],l=new Set;for(const w of i){if(l.has(w.id))continue;l.add(w.id);const v=this.getShapePageBounds(w);if(!v||!((b=(S=this.getShapeUtil(w)).canBeLaidOut)!=null&&b.call(S,w,{type:"stack",shapes:i})))continue;const P=[w],T=[v];this.collectShapesViaArrowBindings({bindings:this.getBindingsToShape(w.id,"arrow"),initialShapes:i,resultShapes:P,resultBounds:T,visited:l});const I=J.Common(T);I&&a.push({shapes:P,pageBounds:I})}const c=a.length;if(s===0&&c<3||c<2)return this;let u,d,h,f;t==="horizontal"?(u="x",d="minX",h="maxX",f="width"):(u="y",d="minY",h="maxY",f="height");let g=0;if(s===0){const w={};a.sort((P,T)=>P.pageBounds[d]-T.pageBounds[d]);for(let P=0;P<c-1;P++){const T=a[P],k=a[P+1].pageBounds[d]-T.pageBounds[h];w[k]||(w[k]=0),w[k]++}let v=1;for(const[P,T]of Object.entries(w))T>v&&(v=T,g=parseFloat(P));if(v===1){let P=0;for(const[T,I]of Object.entries(w))g+=parseFloat(T)*I,P+=I;g/=P}}else g=s;const m=[];let y=a[0].pageBounds[h];for(let w=1;w<a.length;w++){const{shapes:v,pageBounds:P}=a[w],T=new C;T[u]=y+g-P[u];for(const I of v){const k=T.clone(),A=this.getShapeParent(I);if(A){const R=this.getShapePageTransform(A);R&&k.rot(-R.rotation())}k.add(I),m.push(this.getChangesToTranslateShape(I,k))}y+=P[f]+g}return this.updateShapes(m),this}packShapes(e,t){var P,T;if(this.getIsReadonly())return this;const r=t??this.options.adjacentShapeMargin,s=typeof e[0]=="string"?e:e.map(I=>I.id),o=Le(s.map(I=>this.getShape(I))),i=[],a=[],l=new Set;for(const I of o){if(l.has(I.id))continue;l.add(I.id);const k=this.getShapePageBounds(I);if(!k||!((T=(P=this.getShapeUtil(I)).canBeLaidOut)!=null&&T.call(P,I,{type:"pack",shapes:o})))continue;const A=[I],R=[k];this.collectShapesViaArrowBindings({bindings:this.getBindingsToShape(I.id,"arrow"),initialShapes:o,resultShapes:A,resultBounds:R,visited:l});const D=J.Common(R);D&&(i.push({shapes:A,pageBounds:D,nextPageBounds:D.clone()}),a.push(D))}if(i.length<2)return this;let c=0;for(const{pageBounds:I}of i)c+=I.width*I.height;const u=J.Common(a),d=u.width;i.sort((I,k)=>I.pageBounds.width-k.pageBounds.width).sort((I,k)=>I.pageBounds.height-k.pageBounds.height);const h=Math.max(Math.ceil(Math.sqrt(c/.95)),d),f=[new J(u.x,u.y,h,1/0)];let g=0,m=0,y,S;for(const{nextPageBounds:I}of i)for(let k=f.length-1;k>=0;k--)if(y=f[k],!(I.width>y.width||I.height>y.height)){I.x=y.x,I.y=y.y,m=Math.max(m,I.maxY),g=Math.max(g,I.maxX),I.width===y.width&&I.height===y.height?(S=f.pop(),k<f.length&&(f[k]=S)):I.height===y.height?(y.x+=I.width+r,y.width-=I.width+r):I.width===y.width?(y.y+=I.height+r,y.height-=I.height+r):(f.push(new J(y.x+(I.width+r),y.y,y.width-(I.width+r),I.height)),y.y+=I.height+r,y.height-=I.height+r);break}const b=J.Common(i.map(I=>I.nextPageBounds)),w=C.Sub(u.center,b.center),v=[];for(const{shapes:I,pageBounds:k,nextPageBounds:A}of i){const R=C.Sub(A.point,k.point).add(w);for(const D of I){const j=R.clone();if(this.getShapeParent(D)){const M=this.getShapeParentTransform(D);M&&j.rot(-M.rotation())}j.add(D),v.push(this.getChangesToTranslateShape(D,j))}}return v.length&&this.updateShapes(v),this}alignShapes(e,t){var u,d;if(this.getIsReadonly())return this;const r=typeof e[0]=="string"?e:e.map(h=>h.id),s=Le(r.map(h=>this.getShape(h))),o=[],i=[],a=new Set;for(const h of s){if(a.has(h.id))continue;a.add(h.id);const f=this.getShapePageBounds(h);if(!f||!((d=(u=this.getShapeUtil(h)).canBeLaidOut)!=null&&d.call(u,h,{type:"align",shapes:s})))continue;const g=[h],m=[f];this.collectShapesViaArrowBindings({bindings:this.getBindingsToShape(h.id,"arrow"),initialShapes:s,resultShapes:g,resultBounds:m,visited:a});const y=J.Common(m);y&&(o.push({shapes:g,pageBounds:y}),i.push(y))}if(o.length<2)return this;const l=J.Common(i),c=[];return o.forEach(({shapes:h,pageBounds:f})=>{const g=new C;switch(t){case"top":{g.y=l.minY-f.minY;break}case"center-vertical":{g.y=l.midY-f.minY-f.height/2;break}case"bottom":{g.y=l.maxY-f.minY-f.height;break}case"left":{g.x=l.minX-f.minX;break}case"center-horizontal":{g.x=l.midX-f.minX-f.width/2;break}case"right":{g.x=l.maxX-f.minX-f.width;break}}for(const m of h){const y=g.clone(),S=this.getShapeParent(m);if(S){const b=this.getShapePageTransform(S);b&&y.rot(-b.rotation())}y.add(m),c.push(this.getChangesToTranslateShape(m,y))}}),this.updateShapes(c),this}distributeShapes(e,t){var w,v;if(this.getIsReadonly())return this;const r=typeof e[0]=="string"?e:e.map(P=>P.id),s=Le(r.map(P=>this.getShape(P))),o=[],i=new Set;for(const P of s){if(i.has(P.id))continue;i.add(P.id);const T=this.getShapePageBounds(P);if(!T||!((v=(w=this.getShapeUtil(P)).canBeLaidOut)!=null&&v.call(w,P,{type:"distribute",shapes:s})))continue;const I=[P],k=[T];this.collectShapesViaArrowBindings({bindings:this.getBindingsToShape(P.id,"arrow"),initialShapes:s,resultShapes:I,resultBounds:k,visited:i});const A=J.Common(k);A&&o.push({shapes:I,pageBounds:A})}if(o.length<3)return this;let a,l,c,u;t==="horizontal"?(a="x",l="minX",c="maxX",u="width"):(a="y",l="minY",c="maxY",u="height");const d=[],h=o.sort((P,T)=>P.pageBounds[l]-T.pageBounds[l])[0],f=o.sort((P,T)=>T.pageBounds[c]-P.pageBounds[c])[0];if(h===f){const P=new Set(h.shapes.map(T=>T.id));return this.distributeShapes(r.filter(T=>!P.has(T)),t)}const g=o.filter(P=>P!==h&&P!==f).sort((P,T)=>P.pageBounds[l]===T.pageBounds[l]?P.shapes[0].id<T.shapes[0].id?-1:1:P.pageBounds[l]-T.pageBounds[l]),m=h.pageBounds[c],y=f.pageBounds[l]-m,S=g.reduce((P,T)=>P+T.pageBounds[u],0),b=(y-S)/(g.length+1);for(let P=m+b,T=0;T<g.length;T++){const{shapes:I,pageBounds:k}=g[T],A=new C;A[a]=P-k[a],P+k[u]>f.pageBounds[c]-1&&(A[a]=f.pageBounds[c]-k[c]-1);for(const R of I){const D=A.clone(),j=this.getShapeParent(R);if(j){const _=this.getShapePageTransform(j);_&&D.rot(-_.rotation())}D.add(R),d.push(this.getChangesToTranslateShape(R,D))}P+=k[u]+b}return this.updateShapes(d),this}stretchShapes(e,t){var h,f;const r=typeof e[0]=="string"?e:e.map(g=>g.id);if(this.getIsReadonly())return this;const s=Le(r.map(g=>this.getShape(g))).filter(g=>{var m;return((m=this.getShapePageTransform(g))==null?void 0:m.rotation())%(ht/2)===0}),o=[],i=[],a=new Set;for(const g of s){if(a.has(g.id))continue;a.add(g.id);const m=this.getShapePageBounds(g);if(!m)continue;const y=[g],S=[m];if(!((f=(h=this.getShapeUtil(g)).canBeLaidOut)!=null&&f.call(h,g,{type:"stretch"})))continue;this.collectShapesViaArrowBindings({bindings:this.getBindingsToShape(g.id,"arrow"),initialShapes:s,resultShapes:y,resultBounds:S,visited:a});const b=J.Common(S);b&&(o.push({shapes:y,pageBounds:b}),i.push(b))}if(o.length<2)return this;const l=J.Common(i);let c,u,d;return t==="horizontal"?(c="x",u="minX",d="width"):(c="y",u="minY",d="height"),this.run(()=>{o.forEach(({shapes:g,pageBounds:m})=>{const y=new C;y[c]=l[u]-m[u];const S=m.center.clone();S[c]=l[u];const b=new C(1,1);b[c]=l[d]/m[d];for(const w of g){const v=y.clone(),P=this.getShapeParentTransform(w);P&&y.rot(-P.rotation()),v.add(w);const T=this.getChangesToTranslateShape(w,v);this.updateShape(T),this.resizeShape(w.id,b,{initialBounds:this.getShapeGeometry(w).bounds,scaleOrigin:S,isAspectRatioLocked:this.getShapeUtil(w).isAspectRatioLocked(w),scaleAxisRotation:0})}})}),this}resizeShape(e,t,r={}){var g,m,y;const s=typeof e=="string"?e:e.id;if(this.getIsReadonly())return this;Number.isFinite(t.x)||(t=new C(1,t.y)),Number.isFinite(t.y)||(t=new C(t.x,1));const o=r.initialShape??this.getShape(s);if(!o)return this;const i=r.scaleOrigin??((g=this.getShapePageBounds(s))==null?void 0:g.center);if(!i)return this;const a=r.initialPageTransform?Q.Cast(r.initialPageTransform):this.getShapePageTransform(s);if(!a)return this;const l=a.rotation();if(l==null)return this;const c=r.scaleAxisRotation??l,u=r.initialBounds??this.getShapeGeometry(s).bounds;if(!u)return this;const d=r.isAspectRatioLocked??this.getShapeUtil(o).isAspectRatioLocked(o);if(!fA(l,c))return this._resizeUnalignedShape(s,t,{...r,initialBounds:u,scaleOrigin:i,scaleAxisRotation:c,initialPageTransform:a,isAspectRatioLocked:d,initialShape:o});const h=this.getShapeUtil(o);d&&(Math.abs(t.x)>Math.abs(t.y)?t=new C(t.x,Math.sign(t.y)*Math.abs(t.x)):t=new C(Math.sign(t.x)*Math.abs(t.y),t.y));let f=!1;if(h.onResize&&h.canResize(o)){const S=this._scalePagePoint(Q.applyToPoint(a,new C(0,0)),i,t,c),b=this.getPointInParentSpace(o.id,S),w=new C(t.x,t.y),v=tn((l-c)%Math.PI,0);w.x=v?t.x:t.y,w.y=v?t.y:t.x;const P=Q.applyToPoint(a,new C),{x:T,y:I}=this.getPointInParentSpace(o.id,P);let k=o;r.skipStartAndEndCallbacks||(k=Mo(o,((m=h.onResizeStart)==null?void 0:m.call(h,o))??void 0));const A=h.onResize({...o,x:T,y:I},{newPoint:b,handle:r.dragHandle??"bottom_right",mode:r.mode??"scale_shape",scaleX:w.x,scaleY:w.y,initialBounds:u,initialShape:o});A&&(f=!0),k=Mo(k,{id:s,type:o.type,x:b.x,y:b.y,...A}),r.skipStartAndEndCallbacks||(k=Mo(k,((y=h.onResizeEnd)==null?void 0:y.call(h,o,k))??void 0)),this.updateShapes([k])}if(!f){const S=Q.applyToPoint(a,u.center),b=this._scalePagePoint(S,i,t,c),w=this.getPointInParentSpace(o.id,S),v=this.getPointInParentSpace(o.id,b),P=C.Sub(v,w);this.updateShapes([{id:s,type:o.type,x:o.x+P.x,y:o.y+P.y}])}return this}_scalePagePoint(e,t,r,s){const o=C.RotWith(e,t,-s).sub(t),i=C.MulV(o,r);return C.Add(i,t).rotWith(t,s)}_resizeUnalignedShape(e,t,r){const{type:s}=r.initialShape,o=new C(t.x,t.y);if(Math.abs(t.x)>Math.abs(t.y)?o.x=Math.sign(t.x)*Math.abs(t.y):o.y=Math.sign(t.y)*Math.abs(t.x),this.resizeShape(e,o,{initialShape:r.initialShape,initialBounds:r.initialBounds,isAspectRatioLocked:r.isAspectRatioLocked,initialPageTransform:r.initialPageTransform}),Math.sign(t.x)*Math.sign(t.y)<0){const y=this.getShapeParentTransform(e).rotation(),S=-r.initialShape.rotation-2*y;this.updateShapes([{id:e,type:s,rotation:S}])}const i=Q.applyToPoint(r.initialPageTransform,r.initialBounds.center),a=this._scalePagePoint(i,r.scaleOrigin,t,r.scaleAxisRotation),l=this.getShapePageTransform(e),c=this.getShapeGeometry(e).bounds,u=Q.applyToPoint(l,c.center),d=l.point();if(!u||!d)return this;const h=C.Sub(a,u),f=C.Add(d,h),{x:g,y:m}=this.getPointInParentSpace(e,f);return this.updateShapes([{id:e,type:s,x:g,y:m}]),this}getInitialMetaForShape(e){return{}}canCreateShape(e){return this.canCreateShapes([e])}canCreateShapes(e){return e.length+this.getCurrentPageShapeIds().size<=this.options.maxShapesPerPage}createShape(e){return this.createShapes([e]),this}createShapes(e){if(!Array.isArray(e))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getIsReadonly())return this;if(e.length<=0)return this;const t=this.getCurrentPageShapeIds();if(e.length+t.size>this.options.maxShapesPerPage)return Gp(this),this;const s=this.getFocusedGroupId();return this.run(()=>{var u,d;const o=this.getCurrentPageShapesSorted(),i=e.map(h=>{if(h.id||(h={id:St(),...h}),!h.parentId||!(this.store.has(h.parentId)||e.some(f=>f.id===h.parentId))){let f=this.getFocusedGroupId();if(h.x!==void 0&&h.y!==void 0)for(let y=o.length-1;y>=0;y--){const S=o[y];if(this.getShapeUtil(S).canReceiveNewChildrenOfType(S,h.type)&&!this.isShapeHidden(S)&&this.isPointInShape(S,{x:h.x??0,y:h.y??0},{margin:0,hitInside:!0})){f=S.id;break}}const m=h.parentId;if(f===h.id&&(f=s),f!==m&&(h={...h},h.parentId=f,Pr(f))){const y=this.getPointInShapeSpace(this.getShape(f),{x:h.x??0,y:h.y??0});h.x=y.x,h.y=y.y,h.rotation=-this.getShapePageTransform(f).rotation()+(h.rotation??0)}}return h}),a=new Map,l=[],{opacityForNextShape:c}=this.getInstanceState();for(const h of i){const f=this.getShapeUtil(h);let g=h.index;if(!g){const b=h.parentId??s;a.has(b)||a.set(b,this.getHighestIndexForParent(b)),g=a.get(b),a.set(b,Ns(g))}const m=f.getDefaultProps();for(const[b,w]of this.styleProps[h.type])m[w]=this.getStyleForNextShape(b);let y=this.store.schema.types.shape.create({...h,index:g,opacity:h.opacity??c,parentId:h.parentId??s,props:"props"in h?{...m,...h.props}:m});if(y.index===void 0)throw Error("no index!");const S=(d=(u=this.getShapeUtil(y)).onBeforeCreate)==null?void 0:d.call(u,y);S&&(y=S),l.push(y)}l.forEach(h=>{h.meta={...this.getInitialMetaForShape(h),...h.meta}}),this.emit("created-shapes",l),this.emit("edit"),this.store.put(l)}),this}animateShape(e,t={animation:Mx}){return this.animateShapes([e],t)}animateShapes(e,t={animation:Mx}){if(!t.animation)return this;const{duration:r=500,easing:s=ar.linear}=t.animation,o=at();let i=r,a;const l=[];let c,u;for(let h=0,f=e.length;h<f;h++){if(c=e[h],!c)continue;const g=this.getShape(c.id);g&&(u={start:Ft(g),end:Mo(Ft(g),c)},l.push(u),this.animatingShapes.set(g.id,o))}const d=h=>{var y,S;if(i-=h,i<0){const{animatingShapes:b}=this,w=e.filter(v=>v&&b.get(v.id)===o);w.length&&this.updateShapes(w),this.off("tick",d);return}a=s(1-i/r);const{animatingShapes:f}=this,g=[];let m;for(let b=0,w=l.length;b<w;b++){const{start:v,end:P}=l[b];m=f.get(v.id),m===o&&g.push({...P,x:v.x+(P.x-v.x)*a,y:v.y+(P.y-v.y)*a,opacity:v.opacity+(P.opacity-v.opacity)*a,rotation:v.rotation+(P.rotation-v.rotation)*a,props:((S=(y=this.getShapeUtil(P)).getInterpolatedProps)==null?void 0:S.call(y,v,P,a))??P.props})}this._updateShapes(g)};return this.on("tick",d),this}groupShapes(e,t={}){var m;const{groupId:r=St(),select:s=!0}=t;if(!Array.isArray(e))throw Error("Editor.groupShapes: must provide an array of shapes or shape ids");if(this.getIsReadonly())return this;const o=typeof e[0]=="string"?e:e.map(y=>y.id);if(o.length<=1)return this;const i=Le((this._shouldIgnoreShapeLock?o:this._getUnlockedShapeIds(o)).map(y=>this.getShape(y))),a=i.sort(Tn).map(y=>y.id),l=Le(i.map(y=>this.getShapePageBounds(y))),c=J.Common(l);if(!c.isValid())throw Error("Editor.groupShapes: group bounds are invalid (NaN).");const{x:u,y:d}=c.point,h=this.findCommonAncestor(i)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const f=i.filter(y=>y.parentId===h).sort(Tn),g=(m=f[f.length-1])==null?void 0:m.index;return this.run(()=>{this.createShapes([{id:r,type:"group",parentId:h,index:g,x:u,y:d,opacity:1,props:{}}]),this.reparentShapes(a,r),s&&this.select(r)}),this}ungroupShapes(e,t={}){if(this.getIsReadonly())return this;const{select:r=!0}=t,s=typeof e[0]=="string"?e:e.map(l=>l.id),o=Le((this._shouldIgnoreShapeLock?s:this._getUnlockedShapeIds(s)).map(l=>this.getShape(l)));if(o.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const i=new Set,a=[];return o.forEach(l=>{this.isShapeOfType(l,"group")?a.push(l):i.add(l.id)}),a.length===0?this:(this.run(()=>{let l;for(let c=0,u=a.length;c<u;c++){l=a[c];const d=this.getSortedChildIdsForParent(l.id);for(let h=0,f=d.length;h<f;h++)i.add(d[h]);this.reparentShapes(d,l.parentId,l.index)}this.deleteShapes(a.map(c=>c.id)),r&&this.select(...i)}),this)}updateShape(e){return this.updateShapes([e]),this}updateShapes(e){const t=Array(e.length);for(let r=0,s=e.length;r<s;r++){const o=e[r];if(!o)continue;const i=this.getShape(o.id);if(i){if(!this._shouldIgnoreShapeLock){if(i.isLocked){if(!(Object.hasOwn(o,"isLocked")&&!o.isLocked))continue}else if(this.isShapeOrAncestorLocked(i))continue}this.animatingShapes.delete(o.id),t.push(o)}}return this._updateShapes(t),this}_updateShapes(e){this.getIsReadonly()||this.run(()=>{var o,i;const t=[];let r,s;for(let a=0,l=e.length;a<l;a++){const c=e[a];c&&(r=this.getShape(c.id),r&&(s=Mo(r,c),s!==r&&(s=((i=(o=this.getShapeUtil(r)).onBeforeUpdate)==null?void 0:i.call(o,r,s))??s,t.push(s))))}this.emit("edited-shapes",t),this.emit("edit"),this.store.put(t)})}_getUnlockedShapeIds(e){return e.filter(t=>{var r;return!((r=this.getShape(t))!=null&&r.isLocked)})}deleteShapes(e){if(this.getIsReadonly())return this;if(!Array.isArray(e))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const t=typeof e[0]=="string"?e:e.map(o=>o.id),r=this._shouldIgnoreShapeLock?t:this._getUnlockedShapeIds(t);if(r.length===0)return this;const s=new Set(r);for(const o of r)this.visitDescendants(o,i=>{s.add(i)});return this.emit("deleted-shapes",[...s]),this.emit("edit"),this.run(()=>this.store.remove([...s]))}deleteShape(e){return this.deleteShapes([typeof e=="string"?e:e.id]),this}_extractSharedStyles(e,t){if(this.isShapeOfType(e,"group")){const r=this._parentIdsToChildIds.get()[e.id];if(!r)return;for(let s=0,o=r.length;s<o;s++)this._extractSharedStyles(this.getShape(r[s]),t)}else for(const[r,s]of this.styleProps[e.type])t.applyValue(r,un(e.props,s))}_getSelectionSharedStyles(){const e=this.getSelectedShapes(),t=new Lw;for(const r of e)this._extractSharedStyles(r,t);return t}getStyleForNextShape(e){const t=this.getInstanceState().stylesForNextShape[e.id];return t===void 0?e.defaultValue:t}getShapeStyleIfExists(e,t){const r=this.styleProps[e.type].get(t);if(r!==void 0)return un(e.props,r)}getSharedStyles(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0)return this._getSelectionSharedStyles();const e=this.root.getCurrent(),t=new Lw;if(!e)return t;if(e.shapeType)if(e.shapeType==="frame"&&!this.getShapeUtil("frame").options.showColors)for(const r of this.styleProps[e.shapeType].keys())r.id!=="tldraw:color"&&t.applyValue(r,this.getStyleForNextShape(r));else for(const r of this.styleProps[e.shapeType].keys())t.applyValue(r,this.getStyleForNextShape(r));return t}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const e=[],t=s=>{const o=this.getShape(s);if(o)if(this.isShapeOfType(o,"group"))for(const i of this.getSortedChildIdsForParent(o.id))t(i);else e.push(o)};for(const s of this.getSelectedShapeIds())t(s);let r=null;for(const s of e)if(r===null)r=s.opacity;else if(r!==s.opacity)return{type:"mixed"};if(r!==null)return{type:"shared",value:r}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(e,t){return this.updateInstanceState({opacityForNextShape:e},t),this}setOpacityForSelectedShapes(e){const t=this.getSelectedShapes();if(t.length>0){const r=[],s=o=>{if(this.isShapeOfType(o,"group")){const i=this.getSortedChildIdsForParent(o);for(const a of i)s(this.getShape(a))}else r.push(o)};for(const o of t)s(o);this.updateShapes(r.map(o=>({id:o.id,type:o.type,opacity:e})))}return this}setStyleForNextShapes(e,t,r){const s=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...s,[e.id]:t}},r),this}setStyleForSelectedShapes(e,t){const r=this.getSelectedShapes();if(r.length>0){const s=[],o=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i.id);for(const l of a)o(this.getShape(l))}else{const a=this.getShapeUtil(i),l=this.styleProps[i.type].get(e);if(l){const c={id:i.id,type:i.type,props:{[l]:t}};s.push({util:a,originalShape:i,updatePartial:c})}}};for(const i of r)o(i);this.updateShapes(s.map(({updatePartial:i})=>i))}return this}registerExternalAssetHandler(e,t){return this.externalAssetContentHandlers[e]=t,this}createTemporaryAssetPreview(e,t){if(this.temporaryAssetPreview.has(e))return this.temporaryAssetPreview.get(e);const r=URL.createObjectURL(t);return this.temporaryAssetPreview.set(e,r),setTimeout(()=>{this.temporaryAssetPreview.delete(e),URL.revokeObjectURL(r)},this.options.temporaryAssetPreviewLifetimeMs),r}getTemporaryAssetPreview(e){return this.temporaryAssetPreview.get(e)}async getAssetForExternalContent(e){var t,r;return await((r=(t=this.externalAssetContentHandlers)[e.type])==null?void 0:r.call(t,e))}hasExternalAssetHandler(e){return!!this.externalAssetContentHandlers[e]}registerExternalContentHandler(e,t){return this.externalContentHandlers[e]=t,this}async putExternalContent(e,t={}){var r,s;if(!(!t.force&&this.getIsReadonly()))return(s=(r=this.externalContentHandlers)[e.type])==null?void 0:s.call(r,e)}async replaceExternalContent(e,t={}){var r,s;if(!(!t.force&&this.getIsReadonly()))return(s=(r=this.externalContentHandlers)[e.type])==null?void 0:s.call(r,e)}getContentFromCurrentPage(e){const t=typeof e[0]=="string"?e:e.map(s=>s.id);if(!t||t.length===0)return;const r=this.getShapeAndDescendantIds(t);return KT(this,r,s=>{const o=[];for(const u of s){const d=this.getBinding(u);d&&o.push(d)}const i=[],a=[];for(const u of r){const d=this.getShape(u);if(!d)continue;if(!r.has(d.parentId)){const f=this.getShapePageTransform(d.id),g=f.point();a.push({...d,x:g.x,y:g.y,rotation:f.rotation(),parentId:this.getCurrentPageId()}),i.push(d.id)}else a.push(d)}const l=[],c=new Set;for(const u of a){if(!("assetId"in u.props))continue;const d=u.props.assetId;if(!d||c.has(d))continue;c.add(d);const h=this.getAsset(d);h&&l.push(h)}return{schema:this.store.schema.serialize(),shapes:a,rootShapeIds:i,bindings:o,assets:l}})}async resolveAssetsInContent(e){if(!e)return;const t=[];return await Promise.allSettled(e.assets.map(async r=>{var s,o,i;if((r.type==="image"||r.type==="video")&&!((s=r.props.src)!=null&&s.startsWith("data:image"))&&!((o=r.props.src)!=null&&o.startsWith("data:video"))&&!((i=r.props.src)!=null&&i.startsWith("http"))){const a=Ft(r),l=await this.store.props.assets.resolve(r,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginal:!0});a.props.src=await ir.blobToDataUrl(await $i(l).then(c=>c.blob())),t.push(a)}else t.push(r)})),e.assets=t,e}putContentOntoCurrentPage(e,t={}){var R,D,j;if(this.getIsReadonly())return this;if(!e.schema)throw Error(`Could not put content:
75
+ content is missing a schema.`);const{select:r=!1,preserveIds:s=!1,preservePosition:o=!1}=t;let{point:i=void 0}=t;const a=this.getCurrentPageId(),{rootShapeIds:l}=e,c=[],u=[],d=[],h={store:{...Object.fromEntries(e.assets.map(_=>[_.id,_])),...Object.fromEntries(e.shapes.map(_=>[_.id,_])),...Object.fromEntries(((R=e.bindings)==null?void 0:R.map(_=>[_.id,_]))??[])},schema:e.schema},f=this.store.schema.migrateStoreSnapshot(h);if(f.type==="error")throw Error("Could not put content: could not migrate content");for(const _ of Object.values(f.value))switch(_.typeName){case"asset":{c.push(_);break}case"shape":{u.push(_);break}case"binding":{d.push(_);break}}const g=new Map(s?u.map(_=>[_.id,_.id]):u.map(_=>[_.id,St()])),m=new Map(s?d.map(_=>[_.id,_.id]):d.map(_=>[_.id,wl()]));let y=this.getCurrentPageId(),S=1/0,b=[];for(const _ of this.getSelectedShapes()){if(S===0)break;const M=this.isShapeOfType(_,"frame"),O=this.getShapeAncestors(_);M&&O.push(_);const N=M?O.length+1:O.length;if(N<S)S=N,b=O,y=M?_.id:_.parentId;else if(N===S){if(b.length!==O.length)throw Error(`Ancestors: ${b.length} !== ${O.length}`);if(b.length===0){y=a;break}else{y=a;for(let B=0;B<b.length&&O[B]===b[B];B++)y=O[B].id}}}if(i){const _=new Map(u.map(O=>[O.id,O])),M=Le(l.map(O=>_.get(O)));if(M.length>0){const O=this.getShapeAtPoint(i,{hitInside:!0,hitFrameInside:!0,hitLocked:!0,filter:N=>{const B=this.getShapeUtil(N);return B.canReceiveNewChildrenOfType?M.every(H=>B.canReceiveNewChildrenOfType(N,H.type)):!1}});y=O?O.id:a}}let w=!1;if(!On(y)){const _=this.getShape(y);if(_){if(!this.getViewportPageBounds().includes(this.getShapePageBounds(_)))y=a;else if(l.length===1){const M=u.find(O=>O.id===l[0]);this.isShapeOfType(_,"frame")&&this.isShapeOfType(M,"frame")&&M.props.w===(_==null?void 0:_.props.w)&&M.props.h===(_==null?void 0:_.props.h)&&(w=!0)}}else y=a}w||(w=g.has(y)),w&&(y=this.getShape(y).parentId);let v=this.getHighestIndexForParent(y);const P=[],T=u.map(_=>{const M=g.get(_.id),O={..._,id:M};return l.includes(_.id)&&(O.parentId=a,P.push(O)),g.has(O.parentId)?O.parentId=g.get(_.parentId):(l.push(O.id),O.index=v,v=Ns(v)),O});if(T.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage)return Gp(this),this;const I=d.map(_=>({..._,id:Pn(m.get(_.id)),fromId:Pn(g.get(_.fromId)),toId:Pn(g.get(_.toId))})),k=[],A=[];for(const _ of c)this.store.has(_.id)||((_.type==="image"&&((D=_.props.src)!=null&&D.startsWith("data:image"))||_.type==="video"&&((j=_.props.src)!=null&&j.startsWith("data:video")))&&(A.push(Ft(_)),_.props.src=null),k.push(_));return Promise.allSettled(A.map(async _=>{const M=await k9(_.props.src,_.props.name,_.props.mimeType??"image/png"),O=await this.getAssetForExternalContent({type:"file",file:M,assetId:_.id});if(!O){this.deleteAssets([_.id]);return}this.updateAssets([{...O,id:_.id}])})),this.run(()=>{k.length>0&&this.createAssets(k),this.createShapes(T),this.createBindings(I),r&&this.select(...P.map(B=>B.id)),y!==a&&this.reparentShapes(P.map(B=>B.id),y);const _=T.map(B=>this.getShape(B.id)),M=J.Common(_.map(B=>this.getShapePageBounds(B)));if(i===void 0)if(On(y)){const B=this.getViewportPageBounds();o||B.includes(J.From(M))?i=M.center:i=B.center}else{const B=this.getShape(y);i=Q.applyToPoint(this.getShapePageTransform(B),this.getShapeGeometry(B).bounds.center)}if(P.length===1){const B=P[0];if(this.isShapeOfType(B,"frame"))for(;this.getShapesAtPoint(i).some(H=>this.isShapeOfType(H,"frame")&&H.props.w===B.props.w&&H.props.h===B.props.h);)i.x+=M.w+16}const O=J.Common(Le(P.map(({id:B})=>this.getShapePageBounds(B)))).center,N=C.Sub(i,O);this.updateShapes(P.map(({id:B})=>{const H=this.getShape(B),z=this.getShapeParentTransform(B).decompose().rotation,X=C.Rot(N,-z);return{id:H.id,type:H.type,x:H.x+X.x,y:H.y+X.y}}))}),this}async getSvgElement(e,t={}){const r=e.length===0?this.getCurrentPageShapeIdsSorted():typeof e[0]=="string"?e:e.map(s=>s.id);if(r.length!==0)return x9(this,r,t)}async getSvgString(e,t={}){const r=await this.getSvgElement(e,t);return r?{svg:new XMLSerializer().serializeToString(r.svg),width:r.width,height:r.height}:void 0}async toImage(e,t={}){const r={format:"png",scale:1,pixelRatio:t.format==="svg"?void 0:2,...t},s=await this.getSvgString(e,r);if(!s)throw new Error("Could not create SVG");switch(r.format){case"svg":return{blob:new Blob([s.svg],{type:"image/svg+xml"}),width:s.width,height:s.height};case"jpeg":case"png":case"webp":{const o=await T9(s.svg,{type:r.format,quality:r.quality,pixelRatio:r.pixelRatio,width:s.width,height:s.height});if(!o)throw new Error("Could not construct image.");return{blob:o,width:s.width,height:s.height}}default:it(r.format)}}async toImageDataUrl(e,t={}){const{blob:r,width:s,height:o}=await this.toImage(e,t);return{url:await ir.blobToDataUrl(r),width:s,height:o}}cancel(){return this.dispatch({type:"misc",name:"cancel"}),this}interrupt(){return this.dispatch({type:"misc",name:"interrupt"}),this}complete(){return this.dispatch({type:"misc",name:"complete"}),this}updatePointer(e){const t={type:"pointer",target:"canvas",name:"pointer_move",point:(e==null?void 0:e.point)??C.Add(this.inputs.getCurrentScreenPoint(),this.store.unsafeGetWithoutCapture(Er).screenBounds),pointerId:(e==null?void 0:e.pointerId)??0,button:(e==null?void 0:e.button)??0,isPen:(e==null?void 0:e.isPen)??this.inputs.getIsPen(),shiftKey:(e==null?void 0:e.shiftKey)??this.inputs.getShiftKey(),altKey:(e==null?void 0:e.altKey)??this.inputs.getAltKey(),ctrlKey:(e==null?void 0:e.ctrlKey)??this.inputs.getCtrlKey(),metaKey:(e==null?void 0:e.metaKey)??this.inputs.getMetaKey(),accelKey:!1};return t.accelKey=(e==null?void 0:e.accelKey)??this.inputs.getAccelKey(),e!=null&&e.immediate?this._flushEventForTick(t):this.dispatch(t),this}focus({focusContainer:e=!0}={}){return this.getIsFocused()?this:(e&&this.focusManager.focus(),this.updateInstanceState({isFocused:!0}),this)}blur({blurContainer:e=!0}={}){return this.getIsFocused()?(e?this.focusManager.blur():this.complete(),this.updateInstanceState({isFocused:!1}),this):this}getIsFocused(){return this.getInstanceState().isFocused}getIsReadonly(){return this.getInstanceState().isReadonly}getSnapshot(){return y8(this.store)}loadSnapshot(e,t){return NA(this.store,e,t),this}_zoomToFitPageContentAt100Percent(){const e=this.getCurrentPageBounds();e&&this.zoomToBounds(e,{immediate:!0,targetZoom:this.getBaseZoom()})}_navigateToDeepLink(e){this.run(()=>{switch(e.type){case"page":{const t=this.getPage(e.pageId);t&&this.setCurrentPage(t),this._zoomToFitPageContentAt100Percent();return}case"shapes":{const t=Le(e.shapeIds.map(i=>this.getShape(i))),r={};for(const i of t){const a=this.getAncestorPageId(i);a&&(r[a]??(r[a]=[]),r[a].push(i))}const[s,o]=Object.entries(r).sort(([i,a],[l,c])=>c.length-a.length)[0]??["",[]];if(!s||!o.length)this._zoomToFitPageContentAt100Percent();else{this.setCurrentPage(s);const i=J.Common(o.map(a=>this.getShapePageBounds(a)));this.zoomToBounds(i,{immediate:!0,targetZoom:this.getBaseZoom()})}return}case"viewport":{if(e.pageId){if(!this.getPage(e.pageId)){this._zoomToFitPageContentAt100Percent();return}this.setCurrentPage(e.pageId)}this.zoomToBounds(e.bounds,{immediate:!0,inset:0});return}default:it(e)}})}navigateToDeepLink(e){if(e&&"type"in e)return this._navigateToDeepLink(e),this;const r=new URL((e==null?void 0:e.url)??window.location.href).searchParams.get((e==null?void 0:e.param)??"d");if(!r)return this._zoomToFitPageContentAt100Percent(),this;try{this._navigateToDeepLink(A9(r))}catch(s){console.warn(s),this._zoomToFitPageContentAt100Percent()}return this}createDeepLink(e){const t=new URL((e==null?void 0:e.url)??window.location.href);return t.searchParams.set((e==null?void 0:e.param)??"d",M9((e==null?void 0:e.to)??{type:"viewport",pageId:this.options.maxPages===1?void 0:this.getCurrentPageId(),bounds:this.getViewportPageBounds()})),t}registerDeepLinkListener(e){if(e!=null&&e.getUrl&&!(e!=null&&e.onChange))throw Error("[tldraw:urlStateSync] If you specify getUrl, you must also specify the onChange callback.");const t=q("url with state",()=>{var l,c;const i=((l=e==null?void 0:e.getUrl)==null?void 0:l.call(e,this))??window.location.href;return this.createDeepLink({param:e==null?void 0:e.param,url:i,to:(c=e==null?void 0:e.getTarget)==null?void 0:c.call(e,this)}).toString()}),r=(e==null?void 0:e.onChange)??(()=>{var a;const i=this.createDeepLink({param:e==null?void 0:e.param,to:(a=e==null?void 0:e.getTarget)==null?void 0:a.call(e,this)});window.history.replaceState({},document.title,i.toString())}),s=ry(i=>i(),(e==null?void 0:e.debounceMs)??500),o=Mr("update url on state change",()=>r(new URL(t.get()),this),{scheduleEffect:s});return()=>{o(),s.cancel()}}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_setShiftKeyTimeout(){this.inputs.setShiftKey(!1),this.dispatch({type:"keyboard",name:"key_up",key:"Shift",shiftKey:this.inputs.getShiftKey(),ctrlKey:this.inputs.getCtrlKey(),altKey:this.inputs.getAltKey(),metaKey:this.inputs.getMetaKey(),accelKey:this.inputs.getAccelKey(),code:"ShiftLeft"})}_setAltKeyTimeout(){this.inputs.setAltKey(!1),this.dispatch({type:"keyboard",name:"key_up",key:"Alt",shiftKey:this.inputs.getShiftKey(),ctrlKey:this.inputs.getCtrlKey(),altKey:this.inputs.getAltKey(),metaKey:this.inputs.getMetaKey(),accelKey:this.inputs.getAccelKey(),code:"AltLeft"})}_setCtrlKeyTimeout(){this.inputs.setCtrlKey(!1),this.dispatch({type:"keyboard",name:"key_up",key:"Ctrl",shiftKey:this.inputs.getShiftKey(),ctrlKey:this.inputs.getCtrlKey(),altKey:this.inputs.getAltKey(),metaKey:this.inputs.getMetaKey(),accelKey:this.inputs.getAccelKey(),code:"ControlLeft"})}_setMetaKeyTimeout(){this.inputs.setMetaKey(!1),this.dispatch({type:"keyboard",name:"key_up",key:"Meta",shiftKey:this.inputs.getShiftKey(),ctrlKey:this.inputs.getCtrlKey(),altKey:this.inputs.getAltKey(),metaKey:this.inputs.getMetaKey(),accelKey:this.inputs.getAccelKey(),code:"MetaLeft"})}markEventAsHandled(e){const t="nativeEvent"in e?e.nativeEvent:e;this.handledEvents.add(t)}wasEventAlreadyHandled(e){const t="nativeEvent"in e?e.nativeEvent:e;return this.handledEvents.has(t)}dispatch(e){return this._pendingEventsForNextTick.push(e),e.type==="pointer"&&e.name==="pointer_move"||e.type==="wheel"||e.type==="pinch"||this._flushEventsForTick(0),this}_flushEventsForTick(e){this.run(()=>{if(this._pendingEventsForNextTick.length>0){const t=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const r of t)this._flushEventForTick(r)}e>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:e}),this.scribbles.tick(e)})}_flushEventForTick(e){if(this.getCrashingError())return this;this.emit("before-event",e);const{inputs:t}=this,{type:r}=e;if(e.type==="misc"){(e.name==="cancel"||e.name==="complete")&&(this.inputs.setIsDragging(!1),this.inputs.getIsPanning()&&(this.inputs.setIsPanning(!1),this.inputs.setIsSpacebarPanning(!1),this.setCursor({type:this._prevCursor,rotation:0}))),this.root.handleEvent(e),this.emit("event",e);return}e.shiftKey?(clearTimeout(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,t.setShiftKey(!0)):!e.shiftKey&&t.getShiftKey()&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=this.timers.setTimeout(this._setShiftKeyTimeout,150)),e.altKey?(clearTimeout(this._altKeyTimeout),this._altKeyTimeout=-1,t.setAltKey(!0)):!e.altKey&&t.getAltKey()&&this._altKeyTimeout===-1&&(this._altKeyTimeout=this.timers.setTimeout(this._setAltKeyTimeout,150)),e.ctrlKey?(clearTimeout(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,t.setCtrlKey(!0)):!e.ctrlKey&&t.getCtrlKey()&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=this.timers.setTimeout(this._setCtrlKeyTimeout,150)),e.metaKey?(clearTimeout(this._metaKeyTimeout),this._metaKeyTimeout=-1,t.setMetaKey(!0)):!e.metaKey&&t.getMetaKey()&&this._metaKeyTimeout===-1&&(this._metaKeyTimeout=this.timers.setTimeout(this._setMetaKeyTimeout,150)),t.getIsPointing()||t.setIsDragging(!1);const s=this.store.unsafeGetWithoutCapture(Er),o=this.store.get(this._getCurrentPageStateId()),i=this._cameraOptions.__unsafe__getWithoutCapture();switch(r){case"pinch":{if(i.isLocked)return;switch(clearTimeout(this._longPressTimeout),this.inputs.updateFromEvent(e),e.name){case"pinch_start":{if(t.getIsPinching())return;t.getIsEditing()||(this._selectedShapeIdsAtPointerDown=[...o.selectedShapeIds],this._didPinch=!0,t.setIsPinching(!0),this.interrupt()),this.emit("event",e);return}case"pinch":{if(!t.getIsPinching())return;const{point:{z:a=1},delta:{x:l,y:c}}=e,{x:u,y:d}=C.SubXY(e.point,s.screenBounds.x,s.screenBounds.y);this.stopCameraAnimation(),s.followingUserId&&this.stopFollowingUser();const{x:h,y:f,z:g}=gl(()=>this.getCamera()),{panSpeed:m}=i;this._setCamera(new C(h+l*m/g-u/g+u/a,f+c*m/g-d/g+d/a,a),{immediate:!0}),this.emit("event",e);return}case"pinch_end":{if(!t.getIsPinching())return this;t.setIsPinching(!1);const{_selectedShapeIdsAtPointerDown:a}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,a.length>0&&this.once("tick",()=>{this._didPinch||this.setSelectedShapes(a)})),this.emit("event",e);return}}}case"wheel":{if(i.isLocked)return;this.inputs.updateFromEvent(e);const{panSpeed:a,zoomSpeed:l}=i;let c=i.wheelBehavior;const u=this.user.getUserPreferences().inputMode;if(u!==null&&(c=u==="trackpad"?"pan":"zoom"),c!=="none"){this.stopCameraAnimation(),s.followingUserId&&this.stopFollowingUser();const{x:d,y:h,z:f}=gl(()=>this.getCamera()),{x:g,y:m,z:y=0}=e.delta;let S=c;switch(e.ctrlKey&&(S=c==="pan"?"zoom":"pan"),S){case"zoom":{const{x:b,y:w}=this.inputs.getCurrentScreenPoint();let v=y;c==="zoom"&&(Math.abs(m)>10?v=10*Math.sign(m)/100:v=m/100);const P=(this.user.getUserPreferences().isZoomDirectionInverted&&u==="mouse")??!1,T=v??0,I=P?-T:T,k=f+I*l*f;this._setCamera(new C(d+b/k-b/f,h+w/k-w/f,k),{immediate:!0}),this.maybeTrackPerformance("Zooming"),this.root.handleEvent(e),this.emit("event",e);return}case"pan":{this._setCamera(new C(d+g*a/f,h+m*a/f,f),{immediate:!0}),this.maybeTrackPerformance("Panning"),this.root.handleEvent(e),this.emit("event",e);return}}}break}case"pointer":{if(t.getIsPinching())return;this.inputs.updateFromEvent(e);const{isPen:a}=e,{isPenMode:l}=s;switch(e.name){case"pointer_down":{if(l&&!a)return;if(this.inputs.getIsPanning()||(this._longPressTimeout=this.timers.setTimeout(()=>{const c=this.getViewportScreenBounds();this.dispatch({...e,point:this.inputs.getOriginScreenPoint().clone().addXY(c.x,c.y),name:"long_press"})},this.options.longPressDurationMs)),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),e.button===ST&&(this.capturedPointerId=e.pointerId),t.buttons.add(e.button),t.setIsPointing(!0),t.setIsDragging(!1),!l&&a&&this.updateInstanceState({isPenMode:!0}),e.button===xT?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):e.button===zp&&(this.inputs.getIsPanning()||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.setIsPanning(!0),clearTimeout(this._longPressTimeout)),this.inputs.getIsPanning())return this.stopCameraAnimation(),this.setCursor({type:"grabbing",rotation:0}),this;break}case"pointer_move":{if(!a&&l)return;const{x:c,y:u,z:d}=gl(()=>this.getCamera());if(this.inputs.getIsPanning()&&this.inputs.getIsPointing()){const h=this.inputs.getCurrentScreenPoint(),f=this.inputs.getPreviousScreenPoint(),g=C.Sub(h,f);this.setCamera(new C(c+g.x/d,u+g.y/d,d),{immediate:!0}),this.maybeTrackPerformance("Panning");return}t.getIsPointing()&&!t.getIsDragging()&&C.Dist2(t.getOriginPagePoint(),t.getCurrentPagePoint())*this.getZoomLevel()>(s.isCoarsePointer?this.options.coarseDragDistanceSquared:this.options.dragDistanceSquared)/d&&(t.setIsDragging(!0),clearTimeout(this._longPressTimeout));break}case"pointer_up":{if(t.setIsDragging(!1),t.setIsPointing(!1),clearTimeout(this._longPressTimeout),t.buttons.delete(e.button),s.isPenMode&&!a)return;if(this.capturedPointerId===e.pointerId&&(this.capturedPointerId=null,e.button=0),t.getIsPanning()){t.keys.has("Space")||(t.setIsPanning(!1),t.setIsSpacebarPanning(!1));const c=this.inputs.getPointerVelocity(),u=Math.min(2,c.len());switch(e.button){case ST:{this.setCursor({type:"grab",rotation:0});break}case zp:this.inputs.keys.has(" ")?this.setCursor({type:"grab",rotation:0}):this.setCursor({type:this._prevCursor,rotation:0})}u>0&&this.slideCamera({speed:u,direction:c})}else e.button===xT&&(this.complete(),this.setCurrentTool(this._restoreToolId));this._selectedShapeIdsAtPointerDown=[];break}}break}case"keyboard":{switch(e.key==="ShiftRight"&&(e.key="ShiftLeft"),e.key==="AltRight"&&(e.key="AltLeft"),e.code==="ControlRight"&&(e.code="ControlLeft"),e.code==="MetaRight"&&(e.code="MetaLeft"),e.name){case"key_down":{if(t.keys.add(e.code),this.options.spacebarPanning&&(e.code==="Space"&&!e.ctrlKey&&(this.inputs.getIsPanning()||(this._prevCursor=s.cursor.type),this.inputs.setIsPanning(!0),this.inputs.setIsSpacebarPanning(!0),clearTimeout(this._longPressTimeout),this.setCursor({type:this.inputs.getIsPointing()?"grabbing":"grab",rotation:0})),this.inputs.getIsSpacebarPanning())){let a;switch(e.code){case"ArrowUp":{a=new C(0,-1);break}case"ArrowRight":{a=new C(1,0);break}case"ArrowDown":{a=new C(0,1);break}case"ArrowLeft":{a=new C(-1,0);break}}if(a){const l=this.getViewportPageBounds(),c=l.clone().translate(a.mulV({x:l.w,y:l.h}));this._animateToViewport(c,{animation:{duration:320}})}}break}case"key_up":{t.keys.delete(e.code),this.options.spacebarPanning&&e.code==="Space"&&(this.inputs.buttons.has(zp)||(this.inputs.setIsPanning(!1),this.inputs.setIsSpacebarPanning(!1),this.setCursor({type:this._prevCursor,rotation:0})));break}}break}}if(e.type==="pointer"){e.button===zp?e.name="middle_click":e.button===Kv&&(e.name="right_click");const{isPenMode:a}=this.store.unsafeGetWithoutCapture(Er);if(e.isPen===a){const l=this._clickManager.handlePointerEvent(e);if(e.name!==l.name){this.root.handleEvent(e),this.emit("event",e),this.root.handleEvent(l),this.emit("event",l);return}}}return this.root.handleEvent(e),this.emit("event",e),e.type==="pointer"&&e.name==="pointer_down"&&this.menus.clearOpenMenus(),this}maybeTrackPerformance(e){Dt.measurePerformance.get()&&(this.performanceTracker.isStarted()?clearTimeout(this.performanceTrackerTimeout):this.performanceTracker.start(e),this.performanceTrackerTimeout=this.timers.setTimeout(()=>{this.performanceTracker.stop()},50))}};pe=SK(Nw);me(pe,1,"getIsShapeHiddenCache",rR,he);me(pe,1,"canUndo",nR,he);me(pe,1,"canRedo",tR,he);me(pe,1,"getPath",eR,he);me(pe,1,"getCurrentTool",QO,he);me(pe,1,"getCurrentToolId",JO,he);me(pe,1,"getDocumentSettings",ZO,he);me(pe,1,"getInstanceState",qO,he);me(pe,1,"getPageStates",XO,he);me(pe,1,"_getPageStatesQuery",YO,he);me(pe,1,"getCurrentPageState",GO,he);me(pe,1,"_getCurrentPageStateId",VO,he);me(pe,1,"getSelectedShapeIds",WO,he);me(pe,1,"getSelectedShapes",KO,he);me(pe,1,"getCurrentPageShapesInReadingOrder",UO,he);me(pe,1,"getOnlySelectedShapeId",HO,he);me(pe,1,"getOnlySelectedShape",$O,he);me(pe,1,"getSelectionPageBounds",zO,he);me(pe,1,"getSelectionRotation",BO,he);me(pe,1,"getSelectionRotatedPageBounds",FO,he);me(pe,1,"getSelectionRotatedScreenBounds",NO,he);me(pe,1,"getFocusedGroupId",jO,he);me(pe,1,"getFocusedGroup",LO,he);me(pe,1,"getEditingShapeId",RO,he);me(pe,1,"getEditingShape",OO,he);me(pe,1,"getRichTextEditor",DO,he);me(pe,1,"getHoveredShapeId",AO,he);me(pe,1,"getHoveredShape",MO,he);me(pe,1,"getHintingShapeIds",_O,he);me(pe,1,"getHintingShape",kO,he);me(pe,1,"getErasingShapeIds",EO,he);me(pe,1,"getErasingShapes",IO,he);me(pe,1,"_unsafe_getCameraId",TO,he);me(pe,1,"getCamera",PO,he);me(pe,1,"getViewportPageBoundsForFollowing",CO,he);me(pe,1,"getCameraForFollowing",vO,he);me(pe,1,"getZoomLevel",wO,he);me(pe,1,"getDebouncedZoomLevel",bO,he);me(pe,1,"_getAboveDebouncedZoomThreshold",xO,he);me(pe,1,"getEfficientZoomLevel",SO,he);me(pe,1,"getViewportScreenBounds",yO,he);me(pe,1,"getViewportScreenCenter",mO,he);me(pe,1,"getViewportPageBounds",gO,he);me(pe,1,"_getCollaboratorsQuery",fO,he);me(pe,1,"getCollaborators",pO,he);me(pe,1,"getCollaboratorsOnCurrentPage",hO,he);me(pe,1,"getRenderingShapes",uO,he);me(pe,1,"_getAllPagesQuery",dO,he);me(pe,1,"getPages",cO,he);me(pe,1,"getCurrentPageId",lO,he);me(pe,1,"getCurrentPageShapeIdsSorted",aO,he);me(pe,1,"_getAllAssetsQuery",iO,he);me(pe,1,"_getShapeHandlesCache",oO,he);me(pe,1,"_getShapePageTransformCache",sO,he);me(pe,1,"_getShapePageBoundsCache",rO,he);me(pe,1,"_getShapeClipPathCache",nO,he);me(pe,1,"_getShapeMaskCache",tO,he);me(pe,1,"_getShapeMaskedPageBoundsCache",eO,he);me(pe,1,"getNotVisibleShapes",QD,he);me(pe,1,"getCulledShapes",JD,he);me(pe,1,"getCurrentPageBounds",ZD,he);me(pe,1,"getCurrentPageShapes",qD,he);me(pe,1,"getCurrentPageShapesSorted",XD,he);me(pe,1,"getCurrentPageRenderingShapesSorted",YD,he);me(pe,1,"_getBindingsIndexCache",GD,he);me(pe,1,"_getSelectionSharedStyles",VD,he);me(pe,1,"getSharedStyles",WD,he);me(pe,1,"getSharedOpacity",KD,he);me(pe,1,"getIsFocused",UD,he);me(pe,1,"getIsReadonly",HD,he);me(pe,1,"_setShiftKeyTimeout",$D,he);me(pe,1,"_setAltKeyTimeout",zD,he);me(pe,1,"_setCtrlKeyTimeout",BD,he);me(pe,1,"_setMetaKeyTimeout",FD,he);bK(pe,he);function Gp(n,e=n.getCurrentPageId()){const t=n.getPage(e).name;n.emit("max-shapes",{name:t,pageId:e,count:n.options.maxShapesPerPage})}function Mo(n,e){if(!e)return n;let t=null;const r=Object.entries(e);for(let s=0,o=r.length;s<o;s++){const[i,a]=r[s];if(a!==void 0&&!(i==="id"||i==="type"||i==="typeName")&&a!==n[i]){if(t||(t={...n}),i==="props"||i==="meta"){t[i]={...n[i]};for(const[l,c]of Object.entries(a))t[i][l]=c;continue}t[i]=a}}return t||n}function sR(n,e,t){const r=n.getShape(e);if(!r)return;t.push(r);const s=n.getSortedChildIdsForParent(e);for(let o=0,i=s.length;o<i;o++)sR(n,s[o],t)}function KT(n,e,t){let r;if(n.run(()=>{const s=n.store.extractingChanges(()=>{const o=new Set,i=new Set;for(const a of e)if(n.getShape(a))for(const c of n.getBindingsInvolvingShape(a)){const u=e.has(c.fromId),d=e.has(c.toId);if(u&&d){o.add(c.id);continue}(!u||!d)&&i.add(c.id)}n.deleteBindings([...i],{isolateShapes:!0});try{r=zs.ok(t(o))}catch(a){r=zs.err(a)}});n.store.applyDiff(xw(s),{runCallbacks:!1})},{history:"ignore"}),r.ok)return r.value;throw r.error}function WT(n,e){if(!e.constraints)throw Error("Should have constraints here");const{padding:{x:t,y:r}}=e.constraints,s=n.getViewportScreenBounds(),o=J.From(e.constraints.bounds),i=(s.w-t*2)/o.w,a=(s.h-r*2)/o.h;return{zx:i,zy:a}}function Vh(){const n=K(),e=Hh();return W("isDarkMode",()=>(e==null?void 0:e.isDarkMode)??n.user.getIsDarkMode(),[e,n])}const VT="<path d='m19.7432 17.0869-4.072 4.068 2.829 2.828-8.473-.013-.013-8.47 2.841 2.842 4.075-4.068 1.414-1.415-2.844-2.842h8.486v8.484l-2.83-2.827z' fill='%23fff'/><path d='m18.6826 16.7334-4.427 4.424 1.828 1.828-5.056-.016-.014-5.054 1.842 1.841 4.428-4.422 2.474-2.475-1.844-1.843h5.073v5.071l-1.83-1.828z' fill='%23000'/>",GT="<path d='m9 17.9907v.005l5.997 5.996.001-3.999h1.999 2.02v4l5.98-6.001-5.98-5.999.001 4.019-2.021.002h-2l.001-4.022zm1.411.003 3.587-3.588-.001 2.587h3.5 2.521v-2.585l3.565 3.586-3.564 3.585-.001-2.585h-2.521l-3.499-.001-.001 2.586z' fill='%23fff'/><path d='m17.4971 18.9932h2.521v2.586l3.565-3.586-3.565-3.585v2.605h-2.521-3.5v-2.607l-3.586 3.587 3.586 3.586v-2.587z' fill='%23000'/>",Yp='<path d="M22.4789 9.45728L25.9935 12.9942L22.4789 16.5283V14.1032C18.126 14.1502 14.6071 17.6737 14.5675 22.0283H17.05L13.513 25.543L9.97889 22.0283H12.5674C12.6071 16.5691 17.0214 12.1503 22.4789 12.1031L22.4789 9.45728Z" fill="black"/><path fill-rule="evenodd" clip-rule="evenodd" d="M21.4789 7.03223L27.4035 12.9945L21.4789 18.9521V15.1868C18.4798 15.6549 16.1113 18.0273 15.649 21.0284H19.475L13.5128 26.953L7.55519 21.0284H11.6189C12.1243 15.8155 16.2679 11.6677 21.4789 11.1559L21.4789 7.03223ZM22.4789 12.1031C17.0214 12.1503 12.6071 16.5691 12.5674 22.0284H9.97889L13.513 25.543L17.05 22.0284H14.5675C14.5705 21.6896 14.5947 21.3558 14.6386 21.0284C15.1157 17.4741 17.9266 14.6592 21.4789 14.1761C21.8063 14.1316 22.1401 14.1069 22.4789 14.1032V16.5284L25.9935 12.9942L22.4789 9.45729L22.4789 12.1031Z" fill="white"/>';function ra(n,e,t,r,s,o=16,i=16){const a=(-t-e)*(ht/180),l=Math.sin(a),c=Math.cos(a),u=1*c-1*l,d=1*l+1*c;return`url("data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${s};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${u}' dy='${d}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${e+t} 16 16)${r?" scale(-1,-1) translate(0, -32)":""}' filter='url(%23shadow)'>`+n.replaceAll('"',"'")+`</g></svg>") ${o} ${i}, pointer`}const vK=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],CK={none:()=>"none","ew-resize":(n,e,t)=>ra(GT,n,0,e,t),"ns-resize":(n,e,t)=>ra(GT,n,90,e,t),"nesw-resize":(n,e,t)=>ra(VT,n,0,e,t),"nwse-resize":(n,e,t)=>ra(VT,n,90,e,t),"nwse-rotate":(n,e,t)=>ra(Yp,n,0,e,t),"nesw-rotate":(n,e,t)=>ra(Yp,n,90,e,t),"senw-rotate":(n,e,t)=>ra(Yp,n,180,e,t),"swne-rotate":(n,e,t)=>ra(Yp,n,270,e,t)};function ds(n,e=0,t="black"){return CK[n](NU(e),!1,t)}function PK(){const n=K(),e=sn(),t=Vh();Va("useCursor",()=>{const{type:r,rotation:s}=n.getInstanceState().cursor;if(vK.includes(r)){e.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}e.style.setProperty("--tl-cursor",ds(r,s,t?"white":"black"))},[n,e,t])}function TK(){const n=K(),e=sn(),t=Vh(),r=W(Dt.forceSrgb);_e.useEffect(()=>{t?(e.setAttribute("data-color-mode","dark"),e.classList.remove("tl-theme__light"),e.classList.add("tl-theme__dark")):(e.setAttribute("data-color-mode","light"),e.classList.remove("tl-theme__dark"),e.classList.add("tl-theme__light")),r?e.classList.add("tl-theme__force-sRGB"):e.classList.remove("tl-theme__force-sRGB")},[n,e,r,t])}function IK(){const[n,e]=x.useState(0);x.useEffect(()=>e(t=>t+1),[])}const EK=n=>n.props.src,kK={upload:async(n,e)=>({src:await ir.blobToDataUrl(e)})};function _K(n){return"schema"in n&&n.schema?n.schema:EU({shapes:"shapeUtils"in n&&n.shapeUtils?YT(KA(n.shapeUtils)):void 0,bindings:"bindingUtils"in n&&n.bindingUtils?YT(BA(n.bindingUtils)):void 0,migrations:"migrations"in n?n.migrations:void 0})}function Kg({initialData:n,defaultName:e="",id:t,assets:r=kK,onMount:s,collaboration:o,...i}={}){const a=_K(i),l=new Dv({id:t,schema:a,initialData:n,props:{defaultName:e,assets:{upload:r.upload,resolve:r.resolve??EK,remove:r.remove??(()=>Promise.resolve())},onMount:c=>{be(c instanceof he),s==null||s(c)},collaboration:o}});if(i.snapshot){if(n)throw new Error("Cannot provide both initialData and snapshot");NA(l,i.snapshot,{forceOverwriteSessionState:!0})}return l}function YT(n){return Object.fromEntries(n.map(e=>[e.type,{props:e.props,migrations:e.migrations}]))}const MK=(n,e)=>e.some(t=>n instanceof t);let XT,qT;function AK(){return XT||(XT=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function DK(){return qT||(qT=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const oR=new WeakMap,Fw=new WeakMap,iR=new WeakMap,Kx=new WeakMap,c1=new WeakMap;function OK(n){const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("success",o),n.removeEventListener("error",i)},o=()=>{t(Ni(n.result)),s()},i=()=>{r(n.error),s()};n.addEventListener("success",o),n.addEventListener("error",i)});return e.then(t=>{t instanceof IDBCursor&&oR.set(t,n)}).catch(()=>{}),c1.set(e,n),e}function RK(n){if(Fw.has(n))return;const e=new Promise((t,r)=>{const s=()=>{n.removeEventListener("complete",o),n.removeEventListener("error",i),n.removeEventListener("abort",i)},o=()=>{t(),s()},i=()=>{r(n.error||new DOMException("AbortError","AbortError")),s()};n.addEventListener("complete",o),n.addEventListener("error",i),n.addEventListener("abort",i)});Fw.set(n,e)}let Bw={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Fw.get(n);if(e==="objectStoreNames")return n.objectStoreNames||iR.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Ni(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function LK(n){Bw=n(Bw)}function jK(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){const r=n.call(Wx(this),e,...t);return iR.set(r,e.sort?e.sort():[e]),Ni(r)}:DK().includes(n)?function(...e){return n.apply(Wx(this),e),Ni(oR.get(this))}:function(...e){return Ni(n.apply(Wx(this),e))}}function NK(n){return typeof n=="function"?jK(n):(n instanceof IDBTransaction&&RK(n),MK(n,AK())?new Proxy(n,Bw):n)}function Ni(n){if(n instanceof IDBRequest)return OK(n);if(Kx.has(n))return Kx.get(n);const e=NK(n);return e!==n&&(Kx.set(n,e),c1.set(e,n)),e}const Wx=n=>c1.get(n);function aR(n,e,{blocked:t,upgrade:r,blocking:s,terminated:o}={}){const i=indexedDB.open(n,e),a=Ni(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Ni(i.result),l.oldVersion,l.newVersion,Ni(i.transaction),l)}),t&&i.addEventListener("blocked",l=>t(l.oldVersion,l.newVersion,l)),a.then(l=>{o&&l.addEventListener("close",()=>o()),s&&l.addEventListener("versionchange",c=>s(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}function lR(n,{blocked:e}={}){const t=indexedDB.deleteDatabase(n);return e&&t.addEventListener("blocked",r=>e(r.oldVersion,r)),Ni(t).then(()=>{})}const FK=["get","getKey","getAll","getAllKeys","count"],BK=["put","add","delete","clear"],Vx=new Map;function ZT(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(Vx.get(e))return Vx.get(e);const t=e.replace(/FromIndex$/,""),r=e!==t,s=BK.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||FK.includes(t)))return;const o=async function(i,...a){const l=this.transaction(i,s?"readwrite":"readonly");let c=l.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[t](...a),s&&l.done]))[0]};return Vx.set(e,o),o}LK(n=>({...n,get:(e,t,r)=>ZT(e,t)||n.get(e,t,r),has:(e,t)=>!!ZT(e,t)||n.has(e,t)}));const zK="TLDRAW_DOCUMENT_v2",$K="TLDRAW_ASSET_STORE_v1",cR="TLDRAW_DB_NAME_INDEX_v2",et={Records:"records",Schema:"schema",SessionState:"session_state",Assets:"assets"};async function dR(n){const e=zK+n;return UK(e),await aR(e,4,{upgrade(t){t.objectStoreNames.contains(et.Records)||t.createObjectStore(et.Records),t.objectStoreNames.contains(et.Schema)||t.createObjectStore(et.Schema),t.objectStoreNames.contains(et.SessionState)||t.createObjectStore(et.SessionState),t.objectStoreNames.contains(et.Assets)||t.createObjectStore(et.Assets)}})}async function HK(n){const e=window.indexedDB.databases?(await window.indexedDB.databases()).map(h=>h.name):d1(),t=$K+n;if(!e.find(h=>h===t))return;const s=await aR(t,1,{upgrade(h){h.objectStoreNames.contains("assets")||h.createObjectStore("assets")}});if(!s.objectStoreNames.contains("assets"))return;const o=s.transaction(["assets"],"readonly"),i=o.objectStore("assets"),a=await i.getAllKeys(),l=await Promise.all(a.map(async h=>[h,await i.get(h)]));await o.done;const c=await dR(n),u=c.transaction([et.Assets],"readwrite"),d=u.objectStore(et.Assets);for(const[h,f]of l)d.put(f,h);await u.done,s.close(),c.close(),await lR(t)}const Ju=class Ju{constructor(e){E(this,"getDbPromise");E(this,"isClosed",!1);E(this,"pendingTransactionSet",new Set);Ju.connectedInstances.add(this),this.getDbPromise=(async()=>(await HK(e),await dR(e)))()}getDb(){return this.getDbPromise}pending(){return Promise.allSettled([this.getDbPromise,...this.pendingTransactionSet]).then(eh)}async close(){this.isClosed||(this.isClosed=!0,await this.pending(),(await this.getDb()).close(),Ju.connectedInstances.delete(this))}tx(e,t,r){const s=(async()=>{be(!this.isClosed,"db is closed");const i=(await this.getDb()).transaction(t,e),a=i.done.catch(l=>{if(!this.isClosed)throw l});try{return await r(i)}finally{this.isClosed?i.abort():await a}})();return this.pendingTransactionSet.add(s),s.finally(()=>this.pendingTransactionSet.delete(s)),s}async load({sessionId:e}={}){return await this.tx("readonly",[et.Records,et.Schema,et.SessionState],async t=>{var l,c;const r=t.objectStore(et.Records),s=t.objectStore(et.Schema),o=t.objectStore(et.SessionState);let i=e?(l=await o.get(e))==null?void 0:l.snapshot:null;return i||(i=(c=(await o.getAll()).sort((d,h)=>d.updatedAt-h.updatedAt).pop())==null?void 0:c.snapshot),{records:await r.getAll(),schema:await s.get(et.Schema),sessionStateSnapshot:i}})}async storeChanges({schema:e,changes:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[et.Records,et.Schema,et.SessionState],async o=>{const i=o.objectStore(et.Records),a=o.objectStore(et.Schema),l=o.objectStore(et.SessionState);for(const[c,u]of Object.entries(t.added))await i.put(u,c);for(const[c,u]of Object.values(t.updated))await i.put(u,u.id);for(const c of Object.keys(t.removed))await i.delete(c);a.put(e.serialize(),et.Schema),s&&r?l.put({snapshot:s,updatedAt:Date.now(),id:r},r):(s||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async storeSnapshot({schema:e,snapshot:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[et.Records,et.Schema,et.SessionState],async o=>{const i=o.objectStore(et.Records),a=o.objectStore(et.Schema),l=o.objectStore(et.SessionState);await i.clear();for(const[c,u]of Object.entries(t))await i.put(u,c);a.put(e.serialize(),et.Schema),s&&r?l.put({snapshot:s,updatedAt:Date.now(),id:r},r):(s||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async pruneSessions(){await this.tx("readwrite",[et.SessionState],async e=>{const t=e.objectStore(et.SessionState),r=(await t.getAll()).sort((o,i)=>o.updatedAt-i.updatedAt);if(r.length<10){await e.done;return}const s=r.slice(0,r.length-10);for(const{id:o}of s)await t.delete(o)})}async getAsset(e){return await this.tx("readonly",[et.Assets],async t=>await t.objectStore(et.Assets).get(e))}async storeAsset(e,t){await this.tx("readwrite",[et.Assets],async r=>{await r.objectStore(et.Assets).put(t,e)})}async removeAssets(e){await this.tx("readwrite",[et.Assets],async t=>{const r=t.objectStore(et.Assets);for(const s of e)await r.delete(s)})}};E(Ju,"connectedInstances",new Set);let Wg=Ju;function d1(){const n=JSON.parse(gv(cR)||"[]")??[];return Array.isArray(n)?n:[]}function UK(n){const e=new Set(d1());e.add(n),mv(cR,JSON.stringify([...e]))}function KK(){window.alert(`Oops! We could not save changes to your browser's storage. We now need to reload the page and try again.
76
+
77
+ Keep seeing this message?
78
+ • If you're using tldraw in a private or "incognito" window, try loading tldraw in a regular window or in a different browser.
79
+ • If your hard disk is full, try clearing up some space and then reload the page.`)}function WK(){window.alert(`Oops! We could not access your browser's storage—and the app won't work correctly without that. We now need to reload the page and try again.
80
+
81
+ Keep seeing this message?
82
+ • If you're using tldraw in a private or "incognito" window, try loading tldraw in a regular window or in a different browser.`)}const VK=350,GK=1e4,JT=Symbol("UPDATE_INSTANCE_STATE"),YK=n=>n;class XK{constructor(e){E(this,"onmessage")}postMessage(e){}close(){}}const qK=typeof BroadcastChannel>"u"?XK:BroadcastChannel;class ZK{constructor(e,{persistenceKey:t,sessionId:r=$g,onLoad:s,onLoadError:o},i=new qK(`tldraw-tab-sync-${t}`)){E(this,"disposables",new Set);E(this,"diffQueue",[]);E(this,"didDispose",!1);E(this,"shouldDoFullDBWrite",!0);E(this,"isReloading",!1);E(this,"persistenceKey");E(this,"sessionId");E(this,"serializedSchema");E(this,"isDebugging",!1);E(this,"documentTypes");E(this,"$sessionStateSnapshot");E(this,"db");E(this,"initTime",Date.now());E(this,"isPersisting",!1);E(this,"didLastWriteError",!1);E(this,"scheduledPersistTimeout",null);this.store=e,this.channel=i,typeof window<"u"&&(window.tlsync=this),this.persistenceKey=t,this.sessionId=r,this.db=new Wg(t),this.disposables.add(()=>this.db.close()),this.serializedSchema=this.store.schema.serialize(),this.$sessionStateSnapshot=Zv(this.store),this.disposables.add(e.listen(({changes:a})=>{this.diffQueue.push(a),this.channel.postMessage(YK({type:"diff",storeId:this.store.id,changes:a,schema:this.serializedSchema})),this.schedulePersist()},{source:"user",scope:"document"})),this.disposables.add(e.listen(()=>{this.diffQueue.push(JT),this.schedulePersist()},{scope:"session"})),this.connect(s,o),this.documentTypes=new Set(Object.values(this.store.schema.types).filter(a=>a.scope==="document").map(a=>a.typeName))}debug(...e){this.isDebugging&&console.debug(...e)}async connect(e,t){this.debug("connecting");let r;try{r=await this.db.load({sessionId:this.sessionId})}catch(s){t(s),WK();return}if(this.debug("loaded data from store",r,"didDispose",this.didDispose),!this.didDispose)try{if(r){const s=Object.fromEntries(r.records.map(l=>[l.id,l])),o=r.sessionStateSnapshot??m8(s),i=this.store.schema.migrateStoreSnapshot({store:s,schema:r.schema??this.store.schema.serializeEarliestVersion()});if(i.type==="error"){console.error("failed to migrate store",i),t(new Error(`Failed to migrate store: ${i.reason}`));return}const a=Object.values(i.value).filter(l=>this.documentTypes.has(l.typeName));a.length>0&&this.store.mergeRemoteChanges(()=>{this.store.put(a,"initialize")}),o&&Aw(this.store,o,{forceOverwrite:!0})}this.channel.onmessage=({data:s})=>{var a,l;this.debug("got message",s);const o=s,i=this.store.schema.getMigrationsSince(o.schema);if(i.ok){if(i.value.length>0){this.debug("telling them to reload"),this.channel.postMessage({type:"announce",schema:this.serializedSchema}),this.shouldDoFullDBWrite=!0,this.persistIfNeeded();return}}else{if(Date.now()-this.initTime<5e3){t(new Error("Schema mismatch, please close other tabs and reload the page"));return}this.debug("reloading"),this.isReloading=!0,(l=(a=window==null?void 0:window.location)==null?void 0:a.reload)==null||l.call(a);return}o.type==="diff"&&(this.debug("applying diff"),ms(()=>{this.store.mergeRemoteChanges(()=>{this.store.applyDiff(o.changes)})}))},this.channel.postMessage({type:"announce",schema:this.serializedSchema}),this.disposables.add(()=>{this.channel.close()}),e(this)}catch(s){if(this.debug("error loading data from store",s),this.didDispose)return;t(s);return}}close(){this.debug("closing"),this.didDispose=!0,this.disposables.forEach(e=>e())}schedulePersist(){this.debug("schedulePersist",this.scheduledPersistTimeout),!this.scheduledPersistTimeout&&(this.scheduledPersistTimeout=setTimeout(()=>{this.scheduledPersistTimeout=null,this.persistIfNeeded()},this.didLastWriteError?GK:VK))}persistIfNeeded(){this.debug("persistIfNeeded",{isPersisting:this.isPersisting,isReloading:this.isReloading,shouldDoFullDBWrite:this.shouldDoFullDBWrite,diffQueueLength:this.diffQueue.length,storeIsPossiblyCorrupt:this.store.isPossiblyCorrupted()}),this.scheduledPersistTimeout&&(clearTimeout(this.scheduledPersistTimeout),this.scheduledPersistTimeout=null),!this.isPersisting&&(this.isReloading||this.store.isPossiblyCorrupted()||(this.shouldDoFullDBWrite||this.diffQueue.length>0)&&this.doPersist())}async doPersist(){if(be(!this.isPersisting,"persist already in progress"),this.didDispose)return;this.isPersisting=!0,this.debug("doPersist start");const e=this.diffQueue;this.diffQueue=[];try{if(this.shouldDoFullDBWrite)this.shouldDoFullDBWrite=!1,await this.db.storeSnapshot({schema:this.store.schema,snapshot:this.store.serialize(),sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()});else{const t=Av(e.filter(r=>r!==JT));await this.db.storeChanges({changes:t,schema:this.store.schema,sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()})}this.didLastWriteError=!1}catch(t){this.shouldDoFullDBWrite=!0,this.didLastWriteError=!0,console.error("failed to store changes in indexed db",t),KK(),typeof window<"u"&&window.location.reload()}this.isPersisting=!1,this.debug("doPersist end"),this.schedulePersist()}}function uR(n){const e=x.useRef(n),[t,r]=x.useState(n);t!==e.current&&r(e.current);const s=x.useCallback(o=>{typeof o=="function"?e.current=o(e.current):e.current=o,r(e.current)},[]);return[t,s]}function JK(n){const[e,t]=uR({status:"loading"});return n=yd(n),x.useEffect(()=>{const{persistenceKey:r,sessionId:s,...o}=n;if(!r){t({status:"not-synced",store:Kg(o)});return}t({status:"loading"});const i=new Vn,a={upload:async(d,h)=>(await u.db.storeAsset(d.id,h),{src:d.id}),resolve:async d=>d.props.src?d.props.src.startsWith("asset:")?await i.get(d,async()=>{const h=await u.db.getAsset(d.id);return h?URL.createObjectURL(h):null}):d.props.src:null,remove:async d=>{await u.db.removeAssets(d)},...o.assets},l=Kg({...o,assets:a});let c=!1;const u=new ZK(l,{sessionId:s,persistenceKey:r,onLoad(){c||t({store:l,status:"synced-local"})},onLoadError(d){c||t({status:"error",error:d})}});return()=>{c=!0,u.close()}},[n,t]),e}function QK(){const n=K();x.useLayoutEffect(()=>Mr("stateAttribute",()=>{const e=n.getContainer(),t=n.getInstanceState();e.setAttribute("data-state",n.getPath()),e.setAttribute("data-coarse",String(t.isCoarsePointer))}),[n])}function eW(){const n=K(),e=sn();x.useEffect(()=>{const t=o=>e.style.setProperty("--tl-zoom",o.toString()),r=ry(t,100),s=new Wl("useZoomCss",()=>t(n.getEfficientZoomLevel()));return s.attach(),s.execute(),()=>{s.detach(),r.cancel()}},[n,e])}function zw(n){const e=new ArrayBuffer(n.length),t=new Uint8Array(e);for(let r=0,s=n.length;r<s;r++)t[r]=n.charCodeAt(r);return e}function tW(n){const e=atob(n),t=zw(e);return crypto.subtle.importKey("spki",new Uint8Array(t),{name:"ECDSA",namedCurve:"P-256"},!0,["verify"])}const nW=30,Do={ANNUAL_LICENSE:1,PERPETUAL_LICENSE:2,INTERNAL_LICENSE:4,WITH_WATERMARK:8,EVALUATION_LICENSE:16,NATIVE_LICENSE:32},rW=Math.max(...Object.values(Do)),du={ID:0,HOSTS:1,FLAGS:2,EXPIRY_DATE:3},sW=Object.keys(du).length,ic="sales@tldraw.com",oW=`${ln()}/watermarks/watermark-track.svg`;class Gh{constructor(e,t){E(this,"publicKey","MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHJh0uUfxHtCGyerXmmatE368Hd9rI6LH9oPDQihnaCryRFWEVeOvf9U/SPbyxX74LFyJs5tYeAHq5Nc0Ax25LQ");E(this,"isDevelopment");E(this,"isTest");E(this,"isCryptoAvailable");E(this,"state",We("license state","pending"));E(this,"verbose",!0);this.isTest=!1,this.isDevelopment=this.getIsDevelopment(),this.publicKey=t||this.publicKey,this.isCryptoAvailable=!!crypto.subtle,this.getLicenseFromKey(e).then(r=>{const s=iW(r,o=>this.outputMessages(o),this.isDevelopment);this.maybeTrack(r,s),this.state.set(s)}).catch(r=>{console.error("License validation failed:",r),this.state.set("unlicensed")})}getIsDevelopment(){return!["https:","vscode-webview:"].includes(window.location.protocol)||window.location.hostname==="localhost"||!1}getTrackType(e,t){return t==="unlicensed-production"?"unlicensed":this.isDevelopment||!e.isLicenseParseable?null:e.isEvaluationLicense?"evaluation":t==="licensed-with-watermark"?"with_watermark":null}maybeTrack(e,t){const r=this.getTrackType(e,t);if(!r)return;const s=new URL(oW);if(s.searchParams.set("version",Xv),s.searchParams.set("license_type",r),"license"in e){s.searchParams.set("license_id",e.license.id);const o=this.isFlagEnabled(e.license.flags,Do.EVALUATION_LICENSE)?"evaluation":this.isFlagEnabled(e.license.flags,Do.ANNUAL_LICENSE)?"annual":this.isFlagEnabled(e.license.flags,Do.PERPETUAL_LICENSE)?"perpetual":"unknown";s.searchParams.set("sku",o)}s.searchParams.set("url",window.location.href),s.searchParams.set("environment","production"),fetch(s.toString())}async extractLicenseKey(e){const[t,r]=e.split("."),[s,o]=t.split("/");if(!s.startsWith("tldraw-"))throw new Error(`Unsupported prefix '${s}'`);const i=await tW(this.publicKey);let a;try{a=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,new Uint8Array(zw(atob(r))),new Uint8Array(zw(atob(o))))}catch(c){throw console.error(c),new Error("Could not perform signature validation")}if(!a)throw new Error("Invalid signature");let l;try{l=JSON.parse(atob(o))}catch{throw new Error("Could not parse object")}return l.length>sW&&this.outputMessages(["License key contains some unknown properties.","You may want to update tldraw packages to a newer version to get access to new functionality."]),{id:l[du.ID],hosts:l[du.HOSTS],flags:l[du.FLAGS],expiryDate:l[du.EXPIRY_DATE]}}async getLicenseFromKey(e){if(!e)return this.isDevelopment||this.outputNoLicenseKeyProvided(),{isLicenseParseable:!1,reason:"no-key-provided"};if(this.isDevelopment&&!this.isCryptoAvailable)return this.verbose&&(console.log("tldraw: you seem to be in a development environment that does not support crypto. License not verified."),console.log("You should check that this works in production separately.")),{isLicenseParseable:!1,reason:"has-key-development-mode"};let t=e.replace(/[\u200B-\u200D\uFEFF]/g,"");t=t.replace(/\r?\n|\r/g,"");try{const r=await this.extractLicenseKey(t),s=new Date(r.expiryDate),o=this.isFlagEnabled(r.flags,Do.ANNUAL_LICENSE),i=this.isFlagEnabled(r.flags,Do.PERPETUAL_LICENSE),a=this.isFlagEnabled(r.flags,Do.EVALUATION_LICENSE),l=this.getDaysSinceExpiry(s),c={license:r,isLicenseParseable:!0,isDevelopment:this.isDevelopment,isDomainValid:this.isDomainValid(r),expiryDate:s,isAnnualLicense:o,isAnnualLicenseExpired:o&&this.isAnnualLicenseExpired(s),isPerpetualLicense:i,isPerpetualLicenseExpired:i&&this.isPerpetualLicenseExpired(s),isInternalLicense:this.isFlagEnabled(r.flags,Do.INTERNAL_LICENSE),isNativeLicense:this.isNativeLicense(r),isLicensedWithWatermark:this.isFlagEnabled(r.flags,Do.WITH_WATERMARK),isEvaluationLicense:a,isEvaluationLicenseExpired:a&&this.isEvaluationLicenseExpired(s),daysSinceExpiry:l};return this.outputLicenseInfoIfNeeded(c),c}catch(r){return this.outputInvalidLicenseKey(r.message),{isLicenseParseable:!1,reason:"invalid-license-key"}}}isDomainValid(e){const t=window.location.hostname.toLowerCase();return e.hosts.some(r=>{const s=r.toLowerCase().trim();if(s===t||`www.${s}`===t||s===`www.${t}`||r==="*")return!0;if(this.isNativeLicense(e))return new RegExp(s).test(window.location.href);if(r.includes("*")){const o=new RegExp(r.replace(/\*/g,".*?"));return o.test(t)||o.test(`www.${t}`)}if(window.location.protocol==="vscode-webview:"){const i=new URL(window.location.href).searchParams.get("extensionId");if(s===i)return!0}return!1})}isNativeLicense(e){return this.isFlagEnabled(e.flags,Do.NATIVE_LICENSE)}getExpirationDateWithoutGracePeriod(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}getExpirationDateWithGracePeriod(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+nW+1)}isAnnualLicenseExpired(e){const t=this.getExpirationDateWithGracePeriod(e);return new Date>=t}isPerpetualLicenseExpired(e){const t=this.getExpirationDateWithGracePeriod(e),r={major:new Date(wT.major),minor:new Date(wT.minor)};return r.major>=t||r.minor>=t}getDaysSinceExpiry(e){const t=new Date,r=this.getExpirationDateWithoutGracePeriod(e),s=t.getTime()-r.getTime(),o=Math.floor(s/(1e3*60*60*24));return Math.max(0,o)}isEvaluationLicenseExpired(e){const t=new Date,r=this.getExpirationDateWithoutGracePeriod(e);return t>=r}isFlagEnabled(e,t){return(e&t)===t}outputNoLicenseKeyProvided(){}outputInvalidLicenseKey(e){this.outputMessages(["Invalid tldraw license key",`Reason: ${e}`])}outputLicenseInfoIfNeeded(e){e.license.flags>=rW*2&&this.outputMessages(["Warning: This tldraw license contains some unknown flags.","This will still work, however, you may want to update tldraw packages to a newer version to get access to new functionality."],"warning")}outputMessages(e,t="error"){if(!this.isTest&&this.verbose){this.outputDelimiter(t);for(const r of e){const s=t==="warning"?"orange":"crimson";console.log(`%c${r}`,`color: white; background: ${s}; padding: 2px; border-radius: 3px;`)}this.outputDelimiter(t)}}outputDelimiter(e="error"){console.log("%c-------------------------------------------------------------------",`color: white; background: ${e==="warning"?"orange":"crimson"}; padding: 2px; border-radius: 3px;`)}}E(Gh,"className","tl-watermark_SEE-LICENSE");function iW(n,e,t){if(!n.isLicenseParseable)return t?"unlicensed":(n.reason==="no-key-provided"?e(["No tldraw license key provided!","A license is required for production deployments.",`Please reach out to ${ic} to purchase a license.`]):e(["Invalid license key. tldraw requires a valid license for production use.",`Please reach out to ${ic} to purchase a license.`]),"unlicensed-production");if(!n.isDomainValid&&!n.isDevelopment)return e(["License key is not valid for this domain.","A license is required for production deployments.",`Please reach out to ${ic} to purchase a license.`]),"unlicensed-production";if(n.isEvaluationLicense)return n.isEvaluationLicenseExpired?(e(["Your tldraw evaluation license has expired!",`Please reach out to ${ic} to purchase a full license.`]),"expired"):"licensed";if(n.isPerpetualLicenseExpired||n.isAnnualLicenseExpired)return e(["Your tldraw license has been expired for more than 30 days!",`Please reach out to ${ic} to renew your license.`]),"expired";const r=n.daysSinceExpiry;return r>0&&!n.isEvaluationLicense?(e(["Your tldraw license has expired.",`License expired ${r} days ago.`,`Please reach out to ${ic} to renew your license.`]),"licensed"):n.isLicensedWithWatermark?"licensed-with-watermark":"licensed"}var ac={};const hR=x.createContext({}),aW=()=>x.useContext(hR);function QT(n){return n==="expired"||n==="unlicensed-production"}const lW=5e3;function cW({licenseKey:n=uW()??void 0,children:e}){const[t]=x.useState(()=>new Gh(n)),r=W(t.state),[s,o]=x.useState(!0);return x.useEffect(()=>{if(QT(r)&&s){const i=setTimeout(()=>{o(!1)},lW);return()=>clearTimeout(i)}},[r,s]),QT(r)&&!s?p.jsx(dW,{}):p.jsx(hR.Provider,{value:t,children:e})}function dW(){return p.jsx("div",{"data-testid":"tl-license-expired",style:{display:"none"}})}let Xp;function uW(){return Xp!==void 0||(Xp=As(()=>ac.TLDRAW_LICENSE_KEY)||As(()=>ac.NEXT_PUBLIC_TLDRAW_LICENSE_KEY)||As(()=>ac.REACT_APP_TLDRAW_LICENSE_KEY)||As(()=>ac.GATSBY_TLDRAW_LICENSE_KEY)||As(()=>ac.VITE_TLDRAW_LICENSE_KEY)||As(()=>ac.PUBLIC_TLDRAW_LICENSE_KEY)||As(()=>{})||As(()=>{})||As(()=>{})||As(()=>{})||As(()=>{})||As(()=>{})||null),Xp}function As(n){try{return n()}catch{return}}function Jo(n){if(!n)throw Error("usePassThroughWheelEvents must be passed a ref");const e=sn(),t=Xt();x.useEffect(()=>{function r(o){if(!(t!=null&&t.getInstanceState().isFocused)||o.isSpecialRedispatchedEvent)return;const i=n.current;if(i&&i.scrollHeight>i.clientHeight)return;je(o);const a=e.querySelector(".tl-canvas");if(!a)return;const l=new WheelEvent("wheel",o);l.isSpecialRedispatchedEvent=!0,a.dispatchEvent(l)}const s=n.current;if(s)return s.addEventListener("wheel",r,{passive:!1}),()=>{s.removeEventListener("wheel",r)}},[e,t,n])}const hW='<svg xmlns="http://www.w3.org/2000/svg" width="3001" height="1000" fill="none"><path fill="#000" d="M590.656 300.449c0 49.706-40.294 90-90 90-49.705 0-90-40.294-90-90 0-49.705 40.295-90 90-90 49.706 0 90 40.295 90 90M569.431 719.011c-15.247 32.821-56.006 91.589-98.338 91.438-32.004-.115-38.642-30.904-17.414-50.856 17.381-16.337 28.246-48.075 31.995-72.719.415-2.728-1.556-5.197-4.272-5.679-39.666-7.04-70.746-40.877-70.746-83.417 0-48.23 38.983-87.329 87.07-87.329 39.936 0 70.172 22.237 83.369 52.397 18.839 43.055 7.117 115.733-11.664 156.165M2613.29 385.681V239.319c0-11.363 9.22-20.569 20.59-20.569h8.26c11.37 0 20.59 9.206 20.59 20.569v36.911c0 8.629 7 15.625 15.63 15.625h35.25c8.63 0 15.63-6.996 15.63-15.625v-36.911c0-11.363 9.22-20.569 20.59-20.569h8.17c11.37 0 20.59 9.206 20.59 20.569v146.362c0 11.363-9.22 20.569-20.59 20.569h-8.17c-11.37 0-20.59-9.206-20.59-20.569v-36.999c0-8.63-7-15.625-15.63-15.625h-35.25c-8.63 0-15.63 6.995-15.63 15.625v36.999c0 11.363-9.22 20.569-20.59 20.569h-8.26c-11.37 0-20.59-9.206-20.59-20.569M2391.97 239.319v146.362c0 11.348-9.16 20.569-20.49 20.569h-8.2c-11.33 0-20.49-9.221-20.49-20.569V239.319c0-11.348 9.16-20.569 20.49-20.569h8.2c11.33 0 20.49 9.221 20.49 20.569M2098.23 391.43l-42.69-146.361c-3.85-13.171 6.06-26.319 19.79-26.319h10.6c9.59 0 17.93 6.611 20.08 15.952l17.01 73.045c1.48 6.348 10.47 6.478 12.14.176l19.47-73.838c2.38-9.04 10.57-15.335 19.93-15.335h12.1c9.37 0 17.56 6.3 19.94 15.346l19.49 74.067c1.66 6.305 10.65 6.178 12.13-.171l17.09-73.294c2.15-9.339 10.49-15.948 20.08-15.948h10.53c13.72 0 23.63 13.141 19.79 26.31l-42.63 146.361c-2.56 8.789-10.63 14.829-19.79 14.829h-15.68c-9.12 0-17.16-5.98-19.76-14.709l-21.17-71.059c-1.77-5.948-10.19-5.957-11.97-.012l-21.33 71.071c-2.6 8.729-10.64 14.709-19.76 14.709h-15.59c-9.17 0-17.23-6.035-19.8-14.82M2443.23 218.75h118.59c11.38 0 20.62 9.195 20.62 20.557s-9.24 20.556-20.62 20.556h-24.79c-5.53 0-10 4.477-10 10v115.818c0 11.368-9.25 20.569-20.63 20.569h-7.65c-11.39 0-20.63-9.201-20.63-20.569V269.863c0-5.523-4.48-10-10-10h-24.89c-11.37 0-20.61-9.195-20.61-20.556s9.24-20.557 20.61-20.557M1174.15 218.75h24.64c8.35 0 15.88 5.042 19.04 12.764l34.61 83.942c2.13 5.161 9.44 5.155 11.56-.01l34.43-83.932a20.58 20.58 0 0 1 19.04-12.764h24.64c11.37 0 20.58 9.208 20.58 20.569v146.362c0 11.361-9.21 20.569-20.58 20.569h-7.09c-11.36 0-20.58-9.208-20.58-20.569l-.12-50.645c-.01-6.888-9.53-8.688-12.06-2.283l-23.46 59.332a20.57 20.57 0 0 1-19.14 13.009h-3.03a20.57 20.57 0 0 1-19.15-13.046l-23.47-59.68c-2.52-6.416-12.05-4.623-12.06 2.271l-.13 51.042c0 11.361-9.21 20.569-20.57 20.569h-7.1c-11.36 0-20.57-9.208-20.57-20.569V239.319c0-11.361 9.21-20.569 20.57-20.569"/><path fill="#000" fill-rule="evenodd" d="m1449.94 391.836 6.12-19.392a6.255 6.255 0 0 1 5.96-4.369l50.22-.061a6.24 6.24 0 0 1 5.96 4.348l6.23 19.486c2.71 8.581 10.71 14.402 19.74 14.402h9.34c14.13 0 24.15-13.791 19.61-27.151l-49.74-146.361c-2.85-8.37-10.74-13.988-19.61-13.988h-33.16c-8.87 0-16.77 5.618-19.61 13.988l-49.74 146.361c-4.54 13.36 5.48 27.151 19.61 27.151h9.32c9.04 0 17.04-5.827 19.75-14.414m31.1-98.858c1.85-5.807 10.08-5.796 11.91.016l8.83 27.916c1.28 4.028-1.73 8.134-5.96 8.134h-17.74c-4.23 0-7.24-4.119-5.95-8.151zM1681.81 406.25c18.91 0 35.39-3.686 49.36-11.168 13.97-7.544 24.73-18.394 32.24-32.489 7.56-14.105 11.29-30.866 11.29-50.182 0-19.256-3.73-35.957-11.29-50.004-7.57-14.094-18.35-24.912-32.32-32.397-13.91-7.545-30.4-11.26-49.37-11.26h-49.5c-11.38 0-20.63 9.201-20.63 20.569v146.362c0 11.368 9.25 20.569 20.63 20.569zm23.13-47.701c-6.62 3.215-14.85 4.886-24.79 4.886-10.49 0-19-8.507-19-19v-64.34c0-10.149 8.23-18.376 18.38-18.376 10.18 0 18.56 1.703 25.23 4.974 6.59 3.149 11.63 8.315 15.08 15.633 3.45 7.269 5.28 17.268 5.28 30.162 0 12.891-1.82 22.951-5.28 30.347-3.39 7.319-8.36 12.509-14.9 15.714" clip-rule="evenodd"/><path fill="#000" d="M1804.21 385.681V239.319c0-11.361 9.21-20.569 20.58-20.569h91.28c11.36 0 20.57 9.202 20.57 20.557s-9.21 20.556-20.57 20.556h-54.64a7.807 7.807 0 0 0-7.81 7.813v16.366a7.806 7.806 0 0 0 7.81 7.812h48.13c11.37 0 20.58 9.246 20.58 20.602s-9.21 20.601-20.58 20.601h-48.13a7.806 7.806 0 0 0-7.81 7.812v16.455a7.807 7.807 0 0 0 7.81 7.813h54.64c11.36 0 20.57 9.202 20.57 20.556s-9.21 20.557-20.57 20.557h-91.28c-11.37 0-20.58-9.208-20.58-20.569"/><path fill="#000" fill-rule="evenodd" d="M2875.5 68.75h-2750c-31.066 0-56.25 25.184-56.25 56.25v750c0 31.066 25.184 56.25 56.25 56.25h2750c31.07 0 56.25-25.184 56.25-56.25V125c0-31.066-25.18-56.25-56.25-56.25M125.5 0C56.464 0 .5 55.964.5 125v750c0 69.036 55.965 125 125 125h2750c69.04 0 125-55.964 125-125V125c0-69.036-55.96-125-125-125z" clip-rule="evenodd"/><path fill="#000" d="M2476.06 804.813c-10.54 0-19.82-6.947-22.81-17.068L2390.79 575.7c-4.49-15.248 6.92-30.534 22.8-30.534h27.75c11.1 0 20.72 7.686 23.18 18.52L2489 671.402c2.07 9.093 14.93 9.321 17.32.308l28.83-108.844c2.76-10.435 12.19-17.7 22.98-17.7h25.17c10.8 0 20.25 7.293 22.99 17.755l28.27 107.739c2.36 9.001 15.18 8.829 17.3-.232l25.01-106.888c2.51-10.763 12.1-18.374 23.14-18.374h27.87c15.88 0 27.29 15.286 22.8 30.534l-62.46 212.045a23.78 23.78 0 0 1-22.81 17.068h-32.12c-10.39 0-19.58-6.763-22.69-16.696l-32.08-102.694c-2.62-8.397-14.51-8.331-17.04.095l-30.74 102.346c-3.02 10.061-12.27 16.949-22.76 16.949zM1742.44 804.813h-75.81c-13.09 0-23.71-10.656-23.71-23.801V568.967c0-13.145 10.62-23.801 23.71-23.801h74.8c26.6 0 49.59 5.198 68.95 15.594 19.45 10.312 34.44 25.187 44.96 44.627 10.61 19.355 15.91 42.556 15.91 69.602q0 40.57-15.78 69.73c-10.53 19.355-25.43 34.231-44.71 44.627-19.28 10.311-42.05 15.467-68.32 15.467m-29.3-83.642c0 13.145 10.61 23.801 23.71 23.801h3.06c12.8 0 23.7-2.07 32.71-6.212 9.09-4.141 16-11.283 20.71-21.426q7.2-15.213 7.2-42.345 0-27.13-7.32-42.344c-4.8-10.143-11.87-17.285-21.22-21.426-9.26-4.142-20.63-6.212-34.1-6.212h-1.04c-13.1 0-23.71 10.656-23.71 23.801zM1460.86 804.813c-13.12 0-23.76-10.656-23.76-23.801V568.967c0-13.145 10.64-23.801 23.76-23.801h22.84c13.13 0 23.76 10.656 23.76 23.801v155.247c0 13.145 10.64 23.801 23.76 23.801h57.27c13.12 0 23.76 10.656 23.76 23.801v9.196c0 13.145-10.64 23.801-23.76 23.801zM1204.45 601.964c-13.13 0-23.77-10.656-23.77-23.801v-9.196c0-13.145 10.64-23.801 23.77-23.801h177.89c13.13 0 23.78 10.656 23.78 23.801v9.196c0 13.145-10.65 23.801-23.78 23.801h-39.38c-8.21 0-14.86 6.66-14.86 14.875v164.173c0 13.145-10.64 23.801-23.78 23.801h-21.85c-13.13 0-23.78-10.656-23.78-23.801V616.839c0-8.215-6.65-14.875-14.86-14.875z"/><path fill="#000" fill-rule="evenodd" d="M2223.05 787.891c-3.02 10.047-12.27 16.922-22.74 16.922h-25.43c-16.19 0-27.64-15.862-22.57-31.261l69.88-212.045c3.21-9.753 12.31-16.341 22.56-16.341h61.84c10.25 0 19.35 6.588 22.56 16.341l69.87 212.045c5.08 15.399-6.37 31.261-22.56 31.261h-25.43c-10.48 0-19.72-6.875-22.74-16.922l-6.7-22.2a14.84 14.84 0 0 0-14.21-10.576h-63.42c-6.55 0-12.32 4.296-14.22 10.576zm76.13-96.945-14.13-48.436c-2.46-8.451-14.36-8.602-17.04-.217l-15.46 48.436c-1.84 5.759 2.45 11.645 8.48 11.645h29.6c5.94 0 10.22-5.715 8.55-11.428" clip-rule="evenodd"/><path fill="#000" d="M1939.6 804.813c-13.13 0-23.77-10.656-23.77-23.801V568.967c0-13.145 10.64-23.801 23.77-23.801h88.13c19.24 0 36.08 3.508 50.51 10.523s25.65 17.115 33.67 30.3q12.03 19.779 12.03 47.416c0 18.595-4.14 34.273-12.41 47.036-7.64 11.913-18.18 21.101-31.63 27.564-16.98 8.159-36 11.104-54.7 11.104h-43.07c-76.56 0 4.08-135.84 4.08-84.706v7.996c0 12.117 9.81 21.941 21.91 21.941 8.12 0 16.3-.345 24.04-3.043 5.91-2.113 10.43-5.451 13.55-10.015 3.2-4.565 4.81-10.523 4.81-17.877 0-7.437-1.61-13.481-4.81-18.129-3.12-4.733-7.64-8.199-13.55-10.396-7.05-2.766-14.67-3.423-22.18-3.423-13.13 0-23.77 10.656-23.77 23.801v47.71c0 11.825 11.14 16.003 19.91 20.752 12.31 6.671 7.58 25.389-6.42 25.389-7.45 0-13.49 6.048-13.49 13.508v48.395c0 13.145-10.63 23.801-23.76 23.801zm134.89-106.758 5.41 9.95 33.51 61.622c8.62 15.86-2.84 35.186-20.87 35.186h-22.27c-8.74 0-16.77-4.798-20.92-12.496l-35.05-65.04a15.52 15.52 0 0 0-13.66-8.168c-42.24 0 40.62-82.154 73.85-21.054M931.652 0h68.748v1000h-68.748z"/></svg>',pW='<svg xmlns="http://www.w3.org/2000/svg" width="400" height="1601" fill="none"><path fill="#000" d="M72 1319.8c0-10.73 7.071-20.18 17.372-23.22l215.823-63.62c15.519-4.57 31.078 7.05 31.078 23.22v28.26c0 11.31-7.824 21.1-18.85 23.61l-109.636 24.94c-9.254 2.1-9.487 15.2-.313 17.63l110.784 29.37a24.21 24.21 0 0 1 18.015 23.4v25.64c0 11-7.423 20.62-18.071 23.41l-109.659 28.79c-9.162 2.41-8.986 15.47.236 17.63l108.792 25.46c10.955 2.56 18.702 12.33 18.702 23.57v28.39c0 16.17-15.559 27.79-31.078 23.22l-215.823-63.62c-10.3-3.04-17.372-12.49-17.372-23.22v-32.72c0-10.59 6.883-19.95 16.994-23.11l104.523-32.67c8.547-2.67 8.479-14.79-.096-17.36l-104.17-31.3C79.01 1372.42 72 1363 72 1352.31zM72 572.638V495.43c0-13.336 10.846-24.147 24.225-24.147h215.823c13.379 0 24.225 10.811 24.225 24.147v76.179q0 40.645-15.872 70.228-15.743 29.712-45.422 45.79-29.55 16.206-70.843 16.206-41.292 0-70.971-16.078-29.55-16.077-45.422-45.532Q72 612.767 72 572.638m85.132-29.84c-13.379 0-24.225 10.81-24.225 24.146v3.122q0 19.55 6.323 33.313 6.323 13.89 21.807 21.094 15.485 7.332 43.099 7.331t43.1-7.46q15.484-7.33 21.807-21.608 6.323-14.15 6.323-34.728v-1.064c0-13.336-10.846-24.146-24.225-24.146zM72 285.858c0-13.363 10.846-24.197 24.225-24.197h215.823c13.379 0 24.225 10.834 24.225 24.197v23.27c0 13.364-10.846 24.197-24.225 24.197H154.035c-13.379 0-24.225 10.834-24.225 24.197v58.328c0 13.364-10.846 24.197-24.225 24.197h-9.36C82.845 440.047 72 429.214 72 415.85zM278.463 24.72c0-13.374 10.846-24.216 24.225-24.216h9.36c13.379 0 24.225 10.842 24.225 24.216v181.174c0 13.374-10.846 24.216-24.225 24.216h-9.36c-13.379 0-24.225-10.842-24.225-24.216v-40.108c0-8.359-6.779-15.135-15.141-15.135H96.225c-13.38 0-24.225-10.842-24.225-24.216v-22.256c0-13.374 10.846-24.216 24.225-24.216h167.097c8.362 0 15.141-6.776 15.141-15.135z"/><path fill="#000" fill-rule="evenodd" d="M89.224 1062.13C78.997 1059.04 72 1049.63 72 1038.96v-25.9c0-16.486 16.145-28.147 31.818-22.979l215.823 71.169a24.19 24.19 0 0 1 16.632 22.98v62.97c0 10.45-6.706 19.71-16.632 22.98l-215.823 71.17C88.145 1246.51 72 1234.86 72 1218.37v-25.9c0-10.67 6.997-20.08 17.224-23.17l22.595-6.81a15.13 15.13 0 0 0 10.765-14.48v-64.59a15.13 15.13 0 0 0-10.765-14.48zm98.672 77.53 49.299-14.39c8.601-2.51 8.755-14.62.22-17.35l-49.299-15.75c-5.861-1.88-11.852 2.49-11.852 8.64v30.14c0 6.05 5.817 10.41 11.632 8.71" clip-rule="evenodd"/><path fill="#000" d="M72 773.439c0-13.367 10.846-24.203 24.225-24.203h215.823c13.379 0 24.225 10.836 24.225 24.203v89.762q0 29.395-10.711 51.439-10.71 22.046-30.84 34.293t-48.261 12.248q-28.388 0-47.873-12.635-18.187-11.672-28.056-32.218c-8.303-17.289-11.301-36.661-11.301-55.705v-43.867c0-77.976 138.26 4.16 86.215 4.16h-8.138c-12.334 0-22.332 9.989-22.332 22.311 0 8.269.351 16.6 3.097 24.487q3.225 9.024 10.194 13.794 6.968 4.899 18.194 4.899 11.356 0 18.453-4.899 7.226-4.77 10.581-13.794c2.815-7.188 3.484-14.944 3.484-22.596 0-13.366-10.846-24.202-24.225-24.202h-48.56c-12.036 0-16.288 11.345-21.122 20.272-6.79 12.539-25.841 7.72-25.841-6.536 0-7.586-6.156-13.736-13.749-13.736H96.225C82.845 820.916 72 810.08 72 796.714zm108.66 137.378-10.128 5.511-62.72 34.131C91.67 959.243 72 947.569 72 929.205V906.52a24.2 24.2 0 0 1 12.719-21.299l66.199-35.696a15.82 15.82 0 0 0 8.313-13.921c0-43.012 83.618 41.371 21.429 75.213"/></svg>';function fW(n){return W("watermarkState",()=>n.state.get(),[n])}const gW=`data:image/svg+xml;utf8,${encodeURIComponent(hW)}`,mW=`data:image/svg+xml;utf8,${encodeURIComponent(pW)}`,yW=x.memo(function(){const e=aW(),t=K(),r=W("is mobile",()=>t.getViewportScreenBounds().width<700,[t]),s=fW(e);return["licensed-with-watermark","unlicensed"].includes(s)?p.jsxs(p.Fragment,{children:[p.jsx(bW,{}),p.jsx(xW,{src:r?mW:gW,isUnlicensed:s==="unlicensed"})]}):null}),SW=x.memo(function({isDebugMode:e,isMobile:t}){const r=K(),s=fy(),o=x.useRef(null);Jo(o);const i="https://tldraw.dev/pricing?utm_source=sdk&utm_medium=organic&utm_campaign=watermark";return p.jsx("div",{ref:o,className:Gh.className,"data-debug":e,"data-mobile":t,"data-unlicensed":!0,"data-testid":"tl-watermark-unlicensed",draggable:!1,...s,children:p.jsx("button",{draggable:!1,role:"button",onPointerDown:a=>{r.markEventAsHandled(a),je(a)},title:"The tldraw SDK requires a license key to work in production. You can get a free 100-day trial license at tldraw.dev/pricing.",onClick:()=>{Bh.openWindow(i,"_blank",!0)},children:"Get a license for production"})})}),xW=x.memo(function({src:e,isUnlicensed:t}){const r=K(),s=W("debug mode",()=>r.getInstanceState().isDebugMode,[r]),o=W("is mobile",()=>r.getViewportScreenBounds().width<700,[r]),i=fy(),a=x.useRef(null);Jo(a);const l=`url('${e}') center 100% / 100% no-repeat`,c="https://tldraw.dev/?utm_source=sdk&utm_medium=organic&utm_campaign=watermark";return t?p.jsx(SW,{isDebugMode:s,isMobile:o}):p.jsx("div",{ref:a,className:Gh.className,"data-debug":s,"data-mobile":o,"data-testid":"tl-watermark-licensed",draggable:!1,...i,children:p.jsx("button",{draggable:!1,role:"button",onPointerDown:u=>{r.markEventAsHandled(u),je(u)},title:"Build infinite canvas applications with the tldraw SDK. Learn more at https://tldraw.dev.",onClick:()=>{Bh.openWindow(c,"_blank")},style:{mask:l,WebkitMask:l}})})}),bW=x.memo(function(){const e=K(),t=Gh.className,r=`
83
+ /* ------------------- SEE LICENSE -------------------
84
+ The tldraw watermark is part of tldraw's license. It is shown for unlicensed
85
+ or "licensed-with-watermark" users. By using this library, you agree to
86
+ preserve the watermark's behavior, keeping it visible, unobscured, and
87
+ available to user-interaction.
88
+
89
+ To remove the watermark, please purchase a license at tldraw.dev.
90
+ */
91
+
92
+ .${t} {
93
+ position: absolute;
94
+ bottom: max(var(--tl-space-2), env(safe-area-inset-bottom));
95
+ right: max(var(--tl-space-2), env(safe-area-inset-right));
96
+ width: 96px;
97
+ height: 32px;
98
+ display: flex;
99
+ align-items: center;
100
+ justify-content: center;
101
+ z-index: var(--tl-layer-watermark) !important;
102
+ background-color: color-mix(in srgb, var(--tl-color-background) 62%, transparent);
103
+ opacity: 1;
104
+ border-radius: 5px;
105
+ pointer-events: all;
106
+ padding: 2px;
107
+ box-sizing: content-box;
108
+ }
109
+
110
+ .${t} > button {
111
+ position: absolute;
112
+ width: 96px;
113
+ height: 32px;
114
+ pointer-events: all;
115
+ cursor: inherit;
116
+ color: var(--tl-color-text);
117
+ opacity: .38;
118
+ border: 0;
119
+ padding: 0;
120
+ background-color: currentColor;
121
+ }
122
+
123
+ .${t}[data-debug='true'] {
124
+ bottom: max(46px, env(safe-area-inset-bottom));
125
+ }
126
+
127
+ .${t}[data-mobile='true'] {
128
+ border-radius: 4px 0px 0px 4px;
129
+ right: max(-2px, calc(env(safe-area-inset-right) - 2px));
130
+ width: 8px;
131
+ height: 48px;
132
+ }
133
+
134
+ .${t}[data-mobile='true'] > button {
135
+ width: 8px;
136
+ height: 32px;
137
+ }
138
+
139
+ .${t}[data-unlicensed='true'] > button {
140
+ font-size: 100px;
141
+ position: absolute;
142
+ pointer-events: all;
143
+ cursor: pointer;
144
+ color: var(--tl-color-text);
145
+ opacity: 0.8;
146
+ border: 0;
147
+ padding: 0;
148
+ background-color: transparent;
149
+ font-size: 11px;
150
+ font-weight: 600;
151
+ text-align: center;
152
+ }
153
+
154
+ .${t}[data-mobile='true'][data-unlicensed='true'] > button {
155
+ display: none;
156
+ }
157
+
158
+ @media (hover: hover) {
159
+ .${t} > button {
160
+ pointer-events: none;
161
+ }
162
+
163
+ .${t}:hover {
164
+ background-color: var(--tl-color-background);
165
+ transition: background-color 0.2s ease-in-out;
166
+ transition-delay: 0.32s;
167
+ }
168
+
169
+ .${t}:hover > button {
170
+ animation: ${t}_delayed_link 0.2s forwards ease-in-out;
171
+ animation-delay: 0.32s;
172
+ }
173
+
174
+ .${t} > button:focus-visible {
175
+ opacity: 1;
176
+ }
177
+ }
178
+
179
+ @keyframes ${t}_delayed_link {
180
+ 0% {
181
+ cursor: inherit;
182
+ opacity: .38;
183
+ pointer-events: none;
184
+ }
185
+ 100% {
186
+ cursor: pointer;
187
+ opacity: 1;
188
+ pointer-events: all;
189
+ }
190
+ }`;return p.jsx("style",{nonce:e.options.nonce,children:r})}),wW=[],vW=[],CW=[],PW="tl-container",TW=x.memo(function({store:e,components:t,className:r,user:s,options:o,textOptions:i,deepLinks:a,...l}){const[c,u]=x.useState(null),d=x.useMemo(()=>s??RA(),[s]),h=(t==null?void 0:t.ErrorFallback)===void 0?PA:t==null?void 0:t.ErrorFallback,f=x.useMemo(()=>{let m=o;return i&&(m={...m,text:(m==null?void 0:m.text)??i}),a!==void 0&&(m={...m,deepLinks:(m==null?void 0:m.deepLinks)??a}),m},[o,i,a]),g={...l,shapeUtils:l.shapeUtils??wW,bindingUtils:l.bindingUtils??vW,tools:l.tools??CW,components:t,options:yd(f)};return p.jsx("div",{ref:u,"data-tldraw":Xv,draggable:!1,className:xe(`${PW} tl-theme__light`,r),tabIndex:-1,role:"application","aria-label":(o==null?void 0:o.branding)??"tldraw",children:p.jsx(ih,{fallback:h,onError:m=>pv(m,{tags:{origin:"react.tldraw-before-app"}}),children:c&&p.jsx(cW,{licenseKey:l.licenseKey,children:p.jsx(vA,{container:c,children:p.jsx(zW,{overrides:t,children:e?e instanceof Dv?p.jsx(fR,{...g,store:e,user:d}):p.jsx(pR,{...g,store:e,user:d}):p.jsx(IW,{...g,store:e,user:d})})})})})})});function IW(n){const{defaultName:e,snapshot:t,initialData:r,shapeUtils:s,bindingUtils:o,persistenceKey:i,sessionId:a,user:l,assets:c,migrations:u}=n,d=JK({shapeUtils:s,bindingUtils:o,initialData:r,persistenceKey:i,sessionId:a,defaultName:e,snapshot:t,assets:c,migrations:u});return p.jsx(pR,{...n,store:d,user:l})}const pR=x.memo(function({store:e,user:t,...r}){const s=sn();x.useLayoutEffect(()=>{t.userPreferences.get().colorScheme==="dark"&&(s.classList.remove("tl-theme__light"),s.classList.add("tl-theme__dark"))},[s,t]);const{LoadingScreen:o}=xt();switch(e.status){case"error":throw e.error;case"loading":return o?p.jsx(o,{}):null}return p.jsx(fR,{...r,store:e.store,user:t})}),Gx=()=>document.location.search.includes("tldraw_preserve_focus");function fR({onMount:n,children:e,store:t,tools:r,shapeUtils:s,bindingUtils:o,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:u,options:d,licenseKey:h,getShapeVisibility:f,assetUrls:g}){const{ErrorFallback:m}=xt(),y=sn(),[S,b]=uR(null),w=x.useRef(null),v=d==null?void 0:d.deepLinks,P=yd(v===!0?{}:v),T=x.useRef({autoFocus:l&&!Gx(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P});x.useLayoutEffect(()=>{T.current={autoFocus:l&&!Gx(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P}},[l,c,a,u,P]),x.useLayoutEffect(()=>{const{autoFocus:_,inferDarkMode:M,initialState:O,cameraOptions:N,deepLinks:B}=T.current,H=new he({store:t,shapeUtils:s,bindingUtils:o,tools:r,getContainer:()=>y,user:i,initialState:O,autoFocus:_,inferDarkMode:M,cameraOptions:N,options:d,licenseKey:h,getShapeVisibility:f,fontAssetUrls:g==null?void 0:g.fonts});return H.updateViewportScreenBounds(w.current??y),B&&(B!=null&&B.getUrl?H.navigateToDeepLink({...B,url:B.getUrl(H)}):H.navigateToDeepLink(B)),b(H),()=>{H.dispose()}},[o,y,d,s,t,r,i,b,h,f,g]),x.useLayoutEffect(()=>{if(S&&P)return S.registerDeepLinkListener(P)},[S,P]),x.useLayoutEffect(()=>{S&&(u||d!=null&&d.camera)&&S.setCameraOptions({...u,...d==null?void 0:d.camera})},[S,u,d==null?void 0:d.camera]);const I=x.useSyncExternalStore(x.useCallback(_=>S?(S.on("crash",_),()=>S.off("crash",_)):()=>{},[S]),()=>(S==null?void 0:S.getCrashingError())??null);x.useEffect(function(){if(!S)return;function M(){S&&S.focus()}function O(){S&&S.blur()}if(l&&Gx())return S.getContainer().addEventListener("pointerdown",M),document.body.addEventListener("pointerdown",O),()=>{var N;(N=S.getContainer())==null||N.removeEventListener("pointerdown",M),document.body.removeEventListener("pointerdown",O)}},[S,l]);const[k,A]=x.useState(null);let R=k;S!==(R==null?void 0:R.editor)&&(R=null),x.useLayoutEffect(()=>{if(!S)return;if(S.options.maxFontsToLoadBeforeRender===0){A({editor:S,isLoaded:!0});return}let _=!1;return A({editor:S,isLoaded:!1}),S.fonts.loadRequiredFontsForCurrentPage(S.options.maxFontsToLoadBeforeRender).finally(()=>{_||A({editor:S,isLoaded:!0})}),()=>{_=!0}},[S]);const{Canvas:D,LoadingScreen:j}=xt();return!S||!(R!=null&&R.isLoaded)?p.jsxs(p.Fragment,{children:[j&&p.jsx(j,{}),p.jsx("div",{className:"tl-canvas",ref:w})]}):p.jsx(ih,{fallback:m,onError:_=>S.annotateError(_,{origin:"react.tldraw",willCrashApp:!0}),children:I?p.jsx(kW,{crashingError:I}):p.jsx(Gv,{editor:S,children:p.jsxs(EW,{onMount:n,children:[e??(D?p.jsx(D,{},S.contextId):null),p.jsx(yW,{})]})})})}function EW({children:n,onMount:e}){return eW(),PK(),TK(),IK(),QK(),mR(t=>{const r=t.store.props.onMount(t),s=e==null?void 0:e(t);return()=>{r==null||r(),s==null||s()}}),n}function kW({crashingError:n}){throw n}function gR({children:n}){return p.jsx("div",{className:"tl-loading","aria-busy":"true",tabIndex:0,children:n})}function mR(n){const e=K(),t=No(r=>{let s;return r.run(()=>{s=n==null?void 0:n(r),r.emit("mount")},{history:"ignore"}),window.tldrawReady=!0,s});_e.useLayoutEffect(()=>{if(e)return t==null?void 0:t(e)},[e,t])}const _W=()=>{const{Spinner:n}=xt();return p.jsx(gR,{children:n?p.jsx(n,{}):null})};function yR(n,e=!0){const t=n.length;if(t<2)return"";let r=n[0],s=n[1];if(t===2)return`M${jn(r)}L${jn(s)}`;let o="";for(let i=2,a=t-1;i<a;i++)r=n[i],s=n[i+1],o+=Vr(r,s);return e?`M${Vr(n[0],n[1])}Q${jn(n[1])}${Vr(n[1],n[2])}T${o}${Vr(n[t-1],n[0])}${Vr(n[0],n[1])}Z`:`M${jn(n[0])}Q${jn(n[1])}${Vr(n[1],n[2])}${n.length>3?"T":""}${o}L${jn(n[t-1])}`}function eI({scribble:n,zoom:e,color:t,opacity:r,className:s}){return n.points.length?p.jsx("svg",{className:s&&xe("tl-overlays__item",s),children:p.jsx("path",{className:"tl-scribble",d:yR(n.points,!1),stroke:t??`var(--tl-color-${n.color})`,fill:"none",strokeWidth:8/e,opacity:r??n.opacity})}):null}function MW({bounds:n,rotation:e}){const t=K(),r=x.useRef(null),s=W("only selected shape",()=>t.getOnlySelectedShape(),[t]),o=s?t.getShapeUtil(s).expandSelectionOutlinePx(s):0;return jh(r,n==null?void 0:n.x,n==null?void 0:n.y,1,e,{x:-o,y:-o}),n=o instanceof J?n.clone().expand(o).zeroFix():n.clone().expandBy(o).zeroFix(),p.jsx("svg",{ref:r,className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:p.jsx("rect",{className:xe("tl-selection__fg__outline"),width:$(n.width),height:$(n.height)})})}const AW=()=>p.jsx("div",{className:"tl-shape-error-boundary"}),DW=x.memo(({shape:n,util:e})=>oy("Indicator: "+n.type,()=>e.indicator(e.editor.store.unsafeGetWithoutCapture(n.id))),(n,e)=>n.shape.props===e.shape.props&&n.shape.meta===e.shape.meta),OW=x.memo(({editor:n,id:e})=>{const t=W("shape for indicator",()=>n.store.get(e),[n,e]),{ShapeIndicatorErrorFallback:r}=xt();if(!t||t.isLocked)return null;const s=n.getShapeUtil(t);return s.useLegacyIndicator()?p.jsx(ih,{fallback:r,onError:o=>n.annotateError(o,{origin:"react.shapeIndicator",willCrashApp:!1}),children:p.jsx(DW,{shape:t,util:s},t.id)}):null}),tI=x.memo(function({shapeId:e,className:t,color:r,hidden:s,opacity:o}){const i=K(),a=x.useRef(null);return Va("indicator transform",()=>{if(s)return;const l=a.current;if(!l)return;const c=i.getShapePageTransform(e);c&&l.style.setProperty("transform",c.toCssString())},[i,e,s]),x.useLayoutEffect(()=>{const l=a.current;l&&l.style.setProperty("display",s?"none":"block")},[s]),p.jsx("svg",{ref:a,className:xe("tl-overlays__item",t),"aria-hidden":"true",children:p.jsx("g",{className:"tl-shape-indicator",stroke:r??"var(--tl-color-selected)",opacity:o,children:p.jsx(OW,{editor:i,id:e})})})}),RW=()=>p.jsx("circle",{cx:4,cy:4,r:8,strokeWidth:"1",stroke:"red"}),SR=x.memo(function({hideAll:e,showAll:t}){const r=K();if(e&&t)throw Error("You cannot set both hideAll and showAll props to true, cmon now");const s=x.useRef(new Set),o=W("should display selected ids",()=>{const c=s.current,u=new Set,d=r.getInstanceState(),h=d.isChangingStyle,f=r.isInAny("select.idle","select.editing_shape"),g=r.isInAny("select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","select.pointing_handle");if(h||!(f||g))return s.current=u,u;for(const m of r.getSelectedShapeIds())u.add(m);if(f&&d.isHoveringCanvas&&!d.isCoarsePointer){const m=r.getHoveredShapeId();m&&u.add(m)}if(c.size!==u.size)return s.current=u,u;for(const m of u)if(!c.has(m))return s.current=u,u;return c},[r]),i=W("rendering shapes",()=>r.getRenderingShapes(),[r]),{ShapeIndicator:a}=xt(),l=W("shapes to render for svg indicators",()=>i.filter(({id:c})=>{const u=r.getShape(c);return u?r.getShapeUtil(u).useLegacyIndicator():!1}),[r,i]);return a?l.map(({id:c})=>p.jsx(a,{shapeId:c,hidden:!t&&(e||!o.has(c))},c+"_indicator")):null}),LW=x.forwardRef(function({children:e,shape:t,isBackground:r,...s},o){const i="fill"in t.props&&t.props.fill!=="none";return p.jsx("div",{ref:o,"data-shape-type":t.type,"data-shape-is-filled":r?void 0:i,"data-shape-id":t.id,draggable:!1,...s,className:xe("tl-shape",r&&"tl-shape-background",s.className),children:e})});function jW({points:n,zoom:e}){const t=2.5/e,r=n.reduce((h,f)=>Math.min(h,f.x),1/0),s=n.reduce((h,f)=>Math.max(h,f.x),-1/0),o=n.reduce((h,f)=>Math.min(h,f.y),1/0),i=n.reduce((h,f)=>Math.max(h,f.y),-1/0),a=n.some(h=>h.x===r&&h.y===o);let l,c,u,d;return a?(l=r,c=o,u=s,d=i):(l=r,c=i,u=s,d=o),p.jsxs("g",{className:"tl-snap-indicator",stroke:"lime",children:[p.jsx("line",{x1:l,y1:c,x2:u,y2:d}),n.map((h,f)=>p.jsx("g",{transform:`translate(${h.x},${h.y})`,children:p.jsx("path",{className:"tl-snap-point",d:`M ${-t},${-t} L ${t},${t} M ${-t},${t} L ${t},${-t}`})},f))]})}function NW({gaps:n,direction:e,zoom:t}){const r=3.5/t;let s=[-1/0,1/0],o=null;const i=e==="horizontal";for(const l of n){if(o=io(s[0],s[1],i?l.startEdge[0].y:l.startEdge[0].x,i?l.startEdge[1].y:l.startEdge[1].x),o)s=o;else continue;if(o=io(s[0],s[1],i?l.endEdge[0].y:l.endEdge[0].x,i?l.endEdge[1].y:l.endEdge[1].x),o)s=o;else continue}if(s===null)return null;const a=(s[0]+s[1])/2;return p.jsx("g",{className:"tl-snap-indicator",stroke:"cyan",children:n.map(({startEdge:l,endEdge:c},u)=>p.jsx(x.Fragment,{children:i?p.jsxs(p.Fragment,{children:[p.jsx("line",{x1:l[0].x,y1:a-2*r,x2:l[1].x,y2:a+2*r}),p.jsx("line",{x1:c[0].x,y1:a-2*r,x2:c[1].x,y2:a+2*r}),p.jsx("line",{x1:l[0].x,y1:a,x2:c[0].x,y2:a}),p.jsx("line",{x1:(l[0].x+c[0].x)/2,y1:a-r,x2:(l[0].x+c[0].x)/2,y2:a+r})]}):p.jsxs(p.Fragment,{children:[p.jsx("line",{x1:a-2*r,y1:l[0].y,x2:a+2*r,y2:l[1].y}),p.jsx("line",{x1:a-2*r,y1:c[0].y,x2:a+2*r,y2:c[1].y}),p.jsx("line",{x1:a,y1:l[0].y,x2:a,y2:c[0].y}),p.jsx("line",{x1:a-r,y1:(l[0].y+c[0].y)/2,x2:a+r,y2:(l[0].y+c[0].y)/2})]})},u))})}function FW({className:n,line:e,zoom:t}){return p.jsx("svg",{className:xe("tl-overlays__item",n),"aria-hidden":"true",children:e.type==="points"?p.jsx(jW,{...e,zoom:t}):e.type==="gaps"?p.jsx(NW,{...e,zoom:t}):null})}function xR(n){return p.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16","aria-hidden":"false",...n,className:xe("tl-spinner",n.className),children:p.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[p.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),p.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor"})]})})}const BW=()=>null,bR=x.createContext(null);function zW({overrides:n={},children:e}){const t=yd(n),r=x.useMemo(()=>({Background:AU,Brush:kx,Canvas:cG,CollaboratorBrush:kx,CollaboratorCursor:bT,CollaboratorHint:XU,CollaboratorScribble:eI,CollaboratorShapeIndicator:tI,Cursor:bT,Grid:QU,Handle:e8,Handles:t8,InFrontOfTheCanvas:null,LoadingScreen:_W,OnTheCanvas:null,Overlays:null,Scribble:eI,SelectionBackground:null,SelectionForeground:MW,ShapeIndicator:tI,ShapeIndicators:SR,ShapeWrapper:LW,SnapIndicator:FW,Spinner:xR,SvgDefs:BW,ZoomBrush:kx,ErrorFallback:PA,ShapeErrorFallback:AW,ShapeIndicatorErrorFallback:RW,...t}),[t]);return p.jsx(bR.Provider,{value:r,children:e})}function xt(){const n=x.useContext(bR);if(!n)throw new Error("useEditorComponents must be used inside of <EditorComponentsProvider />");return n}const $W=["textarea","input"];function HW(n){const e=K();x.useEffect(()=>{const t=n.current;if(!t)return;const r=s=>{var o;if(s instanceof PointerEvent&&s.pointerType==="pen"){e.markEventAsHandled(s);const{target:i}=s;if($W.includes((o=i.tagName)==null?void 0:o.toLocaleLowerCase())||i.isContentEditable||e.isIn("select.editing_shape"))return;je(s)}};return t.addEventListener("touchstart",r),t.addEventListener("touchend",r),()=>{t.removeEventListener("touchstart",r),t.removeEventListener("touchend",r)}},[e,n])}function UW(n,e,t){return Math.max(e,Math.min(n,t))}const Hn={toVector(n,e){return n===void 0&&(n=e),Array.isArray(n)?n:[n,n]},add(n,e){return[n[0]+e[0],n[1]+e[1]]},sub(n,e){return[n[0]-e[0],n[1]-e[1]]},addTo(n,e){n[0]+=e[0],n[1]+=e[1]},subTo(n,e){n[0]-=e[0],n[1]-=e[1]}};function nI(n,e,t){return e===0||Math.abs(e)===1/0?Math.pow(n,t*5):n*e*t/(e+t*n)}function rI(n,e,t,r=.15){return r===0?UW(n,e,t):n<e?-nI(e-n,t-e,r)+e:n>t?+nI(n-t,t-e,r)+t:n}function KW(n,[e,t],[r,s]){const[[o,i],[a,l]]=n;return[rI(e,o,i,r),rI(t,a,l,s)]}function WW(n,e){if(typeof n!="object"||n===null)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var r=t.call(n,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function VW(n){var e=WW(n,"string");return typeof e=="symbol"?e:String(e)}function sr(n,e,t){return e=VW(e),e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function sI(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),t.push.apply(t,r)}return t}function zt(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?sI(Object(t),!0).forEach(function(r){sr(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):sI(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}const wR={pointer:{start:"down",change:"move",end:"up"},mouse:{start:"down",change:"move",end:"up"},touch:{start:"start",change:"move",end:"end"},gesture:{start:"start",change:"change",end:"end"}};function oI(n){return n?n[0].toUpperCase()+n.slice(1):""}const GW=["enter","leave"];function YW(n=!1,e){return n&&!GW.includes(e)}function XW(n,e="",t=!1){const r=wR[n],s=r&&r[e]||e;return"on"+oI(n)+oI(s)+(YW(t,s)?"Capture":"")}const qW=["gotpointercapture","lostpointercapture"];function ZW(n){let e=n.substring(2).toLowerCase();const t=!!~e.indexOf("passive");t&&(e=e.replace("passive",""));const r=qW.includes(e)?"capturecapture":"capture",s=!!~e.indexOf(r);return s&&(e=e.replace("capture","")),{device:e,capture:s,passive:t}}function JW(n,e=""){const t=wR[n],r=t&&t[e]||e;return n+r}function vR(n){return"touches"in n}function QW(n){return vR(n)?"touch":"pointerType"in n?n.pointerType:"mouse"}function eV(n){return Array.from(n.touches).filter(e=>{var t,r;return e.target===n.currentTarget||((t=n.currentTarget)===null||t===void 0||(r=t.contains)===null||r===void 0?void 0:r.call(t,e.target))})}function $w(n,e){try{const t=e.clientX-n.clientX,r=e.clientY-n.clientY,s=(e.clientX+n.clientX)/2,o=(e.clientY+n.clientY)/2,i=Math.hypot(t,r);return{angle:-(Math.atan2(t,r)*180)/Math.PI,distance:i,origin:[s,o]}}catch{}return null}function tV(n){return eV(n).map(e=>e.identifier)}function iI(n,e){const[t,r]=Array.from(n.touches).filter(s=>e.includes(s.identifier));return $w(t,r)}const aI=40,lI=800;function CR(n){let{deltaX:e,deltaY:t,deltaMode:r}=n;return r===1?(e*=aI,t*=aI):r===2&&(e*=lI,t*=lI),[e,t]}function nV(n){const e={};if("buttons"in n&&(e.buttons=n.buttons),"shiftKey"in n){const{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o}=n;Object.assign(e,{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o})}return e}function Vg(n,...e){return typeof n=="function"?n(...e):n}function rV(){}function sV(...n){return n.length===0?rV:n.length===1?n[0]:function(){let e;for(const t of n)e=t.apply(this,arguments)||e;return e}}function cI(n,e){return Object.assign({},e,n||{})}const oV=32;class PR{constructor(e,t,r){this.ctrl=e,this.args=t,this.key=r,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(e){this.ctrl.state[this.key]=e}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:e,shared:t,ingKey:r,args:s}=this;t[r]=e._active=e.active=e._blocked=e._force=!1,e._step=[!1,!1],e.intentional=!1,e._movement=[0,0],e._distance=[0,0],e._direction=[0,0],e._delta=[0,0],e._bounds=[[-1/0,1/0],[-1/0,1/0]],e.args=s,e.axis=void 0,e.memo=void 0,e.elapsedTime=e.timeDelta=0,e.direction=[0,0],e.distance=[0,0],e.overflow=[0,0],e._movementBound=[!1,!1],e.velocity=[0,0],e.movement=[0,0],e.delta=[0,0],e.timeStamp=0}start(e){const t=this.state,r=this.config;t._active||(this.reset(),this.computeInitial(),t._active=!0,t.target=e.target,t.currentTarget=e.currentTarget,t.lastOffset=r.from?Vg(r.from,t):t.offset,t.offset=t.lastOffset,t.startTime=t.timeStamp=e.timeStamp)}computeValues(e){const t=this.state;t._values=e,t.values=this.config.transform(e)}computeInitial(){const e=this.state;e._initial=e._values,e.initial=e.values}compute(e){const{state:t,config:r,shared:s}=this;t.args=this.args;let o=0;if(e&&(t.event=e,r.preventDefault&&e.cancelable&&t.event.preventDefault(),t.type=e.type,s.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,s.locked=!!document.pointerLockElement,Object.assign(s,nV(e)),s.down=s.pressed=s.buttons%2===1||s.touches>0,o=e.timeStamp-t.timeStamp,t.timeStamp=e.timeStamp,t.elapsedTime=t.timeStamp-t.startTime),t._active){const T=t._delta.map(Math.abs);Hn.addTo(t._distance,T)}this.axisIntent&&this.axisIntent(e);const[i,a]=t._movement,[l,c]=r.threshold,{_step:u,values:d}=t;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=l&&d[0]),u[1]===!1&&(u[1]=Math.abs(a)>=c&&d[1])):(u[0]===!1&&(u[0]=Math.abs(i)>=l&&Math.sign(i)*l),u[1]===!1&&(u[1]=Math.abs(a)>=c&&Math.sign(a)*c)),t.intentional=u[0]!==!1||u[1]!==!1,!t.intentional)return;const h=[0,0];if(r.hasCustomTransform){const[T,I]=d;h[0]=u[0]!==!1?T-u[0]:0,h[1]=u[1]!==!1?I-u[1]:0}else h[0]=u[0]!==!1?i-u[0]:0,h[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!t._blocked&&this.restrictToAxis(h);const f=t.offset,g=t._active&&!t._blocked||t.active;g&&(t.first=t._active&&!t.active,t.last=!t._active&&t.active,t.active=s[this.ingKey]=t._active,e&&(t.first&&("bounds"in r&&(t._bounds=Vg(r.bounds,t)),this.setup&&this.setup()),t.movement=h,this.computeOffset()));const[m,y]=t.offset,[[S,b],[w,v]]=t._bounds;t.overflow=[m<S?-1:m>b?1:0,y<w?-1:y>v?1:0],t._movementBound[0]=t.overflow[0]?t._movementBound[0]===!1?t._movement[0]:t._movementBound[0]:!1,t._movementBound[1]=t.overflow[1]?t._movementBound[1]===!1?t._movement[1]:t._movementBound[1]:!1;const P=t._active?r.rubberband||[0,0]:[0,0];if(t.offset=KW(t._bounds,t.offset,P),t.delta=Hn.sub(t.offset,f),this.computeMovement(),g&&(!t.last||o>oV)){t.delta=Hn.sub(t.offset,f);const T=t.delta.map(Math.abs);Hn.addTo(t.distance,T),t.direction=t.delta.map(Math.sign),t._direction=t._delta.map(Math.sign),!t.first&&o>0&&(t.velocity=[T[0]/o,T[1]/o],t.timeDelta=o)}}emit(){const e=this.state,t=this.shared,r=this.config;if(e._active||this.clean(),(e._blocked||!e.intentional)&&!e._force&&!r.triggerAllEvents)return;const s=this.handler(zt(zt(zt({},t),e),{},{[this.aliasKey]:e.values}));s!==void 0&&(e.memo=s)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function iV([n,e],t){const r=Math.abs(n),s=Math.abs(e);if(r>s&&r>t)return"x";if(s>r&&s>t)return"y"}class aV extends PR{constructor(...e){super(...e),sr(this,"aliasKey","xy")}reset(){super.reset(),this.state.axis=void 0}init(){this.state.offset=[0,0],this.state.lastOffset=[0,0]}computeOffset(){this.state.offset=Hn.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Hn.sub(this.state.offset,this.state.lastOffset)}axisIntent(e){const t=this.state,r=this.config;if(!t.axis&&e){const s=typeof r.axisThreshold=="object"?r.axisThreshold[QW(e)]:r.axisThreshold;t.axis=iV(t._movement,s)}t._blocked=(r.lockDirection||!!r.axis)&&!t.axis||!!r.axis&&r.axis!==t.axis}restrictToAxis(e){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":e[1]=0;break;case"y":e[0]=0;break}}}const lV=n=>n,dI=.15,TR={enabled(n=!0){return n},eventOptions(n,e,t){return zt(zt({},t.shared.eventOptions),n)},preventDefault(n=!1){return n},triggerAllEvents(n=!1){return n},rubberband(n=0){switch(n){case!0:return[dI,dI];case!1:return[0,0];default:return Hn.toVector(n)}},from(n){if(typeof n=="function")return n;if(n!=null)return Hn.toVector(n)},transform(n,e,t){const r=n||t.shared.transform;return this.hasCustomTransform=!!r,r||lV},threshold(n){return Hn.toVector(n,0)}},cV=0,Yh=zt(zt({},TR),{},{axis(n,e,{axis:t}){if(this.lockDirection=t==="lock",!this.lockDirection)return t},axisThreshold(n=cV){return n},bounds(n={}){if(typeof n=="function")return o=>Yh.bounds(n(o));if("current"in n)return()=>n.current;if(typeof HTMLElement=="function"&&n instanceof HTMLElement)return n;const{left:e=-1/0,right:t=1/0,top:r=-1/0,bottom:s=1/0}=n;return[[e,t],[r,s]]}}),Xh=typeof window<"u"&&window.document&&window.document.createElement;function IR(){return Xh&&"ontouchstart"in window}function dV(){return IR()||Xh&&window.navigator.maxTouchPoints>1}function uV(){return Xh&&"onpointerdown"in window}function hV(){return Xh&&"exitPointerLock"in window.document}function pV(){try{return"constructor"in GestureEvent}catch{return!1}}const js={isBrowser:Xh,gesture:pV(),touch:IR(),touchscreen:dV(),pointer:uV(),pointerLock:hV()},fV=250,gV=180,mV=.5,yV=50,SV=250,xV=10,uI={mouse:0,touch:0,pen:8};zt(zt({},Yh),{},{device(n,e,{pointer:{touch:t=!1,lock:r=!1,mouse:s=!1}={}}){return this.pointerLock=r&&js.pointerLock,js.touch&&t?"touch":this.pointerLock?"mouse":js.pointer&&!s?"pointer":js.touch?"touch":"mouse"},preventScrollAxis(n,e,{preventScroll:t}){if(this.preventScrollDelay=typeof t=="number"?t:t||t===void 0&&n?fV:void 0,!(!js.touchscreen||t===!1))return n||(t!==void 0?"y":void 0)},pointerCapture(n,e,{pointer:{capture:t=!0,buttons:r=1,keys:s=!0}={}}){return this.pointerButtons=r,this.keys=s,!this.pointerLock&&this.device==="pointer"&&t},threshold(n,e,{filterTaps:t=!1,tapsThreshold:r=3,axis:s=void 0}){const o=Hn.toVector(n,t?r:s?1:0);return this.filterTaps=t,this.tapsThreshold=r,o},swipe({velocity:n=mV,distance:e=yV,duration:t=SV}={}){return{velocity:this.transform(Hn.toVector(n)),distance:this.transform(Hn.toVector(e)),duration:t}},delay(n=0){switch(n){case!0:return gV;case!1:return 0;default:return n}},axisThreshold(n){return n?zt(zt({},uI),n):uI},keyboardDisplacement(n=xV){return n}});function ER(n){const[e,t]=n.overflow,[r,s]=n._delta,[o,i]=n._direction;(e<0&&r>0&&o<0||e>0&&r<0&&o>0)&&(n._movement[0]=n._movementBound[0]),(t<0&&s>0&&i<0||t>0&&s<0&&i>0)&&(n._movement[1]=n._movementBound[1])}const bV=30,wV=100;class vV extends PR{constructor(...e){super(...e),sr(this,"ingKey","pinching"),sr(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const e=this.state;e._touchIds=[],e.canceled=!1,e.cancel=this.cancel.bind(this),e.turns=0}computeOffset(){const{type:e,movement:t,lastOffset:r}=this.state;e==="wheel"?this.state.offset=Hn.add(t,r):this.state.offset=[(1+t[0])*r[0],t[1]+r[1]]}computeMovement(){const{offset:e,lastOffset:t}=this.state;this.state.movement=[e[0]/t[0],e[1]-t[1]]}axisIntent(){const e=this.state,[t,r]=e._movement;if(!e.axis){const s=Math.abs(t)*bV-Math.abs(r);s<0?e.axis="angle":s>0&&(e.axis="scale")}}restrictToAxis(e){this.config.lockDirection&&(this.state.axis==="scale"?e[1]=0:this.state.axis==="angle"&&(e[0]=0))}cancel(){const e=this.state;e.canceled||setTimeout(()=>{e.canceled=!0,e._active=!1,this.compute(),this.emit()},0)}touchStart(e){this.ctrl.setEventIds(e);const t=this.state,r=this.ctrl.touchIds;if(t._active&&t._touchIds.every(o=>r.has(o))||r.size<2)return;this.start(e),t._touchIds=Array.from(r).slice(0,2);const s=iI(e,t._touchIds);s&&this.pinchStart(e,s)}pointerStart(e){if(e.buttons!=null&&e.buttons%2!==1)return;this.ctrl.setEventIds(e),e.target.setPointerCapture(e.pointerId);const t=this.state,r=t._pointerEvents,s=this.ctrl.pointerIds;if(t._active&&Array.from(r.keys()).every(i=>s.has(i))||(r.size<2&&r.set(e.pointerId,e),t._pointerEvents.size<2))return;this.start(e);const o=$w(...Array.from(r.values()));o&&this.pinchStart(e,o)}pinchStart(e,t){const r=this.state;r.origin=t.origin,this.computeValues([t.distance,t.angle]),this.computeInitial(),this.compute(e),this.emit()}touchMove(e){if(!this.state._active)return;const t=iI(e,this.state._touchIds);t&&this.pinchMove(e,t)}pointerMove(e){const t=this.state._pointerEvents;if(t.has(e.pointerId)&&t.set(e.pointerId,e),!this.state._active)return;const r=$w(...Array.from(t.values()));r&&this.pinchMove(e,r)}pinchMove(e,t){const r=this.state,s=r._values[1],o=t.angle-s;let i=0;Math.abs(o)>270&&(i+=Math.sign(o)),this.computeValues([t.distance,t.angle-360*i]),r.origin=t.origin,r.turns=i,r._movement=[r._values[0]/r._initial[0]-1,r._values[1]-r._initial[1]],this.compute(e),this.emit()}touchEnd(e){this.ctrl.setEventIds(e),this.state._active&&this.state._touchIds.some(t=>!this.ctrl.touchIds.has(t))&&(this.state._active=!1,this.compute(e),this.emit())}pointerEnd(e){const t=this.state;this.ctrl.setEventIds(e);try{e.target.releasePointerCapture(e.pointerId)}catch{}t._pointerEvents.has(e.pointerId)&&t._pointerEvents.delete(e.pointerId),t._active&&t._pointerEvents.size<2&&(t._active=!1,this.compute(e),this.emit())}gestureStart(e){e.cancelable&&e.preventDefault();const t=this.state;t._active||(this.start(e),this.computeValues([e.scale,e.rotation]),t.origin=[e.clientX,e.clientY],this.compute(e),this.emit())}gestureMove(e){if(e.cancelable&&e.preventDefault(),!this.state._active)return;const t=this.state;this.computeValues([e.scale,e.rotation]),t.origin=[e.clientX,e.clientY];const r=t._movement;t._movement=[e.scale-1,e.rotation],t._delta=Hn.sub(t._movement,r),this.compute(e),this.emit()}gestureEnd(e){this.state._active&&(this.state._active=!1,this.compute(e),this.emit())}wheel(e){const t=this.config.modifierKey;t&&(Array.isArray(t)?!t.find(r=>e[r]):!e[t])||(this.state._active?this.wheelChange(e):this.wheelStart(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(e){this.start(e),this.wheelChange(e)}wheelChange(e){"uv"in e||e.cancelable&&e.preventDefault();const r=this.state;r._delta=[-CR(e)[1]/wV*r.offset[0],0],Hn.addTo(r._movement,r._delta),ER(r),this.state.origin=[e.clientX,e.clientY],this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){const t=this.config.device;t&&(e(t,"start",this[t+"Start"].bind(this)),e(t,"change",this[t+"Move"].bind(this)),e(t,"end",this[t+"End"].bind(this)),e(t,"cancel",this[t+"End"].bind(this)),e("lostPointerCapture","",this[t+"End"].bind(this))),this.config.pinchOnWheel&&e("wheel","",this.wheel.bind(this),{passive:!1})}}const CV=zt(zt({},TR),{},{device(n,e,{shared:t,pointer:{touch:r=!1}={}}){if(t.target&&!js.touch&&js.gesture)return"gesture";if(js.touch&&r)return"touch";if(js.touchscreen){if(js.pointer)return"pointer";if(js.touch)return"touch"}},bounds(n,e,{scaleBounds:t={},angleBounds:r={}}){const s=i=>{const a=cI(Vg(t,i),{min:-1/0,max:1/0});return[a.min,a.max]},o=i=>{const a=cI(Vg(r,i),{min:-1/0,max:1/0});return[a.min,a.max]};return typeof t!="function"&&typeof r!="function"?[s(),o()]:i=>[s(i),o(i)]},threshold(n,e,t){return this.lockDirection=t.axis==="lock",Hn.toVector(n,this.lockDirection?[.1,3]:0)},modifierKey(n){return n===void 0?"ctrlKey":n},pinchOnWheel(n=!0){return n}});zt(zt({},Yh),{},{mouseOnly:(n=!0)=>n});class PV extends aV{constructor(...e){super(...e),sr(this,"ingKey","wheeling")}wheel(e){this.state._active||this.start(e),this.wheelChange(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(e){const t=this.state;t._delta=CR(e),Hn.addTo(t._movement,t._delta),ER(t),this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){e("wheel","",this.wheel.bind(this))}}const TV=Yh;zt(zt({},Yh),{},{mouseOnly:(n=!0)=>n});const u1=new Map,Hw=new Map;function IV(n){u1.set(n.key,n.engine),Hw.set(n.key,n.resolver)}const EV={key:"pinch",engine:vV,resolver:CV},kV={key:"wheel",engine:PV,resolver:TV};function _V(n,e){if(n==null)return{};var t={},r=Object.keys(n),s,o;for(o=0;o<r.length;o++)s=r[o],!(e.indexOf(s)>=0)&&(t[s]=n[s]);return t}function MV(n,e){if(n==null)return{};var t=_V(n,e),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(n);for(s=0;s<o.length;s++)r=o[s],!(e.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(n,r)&&(t[r]=n[r])}return t}const AV={target(n){if(n)return()=>"current"in n?n.current:n},enabled(n=!0){return n},window(n=js.isBrowser?window:void 0){return n},eventOptions({passive:n=!0,capture:e=!1}={}){return{passive:n,capture:e}},transform(n){return n}},DV=["target","eventOptions","window","enabled","transform"];function zf(n={},e){const t={};for(const[r,s]of Object.entries(e))switch(typeof s){case"function":t[r]=s.call(t,n[r],r,n);break;case"object":t[r]=zf(n[r],s);break;case"boolean":s&&(t[r]=n[r]);break}return t}function OV(n,e,t={}){const r=n,{target:s,eventOptions:o,window:i,enabled:a,transform:l}=r,c=MV(r,DV);if(t.shared=zf({target:s,eventOptions:o,window:i,enabled:a,transform:l},AV),e){const u=Hw.get(e);t[e]=zf(zt({shared:t.shared},c),u)}else for(const u in c){const d=Hw.get(u);d&&(t[u]=zf(zt({shared:t.shared},c[u]),d))}return t}class kR{constructor(e,t){sr(this,"_listeners",new Set),this._ctrl=e,this._gestureKey=t}add(e,t,r,s,o){const i=this._listeners,a=JW(t,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=zt(zt({},l),o);e.addEventListener(a,s,c);const u=()=>{e.removeEventListener(a,s,c),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(e=>e()),this._listeners.clear()}}class RV{constructor(){sr(this,"_timeouts",new Map)}add(e,t,r=140,...s){this.remove(e),this._timeouts.set(e,window.setTimeout(t,r,...s))}remove(e){const t=this._timeouts.get(e);t&&window.clearTimeout(t)}clean(){this._timeouts.forEach(e=>void window.clearTimeout(e)),this._timeouts.clear()}}class LV{constructor(e){sr(this,"gestures",new Set),sr(this,"_targetEventStore",new kR(this)),sr(this,"gestureEventStores",{}),sr(this,"gestureTimeoutStores",{}),sr(this,"handlers",{}),sr(this,"config",{}),sr(this,"pointerIds",new Set),sr(this,"touchIds",new Set),sr(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),jV(this,e)}setEventIds(e){if(vR(e))return this.touchIds=new Set(tV(e)),this.touchIds;if("pointerId"in e)return e.type==="pointerup"||e.type==="pointercancel"?this.pointerIds.delete(e.pointerId):e.type==="pointerdown"&&this.pointerIds.add(e.pointerId),this.pointerIds}applyHandlers(e,t){this.handlers=e,this.nativeHandlers=t}applyConfig(e,t){this.config=OV(e,t,this.config)}clean(){this._targetEventStore.clean();for(const e of this.gestures)this.gestureEventStores[e].clean(),this.gestureTimeoutStores[e].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...e){const t=this.config.shared,r={};let s;if(!(t.target&&(s=t.target(),!s))){if(t.enabled){for(const i of this.gestures){const a=this.config[i],l=hI(r,a.eventOptions,!!s);if(a.enabled){const c=u1.get(i);new c(this,e,i).bind(l)}}const o=hI(r,t.eventOptions,!!s);for(const i in this.nativeHandlers)o(i,"",a=>this.nativeHandlers[i](zt(zt({},this.state.shared),{},{event:a,args:e})),void 0,!0)}for(const o in r)r[o]=sV(...r[o]);if(!s)return r;for(const o in r){const{device:i,capture:a,passive:l}=ZW(o);this._targetEventStore.add(s,i,"",r[o],{capture:a,passive:l})}}}}function lc(n,e){n.gestures.add(e),n.gestureEventStores[e]=new kR(n,e),n.gestureTimeoutStores[e]=new RV}function jV(n,e){e.drag&&lc(n,"drag"),e.wheel&&lc(n,"wheel"),e.scroll&&lc(n,"scroll"),e.move&&lc(n,"move"),e.pinch&&lc(n,"pinch"),e.hover&&lc(n,"hover")}const hI=(n,e,t)=>(r,s,o,i={},a=!1)=>{var l,c;const u=(l=i.capture)!==null&&l!==void 0?l:e.capture,d=(c=i.passive)!==null&&c!==void 0?c:e.passive;let h=a?r:XW(r,s,u);t&&d&&(h+="Passive"),n[h]=n[h]||[],n[h].push(o)},NV=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function FV(n){const e={},t={},r=new Set;for(let s in n)NV.test(s)?(r.add(RegExp.lastMatch),t[s]=n[s]):e[s]=n[s];return[t,e,r]}function cc(n,e,t,r,s,o){if(!n.has(t)||!u1.has(r))return;const i=t+"Start",a=t+"End",l=c=>{let u;return c.first&&i in e&&e[i](c),t in e&&(u=e[t](c)),c.last&&a in e&&e[a](c),u};s[r]=l,o[r]=o[r]||{}}function BV(n,e){const[t,r,s]=FV(n),o={};return cc(s,t,"onDrag","drag",o,e),cc(s,t,"onWheel","wheel",o,e),cc(s,t,"onScroll","scroll",o,e),cc(s,t,"onPinch","pinch",o,e),cc(s,t,"onMove","move",o,e),cc(s,t,"onHover","hover",o,e),{handlers:o,config:e,nativeHandlers:r}}function zV(n,e={},t,r){const s=_e.useMemo(()=>new LV(n),[]);if(s.applyHandlers(n,r),s.applyConfig(e,t),_e.useEffect(s.effect.bind(s)),_e.useEffect(()=>s.clean.bind(s),[]),e.target===void 0)return s.bind.bind(s)}function $V(n){return n.forEach(IV),function(t,r){const{handlers:s,nativeHandlers:o,config:i}=BV(t,r||{});return zV(s,i,void 0,o)}}const pI=10,HV=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function _R(n){let{deltaY:e,deltaX:t}=n,r=0;return n.ctrlKey||n.altKey||n.metaKey?r=(Math.abs(e)>pI?pI*Math.sign(e):e)/100:n.shiftKey&&!HV&&(t=e,e=0),{x:-t,y:-e,z:-r}}const UV=$V([kV,EV]);let dc;const KV=n=>dc===void 0?(dc=n,!1):n-dc>120&&n-dc<160?(dc=n,!0):(dc=n,!1);function WV(n){const e=K(),t=x.useMemo(()=>{let r="not sure";const s=({event:g})=>{if(!e.getInstanceState().isFocused||(r="not sure",KV(Date.now())))return;const m=e.getEditingShapeId();if(m){const b=e.getShape(m);if(b&&e.getShapeUtil(b).canScroll(b)){const v=e.getShapePageBounds(m);if(v!=null&&v.containsPoint(e.inputs.getCurrentPagePoint()))return}}je(g),g.stopPropagation();const y=_R(g);if(y.x===0&&y.y===0)return;const S={type:"wheel",name:"wheel",delta:y,point:new C(g.clientX,g.clientY),shiftKey:g.shiftKey,altKey:g.altKey,ctrlKey:g.metaKey||g.ctrlKey,metaKey:g.metaKey,accelKey:Jt(g)};e.dispatch(S)};let o=1,i=1,a=0;const l=new C,c=new C,u=g=>{const m=n.current;r="not sure";const{event:y,origin:S,da:b}=g;y instanceof WheelEvent||(y.target===m||m!=null&&m.contains(y.target))&&(c.x=S[0],c.y=S[1],l.x=S[0],l.y=S[1],o=b[0],i=e.getZoomLevel(),e.dispatch({type:"pinch",name:"pinch_start",point:{x:S[0],y:S[1],z:e.getZoomLevel()},delta:{x:0,y:0},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:Jt(y)}))},d=g=>{if(g&&(r="zooming"),r==="zooming")return;const m=Math.abs(a-o),y=C.Dist(l,c);switch(r){case"not sure":{m>24?r="zooming":y>16&&(r="panning");break}case"panning":{m>64&&(r="zooming");break}}};return{onWheel:s,onPinchStart:u,onPinchEnd:g=>{const m=n.current,{event:y,origin:S,offset:b}=g;if(y instanceof WheelEvent||!(y.target===m||m!=null&&m.contains(y.target)))return;const w=b[0]**e.getCameraOptions().zoomSpeed;r="not sure",e.timers.requestAnimationFrame(()=>{e.dispatch({type:"pinch",name:"pinch_end",point:{x:S[0],y:S[1],z:w},delta:{x:S[0],y:S[1]},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:Jt(y)})})},onPinch:g=>{const m=n.current,{event:y,origin:S,offset:b,da:w}=g;if(y instanceof WheelEvent||!(y.target===m||m!=null&&m.contains(y.target)))return;const v=g.type==="gesturechange"||g.type==="gestureend";a=w[0];const P=S[0]-c.x,T=S[1]-c.y;switch(c.x=S[0],c.y=S[1],d(v),r){case"zooming":{const I=b[0]**e.getCameraOptions().zoomSpeed;e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:I},delta:{x:P,y:T},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:Jt(y)});break}case"panning":{e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:i},delta:{x:P,y:T},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:Jt(y)});break}}}}},[e,n]);UV(t,{target:n,eventOptions:{passive:!1},pinch:{from:()=>{const{zoomSpeed:r}=e.getCameraOptions();return[e.getZoomLevel()**(1/r),0]},scaleBounds:()=>{const r=e.getBaseZoom(),{zoomSteps:s,zoomSpeed:o}=e.getCameraOptions(),i=s[0]*r;return{max:(s[s.length-1]*r)**(1/o),min:i**(1/o)}}}})}function Yx(n,e,t){const r=n.getShape(e),s=n.getShapeHandles(r);return{shape:r,handle:s.find(o=>o.id===t)}}function VV(n,e){const t=K();return x.useMemo(()=>{const r=l=>{if(t.wasEventAlreadyHandled(l))return;const c=zg(l.currentTarget);Nh(c,l);const{shape:u,handle:d}=Yx(t,n,e);d&&t.dispatch({type:"pointer",target:"handle",handle:d,shape:u,name:"pointer_down",...$n(t,l)})};let s,o;return{onPointerDown:r,onPointerMove:l=>{if(t.wasEventAlreadyHandled(l)||l.clientX===s&&l.clientY===o)return;s=l.clientX,o=l.clientY;const{shape:c,handle:u}=Yx(t,n,e);u&&t.dispatch({type:"pointer",target:"handle",handle:u,shape:c,name:"pointer_move",...$n(t,l)})},onPointerUp:l=>{if(t.wasEventAlreadyHandled(l))return;const c=zg(l.currentTarget);Fh(c,l);const{shape:u,handle:d}=Yx(t,n,e);d&&t.dispatch({type:"pointer",target:"handle",handle:d,shape:u,name:"pointer_up",...$n(t,l)})}}},[t,n,e])}function GV(n){const e=K();x.useLayoutEffect(()=>{const t=N_(()=>{n.current&&e.updateViewportScreenBounds(n.current)},200,{trailing:!0}),r=e.timers.setInterval(t,1e3);window.addEventListener("resize",t);const s=new ResizeObserver(a=>{a[0].contentRect&&t()}),o=n.current;let i=null;return o&&(s.observe(o),i=YV(o),i.addEventListener("scroll",t)),()=>{clearInterval(r),window.removeEventListener("resize",t),s.disconnect(),i==null||i.removeEventListener("scroll",t),t.cancel()}},[e,n])}/*!
191
+ * Author: excalidraw
192
+ * MIT License: https://github.com/excalidraw/excalidraw/blob/master/LICENSE
193
+ * https://github.com/excalidraw/excalidraw/blob/48c3465b19f10ec755b3eb84e21a01a468e96e43/packages/excalidraw/utils.ts#L600
194
+ */const YV=n=>{let e=n.parentElement;for(;e;){if(e===document.body)return document;const{overflowY:t}=window.getComputedStyle(e);if(e.scrollHeight>e.clientHeight&&(t==="auto"||t==="scroll"||t==="overlay"))return e;e=e.parentElement}return document},XV=rn(function({showStroke:e=!0,showVertices:t=!0,showClosestPointOnOutline:r=!0}){const s=K(),o=s.getZoomLevel(),i=s.getRenderingShapes(),a=s.inputs.getCurrentPagePoint();return p.jsx("svg",{style:{position:"absolute",pointerEvents:"none",zIndex:999999999,top:0,left:0,overflow:"visible"},children:i.map(l=>{const c=s.getShape(l.id);if(c.type==="group")return null;const u=s.getShapeGeometry(c),d=s.getShapePageTransform(c),h=s.getPointInShapeSpace(c,a),f=u.nearestPoint(h),g=u.distanceToPoint(h,!0),m=Math.abs(g)*o,y=g<0,{vertices:S}=u;return p.jsxs("g",{transform:d.toCssString(),strokeLinecap:"round",strokeLinejoin:"round",children:[e&&p.jsx("g",{stroke:u.debugColor??"red",opacity:"1",strokeWidth:2/o,fill:"none",children:p.jsx(MR,{geometry:u})}),t&&S.map((b,w)=>p.jsx("circle",{cx:b.x,cy:b.y,r:2/o,fill:`hsl(${xo(w,[0,S.length-1],[120,200])}, 100%, 50%)`,stroke:"black",strokeWidth:1/o},`v${w}`)),r&&m<150&&p.jsx("line",{x1:f.x,y1:f.y,x2:h.x,y2:h.y,opacity:1-m/150,stroke:y?"goldenrod":"dodgerblue",strokeWidth:2/o})]},l.id+"_outline")})})});function MR({geometry:n}){return n instanceof es?p.jsx("g",{stroke:n.debugColor,children:[...n.children,...n.ignoredChildren].map((e,t)=>p.jsx(MR,{geometry:e},t))}):p.jsx("path",{d:n.toSimpleSvgPath(),stroke:n.debugColor})}function Uw(n,e){return e>n.options.collaboratorInactiveTimeoutMs?"inactive":e>n.options.collaboratorIdleTimeoutMs?"idle":"active"}function AR(n,e,t){const{followingUserId:r,highlightedUserIds:s}=n.getInstanceState();switch(t){case"inactive":return r===e.userId||s.includes(e.userId);case"idle":return e.followingUserId===n.user.getId()?!!(e.chatMessage||s.includes(e.userId)):!0;case"active":return!0}}function DR(n){return E4(n)}function qV(n,e){if(n.size!==e.size)return!1;for(const t of n)if(!e.has(t))return!1;return!0}function OR(){const n=K(),e=vv("userIds",()=>DR(n.getCollaborators().map(t=>t.userId)).sort(),{isEqual:(t,r)=>{var s;return t.join(",")===((s=r.join)==null?void 0:s.call(r,","))}},[n]);return W(e)}function ZV(){const n=md("peerIdsTime",Date.now()),e=K();return x.useEffect(()=>{const t=e.timers.setInterval(()=>{n.set(Date.now())},e.options.collaboratorCheckIntervalMs);return()=>clearInterval(t)},[e,n]),vv("activePeerIds",()=>{const t=n.get();return new Set(e.getCollaborators().filter(r=>{const s=Math.max(0,t-(r.lastActivityTimestamp??1/0)),o=Uw(e,s);return AR(e,r,o)}).map(r=>r.userId))},{isEqual:qV},[e])}function Ey(n){const e=K();return W(`latestPresence:${n}`,()=>e.getCollaborators().find(r=>r.userId===n),[e,n])??null}const JV=rn(function(){return OR().map(t=>p.jsx(QV,{collaboratorId:t},t))}),QV=rn(function({collaboratorId:e}){const t=K(),r=Ey(e),s=tG(t,r);return!(r&&r.currentPageId===t.getCurrentPageId())||!AR(t,r,s)?null:p.jsx(eG,{latestPresence:r})}),eG=rn(function({latestPresence:e}){const t=K(),{CollaboratorBrush:r,CollaboratorScribble:s,CollaboratorCursor:o,CollaboratorHint:i,CollaboratorShapeIndicator:a}=xt(),l=t.getZoomLevel(),c=t.getViewportPageBounds(),{userId:u,chatMessage:d,brush:h,scribbles:f,selectedShapeIds:g,userName:m,cursor:y,color:S}=e;if(!y)return null;const b=!(y.x<c.minX-12/l||y.y<c.minY-16/l||y.x>c.maxX-12/l||y.y>c.maxY-16/l);return p.jsxs(p.Fragment,{children:[h&&r?p.jsx(r,{className:"tl-collaborator__brush",userId:u,brush:h,color:S,opacity:.1},u+"_brush"):null,b&&o?p.jsx(o,{className:"tl-collaborator__cursor",userId:u,point:y,color:S,zoom:l,name:m!=="New User"?m:null,chatMessage:d??""},u+"_cursor"):i?p.jsx(i,{className:"tl-collaborator__cursor-hint",userId:u,point:y,color:S,zoom:l,viewport:c},u+"_cursor_hint"):null,s&&f.length?p.jsx(p.Fragment,{children:f.map(w=>p.jsx(s,{className:"tl-collaborator__scribble",userId:u,scribble:w,color:S,zoom:l,opacity:w.color==="laser"?.5:.1},u+"_scribble_"+w.id))}):null,a&&g.filter(w=>{if(t.isShapeHidden(w))return!1;const v=t.getShape(w);return v?t.getShapeUtil(v).useLegacyIndicator():!1}).map(w=>p.jsx(a,{className:"tl-collaborator__shape-indicator",userId:u,shapeId:w,color:S,opacity:.5},u+"_"+w))]})});function tG(n,e){const t=x.useRef((e==null?void 0:e.lastActivityTimestamp)??-1),[r,s]=x.useState(()=>Uw(n,Date.now()-t.current));return x.useEffect(()=>{const o=n.timers.setInterval(()=>{s(Uw(n,Date.now()-t.current))},n.options.collaboratorCheckIntervalMs);return()=>clearInterval(o)},[n]),e&&(t.current=e.lastActivityTimestamp??1/0),r}function nG(){const n=K(),e=W("is menu open",()=>n.menus.hasAnyOpenMenus(),[n]),[t,r]=x.useState(!1),s=e||t,o=fy(),i=x.useRef({isDown:!1,isDragging:!1,start:new C}),a=x.useCallback(d=>{d.button===0&&(r(!0),i.current={isDown:!0,isDragging:!1,start:new C(d.clientX,d.clientY)},l.current=!1),n.menus.clearOpenMenus()},[n]),l=x.useRef(!1),c=x.useCallback(d=>{var g;if(!i.current.isDown)return;const{x:h,y:f}=i.current.start;l.current||C.Dist2(i.current.start,new C(d.clientX,d.clientY))>n.options.dragDistanceSquared&&(l.current=!0,i.current={...i.current,isDown:!0,isDragging:!0},(g=o.onPointerDown)==null||g.call(o,{...d,clientX:h,clientY:f,button:0})),l.current&&n.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...$n(n,d)})},[o,n]),u=x.useCallback(d=>{var h;(h=o.onPointerUp)==null||h.call(o,d),r(!1),i.current={isDown:!1,isDragging:!1,start:new C(d.clientX,d.clientY)},l.current=!1},[o]);return s&&p.jsx("div",{className:"tlui-menu-click-capture","data-testid":"menu-click-capture.content",...o,onPointerDown:a,onPointerMove:c,onPointerUp:u})}function fI(n,e){if(n.size!==e.size)return!1;for(const t of n)if(!e.has(t))return!1;return!0}function RR(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function rG(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t].color!==e[t].color||!RR(n[t].shapeIds,e[t].shapeIds))return!1;return!0}function sG(n,e){return fI(n.idsToDisplay,e.idsToDisplay)&&fI(n.renderingShapeIds,e.renderingShapeIds)&&RR(n.hintingShapeIds,e.hintingShapeIds)&&rG(n.collaboratorIndicators,e.collaboratorIndicators)}const oG=Rh("indicatorPath",(n,e)=>n.getShapeUtil(e).getIndicatorPath(e)),iG=(n,e)=>oG.get(n,e.id);function Xx(n,e,t,r){if(!r.has(t))return!1;const s=e.getShape(t);if(!s||s.isLocked)return!1;const o=e.getShapePageTransform(s);if(!o)return!1;const i=iG(e,s);return i?(n.save(),n.transform(o.a,o.b,o.c,o.d,o.e,o.f),aG(n,i),n.restore(),!0):!1}function aG(n,e){if(e instanceof Path2D)n.stroke(e);else{const{path:t,clipPath:r,additionalPaths:s}=e;if(r?(n.save(),n.clip(r,"evenodd"),n.stroke(t),n.restore()):n.stroke(t),s)for(const o of s)n.stroke(o)}}const lG=x.memo(function(){const e=K(),t=x.useRef(null),r=x.useRef(null),s=Vh();x.useEffect(()=>{const a=e.timers.setTimeout(()=>{r.current=null},0);return()=>clearTimeout(a)},[s,e]);const o=ZV(),i=vv("indicator render data",()=>{const a=new Set(e.getRenderingShapes().map(b=>b.id)),l=new Set,c=e.getInstanceState(),u=c.isChangingStyle,d=e.isInAny("select.idle","select.editing_shape"),h=e.isInAny("select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","select.pointing_handle");if(!u&&(d||h)){for(const b of e.getSelectedShapeIds())l.add(b);if(d&&c.isHoveringCanvas&&!c.isCoarsePointer){const b=e.getHoveredShapeId();b&&l.add(b)}}const f=ny(e.getHintingShapeIds()),g=[],m=e.getCurrentPageId(),y=o.get(),S=e.getCollaborators();for(const b of y.values()){const w=S.find(P=>P.userId===b);if(!w||w.currentPageId!==m)continue;const v=w.selectedShapeIds.filter(P=>a.has(P)&&!e.isShapeHidden(P));v.length>0&&g.push({color:w.color,shapeIds:v})}return{idsToDisplay:l,renderingShapeIds:a,hintingShapeIds:f,collaboratorIndicators:g}},{isEqual:sG},[e,o]);return Va("canvas indicators render",()=>{const a=t.current;if(!a)return;const l=a.getContext("2d");if(!l)return;const{idsToDisplay:c,renderingShapeIds:u,hintingShapeIds:d,collaboratorIndicators:h}=i.get(),{w:f,h:g}=e.getViewportScreenBounds(),m=window.devicePixelRatio||1,{x:y,y:S,z:b}=e.getCamera(),w=Math.ceil(f*m),v=Math.ceil(g*m);(a.width!==w||a.height!==v)&&(a.width=w,a.height=v,a.style.width=`${f}px`,a.style.height=`${g}px`),l.resetTransform(),l.clearRect(0,0,a.width,a.height),l.scale(m,m),l.scale(b,b),l.translate(y,S),l.lineCap="round",l.lineJoin="round",l.lineWidth=1.5/b;for(const P of h){l.strokeStyle=P.color,l.globalAlpha=.7;for(const T of P.shapeIds)Xx(l,e,T,u)}l.globalAlpha=1,r.current||(r.current=getComputedStyle(a).getPropertyValue("--tl-color-selected")),l.strokeStyle=r.current,l.lineWidth=1.5/b;for(const P of c)Xx(l,e,P,u);if(d.length>0){l.lineWidth=2.5/b;for(const P of d)Xx(l,e,P,u)}},[e,i]),p.jsx("canvas",{ref:t,className:"tl-canvas-indicators"})});function cG({className:n}){const e=K(),{SelectionBackground:t,Background:r,SvgDefs:s,ShapeIndicators:o}=xt(),i=x.useRef(null),a=x.useRef(null),l=x.useRef(null),c=sn();GV(i),YU(),GU(),WV(i),HW(i);const u=x.useRef({lodDisableTextOutline:!1,allowTextOutline:!0});Va("position layers",function(){const{x:w,y:v,z:P}=e.getCamera();if(u.current.allowTextOutline&&dt.isSafari&&(c.style.setProperty("--tl-text-outline","none"),u.current.allowTextOutline=!1),u.current.allowTextOutline&&P<e.options.textShadowLod!==u.current.lodDisableTextOutline){const k=P<e.options.textShadowLod;c.style.setProperty("--tl-text-outline",k?"none":"var(--tl-text-outline-reference)"),u.current.lodDisableTextOutline=k}const T=P>=1?xo(P,[1,8],[.125,.5],!0):xo(P,[.1,1],[-2,.125],!0),I=`scale(${$(P)}) translate(${$(w+T)}px,${$(v+T)}px)`;Cn(a.current,"transform",I),Cn(l.current,"transform",I)},[e,c]);const d=fy(),h=W("shapeSvgDefs",()=>{const b=new Map;for(const w of Et(e.shapeUtils)){if(!w)return;const v=w.getCanvasSvgDefs();for(const{key:P,component:T}of v)b.has(P)||b.set(P,p.jsx(T,{},P))}return[...b.values()]},[e]),f=W("debug_shapes",()=>Dt.hideShapes.get(),[Dt]),g=W("debug_svg",()=>Dt.debugSvg.get(),[Dt]),m=W("debug_geometry",()=>Dt.debugGeometry.get(),[Dt]),y=W("isEditingAnything",()=>e.getEditingShapeId()!==null,[e]),S=W("isSelectingAnything",()=>!!e.getSelectedShapeIds().length,[e]);return p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:i,draggable:!1,"data-iseditinganything":y,"data-isselectinganything":S,className:xe("tl-canvas",n),"data-testid":"canvas",...d,children:[p.jsx("svg",{className:"tl-svg-context","aria-hidden":"true",children:p.jsxs("defs",{children:[h,p.jsx(TG,{}),p.jsx(IG,{}),s&&p.jsx(s,{})]})}),r&&p.jsx("div",{className:"tl-background__wrapper",children:p.jsx(r,{})}),p.jsx(uG,{}),p.jsxs("div",{ref:a,className:"tl-html-layer tl-shapes",draggable:!1,children:[p.jsx(MG,{}),t&&p.jsx(_G,{}),f?null:g?p.jsx(bG,{}):p.jsx(CG,{})]}),p.jsxs("div",{className:"tl-overlays",children:[p.jsx(lG,{}),p.jsxs("div",{ref:l,className:"tl-html-layer",children:[m?p.jsx(XV,{}):null,p.jsx(pG,{}),p.jsx(hG,{}),p.jsx(fG,{}),o&&p.jsx(o,{}),p.jsx(PG,{}),p.jsx(gG,{}),p.jsx(kG,{}),p.jsx(mG,{}),p.jsx(xG,{}),p.jsx(JV,{})]})]}),p.jsx(AG,{})]}),p.jsx("div",{className:"tl-canvas__in-front",onPointerDown:e.markEventAsHandled,onPointerUp:e.markEventAsHandled,onTouchStart:e.markEventAsHandled,onTouchEnd:e.markEventAsHandled,children:p.jsx(dG,{})}),p.jsx(nG,{})]})}function dG(){const{InFrontOfTheCanvas:n}=xt();return n?p.jsx(n,{}):null}function uG(){const n=K(),e=W("gridSize",()=>n.getDocumentSettings().gridSize,[n]),{x:t,y:r,z:s}=W("camera",()=>n.getCamera(),[n]),o=W("isGridMode",()=>n.getInstanceState().isGridMode,[n]),{Grid:i}=xt();return i&&o?p.jsx(i,{x:t,y:r,z:s,size:e}):null}function hG(){const n=K(),e=W("scribbles",()=>n.getInstanceState().scribbles,[n]),t=W("zoomLevel",()=>n.getEfficientZoomLevel(),[n]),{Scribble:r}=xt();return r&&e.length?e.map(s=>p.jsx(r,{className:"tl-user-scribble",scribble:s,zoom:t},s.id)):null}function pG(){const n=K(),e=W("brush",()=>n.getInstanceState().brush,[n]),{Brush:t}=xt();return t&&e?p.jsx(t,{className:"tl-user-brush",brush:e}):null}function fG(){const n=K(),e=W("zoomBrush",()=>n.getInstanceState().zoomBrush,[n]),{ZoomBrush:t}=xt();return t&&e?p.jsx(t,{className:"tl-user-brush tl-zoom-brush",brush:e}):null}function gG(){const n=K(),e=W("snapLines",()=>n.snaps.getIndicators(),[n]),t=W("zoomLevel",()=>n.getEfficientZoomLevel(),[n]),{SnapIndicator:r}=xt();return r&&e.length>0?e.map(s=>p.jsx(r,{className:"tl-user-snapline",line:s,zoom:t},s.id)):null}function mG(){const n=K(),e=W("handles shapeIdWithHandles",()=>{const{isReadonly:t,isChangingStyle:r}=n.getInstanceState();if(t||r)return!1;const s=n.getOnlySelectedShape();return!s||!n.getShapeHandles(s)?!1:s.id},[n]);return e?p.jsx(yG,{shapeId:e}):null}function yG({shapeId:n}){const e=K(),{Handles:t}=xt(),r=W("zoomLevel",()=>e.getEfficientZoomLevel(),[e]),s=W("coarse pointer",()=>e.getInstanceState().isCoarsePointer,[e]),o=W("handles transform",()=>e.getShapePageTransform(n),[e,n]),i=W("handles",()=>{const l=e.getShapeHandles(n);if(!l)return null;const c=(s?e.options.coarseHandleRadius:e.options.handleRadius)/r*2;return l.filter(u=>u.type!=="virtual"||!l.some(d=>d!==u&&d.type==="vertex"&&C.Dist(u,d)<c)).sort(u=>u.type==="vertex"?1:-1)},[e,r,s,n]),a=W("isHidden",()=>e.isShapeHidden(n),[e,n]);return!t||!i||!o||a?null:p.jsx(t,{children:p.jsx("g",{transform:Q.toCssString(o),children:i.map(l=>p.jsx(SG,{shapeId:n,handle:l,zoom:r,isCoarse:s},l.id))})})}function SG({shapeId:n,handle:e,zoom:t,isCoarse:r}){const s=VV(n,e.id),{Handle:o}=xt();return o?p.jsx("g",{role:"button","aria-label":e.label||"handle",transform:`translate(${e.x}, ${e.y})`,...s,children:p.jsx(o,{shapeId:n,handle:e,zoom:t,isCoarse:r})}):null}function xG(){const{Overlays:n}=xt();return n?p.jsx("div",{className:"tl-custom-overlays tl-overlays__item",children:p.jsx(n,{})}):null}function bG(){const n=K();return W("rendering shapes",()=>n.getRenderingShapes(),[n]).map(t=>p.jsxs(x.Fragment,{children:[p.jsx(l2,{...t}),p.jsx(EG,{id:t.id,mode:"iframe"})]},t.id+"_fragment"))}function wG(){const n=K(),e=x.useRef(new Set);return Va("reflow for culled shapes",()=>{const t=n.getCulledShapes();if(e.current===t)return;e.current=t;const r=document.getElementsByClassName("tl-canvas");r.length!==0&&r[0].offsetHeight},[n]),null}function vG(){const n=K(),{updateCulling:e}=a2();return Va("update shape culling",()=>{const t=n.getCulledShapes();e(t)},[n,e]),null}function CG(){const n=K(),e=W("rendering shapes",()=>n.getRenderingShapes(),[n]);return p.jsxs(s9,{children:[e.map(t=>p.jsx(l2,{...t},t.id+"_shape")),p.jsx(vG,{}),dt.isSafari&&p.jsx(wG,{})]})}function PG(){const n=K(),{ShapeIndicator:e}=xt(),t=W("hinting shape ids without canvas indicator",()=>ny(n.getHintingShapeIds()).filter(r=>{const s=n.getShape(r);return s?n.getShapeUtil(s).useLegacyIndicator():!1}),[n]);return!t.length||!e?null:t.map(r=>p.jsx(e,{className:"tl-user-indicator__hint",shapeId:r},r+"_hinting"))}function TG(){return p.jsxs("g",{id:fo("cursor"),children:[p.jsxs("g",{fill:"rgba(0,0,0,.2)",transform:"translate(-11,-11)",children:[p.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),p.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),p.jsxs("g",{fill:"white",transform:"translate(-12,-12)",children:[p.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),p.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),p.jsxs("g",{fill:"currentColor",transform:"translate(-12,-12)",children:[p.jsx("path",{d:"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z"}),p.jsx("path",{d:"m13 10.814v11.188l2.969-2.866.428-.139h4.768z"})]})]})}function IG(){const n=fo("cursor_hint");return p.jsx("path",{id:n,fill:"currentColor",d:"M -2,-5 2,0 -2,5 Z"})}function EG({id:n,mode:e}){const t=K(),[r,s]=x.useState(null),o=W("is in root",()=>{const i=t.getShape(n);return(i==null?void 0:i.parentId)===t.getCurrentPageId()},[t,n]);return x.useEffect(()=>{if(!o)return;let i=null;const a=Mr("shape to svg",async()=>{const l=Math.random();i=l;const u=t.isShapeOfType(n,"frame")?0:10;let d=t.getShapePageBounds(n);if(!d)return;d=d.clone().expandBy(u);const h=await t.getSvgString([n],{padding:u});if(i!==l||!h)return;const f=`data:image/svg+xml;utf8,${encodeURIComponent(h.svg)}`;s({src:f,bounds:d})});return()=>{i=null,a()}},[t,n,o]),!o||!r?null:e==="iframe"?p.jsx("iframe",{src:r.src,width:r.bounds.width,height:r.bounds.height,referrerPolicy:"no-referrer",style:{position:"absolute",top:0,left:0,border:"none",transform:`translate(${r.bounds.x}px, ${r.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}}):p.jsx("img",{src:r.src,width:r.bounds.width,height:r.bounds.height,referrerPolicy:"no-referrer",style:{position:"absolute",top:0,left:0,transform:`translate(${r.bounds.x}px, ${r.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}})}function kG(){const n=K(),e=W("selection rotation",function(){return n.getSelectionRotation()},[n]),t=W("selection bounds",()=>n.getSelectionRotatedPageBounds(),[n]),{SelectionForeground:r}=xt();return!t||!r?null:p.jsx(r,{bounds:t,rotation:e})}function _G(){const n=K(),e=W("selection rotation",()=>n.getSelectionRotation(),[n]),t=W("selection bounds",()=>n.getSelectionRotatedPageBounds(),[n]),{SelectionBackground:r}=xt();return!t||!r?null:p.jsx(r,{bounds:t,rotation:e})}function MG(){const{OnTheCanvas:n}=xt();return n?p.jsx(n,{}):null}function AG(){const n=K(),e=W("camera state",()=>n.getCameraState(),[n]);return p.jsx("div",{className:xe("tl-hit-test-blocker",{"tl-hit-test-blocker__hidden":e==="idle"})})}function Jr({children:n,className:e="",...t}){return p.jsx("div",{...t,className:xe("tl-html-container",e),children:n})}class $f{constructor(e){this.editor=e}}E($f,"props"),E($f,"migrations"),E($f,"type");function ky(n,e,t={}){const{newPoint:r,handle:s,scaleX:o,scaleY:i}=e,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=t;let d=n.props.w*o,h=n.props.h*i;const f=new C(0,0);if(d>0){if(d<a){switch(s){case"top_left":case"left":case"bottom_left":{f.x=d-a;break}case"top":case"bottom":{f.x=(d-a)/2;break}default:f.x=0}d=a}}else if(f.x=d,d=-d,d<a){switch(s){case"top_left":case"left":case"bottom_left":{f.x=-d;break}default:f.x=-a}d=a}if(h>0){if(h<c){switch(s){case"top_left":case"top":case"top_right":{f.y=h-c;break}case"right":case"left":{f.y=(h-c)/2;break}default:f.y=0}h=c}}else if(f.y=h,h=-h,h<c){switch(s){case"top_left":case"top":case"top_right":{f.y=-h;break}default:f.y=-c}h=c}const{x:g,y:m}=f.rot(n.rotation).add(r);return{...n,x:g,y:m,props:{w:Math.min(l,d),h:Math.min(u,h)}}}class Gs extends go{getGeometry(e){return new bo({width:e.props.w,height:e.props.h,isFilled:!0})}onResize(e,t){return ky(e,t)}getHandleSnapGeometry(e){return{points:this.getGeometry(e).bounds.cornersAndCenter}}getInterpolatedProps(e,t,r){return{...t.props,w:Ue(e.props.w,t.props.w,r),h:Ue(e.props.h,t.props.h,r)}}}function LR(n,{initialBounds:e,scaleX:t,scaleY:r,newPoint:s,handle:o}){let i;switch(o){case"bottom_left":case"bottom_right":case"top_left":case"top_right":{i=Math.max(.01,Math.max(Math.abs(t),Math.abs(r)));break}case"left":case"right":{i=Math.max(.01,Math.abs(t));break}case"bottom":case"top":{i=Math.max(.01,Math.abs(r));break}default:throw it(o)}const a=new C(0,0);t<0&&(a.x=-(e.width*i)),r<0&&(a.y=-(e.height*i));const{x:l,y:c}=C.Add(s,a.rot(n.rotation));return{x:l,y:c,props:{scale:i*n.props.scale}}}var qb;let DG=(qb=class extends ve{onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onCancel(){this.editor.setCurrentTool("select")}},E(qb,"id","idle"),qb);var Zb;let OG=(Zb=class extends ve{onPointerMove(e){const{editor:t}=this;if(t.inputs.getIsDragging()){const r=t.inputs.getOriginPagePoint(),s=this.parent.shapeType,o=St(),i=t.markHistoryStoppingPoint(`creating_box:${o}`),a=ws(r,t);if(this.editor.createShapes([{id:o,type:s,x:a.x,y:a.y,props:{w:1,h:1}}]),!t.getShape(o)){this.cancel();return}t.select(o);const c=this.parent;this.editor.setCurrentTool("select.resizing",{...e,target:"selection",handle:"bottom_right",isCreating:!0,creatingMarkId:i,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:c.onCreate?u=>{var d;return(d=c.onCreate)==null?void 0:d.call(c,u)}:void 0})}}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.cancel()}complete(){const e=this.editor.inputs.getOriginPagePoint(),t=this.parent.shapeType,r=St();this.editor.markHistoryStoppingPoint(`creating_box:${r}`),this.editor.createShapes([{id:r,type:t,x:e.x,y:e.y}]);const s=this.editor.getShape(r);if(!s){this.cancel();return}let{w:o,h:i}=s.props;const a=new C(o/2,i/2),l=this.editor.getShapeParentTransform(s);l&&a.rot(-l.rotation());let c=1;this.editor.user.getIsDynamicResizeMode()&&(c=1/this.editor.getZoomLevel(),o*=c,i*=c,a.mul(c));const u=Ft(s),d=ws(new C(s.x-a.x,s.y-a.y),this.editor);u.x=d.x,u.y=d.y,u.props.w=o,u.props.h=i,"scale"in s.props&&(u.props.scale=c),this.editor.updateShape(u),this.editor.setSelectedShapes([r]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},E(Zb,"id","pointing"),Zb);function ws(n,e){const t=e.getInstanceState().isGridMode,r=e.getDocumentSettings().gridSize;return t?n.clone().snapToGrid(r):n.clone()}class Kw extends ve{static children(){return[DG,OG]}}E(Kw,"id","box"),E(Kw,"initial","idle");function RG(n,e,t){const r=x.useRef(!1),s=x.useCallback(i=>{r.current=i,i?Tr.addOpenMenu(n):Tr.deleteOpenMenu(n),e==null||e(i)},[n,e]),o=W("is menu open",()=>Tr.getOpenMenus().includes(n),[n]);return x.useEffect(()=>(r.current&&(t==null||t("open-menu"),Tr.addOpenMenu(n)),()=>{r.current&&(Tr.deleteOpenMenu(n),Tr.getOpenMenus().forEach(i=>{i.startsWith(n)&&(t==null||t("close-menu"),Tr.deleteOpenMenu(i))}),r.current=!1)}),[n,t]),[o,s]}function qh(n){const e=K();return W("isEditing",()=>e.getEditingShapeId()===n,[e,n])}function LG(n){if(!n)throw Error("usePassThroughWheelEvents must be passed a ref");const e=sn(),t=Xt();x.useEffect(()=>{function r(o){if(!(t!=null&&t.getInstanceState().isFocused)||o.isSpecialRedispatchedEvent)return;je(o);const i=e.querySelector(".tl-canvas");if(!i)return;const a=new PointerEvent(o.type,o);a.isSpecialRedispatchedEvent=!0,i.dispatchEvent(a)}const s=n.current;if(s)return s.addEventListener("mouseover",r,{passive:!1}),()=>{s.removeEventListener("mouseover",r)}},[e,t,n])}function Oo(n){const e=K();return x.useMemo(function(){const s=c=>{if(e.wasEventAlreadyHandled(c))return;if(c.button===Kv){e.dispatch({type:"pointer",target:"selection",handle:n,name:"right_click",...$n(e,c)});return}if(c.button!==0)return;const u=zg(c.currentTarget);function d(){u.removeEventListener("pointerup",d),Fh(u,c)}Nh(u,c),u.addEventListener("pointerup",d),e.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:n,...$n(e,c)}),e.markEventAsHandled(c)};let o,i;function a(c){e.wasEventAlreadyHandled(c)||c.button===0&&(c.clientX===o&&c.clientY===i||(o=c.clientX,i=c.clientY,e.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:n,...$n(e,c)})))}return{onPointerDown:s,onPointerMove:a,onPointerUp:c=>{e.wasEventAlreadyHandled(c)||c.button===0&&e.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:n,...$n(e,c)})}}},[e,n])}function jG(n){const[e,t]=x.useState(()=>({store:Kg(n),opts:n}));if(!V_(e.opts,n)){const r={store:Kg(n),opts:n};return t(r),r.store}return e.store}const NG=20,FG=8;function _y(n,e=NG){return Math.max(FG,Math.ceil(n/e))}class jR extends Ya{constructor(t){super({...t,isFilled:!1,isClosed:!1});E(this,"_center");E(this,"_radius");E(this,"_start");E(this,"_end");E(this,"_largeArcFlag");E(this,"_sweepFlag");E(this,"_measure");E(this,"_angleStart");E(this,"_angleEnd");const{center:r,sweepFlag:s,largeArcFlag:o,start:i,end:a}=t;if(i.equals(a))throw Error("Arc must have different start and end points.");this._angleStart=C.Angle(r,i),this._angleEnd=C.Angle(r,a),this._radius=C.Dist(r,i),this._measure=FU(this._angleStart,this._angleEnd,s,o),this._start=i,this._end=a,this._sweepFlag=s,this._largeArcFlag=o,this._center=r}nearestPoint(t){const{_center:r,_measure:s,_radius:o,_angleEnd:i,_angleStart:a,_start:l,_end:c}=this,u=mT(s,a,i,r.angle(t));if(u<=0)return l;if(u>=1)return c;const d=C.Sub(t,r).uni().mul(o).add(r);let h,f=1/0,g;for(const m of[l,c,d])g=C.Dist2(t,m),g<f&&(h=m,f=g);if(!h)throw Error("nearest point not found");return h}hitTestLineSegment(t,r){const{_center:s,_radius:o,_measure:i,_angleStart:a,_angleEnd:l}=this,c=zh(t,r,s,o);return c===null?!1:c.some(u=>{const d=mT(i,a,l,s.angle(u));return d>=0&&d<=1})}getVertices(){const{_center:t,_measure:r,length:s,_radius:o,_angleStart:i}=this,a=[];for(let l=0,c=_y(Math.abs(s));l<c+1;l++){const u=l/c*r,d=i+u;a.push(Uv(t,o,d))}return a}getSvgPathData(t=!0){const{_start:r,_end:s,_radius:o,_largeArcFlag:i,_sweepFlag:a}=this;return`${t?`M${r.toFixed()}`:""} A${o} ${o} 0 ${i} ${a} ${s.toFixed()}`}getLength(){return Math.abs(this._measure*this._radius)}}class Gg extends Ya{constructor(t){super({isClosed:!0,...t});E(this,"_center");E(this,"_radius");E(this,"_x");E(this,"_y");this.config=t;const{x:r=0,y:s=0,radius:o}=t;this._x=r,this._y=s,this._center=new C(o+r,o+s),this._radius=o}getBounds(){return new J(this._x,this._y,this._radius*2,this._radius*2)}getVertices(){const{_center:t,_radius:r}=this,s=vt*r,o=[];for(let i=0,a=_y(s);i<a;i++){const l=i/a*vt;o.push(Uv(t,r,l))}return o}nearestPoint(t){const{_center:r,_radius:s}=this;return r.equals(t)?C.AddXY(r,s,0):C.Sub(t,r).uni().mul(s).add(r)}hitTestLineSegment(t,r,s=0){const{_center:o,_radius:i}=this;return zh(t,r,o,i+s)!==null}getSvgPathData(){const{_center:t,_radius:r}=this;return`M${t.x+r},${t.y} a${r},${r} 0 1,0 ${r*2},0a${r},${r} 0 1,0 -${r*2},0`}}class h1 extends $h{constructor(t){const{start:r,cp1:s,cp2:o,end:i}=t;super({...t,points:[r,i]});E(this,"_a");E(this,"_b");E(this,"_c");E(this,"_d");E(this,"_resolution");this._a=r,this._b=s,this._c=o,this._d=i,this._resolution=t.resolution??10}getVertices(){const t=[],{_a:r,_b:s,_c:o,_d:i}=this;for(let a=0,l=this._resolution;a<=l;a++){const c=a/l;t.push(new C((1-c)*(1-c)*(1-c)*r.x+3*((1-c)*(1-c))*c*s.x+3*(1-c)*(c*c)*o.x+c*c*c*i.x,(1-c)*(1-c)*(1-c)*r.y+3*((1-c)*(1-c))*c*s.y+3*(1-c)*(c*c)*o.y+c*c*c*i.y))}return t}nearestPoint(t){let r,s=1/0,o,i;for(const a of this.segments)i=a.nearestPoint(t),o=C.Dist2(i,t),o<s&&(r=i,s=o);if(!r)throw Error("nearest point not found");return r}getSvgPathData(t=!0){const{_a:r,_b:s,_c:o,_d:i}=this;return`${t?`M ${r.toFixed()} `:""} C${s.toFixed()} ${o.toFixed()} ${i.toFixed()}`}static GetAtT(t,r){const{_a:s,_b:o,_c:i,_d:a}=t;return new C((1-r)*(1-r)*(1-r)*s.x+3*((1-r)*(1-r))*r*o.x+3*(1-r)*(r*r)*i.x+r*r*r*a.x,(1-r)*(1-r)*(1-r)*s.y+3*((1-r)*(1-r))*r*o.y+3*(1-r)*(r*r)*i.y+r*r*r*a.y)}getLength(t,r=32){let s,o=this._a,i=0;for(let a=1;a<=r;a++)s=h1.GetAtT(this,a/r),i+=C.Dist(o,s),o=s;return i}}class BG extends Ya{constructor(t){super({...t,isClosed:!0});E(this,"_w");E(this,"_h");E(this,"_edges");this.config=t;const{width:r,height:s}=t;this._w=r,this._h=s}get edges(){if(!this._edges){const{vertices:t}=this;this._edges=[];for(let r=0,s=t.length;r<s;r++){const o=t[r],i=t[(r+1)%s];this._edges.push(new Qc({start:o,end:i}))}}return this._edges}getVertices(){const t=Math.max(1,this._w),r=Math.max(1,this._h),s=t/2,o=r/2,i=Math.pow(s-o,2)/Math.pow(s+o,2),a=ht*(s+o)*(1+3*i/(10+Math.sqrt(4-3*i))),l=_y(a),c=vt/l,u=Math.cos(c),d=Math.sin(c);let h=0,f=1,g=0,m=1;const y=Array(l);for(let S=0;S<l;S++)y[S]=new C(Fe(s+s*f,0,t),Fe(o+o*h,0,r)),g=d*f+u*h,m=u*f-d*h,h=g,f=m;return y}nearestPoint(t){let r,s=1/0,o,i;for(const a of this.edges)i=a.nearestPoint(t),o=C.Dist2(i,t),o<s&&(r=i,s=o);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(t,r){return this.edges.some(s=>s.hitTestLineSegment(t,r))}getBounds(){return new J(0,0,this._w,this._h)}getLength(){const{_w:t,_h:r}=this,s=t/2,o=r/2,i=Math.max(0,s),a=Math.max(0,o);return RU(i,a)}getSvgPathData(t=!1){const{_w:r,_h:s}=this,o=r/2,i=s/2,a=Math.max(0,o),l=Math.max(0,i);return`${t?`M${o-a},${i}`:""} a${a},${l},0,1,1,${a*2},0a${a},${l},0,1,1,-${a*2},0`}}function mt(n,e,t){var a;const r=new Set;for(const l of e){const c=n.getShape(l);if(!c)continue;r.add(c);const u=n.getShape(c.parentId);u&&r.add(u)}const s=new Map;for(const l of r){const c=n.getSortedChildIdsForParent(l);if(t!=null&&t.filter&&!t.filter(l))s.set(l,c);else{const u=zG(n,l.id,c);u.length<c.length&&s.set(l,c.filter(d=>!u.includes(d)))}}const o=n.getCurrentPageShapesSorted().map(l=>l.id),i={};for(const[l,c]of s){const u=Le(c.map(f=>n.getShape(f))),{reparenting:d,remainingShapesToReparent:h}=$G(n,u,(f,g)=>t!=null&&t.filter&&!t.filter(g)?!1:g.id!==l.id&&o.indexOf(g.id)<o.indexOf(f.id));if(d.forEach((f,g)=>{f.length!==0&&(i[g]||(i[g]={parentId:g,shapeIds:[]}),i[g].shapeIds.push(...f.map(m=>m.id)))}),h.size>0){const f=((a=n.findShapeAncestor(l,g=>n.isShapeOfType(g,"group")))==null?void 0:a.id)??n.getCurrentPageId();h.forEach(g=>{if(!i[f]){let m;const y=n.getSortedChildIdsForParent(f),S=y.indexOf(l.id);if(S>-1){const b=y[S+1],w=b?n.getShape(b).index:Ns(l.index);m=Xc(l.index,w)}i[f]={parentId:f,shapeIds:[],index:m}}i[f].shapeIds.push(g.id)})}}n.run(()=>{Object.values(i).forEach(({parentId:l,shapeIds:c,index:u})=>{c.length!==0&&(c.sort((d,h)=>o.indexOf(d)<o.indexOf(h)?-1:1),n.reparentShapes(c,l,u))})})}function zG(n,e,t){var h,f;if(t.length===0)return Yt;const r=n.getShapePageBounds(e);if(!r)return Yt;const s=n.getShapeGeometry(e),i=n.getShapePageTransform(e).applyToPoints(s.vertices),a=n.getShape(e);if(!a)return Yt;const l=n.getShapePageTransform(e),c=(f=(h=n.getShapeUtil(a.type)).getClipPath)==null?void 0:f.call(h,a),u=c?l.applyToPoints(c):void 0,d=u?Hg(u,i):i;return d?t.filter(g=>{const m=n.getShapePageBounds(g);if(!m||!r.includes(m))return!1;const y=n.getShapePageTransform(g).clone().invert().applyToPoints(d);return n.getShapeGeometry(g).overlapsPolygon(y)}):Yt}function $G(n,e,t){var c,u,d,h;const r=new Set(e),s=new Set;for(const f of e){const g=n.getShapeParent(f);g&&n.isShapeOfType(g,"group")&&(s.has(g)||s.add(g))}for(const f of s){const g=Le(n.getSortedChildIdsForParent(f).map(m=>n.getShape(m)));for(const m of g)r.delete(m);r.add(f)}const o=new Map,i=new Map,a=new Set(r),l=n.getCurrentPageShapesSorted().filter(f=>{var g,m;return((m=(g=n.getShapeUtil(f)).canReceiveNewChildrenOfType)==null?void 0:m.call(g,f,f.type))&&!a.has(f)});e:for(let f=l.length-1;f>=0;f--){const g=l[f],m=(c=n.findShapeAncestor(g,T=>n.isShapeOfType(T,"group")))==null?void 0:c.id,y=n.getShapeGeometry(g),S=n.getShapePageTransform(g),b=n.getShapeMask(g),w=S.applyToPoints(y.vertices),v=b?Hg(b,w):w;if(!v)continue e;const P=[];t:for(const T of a){if(g.id===T.id||t&&!t(T,g)||(o.has(T.id)||o.set(T.id,(u=n.findShapeAncestor(T,A=>n.isShapeOfType(A,"group")))==null?void 0:u.id),o.get(T.id)!==m)||n.findShapeAncestor(g,A=>T.id===A.id))continue t;const k=n.getShapePageTransform(T).clone().invert().applyToPoints(v);if(n.getShapeGeometry(T).overlapsPolygon(k)){if(!((h=(d=n.getShapeUtil(g)).canReceiveNewChildrenOfType)!=null&&h.call(d,g,T.type)))continue t;T.parentId!==g.id&&P.push(T),a.delete(T);continue t}}P.length&&i.set(g.id,P)}return{reparenting:i,remainingShapesToReparent:a}}function Rn(n){this.content=n}Rn.prototype={constructor:Rn,find:function(n){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===n)return e;return-1},get:function(n){var e=this.find(n);return e==-1?void 0:this.content[e+1]},update:function(n,e,t){var r=t&&t!=n?this.remove(t):this,s=r.find(n),o=r.content.slice();return s==-1?o.push(t||n,e):(o[s+1]=e,t&&(o[s]=t)),new Rn(o)},remove:function(n){var e=this.find(n);if(e==-1)return this;var t=this.content.slice();return t.splice(e,2),new Rn(t)},addToStart:function(n,e){return new Rn([n,e].concat(this.remove(n).content))},addToEnd:function(n,e){var t=this.remove(n).content.slice();return t.push(n,e),new Rn(t)},addBefore:function(n,e,t){var r=this.remove(e),s=r.content.slice(),o=r.find(n);return s.splice(o==-1?s.length:o,0,e,t),new Rn(s)},forEach:function(n){for(var e=0;e<this.content.length;e+=2)n(this.content[e],this.content[e+1])},prepend:function(n){return n=Rn.from(n),n.size?new Rn(n.content.concat(this.subtract(n).content)):this},append:function(n){return n=Rn.from(n),n.size?new Rn(this.subtract(n).content.concat(n.content)):this},subtract:function(n){var e=this;n=Rn.from(n);for(var t=0;t<n.content.length;t+=2)e=e.remove(n.content[t]);return e},toObject:function(){var n={};return this.forEach(function(e,t){n[e]=t}),n},get size(){return this.content.length>>1}};Rn.from=function(n){if(n instanceof Rn)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new Rn(e)};function NR(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let s=n.child(r),o=e.child(r);if(s==o){t+=s.nodeSize;continue}if(!s.sameMarkup(o))return t;if(s.isText&&s.text!=o.text){for(let i=0;s.text[i]==o.text[i];i++)t++;return t}if(s.content.size||o.content.size){let i=NR(s.content,o.content,t+1);if(i!=null)return i}t+=s.nodeSize}}function FR(n,e,t,r){for(let s=n.childCount,o=e.childCount;;){if(s==0||o==0)return s==o?null:{a:t,b:r};let i=n.child(--s),a=e.child(--o),l=i.nodeSize;if(i==a){t-=l,r-=l;continue}if(!i.sameMarkup(a))return{a:t,b:r};if(i.isText&&i.text!=a.text){let c=0,u=Math.min(i.text.length,a.text.length);for(;c<u&&i.text[i.text.length-c-1]==a.text[a.text.length-c-1];)c++,t--,r--;return{a:t,b:r}}if(i.content.size||a.content.size){let c=FR(i.content,a.content,t-1,r-1);if(c)return c}t-=l,r-=l}}class ne{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;r<e.length;r++)this.size+=e[r].nodeSize}nodesBetween(e,t,r,s=0,o){for(let i=0,a=0;a<t;i++){let l=this.content[i],c=a+l.nodeSize;if(c>e&&r(l,s+a,o||null,i)!==!1&&l.content.size){let u=a+1;l.nodesBetween(Math.max(0,e-u),Math.min(l.content.size,t-u),r,s+u)}a=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,s){let o="",i=!0;return this.nodesBetween(e,t,(a,l)=>{let c=a.isText?a.text.slice(Math.max(e,l)-l,t-l):a.isLeaf?s?typeof s=="function"?s(a):s:a.type.spec.leafText?a.type.spec.leafText(a):"":"";a.isBlock&&(a.isLeaf&&c||a.isTextblock)&&r&&(i?i=!1:o+=r),o+=c},0),o}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,s=this.content.slice(),o=0;for(t.isText&&t.sameMarkup(r)&&(s[s.length-1]=t.withText(t.text+r.text),o=1);o<e.content.length;o++)s.push(e.content[o]);return new ne(s,this.size+e.size)}cut(e,t=this.size){if(e==0&&t==this.size)return this;let r=[],s=0;if(t>e)for(let o=0,i=0;i<t;o++){let a=this.content[o],l=i+a.nodeSize;l>e&&((i<e||l>t)&&(a.isText?a=a.cut(Math.max(0,e-i),Math.min(a.text.length,t-i)):a=a.cut(Math.max(0,e-i-1),Math.min(a.content.size,t-i-1))),r.push(a),s+=a.nodeSize),i=l}return new ne(r,s)}cutByIndex(e,t){return e==t?ne.empty:e==0&&t==this.content.length?this:new ne(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let s=this.content.slice(),o=this.size+t.nodeSize-r.nodeSize;return s[e]=t,new ne(s,o)}addToStart(e){return new ne([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new ne(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;t<this.content.length;t++)if(!this.content[t].eq(e.content[t]))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(e){let t=this.content[e];if(!t)throw new RangeError("Index "+e+" out of range for "+this);return t}maybeChild(e){return this.content[e]||null}forEach(e){for(let t=0,r=0;t<this.content.length;t++){let s=this.content[t];e(s,r,t),r+=s.nodeSize}}findDiffStart(e,t=0){return NR(this,e,t)}findDiffEnd(e,t=this.size,r=e.size){return FR(this,e,t,r)}findIndex(e){if(e==0)return qp(0,e);if(e==this.size)return qp(this.content.length,e);if(e>this.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let s=this.child(t),o=r+s.nodeSize;if(o>=e)return o==e?qp(t+1,o):qp(t,r);r=o}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return ne.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return new ne(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return ne.empty;let t,r=0;for(let s=0;s<e.length;s++){let o=e[s];r+=o.nodeSize,s&&o.isText&&e[s-1].sameMarkup(o)?(t||(t=e.slice(0,s)),t[t.length-1]=o.withText(t[t.length-1].text+o.text)):t&&t.push(o)}return new ne(t||e,r)}static from(e){if(!e)return ne.empty;if(e instanceof ne)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new ne([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}ne.empty=new ne([],0);const qx={index:0,offset:0};function qp(n,e){return qx.index=n,qx.offset=e,qx}function Yg(n,e){if(n===e)return!0;if(!(n&&typeof n=="object")||!(e&&typeof e=="object"))return!1;let t=Array.isArray(n);if(Array.isArray(e)!=t)return!1;if(t){if(n.length!=e.length)return!1;for(let r=0;r<n.length;r++)if(!Yg(n[r],e[r]))return!1}else{for(let r in n)if(!(r in e)||!Yg(n[r],e[r]))return!1;for(let r in e)if(!(r in n))return!1}return!0}let wt=class Ww{constructor(e,t){this.type=e,this.attrs=t}addToSet(e){let t,r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(this.eq(o))return e;if(this.type.excludes(o.type))t||(t=e.slice(0,s));else{if(o.type.excludes(this.type))return e;!r&&o.type.rank>this.type.rank&&(t||(t=e.slice(0,s)),t.push(this),r=!0),t&&t.push(o)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return e.slice(0,t).concat(e.slice(t+1));return e}isInSet(e){for(let t=0;t<e.length;t++)if(this.eq(e[t]))return!0;return!1}eq(e){return this==e||this.type==e.type&&Yg(this.attrs,e.attrs)}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Mark.fromJSON");let r=e.marks[t.type];if(!r)throw new RangeError(`There is no mark type ${t.type} in this schema`);let s=r.create(t.attrs);return r.checkAttrs(s.attrs),s}static sameSet(e,t){if(e==t)return!0;if(e.length!=t.length)return!1;for(let r=0;r<e.length;r++)if(!e[r].eq(t[r]))return!1;return!0}static setFrom(e){if(!e||Array.isArray(e)&&e.length==0)return Ww.none;if(e instanceof Ww)return[e];let t=e.slice();return t.sort((r,s)=>r.type.rank-s.type.rank),t}};wt.none=[];class Xg extends Error{}class ye{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=zR(this.content,e+this.openStart,t);return r&&new ye(r,this.openStart,this.openEnd)}removeBetween(e,t){return new ye(BR(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return ye.empty;let r=t.openStart||0,s=t.openEnd||0;if(typeof r!="number"||typeof s!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ye(ne.fromJSON(e,t.content),r,s)}static maxOpen(e,t=!0){let r=0,s=0;for(let o=e.firstChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=e.lastChild;o&&!o.isLeaf&&(t||!o.type.spec.isolating);o=o.lastChild)s++;return new ye(e,r,s)}}ye.empty=new ye(ne.empty,0,0);function BR(n,e,t){let{index:r,offset:s}=n.findIndex(e),o=n.maybeChild(r),{index:i,offset:a}=n.findIndex(t);if(s==e||o.isText){if(a!=t&&!n.child(i).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=i)throw new RangeError("Removing non-flat range");return n.replaceChild(r,o.copy(BR(o.content,e-s-1,t-s-1)))}function zR(n,e,t,r){let{index:s,offset:o}=n.findIndex(e),i=n.maybeChild(s);if(o==e||i.isText)return r&&!r.canReplace(s,s,t)?null:n.cut(0,e).append(t).append(n.cut(e));let a=zR(i.content,e-o-1,t,i);return a&&n.replaceChild(s,i.copy(a))}function HG(n,e,t){if(t.openStart>n.depth)throw new Xg("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new Xg("Inconsistent open depths");return $R(n,e,t,0)}function $R(n,e,t,r){let s=n.index(r),o=n.node(r);if(s==e.index(r)&&r<n.depth-t.openStart){let i=$R(n,e,t,r+1);return o.copy(o.content.replaceChild(s,i))}else if(t.content.size)if(!t.openStart&&!t.openEnd&&n.depth==r&&e.depth==r){let i=n.parent,a=i.content;return Cl(i,a.cut(0,n.parentOffset).append(t.content).append(a.cut(e.parentOffset)))}else{let{start:i,end:a}=UG(t,n);return Cl(o,UR(n,i,a,e,r))}else return Cl(o,qg(n,e,r))}function HR(n,e){if(!e.type.compatibleContent(n.type))throw new Xg("Cannot join "+e.type.name+" onto "+n.type.name)}function Vw(n,e,t){let r=n.node(t);return HR(r,e.node(t)),r}function vl(n,e){let t=e.length-1;t>=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function Nu(n,e,t,r){let s=(e||n).node(t),o=0,i=e?e.index(t):s.childCount;n&&(o=n.index(t),n.depth>t?o++:n.textOffset&&(vl(n.nodeAfter,r),o++));for(let a=o;a<i;a++)vl(s.child(a),r);e&&e.depth==t&&e.textOffset&&vl(e.nodeBefore,r)}function Cl(n,e){return n.type.checkContent(e),n.copy(e)}function UR(n,e,t,r,s){let o=n.depth>s&&Vw(n,e,s+1),i=r.depth>s&&Vw(t,r,s+1),a=[];return Nu(null,n,s,a),o&&i&&e.index(s)==t.index(s)?(HR(o,i),vl(Cl(o,UR(n,e,t,r,s+1)),a)):(o&&vl(Cl(o,qg(n,e,s+1)),a),Nu(e,t,s,a),i&&vl(Cl(i,qg(t,r,s+1)),a)),Nu(r,null,s,a),new ne(a)}function qg(n,e,t){let r=[];if(Nu(null,n,t,r),n.depth>t){let s=Vw(n,e,t+1);vl(Cl(s,qg(n,e,t+1)),r)}return Nu(e,null,t,r),new ne(r)}function UG(n,e){let t=e.depth-n.openStart,s=e.node(t).copy(n.content);for(let o=t-1;o>=0;o--)s=e.node(o).copy(ne.from(s));return{start:s.resolveNoCache(n.openStart+t),end:s.resolveNoCache(s.content.size-n.openEnd-t)}}class lh{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],s=e.child(t);return r?e.child(t).cut(r):s}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],s=t==0?0:this.path[t*3-1]+1;for(let o=0;o<e;o++)s+=r.child(o).nodeSize;return s}marks(){let e=this.parent,t=this.index();if(e.content.size==0)return wt.none;if(this.textOffset)return e.child(t).marks;let r=e.maybeChild(t-1),s=e.maybeChild(t);if(!r){let a=r;r=s,s=a}let o=r.marks;for(var i=0;i<o.length;i++)o[i].type.spec.inclusive===!1&&(!s||!o[i].isInSet(s.marks))&&(o=o[i--].removeFromSet(o));return o}marksAcross(e){let t=this.parent.maybeChild(this.index());if(!t||!t.isInline)return null;let r=t.marks,s=e.parent.maybeChild(e.index());for(var o=0;o<r.length;o++)r[o].type.spec.inclusive===!1&&(!s||!r[o].isInSet(s.marks))&&(r=r[o--].removeFromSet(r));return r}sharedDepth(e){for(let t=this.depth;t>0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos<this.pos)return e.blockRange(this);for(let r=this.depth-(this.parent.inlineContent||this.pos==e.pos?1:0);r>=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Zg(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos<this.pos?e:this}toString(){let e="";for(let t=1;t<=this.depth;t++)e+=(e?"/":"")+this.node(t).type.name+"_"+this.index(t-1);return e+":"+this.parentOffset}static resolve(e,t){if(!(t>=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],s=0,o=t;for(let i=e;;){let{index:a,offset:l}=i.content.findIndex(o),c=o-l;if(r.push(i,a,s+l),!c||(i=i.child(a),i.isText))break;o=c-1,s+=l+1}return new lh(t,r,o)}static resolveCached(e,t){let r=gI.get(e);if(r)for(let o=0;o<r.elts.length;o++){let i=r.elts[o];if(i.pos==t)return i}else gI.set(e,r=new KG);let s=r.elts[r.i]=lh.resolve(e,t);return r.i=(r.i+1)%WG,s}}class KG{constructor(){this.elts=[],this.i=0}}const WG=12,gI=new WeakMap;class Zg{constructor(e,t,r){this.$from=e,this.$to=t,this.depth=r}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 VG=Object.create(null);let mo=class Gw{constructor(e,t,r,s=wt.none){this.type=e,this.attrs=t,this.marks=s,this.content=r||ne.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(e){return this.content.child(e)}maybeChild(e){return this.content.maybeChild(e)}forEach(e){this.content.forEach(e)}nodesBetween(e,t,r,s=0){this.content.nodesBetween(e,t,r,s,this)}descendants(e){this.nodesBetween(0,this.content.size,e)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(e,t,r,s){return this.content.textBetween(e,t,r,s)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(e){return this==e||this.sameMarkup(e)&&this.content.eq(e.content)}sameMarkup(e){return this.hasMarkup(e.type,e.attrs,e.marks)}hasMarkup(e,t,r){return this.type==e&&Yg(this.attrs,t||e.defaultAttrs||VG)&&wt.sameSet(this.marks,r||wt.none)}copy(e=null){return e==this.content?this:new Gw(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new Gw(this.type,this.attrs,this.content,e)}cut(e,t=this.content.size){return e==0&&t==this.content.size?this:this.copy(this.content.cut(e,t))}slice(e,t=this.content.size,r=!1){if(e==t)return ye.empty;let s=this.resolve(e),o=this.resolve(t),i=r?0:s.sharedDepth(t),a=s.start(i),c=s.node(i).content.cut(s.pos-a,o.pos-a);return new ye(c,s.depth-i,o.depth-i)}replace(e,t,r){return HG(this.resolve(e),this.resolve(t),r)}nodeAt(e){for(let t=this;;){let{index:r,offset:s}=t.content.findIndex(e);if(t=t.maybeChild(r),!t)return null;if(s==e||t.isText)return t;e-=s+1}}childAfter(e){let{index:t,offset:r}=this.content.findIndex(e);return{node:this.content.maybeChild(t),index:t,offset:r}}childBefore(e){if(e==0)return{node:null,index:0,offset:0};let{index:t,offset:r}=this.content.findIndex(e);if(r<e)return{node:this.content.child(t),index:t,offset:r};let s=this.content.child(t-1);return{node:s,index:t-1,offset:r-s.nodeSize}}resolve(e){return lh.resolveCached(this,e)}resolveNoCache(e){return lh.resolve(this,e)}rangeHasMark(e,t,r){let s=!1;return t>e&&this.nodesBetween(e,t,o=>(r.isInSet(o.marks)&&(s=!0),!s)),s}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),KR(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=ne.empty,s=0,o=r.childCount){let i=this.contentMatchAt(e).matchFragment(r,s,o),a=i&&i.matchFragment(this.content,t);if(!a||!a.validEnd)return!1;for(let l=s;l<o;l++)if(!this.type.allowsMarks(r.child(l).marks))return!1;return!0}canReplaceWith(e,t,r,s){if(s&&!this.type.allowsMarks(s))return!1;let o=this.contentMatchAt(e).matchType(r),i=o&&o.matchFragment(this.content,t);return i?i.validEnd:!1}canAppend(e){return e.content.size?this.canReplace(this.childCount,this.childCount,e.content):this.type.compatibleContent(e.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let e=wt.none;for(let t=0;t<this.marks.length;t++){let r=this.marks[t];r.type.checkAttrs(r.attrs),e=r.addToSet(e)}if(!wt.sameSet(e,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 e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let s=ne.fromJSON(e,t.content),o=e.nodeType(t.type).create(t.attrs,s,r);return o.type.checkAttrs(o.attrs),o}};mo.prototype.text=void 0;class Jg extends mo{constructor(e,t,r,s){if(super(e,t,null,s),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):KR(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Jg(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Jg(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function KR(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}class Al{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new GG(e,t);if(r.next==null)return Al.empty;let s=WR(r);r.next&&r.err("Unexpected trailing text");let o=eY(QG(s));return tY(o,r),o}matchType(e){for(let t=0;t<this.next.length;t++)if(this.next[t].type==e)return this.next[t].next;return null}matchFragment(e,t=0,r=e.childCount){let s=this;for(let o=t;s&&o<r;o++)s=s.matchType(e.child(o).type);return s}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let e=0;e<this.next.length;e++){let{type:t}=this.next[e];if(!(t.isText||t.hasRequiredAttrs()))return t}return null}compatible(e){for(let t=0;t<this.next.length;t++)for(let r=0;r<e.next.length;r++)if(this.next[t].type==e.next[r].type)return!0;return!1}fillBefore(e,t=!1,r=0){let s=[this];function o(i,a){let l=i.matchFragment(e,r);if(l&&(!t||l.validEnd))return ne.from(a.map(c=>c.createAndFill()));for(let c=0;c<i.next.length;c++){let{type:u,next:d}=i.next[c];if(!(u.isText||u.hasRequiredAttrs())&&s.indexOf(d)==-1){s.push(d);let h=o(d,a.concat(u));if(h)return h}}return null}return o(this,[])}findWrapping(e){for(let r=0;r<this.wrapCache.length;r+=2)if(this.wrapCache[r]==e)return this.wrapCache[r+1];let t=this.computeWrapping(e);return this.wrapCache.push(e,t),t}computeWrapping(e){let t=Object.create(null),r=[{match:this,type:null,via:null}];for(;r.length;){let s=r.shift(),o=s.match;if(o.matchType(e)){let i=[];for(let a=s;a.type;a=a.via)i.push(a.type);return i.reverse()}for(let i=0;i<o.next.length;i++){let{type:a,next:l}=o.next[i];!a.isLeaf&&!a.hasRequiredAttrs()&&!(a.name in t)&&(!s.type||l.validEnd)&&(r.push({match:a.contentMatch,type:a,via:s}),t[a.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(e){if(e>=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let s=0;s<r.next.length;s++)e.indexOf(r.next[s].next)==-1&&t(r.next[s].next)}return t(this),e.map((r,s)=>{let o=s+(r.validEnd?"*":" ")+" ";for(let i=0;i<r.next.length;i++)o+=(i?", ":"")+r.next[i].type.name+"->"+e.indexOf(r.next[i].next);return o}).join(`
195
+ `)}}Al.empty=new Al(!0);class GG{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function WR(n){let e=[];do e.push(YG(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function YG(n){let e=[];do e.push(XG(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function XG(n){let e=JG(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=qG(n,e);else break;return e}function mI(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function qG(n,e){let t=mI(n),r=t;return n.eat(",")&&(n.next!="}"?r=mI(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function ZG(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let s=[];for(let o in t){let i=t[o];i.isInGroup(e)&&s.push(i)}return s.length==0&&n.err("No node type or group '"+e+"' found"),s}function JG(n){if(n.eat("(")){let e=WR(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=ZG(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function QG(n){let e=[[]];return s(o(n,0),t()),e;function t(){return e.push([])-1}function r(i,a,l){let c={term:l,to:a};return e[i].push(c),c}function s(i,a){i.forEach(l=>l.to=a)}function o(i,a){if(i.type=="choice")return i.exprs.reduce((l,c)=>l.concat(o(c,a)),[]);if(i.type=="seq")for(let l=0;;l++){let c=o(i.exprs[l],a);if(l==i.exprs.length-1)return c;s(c,a=t())}else if(i.type=="star"){let l=t();return r(a,l),s(o(i.expr,l),l),[r(l)]}else if(i.type=="plus"){let l=t();return s(o(i.expr,a),l),s(o(i.expr,l),l),[r(l)]}else{if(i.type=="opt")return[r(a)].concat(o(i.expr,a));if(i.type=="range"){let l=a;for(let c=0;c<i.min;c++){let u=t();s(o(i.expr,l),u),l=u}if(i.max==-1)s(o(i.expr,l),l);else for(let c=i.min;c<i.max;c++){let u=t();r(l,u),s(o(i.expr,l),u),l=u}return[r(l)]}else{if(i.type=="name")return[r(a,void 0,i.value)];throw new Error("Unknown expr type")}}}}function VR(n,e){return e-n}function yI(n,e){let t=[];return r(e),t.sort(VR);function r(s){let o=n[s];if(o.length==1&&!o[0].term)return r(o[0].to);t.push(s);for(let i=0;i<o.length;i++){let{term:a,to:l}=o[i];!a&&t.indexOf(l)==-1&&r(l)}}}function eY(n){let e=Object.create(null);return t(yI(n,0));function t(r){let s=[];r.forEach(i=>{n[i].forEach(({term:a,to:l})=>{if(!a)return;let c;for(let u=0;u<s.length;u++)s[u][0]==a&&(c=s[u][1]);yI(n,l).forEach(u=>{c||s.push([a,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let o=e[r.join(",")]=new Al(r.indexOf(n.length-1)>-1);for(let i=0;i<s.length;i++){let a=s[i][1].sort(VR);o.next.push({type:s[i][0],next:e[a.join(",")]||t(a)})}return o}}function tY(n,e){for(let t=0,r=[n];t<r.length;t++){let s=r[t],o=!s.validEnd,i=[];for(let a=0;a<s.next.length;a++){let{type:l,next:c}=s.next[a];i.push(l.name),o&&!(l.isText||l.hasRequiredAttrs())&&(o=!1),r.indexOf(c)==-1&&r.push(c)}o&&e.err("Only non-generatable nodes ("+i.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}function GR(n){let e=Object.create(null);for(let t in n){let r=n[t];if(!r.hasDefault)return null;e[t]=r.default}return e}function YR(n,e){let t=Object.create(null);for(let r in n){let s=e&&e[r];if(s===void 0){let o=n[r];if(o.hasDefault)s=o.default;else throw new RangeError("No value supplied for attribute "+r)}t[r]=s}return t}function XR(n,e,t,r){for(let s in e)if(!(s in n))throw new RangeError(`Unsupported attribute ${s} for ${t} of type ${s}`);for(let s in n){let o=n[s];o.validate&&o.validate(e[s])}}function qR(n,e){let t=Object.create(null);if(e)for(let r in e)t[r]=new rY(n,r,e[r]);return t}let SI=class ZR{constructor(e,t,r){this.name=e,this.schema=t,this.spec=r,this.markSet=null,this.groups=r.group?r.group.split(" "):[],this.attrs=qR(e,r.attrs),this.defaultAttrs=GR(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(r.inline||e=="text"),this.isText=e=="text"}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==Al.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(e){return this.groups.indexOf(e)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:YR(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new mo(this,this.computeAttrs(e),ne.from(t),wt.setFrom(r))}createChecked(e=null,t,r){return t=ne.from(t),this.checkContent(t),new mo(this,this.computeAttrs(e),t,wt.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=ne.from(t),t.size){let i=this.contentMatch.fillBefore(t);if(!i)return null;t=i.append(t)}let s=this.contentMatch.matchFragment(t),o=s&&s.fillBefore(ne.empty,!0);return o?new mo(this,e,t.append(o),wt.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r<e.childCount;r++)if(!this.allowsMarks(e.child(r).marks))return!1;return!0}checkContent(e){if(!this.validContent(e))throw new RangeError(`Invalid content for node ${this.name}: ${e.toString().slice(0,50)}`)}checkAttrs(e){XR(this.attrs,e,"node",this.name)}allowsMarkType(e){return this.markSet==null||this.markSet.indexOf(e)>-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;t<e.length;t++)if(!this.allowsMarkType(e[t].type))return!1;return!0}allowedMarks(e){if(this.markSet==null)return e;let t;for(let r=0;r<e.length;r++)this.allowsMarkType(e[r].type)?t&&t.push(e[r]):t||(t=e.slice(0,r));return t?t.length?t:wt.none:e}static compile(e,t){let r=Object.create(null);e.forEach((o,i)=>r[o]=new ZR(o,t,i));let s=t.spec.topNode||"doc";if(!r[s])throw new RangeError("Schema is missing its top node type ('"+s+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let o in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function nY(n,e,t){let r=t.split("|");return s=>{let o=s===null?"null":typeof s;if(r.indexOf(o)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${o}`)}}class rY{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?nY(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class My{constructor(e,t,r,s){this.name=e,this.rank=t,this.schema=r,this.spec=s,this.attrs=qR(e,s.attrs),this.excluded=null;let o=GR(this.attrs);this.instance=o?new wt(this,o):null}create(e=null){return!e&&this.instance?this.instance:new wt(this,YR(this.attrs,e))}static compile(e,t){let r=Object.create(null),s=0;return e.forEach((o,i)=>r[o]=new My(o,s++,t,i)),r}removeFromSet(e){for(var t=0;t<e.length;t++)e[t].type==this&&(e=e.slice(0,t).concat(e.slice(t+1)),t--);return e}isInSet(e){for(let t=0;t<e.length;t++)if(e[t].type==this)return e[t]}checkAttrs(e){XR(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class JR{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let s in e)t[s]=e[s];t.nodes=Rn.from(e.nodes),t.marks=Rn.from(e.marks||{}),this.nodes=SI.compile(this.spec.nodes,this),this.marks=My.compile(this.spec.marks,this);let r=Object.create(null);for(let s in this.nodes){if(s in this.marks)throw new RangeError(s+" can not be both a node and a mark");let o=this.nodes[s],i=o.spec.content||"",a=o.spec.marks;if(o.contentMatch=r[i]||(r[i]=Al.parse(i,this.nodes)),o.inlineContent=o.contentMatch.inlineContent,o.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!o.isInline||!o.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=o}o.markSet=a=="_"?null:a?xI(this,a.split(" ")):a==""||!o.inlineContent?[]:null}for(let s in this.marks){let o=this.marks[s],i=o.spec.excludes;o.excluded=i==null?[o]:i==""?[]:xI(this,i.split(" "))}this.nodeFromJSON=s=>mo.fromJSON(this,s),this.markFromJSON=s=>wt.fromJSON(this,s),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,s){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof SI){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,s)}text(e,t){let r=this.nodes.text;return new Jg(r,r.defaultAttrs,e,wt.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function xI(n,e){let t=[];for(let r=0;r<e.length;r++){let s=e[r],o=n.marks[s],i=o;if(o)t.push(o);else for(let a in n.marks){let l=n.marks[a];(s=="_"||l.spec.group&&l.spec.group.split(" ").indexOf(s)>-1)&&t.push(i=l)}if(!i)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function sY(n){return n.tag!=null}function oY(n){return n.style!=null}let Hc=class Yw{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(s=>{if(sY(s))this.tags.push(s);else if(oY(s)){let o=/[^=]*/.exec(s.style)[0];r.indexOf(o)<0&&r.push(o),this.styles.push(s)}}),this.normalizeLists=!this.tags.some(s=>{if(!/^(ul|ol)\b/.test(s.tag)||!s.node)return!1;let o=e.nodes[s.node];return o.contentMatch.matchType(o)})}parse(e,t={}){let r=new wI(this,t,!1);return r.addAll(e,wt.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new wI(this,t,!0);return r.addAll(e,wt.none,t.from,t.to),ye.maxOpen(r.finish())}matchTag(e,t,r){for(let s=r?this.tags.indexOf(r)+1:0;s<this.tags.length;s++){let o=this.tags[s];if(lY(e,o.tag)&&(o.namespace===void 0||e.namespaceURI==o.namespace)&&(!o.context||t.matchesContext(o.context))){if(o.getAttrs){let i=o.getAttrs(e);if(i===!1)continue;o.attrs=i||void 0}return o}}}matchStyle(e,t,r,s){for(let o=s?this.styles.indexOf(s)+1:0;o<this.styles.length;o++){let i=this.styles[o],a=i.style;if(!(a.indexOf(e)!=0||i.context&&!r.matchesContext(i.context)||a.length>e.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=t))){if(i.getAttrs){let l=i.getAttrs(t);if(l===!1)continue;i.attrs=l||void 0}return i}}}static schemaRules(e){let t=[];function r(s){let o=s.priority==null?50:s.priority,i=0;for(;i<t.length;i++){let a=t[i];if((a.priority==null?50:a.priority)<o)break}t.splice(i,0,s)}for(let s in e.marks){let o=e.marks[s].spec.parseDOM;o&&o.forEach(i=>{r(i=vI(i)),i.mark||i.ignore||i.clearMark||(i.mark=s)})}for(let s in e.nodes){let o=e.nodes[s].spec.parseDOM;o&&o.forEach(i=>{r(i=vI(i)),i.node||i.ignore||i.mark||(i.node=s)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Yw(e,Yw.schemaRules(e)))}};const QR={address:!0,article:!0,aside:!0,blockquote:!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},iY={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},eL={ol:!0,ul:!0},ch=1,Xw=2,Fu=4;function bI(n,e,t){return e!=null?(e?ch:0)|(e==="full"?Xw:0):n&&n.whitespace=="pre"?ch|Xw:t&~Fu}class Zp{constructor(e,t,r,s,o,i){this.type=e,this.attrs=t,this.marks=r,this.solid=s,this.options=i,this.content=[],this.activeMarks=wt.none,this.match=o||(i&Fu?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(ne.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,s;return(s=r.findWrapping(e.type))?(this.match=r,s):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&ch)){let r=this.content[this.content.length-1],s;if(r&&r.isText&&(s=/[ \t\r\n\u000c]+$/.exec(r.text))){let o=r;r.text.length==s[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-s[0].length))}}let t=ne.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(ne.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!QR.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class wI{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let s=t.topNode,o,i=bI(null,t.preserveWhitespace,0)|(r?Fu:0);s?o=new Zp(s.type,s.attrs,wt.none,!0,t.topMatch||s.type.contentMatch,i):r?o=new Zp(null,null,wt.none,!0,null,i):o=new Zp(e.schema.topNodeType,null,wt.none,!0,null,i),this.nodes=[o],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,s=this.top,o=s.options&Xw?"full":this.localPreserveWS||(s.options&ch)>0,{schema:i}=this.parser;if(o==="full"||s.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(o)if(o==="full")r=r.replace(/\r\n?/g,`
196
+ `);else if(i.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(i.linebreakReplacement.create())){let a=r.split(/\r?\n|\r/);for(let l=0;l<a.length;l++)l&&this.insertNode(i.linebreakReplacement.create(),t,!0),a[l]&&this.insertNode(i.text(a[l]),t,!/\S/.test(a[l]));r=""}else r=r.replace(/\r?\n|\r/g," ");else if(r=r.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(r)&&this.open==this.nodes.length-1){let a=s.content[s.content.length-1],l=e.previousSibling;(!a||l&&l.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(r=r.slice(1))}r&&this.insertNode(i.text(r),t,!/\S/.test(r)),this.findInText(e)}else this.findInside(e)}addElement(e,t,r){let s=this.localPreserveWS,o=this.top;(e.tagName=="PRE"||/pre/.test(e.style&&e.style.whiteSpace))&&(this.localPreserveWS=!0);let i=e.nodeName.toLowerCase(),a;eL.hasOwnProperty(i)&&this.parser.normalizeLists&&aY(e);let l=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,r));e:if(l?l.ignore:iY.hasOwnProperty(i))this.findInside(e),this.ignoreFallback(e,t);else if(!l||l.skip||l.closeParent){l&&l.closeParent?this.open=Math.max(0,this.open-1):l&&l.skip.nodeType&&(e=l.skip);let c,u=this.needsBlock;if(QR.hasOwnProperty(i))o.content.length&&o.content[0].isInline&&this.open&&(this.open--,o=this.top),c=!0,o.type||(this.needsBlock=!0);else if(!e.firstChild){this.leafFallback(e,t);break e}let d=l&&l.skip?t:this.readStyles(e,t);d&&this.addAll(e,d),c&&this.sync(o),this.needsBlock=u}else{let c=this.readStyles(e,t);c&&this.addElementByRule(e,l,c,l.consuming===!1?a:void 0)}this.localPreserveWS=s}leafFallback(e,t){e.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(e.ownerDocument.createTextNode(`
197
+ `),t)}ignoreFallback(e,t){e.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"),t,!0)}readStyles(e,t){let r=e.style;if(r&&r.length)for(let s=0;s<this.parser.matchedStyles.length;s++){let o=this.parser.matchedStyles[s],i=r.getPropertyValue(o);if(i)for(let a=void 0;;){let l=this.parser.matchStyle(o,i,this,a);if(!l)break;if(l.ignore)return null;if(l.clearMark?t=t.filter(c=>!l.clearMark(c)):t=t.concat(this.parser.schema.marks[l.mark].create(l.attrs)),l.consuming===!1)a=l;else break}}return t}addElementByRule(e,t,r,s){let o,i;if(t.node)if(i=this.parser.schema.nodes[t.node],i.isLeaf)this.insertNode(i.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let l=this.enter(i,t.attrs||null,r,t.preserveWhitespace);l&&(o=!0,r=l)}else{let l=this.parser.schema.marks[t.mark];r=r.concat(l.create(t.attrs))}let a=this.top;if(i&&i.isLeaf)this.findInside(e);else if(s)this.addElement(e,r,s);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(l=>this.insertNode(l,r,!1));else{let l=e;typeof t.contentElement=="string"?l=e.querySelector(t.contentElement):typeof t.contentElement=="function"?l=t.contentElement(e):t.contentElement&&(l=t.contentElement),this.findAround(e,l,!0),this.addAll(l,r),this.findAround(e,l,!1)}o&&this.sync(a)&&this.open--}addAll(e,t,r,s){let o=r||0;for(let i=r?e.childNodes[r]:e.firstChild,a=s==null?null:e.childNodes[s];i!=a;i=i.nextSibling,++o)this.findAtPoint(e,o),this.addDOM(i,t);this.findAtPoint(e,o)}findPlace(e,t,r){let s,o;for(let i=this.open,a=0;i>=0;i--){let l=this.nodes[i],c=l.findWrapping(e);if(c&&(!s||s.length>c.length+a)&&(s=c,o=l,!c.length))break;if(l.solid){if(r)break;a+=2}}if(!s)return null;this.sync(o);for(let i=0;i<s.length;i++)t=this.enterInner(s[i],null,t,!1);return t}insertNode(e,t,r){if(e.isInline&&this.needsBlock&&!this.top.type){let o=this.textblockFromContext();o&&(t=this.enterInner(o,null,t))}let s=this.findPlace(e,t,r);if(s){this.closeExtra();let o=this.top;o.match&&(o.match=o.match.matchType(e.type));let i=wt.none;for(let a of s.concat(e.marks))(o.type?o.type.allowsMarkType(a.type):CI(a.type,e.type))&&(i=a.addToSet(i));return o.content.push(e.mark(i)),!0}return!1}enter(e,t,r,s){let o=this.findPlace(e.create(t),r,!1);return o&&(o=this.enterInner(e,t,r,!0,s)),o}enterInner(e,t,r,s=!1,o){this.closeExtra();let i=this.top;i.match=i.match&&i.match.matchType(e);let a=bI(e,o,i.options);i.options&Fu&&i.content.length==0&&(a|=Fu);let l=wt.none;return r=r.filter(c=>(i.type?i.type.allowsMarkType(c.type):CI(c.type,e))?(l=c.addToSet(l),!1):!0),this.nodes.push(new Zp(e,t,l,s,null,a)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=ch)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let s=r.length-1;s>=0;s--)e+=r[s].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==e&&this.find[r].offset==t&&(this.find[r].pos=this.currentPos)}findInside(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].pos==null&&e.nodeType==1&&e.contains(this.find[t].node)&&(this.find[t].pos=this.currentPos)}findAround(e,t,r){if(e!=t&&this.find)for(let s=0;s<this.find.length;s++)this.find[s].pos==null&&e.nodeType==1&&e.contains(this.find[s].node)&&t.compareDocumentPosition(this.find[s].node)&(r?2:4)&&(this.find[s].pos=this.currentPos)}findInText(e){if(this.find)for(let t=0;t<this.find.length;t++)this.find[t].node==e&&(this.find[t].pos=this.currentPos-(e.nodeValue.length-this.find[t].offset))}matchesContext(e){if(e.indexOf("|")>-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,s=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(s?0:1),i=(a,l)=>{for(;a>=0;a--){let c=t[a];if(c==""){if(a==t.length-1||a==0)continue;for(;l>=o;l--)if(i(a-1,l))return!0;return!1}else{let u=l>0||l==0&&s?this.nodes[l].type:r&&l>=o?r.node(l-o).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;l--}}return!0};return i(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function aY(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&eL.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function lY(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function vI(n){let e={};for(let t in n)e[t]=n[t];return e}function CI(n,e){let t=e.schema.nodes;for(let r in t){let s=t[r];if(!s.allowsMarkType(n))continue;let o=[],i=a=>{o.push(a);for(let l=0;l<a.edgeCount;l++){let{type:c,next:u}=a.edge(l);if(c==e||o.indexOf(u)<0&&i(u))return!0}};if(i(s.contentMatch))return!0}}class ql{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},r){r||(r=Zx(t).createDocumentFragment());let s=r,o=[];return e.forEach(i=>{if(o.length||i.marks.length){let a=0,l=0;for(;a<o.length&&l<i.marks.length;){let c=i.marks[l];if(!this.marks[c.type.name]){l++;continue}if(!c.eq(o[a][0])||c.type.spec.spanning===!1)break;a++,l++}for(;a<o.length;)s=o.pop()[1];for(;l<i.marks.length;){let c=i.marks[l++],u=this.serializeMark(c,i.isInline,t);u&&(o.push([c,s]),s.appendChild(u.dom),s=u.contentDOM||u.dom)}}s.appendChild(this.serializeNodeInner(i,t))}),r}serializeNodeInner(e,t){let{dom:r,contentDOM:s}=Hf(Zx(t),this.nodes[e.type.name](e),null,e.attrs);if(s){if(e.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(e.content,t,s)}return r}serializeNode(e,t={}){let r=this.serializeNodeInner(e,t);for(let s=e.marks.length-1;s>=0;s--){let o=this.serializeMark(e.marks[s],e.isInline,t);o&&((o.contentDOM||o.dom).appendChild(r),r=o.dom)}return r}serializeMark(e,t,r={}){let s=this.marks[e.type.name];return s&&Hf(Zx(r),s(e,t),null,e.attrs)}static renderSpec(e,t,r=null,s){return Hf(e,t,r,s)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new ql(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=PI(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return PI(e.marks)}}function PI(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Zx(n){return n.document||window.document}const TI=new WeakMap;function cY(n){let e=TI.get(n);return e===void 0&&TI.set(n,e=dY(n)),e}function dY(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let s=0;s<r.length;s++)t(r[s]);else for(let s in r)t(r[s])}return t(n),e}function Hf(n,e,t,r){if(typeof e=="string")return{dom:n.createTextNode(e)};if(e.nodeType!=null)return{dom:e};if(e.dom&&e.dom.nodeType!=null)return e;let s=e[0],o;if(typeof s!="string")throw new RangeError("Invalid array passed to renderSpec");if(r&&(o=cY(r))&&o.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 i=s.indexOf(" ");i>0&&(t=s.slice(0,i),s=s.slice(i+1));let a,l=t?n.createElementNS(t,s):n.createElement(s),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let h=d.indexOf(" ");h>0?l.setAttributeNS(d.slice(0,h),d.slice(h+1),c[d]):d=="style"&&l.style?l.style.cssText=c[d]:l.setAttribute(d,c[d])}}for(let d=u;d<e.length;d++){let h=e[d];if(h===0){if(d<e.length-1||d>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:l,contentDOM:l}}else{let{dom:f,contentDOM:g}=Hf(n,h,t,r);if(l.appendChild(f),g){if(a)throw new RangeError("Multiple content holes");a=g}}}return{dom:l,contentDOM:a}}const tL=65535,nL=Math.pow(2,16);function uY(n,e){return n+e*nL}function II(n){return n&tL}function hY(n){return(n-(n&tL))/nL}const rL=1,sL=2,Uf=4,oL=8;class qw{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&oL)>0}get deletedBefore(){return(this.delInfo&(rL|Uf))>0}get deletedAfter(){return(this.delInfo&(sL|Uf))>0}get deletedAcross(){return(this.delInfo&Uf)>0}}class ps{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&ps.empty)return ps.empty}recover(e){let t=0,r=II(e);if(!this.inverted)for(let s=0;s<r;s++)t+=this.ranges[s*3+2]-this.ranges[s*3+1];return this.ranges[r*3]+t+hY(e)}mapResult(e,t=1){return this._map(e,t,!1)}map(e,t=1){return this._map(e,t,!0)}_map(e,t,r){let s=0,o=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?s:0);if(l>e)break;let c=this.ranges[a+o],u=this.ranges[a+i],d=l+c;if(e<=d){let h=c?e==l?-1:e==d?1:t:t,f=l+s+(h<0?0:u);if(r)return f;let g=e==(t<0?l:d)?null:uY(a/3,e-l),m=e==l?sL:e==d?rL:Uf;return(t<0?e!=l:e!=d)&&(m|=oL),new qw(f,m,g)}s+=u-c}return r?e+s:new qw(e+s,0,null)}touches(e,t){let r=0,s=II(t),o=this.inverted?2:1,i=this.inverted?1:2;for(let a=0;a<this.ranges.length;a+=3){let l=this.ranges[a]-(this.inverted?r:0);if(l>e)break;let c=this.ranges[a+o],u=l+c;if(e<=u&&a==s*3)return!0;r+=this.ranges[a+i]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let s=0,o=0;s<this.ranges.length;s+=3){let i=this.ranges[s],a=i-(this.inverted?o:0),l=i+(this.inverted?0:o),c=this.ranges[s+t],u=this.ranges[s+r];e(a,a+c,l,l+u),o+=u-c}}invert(){return new ps(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?ps.empty:new ps(e<0?[0,-e,0]:[0,0,e])}}ps.empty=new ps([]);class dh{constructor(e,t,r=0,s=e?e.length:0){this.mirror=t,this.from=r,this.to=s,this._maps=e||[],this.ownData=!(e||t)}get maps(){return this._maps}slice(e=0,t=this.maps.length){return new dh(this._maps,this.mirror,e,t)}appendMap(e,t){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(e),t!=null&&this.setMirror(this._maps.length-1,t)}appendMapping(e){for(let t=0,r=this._maps.length;t<e._maps.length;t++){let s=e.getMirror(t);this.appendMap(e._maps[t],s!=null&&s<t?r+s:void 0)}}getMirror(e){if(this.mirror){for(let t=0;t<this.mirror.length;t++)if(this.mirror[t]==e)return this.mirror[t+(t%2?-1:1)]}}setMirror(e,t){this.mirror||(this.mirror=[]),this.mirror.push(e,t)}appendMappingInverted(e){for(let t=e.maps.length-1,r=this._maps.length+e._maps.length;t>=0;t--){let s=e.getMirror(t);this.appendMap(e._maps[t].invert(),s!=null&&s>t?r-s-1:void 0)}}invert(){let e=new dh;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;r<this.to;r++)e=this._maps[r].map(e,t);return e}mapResult(e,t=1){return this._map(e,t,!1)}_map(e,t,r){let s=0;for(let o=this.from;o<this.to;o++){let i=this._maps[o],a=i.mapResult(e,t);if(a.recover!=null){let l=this.getMirror(o);if(l!=null&&l>o&&l<this.to){o=l,e=this._maps[l].recover(a.recover);continue}}s|=a.delInfo,e=a.pos}return r?e:new qw(e,s,null)}}const Jx=Object.create(null);class pr{getMap(){return ps.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Jx[t.stepType];if(!r)throw new RangeError(`No step type ${t.stepType} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Jx)throw new RangeError("Duplicate use of step JSON ID "+e);return Jx[e]=t,t.prototype.jsonID=e,t}}class hn{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new hn(e,null)}static fail(e){return new hn(null,e)}static fromReplace(e,t,r,s){try{return hn.ok(e.replace(t,r,s))}catch(o){if(o instanceof Xg)return hn.fail(o.message);throw o}}}function p1(n,e,t){let r=[];for(let s=0;s<n.childCount;s++){let o=n.child(s);o.content.size&&(o=o.copy(p1(o.content,e,o))),o.isInline&&(o=e(o,t,s)),r.push(o)}return ne.fromArray(r)}class Ca extends pr{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=e.resolve(this.from),s=r.node(r.sharedDepth(this.to)),o=new ye(p1(t.content,(i,a)=>!i.isAtom||!a.type.allowsMarkType(this.mark.type)?i:i.mark(this.mark.addToSet(i.marks)),s),t.openStart,t.openEnd);return hn.fromReplace(e,this.from,this.to,o)}invert(){return new ho(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Ca(t.pos,r.pos,this.mark)}merge(e){return e instanceof Ca&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ca(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Ca(t.from,t.to,e.markFromJSON(t.mark))}}pr.jsonID("addMark",Ca);class ho extends pr{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new ye(p1(t.content,s=>s.mark(this.mark.removeFromSet(s.marks)),e),t.openStart,t.openEnd);return hn.fromReplace(e,this.from,this.to,r)}invert(){return new Ca(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new ho(t.pos,r.pos,this.mark)}merge(e){return e instanceof ho&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ho(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ho(t.from,t.to,e.markFromJSON(t.mark))}}pr.jsonID("removeMark",ho);class Pa extends pr{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return hn.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return hn.fromReplace(e,this.pos,this.pos+1,new ye(ne.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let s=0;s<t.marks.length;s++)if(!t.marks[s].isInSet(r))return new Pa(this.pos,t.marks[s]);return new Pa(this.pos,this.mark)}}return new Dl(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Pa(t.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Pa(t.pos,e.markFromJSON(t.mark))}}pr.jsonID("addNodeMark",Pa);class Dl extends pr{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return hn.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return hn.fromReplace(e,this.pos,this.pos+1,new ye(ne.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new Pa(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Dl(t.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new Dl(t.pos,e.markFromJSON(t.mark))}}pr.jsonID("removeNodeMark",Dl);class In extends pr{constructor(e,t,r,s=!1){super(),this.from=e,this.to=t,this.slice=r,this.structure=s}apply(e){return this.structure&&Zw(e,this.from,this.to)?hn.fail("Structure replace would overwrite content"):hn.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new ps([this.from,this.to-this.from,this.slice.size])}invert(e){return new In(this.from,this.from+this.slice.size,e.slice(this.from,this.to))}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deletedAcross&&r.deletedAcross?null:new In(t.pos,Math.max(t.pos,r.pos),this.slice,this.structure)}merge(e){if(!(e instanceof In)||e.structure||this.structure)return null;if(this.from+this.slice.size==e.from&&!this.slice.openEnd&&!e.slice.openStart){let t=this.slice.size+e.slice.size==0?ye.empty:new ye(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new In(this.from,this.to+(e.to-e.from),t,this.structure)}else if(e.to==this.from&&!this.slice.openStart&&!e.slice.openEnd){let t=this.slice.size+e.slice.size==0?ye.empty:new ye(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new In(e.from,this.to,t,this.structure)}else return null}toJSON(){let e={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new In(t.from,t.to,ye.fromJSON(e,t.slice),!!t.structure)}}pr.jsonID("replace",In);class kn extends pr{constructor(e,t,r,s,o,i,a=!1){super(),this.from=e,this.to=t,this.gapFrom=r,this.gapTo=s,this.slice=o,this.insert=i,this.structure=a}apply(e){if(this.structure&&(Zw(e,this.from,this.gapFrom)||Zw(e,this.gapTo,this.to)))return hn.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return hn.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,t.content);return r?hn.fromReplace(e,this.from,this.to,r):hn.fail("Content does not fit in gap")}getMap(){return new ps([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(e){let t=this.gapTo-this.gapFrom;return new kn(this.from,this.from+this.slice.size+t,this.from+this.insert,this.from+this.insert+t,e.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1),s=this.from==this.gapFrom?t.pos:e.map(this.gapFrom,-1),o=this.to==this.gapTo?r.pos:e.map(this.gapTo,1);return t.deletedAcross&&r.deletedAcross||s<t.pos||o>r.pos?null:new kn(t.pos,r.pos,s,o,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new kn(t.from,t.to,t.gapFrom,t.gapTo,ye.fromJSON(e,t.slice),t.insert,!!t.structure)}}pr.jsonID("replaceAround",kn);function Zw(n,e,t){let r=n.resolve(e),s=t-e,o=r.depth;for(;s>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,s--;if(s>0){let i=r.node(o).maybeChild(r.indexAfter(o));for(;s>0;){if(!i||i.isLeaf)return!0;i=i.firstChild,s--}}return!1}function pY(n,e,t,r){let s=[],o=[],i,a;n.doc.nodesBetween(e,t,(l,c,u)=>{if(!l.isInline)return;let d=l.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let h=Math.max(c,e),f=Math.min(c+l.nodeSize,t),g=r.addToSet(d);for(let m=0;m<d.length;m++)d[m].isInSet(g)||(i&&i.to==h&&i.mark.eq(d[m])?i.to=f:s.push(i=new ho(h,f,d[m])));a&&a.to==h?a.to=f:o.push(a=new Ca(h,f,r))}}),s.forEach(l=>n.step(l)),o.forEach(l=>n.step(l))}function fY(n,e,t,r){let s=[],o=0;n.doc.nodesBetween(e,t,(i,a)=>{if(!i.isInline)return;o++;let l=null;if(r instanceof My){let c=i.marks,u;for(;u=r.isInSet(c);)(l||(l=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(i.marks)&&(l=[r]):l=i.marks;if(l&&l.length){let c=Math.min(a+i.nodeSize,t);for(let u=0;u<l.length;u++){let d=l[u],h;for(let f=0;f<s.length;f++){let g=s[f];g.step==o-1&&d.eq(s[f].style)&&(h=g)}h?(h.to=c,h.step=o):s.push({style:d,from:Math.max(a,e),to:c,step:o})}}}),s.forEach(i=>n.step(new ho(i.from,i.to,i.style)))}function f1(n,e,t,r=t.contentMatch,s=!0){let o=n.doc.nodeAt(e),i=[],a=e+1;for(let l=0;l<o.childCount;l++){let c=o.child(l),u=a+c.nodeSize,d=r.matchType(c.type);if(!d)i.push(new In(a,u,ye.empty));else{r=d;for(let h=0;h<c.marks.length;h++)t.allowsMarkType(c.marks[h].type)||n.step(new ho(a,u,c.marks[h]));if(s&&c.isText&&t.whitespace!="pre"){let h,f=/\r?\n|\r/g,g;for(;h=f.exec(c.text);)g||(g=new ye(ne.from(t.schema.text(" ",t.allowedMarks(c.marks))),0,0)),i.push(new In(a+h.index,a+h.index+h[0].length,g))}}a=u}if(!r.validEnd){let l=r.fillBefore(ne.empty,!0);n.replace(a,a,new ye(l,0,0))}for(let l=i.length-1;l>=0;l--)n.step(i[l])}function gY(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function bd(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,s=0,o=0;;--r){let i=n.$from.node(r),a=n.$from.index(r)+s,l=n.$to.indexAfter(r)-o;if(r<n.depth&&i.canReplace(a,l,t))return r;if(r==0||i.type.spec.isolating||!gY(i,a,l))break;a&&(s=1),l<i.childCount&&(o=1)}return null}function mY(n,e,t){let{$from:r,$to:s,depth:o}=e,i=r.before(o+1),a=s.after(o+1),l=i,c=a,u=ne.empty,d=0;for(let g=o,m=!1;g>t;g--)m||r.index(g)>0?(m=!0,u=ne.from(r.node(g).copy(u)),d++):l--;let h=ne.empty,f=0;for(let g=o,m=!1;g>t;g--)m||s.after(g+1)<s.end(g)?(m=!0,h=ne.from(s.node(g).copy(h)),f++):c++;n.step(new kn(l,c,i,a,new ye(u.append(h),d,f),u.size-d,!0))}function g1(n,e,t=null,r=n){let s=yY(n,e),o=s&&SY(r,e);return o?s.map(EI).concat({type:e,attrs:t}).concat(o.map(EI)):null}function EI(n){return{type:n,attrs:null}}function yY(n,e){let{parent:t,startIndex:r,endIndex:s}=n,o=t.contentMatchAt(r).findWrapping(e);if(!o)return null;let i=o.length?o[0]:e;return t.canReplaceWith(r,s,i)?o:null}function SY(n,e){let{parent:t,startIndex:r,endIndex:s}=n,o=t.child(r),i=e.contentMatch.findWrapping(o.type);if(!i)return null;let l=(i.length?i[i.length-1]:e).contentMatch;for(let c=r;l&&c<s;c++)l=l.matchType(t.child(c).type);return!l||!l.validEnd?null:i}function xY(n,e,t){let r=ne.empty;for(let i=t.length-1;i>=0;i--){if(r.size){let a=t[i].type.contentMatch.matchFragment(r);if(!a||!a.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=ne.from(t[i].type.create(t[i].attrs,r))}let s=e.start,o=e.end;n.step(new kn(s,o,s,o,new ye(r,0,0),t.length,!0))}function bY(n,e,t,r,s){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let o=n.steps.length;n.doc.nodesBetween(e,t,(i,a)=>{let l=typeof s=="function"?s(i):s;if(i.isTextblock&&!i.hasMarkup(r,l)&&wY(n.doc,n.mapping.slice(o).map(a),r)){let c=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!g?c=!1:!f&&g&&(c=!0)}c===!1&&aL(n,i,a,o),f1(n,n.mapping.slice(o).map(a,1),r,void 0,c===null);let u=n.mapping.slice(o),d=u.map(a,1),h=u.map(a+i.nodeSize,1);return n.step(new kn(d,h,d+1,h-1,new ye(ne.from(r.create(l,null,i.marks)),0,0),1,!0)),c===!0&&iL(n,i,a,o),!1}})}function iL(n,e,t,r){e.forEach((s,o)=>{if(s.isText){let i,a=/\r?\n|\r/g;for(;i=a.exec(s.text);){let l=n.mapping.slice(r).map(t+1+o+i.index);n.replaceWith(l,l+1,e.type.schema.linebreakReplacement.create())}}})}function aL(n,e,t,r){e.forEach((s,o)=>{if(s.type==s.type.schema.linebreakReplacement){let i=n.mapping.slice(r).map(t+1+o);n.replaceWith(i,i+1,e.type.schema.text(`
198
+ `))}})}function wY(n,e,t){let r=n.resolve(e),s=r.index();return r.parent.canReplaceWith(s,s+1,t)}function vY(n,e,t,r,s){let o=n.doc.nodeAt(e);if(!o)throw new RangeError("No node at given position");t||(t=o.type);let i=t.create(r,null,s||o.marks);if(o.isLeaf)return n.replaceWith(e,e+o.nodeSize,i);if(!t.validContent(o.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new kn(e,e+o.nodeSize,e+1,e+o.nodeSize-1,new ye(ne.from(i),0,0),1,!0))}function Fi(n,e,t=1,r){let s=n.resolve(e),o=s.depth-t,i=r&&r[r.length-1]||s.parent;if(o<0||s.parent.type.spec.isolating||!s.parent.canReplace(s.index(),s.parent.childCount)||!i.type.validContent(s.parent.content.cutByIndex(s.index(),s.parent.childCount)))return!1;for(let c=s.depth-1,u=t-2;c>o;c--,u--){let d=s.node(c),h=s.index(c);if(d.type.spec.isolating)return!1;let f=d.content.cutByIndex(h,d.childCount),g=r&&r[u+1];g&&(f=f.replaceChild(0,g.type.create(g.attrs)));let m=r&&r[u]||d;if(!d.canReplace(h+1,d.childCount)||!m.type.validContent(f))return!1}let a=s.indexAfter(o),l=r&&r[0];return s.node(o).canReplaceWith(a,a,l?l.type:s.node(o+1).type)}function CY(n,e,t=1,r){let s=n.doc.resolve(e),o=ne.empty,i=ne.empty;for(let a=s.depth,l=s.depth-t,c=t-1;a>l;a--,c--){o=ne.from(s.node(a).copy(o));let u=r&&r[c];i=ne.from(u?u.type.create(u.attrs,i):s.node(a).copy(i))}n.step(new In(e,e,new ye(o.append(i),t,t),!0))}function Xa(n,e){let t=n.resolve(e),r=t.index();return lL(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function PY(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let s=0;s<e.childCount;s++){let o=e.child(s),i=o.type==r?n.type.schema.nodes.text:o.type;if(t=t.matchType(i),!t||!n.type.allowsMarks(o.marks))return!1}return t.validEnd}function lL(n,e){return!!(n&&e&&!n.isLeaf&&PY(n,e))}function Ay(n,e,t=-1){let r=n.resolve(e);for(let s=r.depth;;s--){let o,i,a=r.index(s);if(s==r.depth?(o=r.nodeBefore,i=r.nodeAfter):t>0?(o=r.node(s+1),a++,i=r.node(s).maybeChild(a)):(o=r.node(s).maybeChild(a-1),i=r.node(s+1)),o&&!o.isTextblock&&lL(o,i)&&r.node(s).canReplace(a,a+1))return e;if(s==0)break;e=t<0?r.before(s):r.after(s)}}function TY(n,e,t){let r=null,{linebreakReplacement:s}=n.doc.type.schema,o=n.doc.resolve(e-t),i=o.node().type;if(s&&i.inlineContent){let u=i.whitespace=="pre",d=!!i.contentMatch.matchType(s);u&&!d?r=!1:!u&&d&&(r=!0)}let a=n.steps.length;if(r===!1){let u=n.doc.resolve(e+t);aL(n,u.node(),u.before(),a)}i.inlineContent&&f1(n,e+t-1,i,o.node().contentMatchAt(o.index()),r==null);let l=n.mapping.slice(a),c=l.map(e-t);if(n.step(new In(c,l.map(e+t,-1),ye.empty,!0)),r===!0){let u=n.doc.resolve(c);iL(n,u.node(),u.before(),n.steps.length)}return n}function IY(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let s=r.depth-1;s>=0;s--){let o=r.index(s);if(r.node(s).canReplaceWith(o,o,t))return r.before(s+1);if(o>0)return null}if(r.parentOffset==r.parent.content.size)for(let s=r.depth-1;s>=0;s--){let o=r.indexAfter(s);if(r.node(s).canReplaceWith(o,o,t))return r.after(s+1);if(o<r.node(s).childCount)return null}return null}function cL(n,e,t){let r=n.resolve(e);if(!t.content.size)return e;let s=t.content;for(let o=0;o<t.openStart;o++)s=s.firstChild.content;for(let o=1;o<=(t.openStart==0&&t.size?2:1);o++)for(let i=r.depth;i>=0;i--){let a=i==r.depth?0:r.pos<=(r.start(i+1)+r.end(i+1))/2?-1:1,l=r.index(i)+(a>0?1:0),c=r.node(i),u=!1;if(o==1)u=c.canReplace(l,l,s);else{let d=c.contentMatchAt(l).findWrapping(s.firstChild.type);u=d&&c.canReplaceWith(l,l,d[0])}if(u)return a==0?r.pos:a<0?r.before(i+1):r.after(i+1)}return null}function Dy(n,e,t=e,r=ye.empty){if(e==t&&!r.size)return null;let s=n.resolve(e),o=n.resolve(t);return dL(s,o,r)?new In(e,t,r):new EY(s,o,r).fit()}function dL(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class EY{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=ne.empty;for(let s=0;s<=e.depth;s++){let o=e.node(s);this.frontier.push({type:o.type,match:o.contentMatchAt(e.indexAfter(s))})}for(let s=e.depth;s>0;s--)this.placed=ne.from(e.node(s).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,s=this.close(e<0?this.$to:r.doc.resolve(e));if(!s)return null;let o=this.placed,i=r.depth,a=s.depth;for(;i&&a&&o.childCount==1;)o=o.firstChild.content,i--,a--;let l=new ye(o,i,a);return e>-1?new kn(r.pos,e,this.$to.pos,this.$to.end(),l,t):l.size||r.pos!=this.$to.pos?new In(r.pos,s.pos,l):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,s=this.unplaced.openEnd;r<e;r++){let o=t.firstChild;if(t.childCount>1&&(s=0),o.type.spec.isolating&&s<=r){e=r;break}t=o.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let s,o=null;r?(o=Qx(this.unplaced.content,r-1).firstChild,s=o.content):s=this.unplaced.content;let i=s.firstChild;for(let a=this.depth;a>=0;a--){let{type:l,match:c}=this.frontier[a],u,d=null;if(t==1&&(i?c.matchType(i.type)||(d=c.fillBefore(ne.from(i),!1)):o&&l.compatibleContent(o.type)))return{sliceDepth:r,frontierDepth:a,parent:o,inject:d};if(t==2&&i&&(u=c.findWrapping(i.type)))return{sliceDepth:r,frontierDepth:a,parent:o,wrap:u};if(o&&c.matchType(o.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=Qx(e,t);return!s.childCount||s.firstChild.isLeaf?!1:(this.unplaced=new ye(e,t+1,Math.max(r,s.size+t>=e.size-r?t+1:0)),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,s=Qx(e,t);if(s.childCount<=1&&t>0){let o=e.size-t<=t+s.size;this.unplaced=new ye(uu(e,t-1,1),t-1,o?t-1:r)}else this.unplaced=new ye(uu(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:s,wrap:o}){for(;this.depth>t;)this.closeFrontierNode();if(o)for(let m=0;m<o.length;m++)this.openFrontierNode(o[m]);let i=this.unplaced,a=r?r.content:i.content,l=i.openStart-e,c=0,u=[],{match:d,type:h}=this.frontier[t];if(s){for(let m=0;m<s.childCount;m++)u.push(s.child(m));d=d.matchFragment(s)}let f=a.size+e-(i.content.size-i.openEnd);for(;c<a.childCount;){let m=a.child(c),y=d.matchType(m.type);if(!y)break;c++,(c>1||l==0||m.content.size)&&(d=y,u.push(uL(m.mark(h.allowedMarks(m.marks)),c==1?l:0,c==a.childCount?f:-1)))}let g=c==a.childCount;g||(f=-1),this.placed=hu(this.placed,t,ne.from(u)),this.frontier[t].match=d,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,y=a;m<f;m++){let S=y.lastChild;this.frontier.push({type:S.type,match:S.contentMatchAt(S.childCount)}),y=S.content}this.unplaced=g?e==0?ye.empty:new ye(uu(i.content,e-1,1),e-1,f<0?i.openEnd:e-1):new ye(uu(i.content,e,c),i.openStart,i.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let e=this.frontier[this.depth],t;if(!e.type.isTextblock||!eb(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:r}=this.$to,s=this.$to.after(r);for(;r>1&&s==this.$to.end(--r);)++s;return s}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:s}=this.frontier[t],o=t<e.depth&&e.end(t+1)==e.pos+(e.depth-(t+1)),i=eb(e,t,s,r,o);if(i){for(let a=t-1;a>=0;a--){let{match:l,type:c}=this.frontier[a],u=eb(e,a,c,l,!0);if(!u||u.childCount)continue e}return{depth:t,fit:i,move:o?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=hu(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let s=e.node(r),o=s.type.contentMatch.fillBefore(s.content,!0,e.index(r));this.openFrontierNode(s.type,s.attrs,o)}return e}openFrontierNode(e,t=null,r){let s=this.frontier[this.depth];s.match=s.match.matchType(e),this.placed=hu(this.placed,this.depth,ne.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(ne.empty,!0);t.childCount&&(this.placed=hu(this.placed,this.frontier.length,t))}}function uu(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(uu(n.firstChild.content,e-1,t)))}function hu(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(hu(n.lastChild.content,e-1,t)))}function Qx(n,e){for(let t=0;t<e;t++)n=n.firstChild.content;return n}function uL(n,e,t){if(e<=0)return n;let r=n.content;return e>1&&(r=r.replaceChild(0,uL(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(ne.empty,!0)))),n.copy(r)}function eb(n,e,t,r,s){let o=n.node(e),i=s?n.indexAfter(e):n.index(e);if(i==o.childCount&&!t.compatibleContent(o.type))return null;let a=r.fillBefore(o.content,!0,i);return a&&!kY(t,o.content,i)?a:null}function kY(n,e,t){for(let r=t;r<e.childCount;r++)if(!n.allowsMarks(e.child(r).marks))return!0;return!1}function _Y(n){return n.spec.defining||n.spec.definingForContent}function MY(n,e,t,r){if(!r.size)return n.deleteRange(e,t);let s=n.doc.resolve(e),o=n.doc.resolve(t);if(dL(s,o,r))return n.step(new In(e,t,r));let i=pL(s,o);i[i.length-1]==0&&i.pop();let a=-(s.depth+1);i.unshift(a);for(let h=s.depth,f=s.pos-1;h>0;h--,f--){let g=s.node(h).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;i.indexOf(h)>-1?a=h:s.before(h)==f&&i.splice(1,0,-h)}let l=i.indexOf(a),c=[],u=r.openStart;for(let h=r.content,f=0;;f++){let g=h.firstChild;if(c.push(g),f==r.openStart)break;h=g.content}for(let h=u-1;h>=0;h--){let f=c[h],g=_Y(f.type);if(g&&!f.sameMarkup(s.node(Math.abs(a)-1)))u=h;else if(g||!f.type.isTextblock)break}for(let h=r.openStart;h>=0;h--){let f=(h+u+1)%(r.openStart+1),g=c[f];if(g)for(let m=0;m<i.length;m++){let y=i[(m+l)%i.length],S=!0;y<0&&(S=!1,y=-y);let b=s.node(y-1),w=s.index(y-1);if(b.canReplaceWith(w,w,g.type,g.marks))return n.replace(s.before(y),S?o.after(y):t,new ye(hL(r.content,0,r.openStart,f),f,r.openEnd))}}let d=n.steps.length;for(let h=i.length-1;h>=0&&(n.replace(e,t,r),!(n.steps.length>d));h--){let f=i[h];f<0||(e=s.before(f),t=o.after(f))}}function hL(n,e,t,r,s){if(e<t){let o=n.firstChild;n=n.replaceChild(0,o.copy(hL(o.content,e+1,t,r,o)))}if(e>r){let o=s.contentMatchAt(0),i=o.fillBefore(n).append(n);n=i.append(o.matchFragment(i).fillBefore(ne.empty,!0))}return n}function AY(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let s=IY(n.doc,e,r.type);s!=null&&(e=t=s)}n.replaceRange(e,t,new ye(ne.from(r),0,0))}function DY(n,e,t){let r=n.doc.resolve(e),s=n.doc.resolve(t),o=pL(r,s);for(let i=0;i<o.length;i++){let a=o[i],l=i==o.length-1;if(l&&a==0||r.node(a).type.contentMatch.validEnd)return n.delete(r.start(a),s.end(a));if(a>0&&(l||r.node(a-1).canReplace(r.index(a-1),s.indexAfter(a-1))))return n.delete(r.before(a),s.after(a))}for(let i=1;i<=r.depth&&i<=s.depth;i++)if(e-r.start(i)==r.depth-i&&t>r.end(i)&&s.end(i)-t!=s.depth-i&&r.start(i-1)==s.start(i-1)&&r.node(i-1).canReplace(r.index(i-1),s.index(i-1)))return n.delete(r.before(i),t);n.delete(e,t)}function pL(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let s=r;s>=0;s--){let o=n.start(s);if(o<n.pos-(n.depth-s)||e.end(s)>e.pos+(e.depth-s)||n.node(s).type.spec.isolating||e.node(s).type.spec.isolating)break;(o==e.start(s)||s==n.depth&&s==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&s&&e.start(s-1)==o-1)&&t.push(s)}return t}class Uc extends pr{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return hn.fail("No node at attribute step's position");let r=Object.create(null);for(let o in t.attrs)r[o]=t.attrs[o];r[this.attr]=this.value;let s=t.type.create(r,null,t.marks);return hn.fromReplace(e,this.pos,this.pos+1,new ye(ne.from(s),0,t.isLeaf?0:1))}getMap(){return ps.empty}invert(e){return new Uc(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Uc(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Uc(t.pos,t.attr,t.value)}}pr.jsonID("attr",Uc);class uh extends pr{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let s in e.attrs)t[s]=e.attrs[s];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return hn.ok(r)}getMap(){return ps.empty}invert(e){return new uh(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new uh(t.attr,t.value)}}pr.jsonID("docAttr",uh);let td=class extends Error{};td=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};td.prototype=Object.create(Error.prototype);td.prototype.constructor=td;td.prototype.name="TransformError";class fL{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new dh}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new td(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r<this.mapping.maps.length;r++){let s=this.mapping.maps[r];r&&(e=s.map(e,1),t=s.map(t,-1)),s.forEach((o,i,a,l)=>{e=Math.min(e,a),t=Math.max(t,l)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=ye.empty){let s=Dy(this.doc,e,t,r);return s&&this.step(s),this}replaceWith(e,t,r){return this.replace(e,t,new ye(ne.from(r),0,0))}delete(e,t){return this.replace(e,t,ye.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return MY(this,e,t,r),this}replaceRangeWith(e,t,r){return AY(this,e,t,r),this}deleteRange(e,t){return DY(this,e,t),this}lift(e,t){return mY(this,e,t),this}join(e,t=1){return TY(this,e,t),this}wrap(e,t){return xY(this,e,t),this}setBlockType(e,t=e,r,s=null){return bY(this,e,t,r,s),this}setNodeMarkup(e,t,r=null,s){return vY(this,e,t,r,s),this}setNodeAttribute(e,t,r){return this.step(new Uc(e,t,r)),this}setDocAttribute(e,t){return this.step(new uh(e,t)),this}addNodeMark(e,t){return this.step(new Pa(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof wt)t.isInSet(r.marks)&&this.step(new Dl(e,t));else{let s=r.marks,o,i=[];for(;o=t.isInSet(s);)i.push(new Dl(e,o)),s=o.removeFromSet(s);for(let a=i.length-1;a>=0;a--)this.step(i[a])}return this}split(e,t=1,r){return CY(this,e,t,r),this}addMark(e,t,r){return pY(this,e,t,r),this}removeMark(e,t,r){return fY(this,e,t,r),this}clearIncompatible(e,t,r){return f1(this,e,t,r),this}}const tb=Object.create(null);class Je{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new OY(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t<e.length;t++)if(e[t].$from.pos!=e[t].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(e,t=ye.empty){let r=t.content.lastChild,s=null;for(let a=0;a<t.openEnd;a++)s=r,r=r.lastChild;let o=e.steps.length,i=this.ranges;for(let a=0;a<i.length;a++){let{$from:l,$to:c}=i[a],u=e.mapping.slice(o);e.replaceRange(u.map(l.pos),u.map(c.pos),a?ye.empty:t),a==0&&MI(e,o,(r?r.isInline:s&&s.isTextblock)?-1:1)}}replaceWith(e,t){let r=e.steps.length,s=this.ranges;for(let o=0;o<s.length;o++){let{$from:i,$to:a}=s[o],l=e.mapping.slice(r),c=l.map(i.pos),u=l.map(a.pos);o?e.deleteRange(c,u):(e.replaceRangeWith(c,u,t),MI(e,r,t.isInline?-1:1))}}static findFrom(e,t,r=!1){let s=e.parent.inlineContent?new He(e):Cc(e.node(0),e.parent,e.pos,e.index(),t,r);if(s)return s;for(let o=e.depth-1;o>=0;o--){let i=t<0?Cc(e.node(0),e.node(o),e.before(o+1),e.index(o),t,r):Cc(e.node(0),e.node(o),e.after(o+1),e.index(o)+1,t,r);if(i)return i}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new Ss(e.node(0))}static atStart(e){return Cc(e,e,0,0,1)||new Ss(e)}static atEnd(e){return Cc(e,e,e.content.size,e.childCount,-1)||new Ss(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=tb[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in tb)throw new RangeError("Duplicate use of selection JSON ID "+e);return tb[e]=t,t.prototype.jsonID=e,t}getBookmark(){return He.between(this.$anchor,this.$head).getBookmark()}}Je.prototype.visible=!0;class OY{constructor(e,t){this.$from=e,this.$to=t}}let kI=!1;function _I(n){!kI&&!n.parent.inlineContent&&(kI=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class He extends Je{constructor(e,t=e){_I(e),_I(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return Je.near(r);let s=e.resolve(t.map(this.anchor));return new He(s.parent.inlineContent?s:r,r)}replace(e,t=ye.empty){if(super.replace(e,t),t==ye.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof He&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new Oy(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new He(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let s=e.resolve(t);return new this(s,r==t?s:e.resolve(r))}static between(e,t,r){let s=e.pos-t.pos;if((!r||s)&&(r=s>=0?1:-1),!t.parent.inlineContent){let o=Je.findFrom(t,r,!0)||Je.findFrom(t,-r,!0);if(o)t=o.$head;else return Je.near(t,r)}return e.parent.inlineContent||(s==0?e=t:(e=(Je.findFrom(e,-r,!0)||Je.findFrom(e,r,!0)).$anchor,e.pos<t.pos!=s<0&&(e=t))),new He(e,t)}}Je.jsonID("text",He);class Oy{constructor(e,t){this.anchor=e,this.head=t}map(e){return new Oy(e.map(this.anchor),e.map(this.head))}resolve(e){return He.between(e.resolve(this.anchor),e.resolve(this.head))}}class Me extends Je{constructor(e){let t=e.nodeAfter,r=e.node(0).resolve(e.pos+t.nodeSize);super(e,r),this.node=t}map(e,t){let{deleted:r,pos:s}=t.mapResult(this.anchor),o=e.resolve(s);return r?Je.near(o):new Me(o)}content(){return new ye(ne.from(this.node),0,0)}eq(e){return e instanceof Me&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new m1(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Me(e.resolve(t.anchor))}static create(e,t){return new Me(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}}Me.prototype.visible=!1;Je.jsonID("node",Me);class m1{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:r}=e.mapResult(this.anchor);return t?new Oy(r,r):new m1(r)}resolve(e){let t=e.resolve(this.anchor),r=t.nodeAfter;return r&&Me.isSelectable(r)?new Me(t):Je.near(t)}}class Ss extends Je{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=ye.empty){if(t==ye.empty){e.delete(0,e.doc.content.size);let r=Je.atStart(e.doc);r.eq(e.selection)||e.setSelection(r)}else super.replace(e,t)}toJSON(){return{type:"all"}}static fromJSON(e){return new Ss(e)}map(e){return new Ss(e)}eq(e){return e instanceof Ss}getBookmark(){return RY}}Je.jsonID("all",Ss);const RY={map(){return this},resolve(n){return new Ss(n)}};function Cc(n,e,t,r,s,o=!1){if(e.inlineContent)return He.create(n,t);for(let i=r-(s>0?0:1);s>0?i<e.childCount:i>=0;i+=s){let a=e.child(i);if(a.isAtom){if(!o&&Me.isSelectable(a))return Me.create(n,t-(s<0?a.nodeSize:0))}else{let l=Cc(n,a,t+s,s<0?a.childCount:0,s,o);if(l)return l}t+=a.nodeSize*s}return null}function MI(n,e,t){let r=n.steps.length-1;if(r<e)return;let s=n.steps[r];if(!(s instanceof In||s instanceof kn))return;let o=n.mapping.maps[r],i;o.forEach((a,l,c,u)=>{i==null&&(i=u)}),n.setSelection(Je.near(n.doc.resolve(i),t))}const AI=1,Jp=2,DI=4;class LY extends fL{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(e){if(e.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=e,this.curSelectionFor=this.steps.length,this.updated=(this.updated|AI)&~Jp,this.storedMarks=null,this}get selectionSet(){return(this.updated&AI)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Jp,this}ensureMarks(e){return wt.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Jp)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Jp,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||wt.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let s=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(s.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let o=this.storedMarks;if(!o){let i=this.doc.resolve(t);o=r==t?i.marks():i.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,s.text(e,o)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(Je.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=DI,this}get scrolledIntoView(){return(this.updated&DI)>0}}function OI(n,e){return!e||!n?n:n.bind(e)}class pu{constructor(e,t,r){this.name=e,this.init=OI(t.init,r),this.apply=OI(t.apply,r)}}const jY=[new pu("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new pu("selection",{init(n,e){return n.selection||Je.atStart(e.doc)},apply(n){return n.selection}}),new pu("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new pu("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class nb{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=jY.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new pu(r.key,r.spec.state,r))})}}class Mc{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;r<this.config.plugins.length;r++)if(r!=t){let s=this.config.plugins[r];if(s.spec.filterTransaction&&!s.spec.filterTransaction.call(s,e,this))return!1}return!0}applyTransaction(e){if(!this.filterTransaction(e))return{state:this,transactions:[]};let t=[e],r=this.applyInner(e),s=null;for(;;){let o=!1;for(let i=0;i<this.config.plugins.length;i++){let a=this.config.plugins[i];if(a.spec.appendTransaction){let l=s?s[i].n:0,c=s?s[i].state:this,u=l<t.length&&a.spec.appendTransaction.call(a,l?t.slice(l):t,c,r);if(u&&r.filterTransaction(u,i)){if(u.setMeta("appendedTransaction",e),!s){s=[];for(let d=0;d<this.config.plugins.length;d++)s.push(d<i?{state:r,n:t.length}:{state:this,n:0})}t.push(u),r=r.applyInner(u),o=!0}s&&(s[i]={state:r,n:t.length})}}if(!o)return{state:r,transactions:t}}}applyInner(e){if(!e.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let t=new Mc(this.config),r=this.config.fields;for(let s=0;s<r.length;s++){let o=r[s];t[o.name]=o.apply(e,this[o.name],this,t)}return t}get tr(){return new LY(this)}static create(e){let t=new nb(e.doc?e.doc.type.schema:e.schema,e.plugins),r=new Mc(t);for(let s=0;s<t.fields.length;s++)r[t.fields[s].name]=t.fields[s].init(e,r);return r}reconfigure(e){let t=new nb(this.schema,e.plugins),r=t.fields,s=new Mc(t);for(let o=0;o<r.length;o++){let i=r[o].name;s[i]=this.hasOwnProperty(i)?this[i]:r[o].init(e,s)}return s}toJSON(e){let t={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(t.storedMarks=this.storedMarks.map(r=>r.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let s=e[r],o=s.spec.state;o&&o.toJSON&&(t[r]=o.toJSON.call(s,this[s.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let s=new nb(e.schema,e.plugins),o=new Mc(s);return s.fields.forEach(i=>{if(i.name=="doc")o.doc=mo.fromJSON(e.schema,t.doc);else if(i.name=="selection")o.selection=Je.fromJSON(o.doc,t.selection);else if(i.name=="storedMarks")t.storedMarks&&(o.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let a in r){let l=r[a],c=l.spec.state;if(l.key==i.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,a)){o[i.name]=c.fromJSON.call(l,e,t[a],o);return}}o[i.name]=i.init(e,o)}}),o}}function gL(n,e,t){for(let r in n){let s=n[r];s instanceof Function?s=s.bind(e):r=="handleDOMEvents"&&(s=gL(s,e,{})),t[r]=s}return t}class Ht{constructor(e){this.spec=e,this.props={},e.props&&gL(e.props,this,this.props),this.key=e.key?e.key.key:mL("plugin")}getState(e){return e[this.key]}}const rb=Object.create(null);function mL(n){return n in rb?n+"$"+ ++rb[n]:(rb[n]=0,n+"$")}class Sn{constructor(e="key"){this.key=mL(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const y1=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function yL(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const SL=(n,e,t)=>{let r=yL(n,t);if(!r)return!1;let s=S1(r);if(!s){let i=r.blockRange(),a=i&&bd(i);return a==null?!1:(e&&e(n.tr.lift(i,a).scrollIntoView()),!0)}let o=s.nodeBefore;if(EL(n,s,e,-1))return!0;if(r.parent.content.size==0&&(nd(o,"end")||Me.isSelectable(o)))for(let i=r.depth;;i--){let a=Dy(n.doc,r.before(i),r.after(i),ye.empty);if(a&&a.slice.size<a.to-a.from){if(e){let l=n.tr.step(a);l.setSelection(nd(o,"end")?Je.findFrom(l.doc.resolve(l.mapping.map(s.pos,-1)),-1):Me.create(l.doc,s.pos-o.nodeSize)),e(l.scrollIntoView())}return!0}if(i==1||r.node(i-1).childCount>1)break}return o.isAtom&&s.depth==r.depth-1?(e&&e(n.tr.delete(s.pos-o.nodeSize,s.pos).scrollIntoView()),!0):!1},NY=(n,e,t)=>{let r=yL(n,t);if(!r)return!1;let s=S1(r);return s?xL(n,s,e):!1},FY=(n,e,t)=>{let r=wL(n,t);if(!r)return!1;let s=x1(r);return s?xL(n,s,e):!1};function xL(n,e,t){let r=e.nodeBefore,s=r,o=e.pos-1;for(;!s.isTextblock;o--){if(s.type.spec.isolating)return!1;let u=s.lastChild;if(!u)return!1;s=u}let i=e.nodeAfter,a=i,l=e.pos+1;for(;!a.isTextblock;l++){if(a.type.spec.isolating)return!1;let u=a.firstChild;if(!u)return!1;a=u}let c=Dy(n.doc,o,l,ye.empty);if(!c||c.from!=o||c instanceof In&&c.slice.size>=l-o)return!1;if(t){let u=n.tr.step(c);u.setSelection(He.create(u.doc,o)),t(u.scrollIntoView())}return!0}function nd(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const bL=(n,e,t)=>{let{$head:r,empty:s}=n.selection,o=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;o=S1(r)}let i=o&&o.nodeBefore;return!i||!Me.isSelectable(i)?!1:(e&&e(n.tr.setSelection(Me.create(n.doc,o.pos-i.nodeSize)).scrollIntoView()),!0)};function S1(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function wL(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset<t.parent.content.size)?null:t}const vL=(n,e,t)=>{let r=wL(n,t);if(!r)return!1;let s=x1(r);if(!s)return!1;let o=s.nodeAfter;if(EL(n,s,e,1))return!0;if(r.parent.content.size==0&&(nd(o,"start")||Me.isSelectable(o))){let i=Dy(n.doc,r.before(),r.after(),ye.empty);if(i&&i.slice.size<i.to-i.from){if(e){let a=n.tr.step(i);a.setSelection(nd(o,"start")?Je.findFrom(a.doc.resolve(a.mapping.map(s.pos)),1):Me.create(a.doc,a.mapping.map(s.pos))),e(a.scrollIntoView())}return!0}}return o.isAtom&&s.depth==r.depth-1?(e&&e(n.tr.delete(s.pos,s.pos+o.nodeSize).scrollIntoView()),!0):!1},CL=(n,e,t)=>{let{$head:r,empty:s}=n.selection,o=r;if(!s)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset<r.parent.content.size)return!1;o=x1(r)}let i=o&&o.nodeAfter;return!i||!Me.isSelectable(i)?!1:(e&&e(n.tr.setSelection(Me.create(n.doc,o.pos)).scrollIntoView()),!0)};function x1(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){let t=n.node(e);if(n.index(e)+1<t.childCount)return n.doc.resolve(n.after(e+1));if(t.type.spec.isolating)break}return null}const BY=(n,e)=>{let t=n.selection,r=t instanceof Me,s;if(r){if(t.node.isTextblock||!Xa(n.doc,t.from))return!1;s=t.from}else if(s=Ay(n.doc,t.from,-1),s==null)return!1;if(e){let o=n.tr.join(s);r&&o.setSelection(Me.create(o.doc,s-n.doc.resolve(s).nodeBefore.nodeSize)),e(o.scrollIntoView())}return!0},zY=(n,e)=>{let t=n.selection,r;if(t instanceof Me){if(t.node.isTextblock||!Xa(n.doc,t.to))return!1;r=t.to}else if(r=Ay(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},$Y=(n,e)=>{let{$from:t,$to:r}=n.selection,s=t.blockRange(r),o=s&&bd(s);return o==null?!1:(e&&e(n.tr.lift(s,o).scrollIntoView()),!0)},PL=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(`
199
+ `).scrollIntoView()),!0)};function b1(n){for(let e=0;e<n.edgeCount;e++){let{type:t}=n.edge(e);if(t.isTextblock&&!t.hasRequiredAttrs())return t}return null}const HY=(n,e)=>{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let s=t.node(-1),o=t.indexAfter(-1),i=b1(s.contentMatchAt(o));if(!i||!s.canReplaceWith(o,o,i))return!1;if(e){let a=t.after(),l=n.tr.replaceWith(a,a,i.createAndFill());l.setSelection(Je.near(l.doc.resolve(a),1)),e(l.scrollIntoView())}return!0},TL=(n,e)=>{let t=n.selection,{$from:r,$to:s}=t;if(t instanceof Ss||r.parent.inlineContent||s.parent.inlineContent)return!1;let o=b1(s.parent.contentMatchAt(s.indexAfter()));if(!o||!o.isTextblock)return!1;if(e){let i=(!r.parentOffset&&s.index()<s.parent.childCount?r:s).pos,a=n.tr.insert(i,o.createAndFill());a.setSelection(He.create(a.doc,i+1)),e(a.scrollIntoView())}return!0},IL=(n,e)=>{let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let o=t.before();if(Fi(n.doc,o))return e&&e(n.tr.split(o).scrollIntoView()),!0}let r=t.blockRange(),s=r&&bd(r);return s==null?!1:(e&&e(n.tr.lift(r,s).scrollIntoView()),!0)};function UY(n){return(e,t)=>{let{$from:r,$to:s}=e.selection;if(e.selection instanceof Me&&e.selection.node.isBlock)return!r.parentOffset||!Fi(e.doc,r.pos)?!1:(t&&t(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let o=[],i,a,l=!1,c=!1;for(let f=r.depth;;f--)if(r.node(f).isBlock){l=r.end(f)==r.pos+(r.depth-f),c=r.start(f)==r.pos-(r.depth-f),a=b1(r.node(f-1).contentMatchAt(r.indexAfter(f-1))),o.unshift(l&&a?{type:a}:null),i=f;break}else{if(f==1)return!1;o.unshift(null)}let u=e.tr;(e.selection instanceof He||e.selection instanceof Ss)&&u.deleteSelection();let d=u.mapping.map(r.pos),h=Fi(u.doc,d,o.length,o);if(h||(o[0]=a?{type:a}:null,h=Fi(u.doc,d,o.length,o)),!h)return!1;if(u.split(d,o.length,o),!l&&c&&r.node(i).type!=a){let f=u.mapping.map(r.before(i)),g=u.doc.resolve(f);a&&r.node(i-1).canReplaceWith(g.index(),g.index()+1,a)&&u.setNodeMarkup(u.mapping.map(r.before(i)),a)}return t&&t(u.scrollIntoView()),!0}}const KY=UY(),WY=(n,e)=>{let{$from:t,to:r}=n.selection,s,o=t.sharedDepth(r);return o==0?!1:(s=t.before(o),e&&e(n.tr.setSelection(Me.create(n.doc,s))),!0)};function VY(n,e,t){let r=e.nodeBefore,s=e.nodeAfter,o=e.index();return!r||!s||!r.type.compatibleContent(s.type)?!1:!r.content.size&&e.parent.canReplace(o-1,o)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(o,o+1)||!(s.isTextblock||Xa(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function EL(n,e,t,r){let s=e.nodeBefore,o=e.nodeAfter,i,a,l=s.type.spec.isolating||o.type.spec.isolating;if(!l&&VY(n,e,t))return!0;let c=!l&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(i=(a=s.contentMatchAt(s.childCount)).findWrapping(o.type))&&a.matchType(i[0]||o.type).validEnd){if(t){let f=e.pos+o.nodeSize,g=ne.empty;for(let S=i.length-1;S>=0;S--)g=ne.from(i[S].create(null,g));g=ne.from(s.copy(g));let m=n.tr.step(new kn(e.pos-1,f,e.pos,f,new ye(g,1,0),i.length,!0)),y=m.doc.resolve(f+2*i.length);y.nodeAfter&&y.nodeAfter.type==s.type&&Xa(m.doc,y.pos)&&m.join(y.pos),t(m.scrollIntoView())}return!0}let u=o.type.spec.isolating||r>0&&l?null:Je.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),h=d&&bd(d);if(h!=null&&h>=e.depth)return t&&t(n.tr.lift(d,h).scrollIntoView()),!0;if(c&&nd(o,"start",!0)&&nd(s,"end")){let f=s,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let m=o,y=1;for(;!m.isTextblock;m=m.firstChild)y++;if(f.canReplace(f.childCount,f.childCount,m.content)){if(t){let S=ne.empty;for(let w=g.length-1;w>=0;w--)S=ne.from(g[w].copy(S));let b=n.tr.step(new kn(e.pos-g.length,e.pos+o.nodeSize,e.pos+y,e.pos+o.nodeSize-y,new ye(S,g.length,0),0,!0));t(b.scrollIntoView())}return!0}}return!1}function kL(n){return function(e,t){let r=e.selection,s=n<0?r.$from:r.$to,o=s.depth;for(;s.node(o).isInline;){if(!o)return!1;o--}return s.node(o).isTextblock?(t&&t(e.tr.setSelection(He.create(e.doc,n<0?s.start(o):s.end(o)))),!0):!1}}const GY=kL(-1),YY=kL(1);function XY(n,e=null){return function(t,r){let{$from:s,$to:o}=t.selection,i=s.blockRange(o),a=i&&g1(i,n,e);return a?(r&&r(t.tr.wrap(i,a).scrollIntoView()),!0):!1}}function RI(n,e=null){return function(t,r){let s=!1;for(let o=0;o<t.selection.ranges.length&&!s;o++){let{$from:{pos:i},$to:{pos:a}}=t.selection.ranges[o];t.doc.nodesBetween(i,a,(l,c)=>{if(s)return!1;if(!(!l.isTextblock||l.hasMarkup(n,e)))if(l.type==n)s=!0;else{let u=t.doc.resolve(c),d=u.index();s=u.parent.canReplaceWith(d,d+1,n)}})}if(!s)return!1;if(r){let o=t.tr;for(let i=0;i<t.selection.ranges.length;i++){let{$from:{pos:a},$to:{pos:l}}=t.selection.ranges[i];o.setBlockType(a,l,n,e)}r(o.scrollIntoView())}return!0}}function w1(...n){return function(e,t,r){for(let s=0;s<n.length;s++)if(n[s](e,t,r))return!0;return!1}}w1(y1,SL,bL);w1(y1,vL,CL);w1(PL,TL,IL,KY);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function qY(n,e=null){return function(t,r){let{$from:s,$to:o}=t.selection,i=s.blockRange(o);if(!i)return!1;let a=r?t.tr:null;return ZY(a,i,n,e)?(r&&r(a.scrollIntoView()),!0):!1}}function ZY(n,e,t,r=null){let s=!1,o=e,i=e.$from.doc;if(e.depth>=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let l=i.resolve(e.start-2);o=new Zg(l,l,e.depth),e.endIndex<e.parent.childCount&&(e=new Zg(e.$from,i.resolve(e.$to.end(e.depth)),e.depth)),s=!0}let a=g1(o,t,r,e);return a?(n&&JY(n,e,a,s,t),!0):!1}function JY(n,e,t,r,s){let o=ne.empty;for(let u=t.length-1;u>=0;u--)o=ne.from(t[u].type.create(t[u].attrs,o));n.step(new kn(e.start-(r?2:0),e.end,e.start,e.end,new ye(o,0,0),t.length,!0));let i=0;for(let u=0;u<t.length;u++)t[u].type==s&&(i=u+1);let a=t.length-i,l=e.start+t.length-(r?2:0),c=e.parent;for(let u=e.startIndex,d=e.endIndex,h=!0;u<d;u++,h=!1)!h&&Fi(n.doc,l,a)&&(n.split(l,a),l+=2*a),l+=c.child(u).nodeSize;return n}function QY(n){return function(e,t){let{$from:r,$to:s}=e.selection,o=r.blockRange(s,i=>i.childCount>0&&i.firstChild.type==n);return o?t?r.node(o.depth-1).type==n?eX(e,t,n,o):tX(e,t,o):!0:!1}}function eX(n,e,t,r){let s=n.tr,o=r.end,i=r.$to.end(r.depth);o<i&&(s.step(new kn(o-1,i,o,i,new ye(ne.from(t.create(null,r.parent.copy())),1,0),1,!0)),r=new Zg(s.doc.resolve(r.$from.pos),s.doc.resolve(i),r.depth));const a=bd(r);if(a==null)return!1;s.lift(r,a);let l=s.doc.resolve(s.mapping.map(o,-1)-1);return Xa(s.doc,l.pos)&&l.nodeBefore.type==l.nodeAfter.type&&s.join(l.pos),e(s.scrollIntoView()),!0}function tX(n,e,t){let r=n.tr,s=t.parent;for(let f=t.end,g=t.endIndex-1,m=t.startIndex;g>m;g--)f-=s.child(g).nodeSize,r.delete(f-1,f+1);let o=r.doc.resolve(t.start),i=o.nodeAfter;if(r.mapping.map(t.end)!=t.start+o.nodeAfter.nodeSize)return!1;let a=t.startIndex==0,l=t.endIndex==s.childCount,c=o.node(-1),u=o.index(-1);if(!c.canReplace(u+(a?0:1),u+1,i.content.append(l?ne.empty:ne.from(s))))return!1;let d=o.pos,h=d+i.nodeSize;return r.step(new kn(d-(a?1:0),h+(l?1:0),d+1,h-1,new ye((a?ne.empty:ne.from(s.copy(ne.empty))).append(l?ne.empty:ne.from(s.copy(ne.empty))),a?0:1,l?0:1),a?0:1)),e(r.scrollIntoView()),!0}function nX(n){return function(e,t){let{$from:r,$to:s}=e.selection,o=r.blockRange(s,c=>c.childCount>0&&c.firstChild.type==n);if(!o)return!1;let i=o.startIndex;if(i==0)return!1;let a=o.parent,l=a.child(i-1);if(l.type!=n)return!1;if(t){let c=l.lastChild&&l.lastChild.type==a.type,u=ne.from(c?n.create():null),d=new ye(ne.from(n.create(null,ne.from(a.type.create(null,u)))),c?3:1,0),h=o.start,f=o.end;t(e.tr.step(new kn(h-(c?3:1),f,h,f,d,1,!0)).scrollIntoView())}return!0}}const Nn=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},rd=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Jw=null;const ki=function(n,e,t){let r=Jw||(Jw=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},rX=function(){Jw=null},Ol=function(n,e,t,r){return t&&(LI(n,e,t,r,-1)||LI(n,e,t,r,1))},sX=/^(img|br|input|textarea|hr)$/i;function LI(n,e,t,r,s){for(var o;;){if(n==t&&e==r)return!0;if(e==(s<0?0:Fs(n))){let i=n.parentNode;if(!i||i.nodeType!=1||Zh(n)||sX.test(n.nodeName)||n.contentEditable=="false")return!1;e=Nn(n)+(s<0?0:1),n=i}else if(n.nodeType==1){let i=n.childNodes[e+(s<0?-1:0)];if(i.nodeType==1&&i.contentEditable=="false")if(!((o=i.pmViewDesc)===null||o===void 0)&&o.ignoreForSelection)e+=s;else return!1;else n=i,e=s<0?Fs(n):0}else return!1}}function Fs(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function oX(n,e){for(;;){if(n.nodeType==3&&e)return n;if(n.nodeType==1&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=Fs(n)}else if(n.parentNode&&!Zh(n))e=Nn(n),n=n.parentNode;else return null}}function iX(n,e){for(;;){if(n.nodeType==3&&e<n.nodeValue.length)return n;if(n.nodeType==1&&e<n.childNodes.length){if(n.contentEditable=="false")return null;n=n.childNodes[e],e=0}else if(n.parentNode&&!Zh(n))e=Nn(n)+1,n=n.parentNode;else return null}}function aX(n,e,t){for(let r=e==0,s=e==Fs(n);r||s;){if(n==t)return!0;let o=Nn(n);if(n=n.parentNode,!n)return!1;r=r&&o==0,s=s&&o==Fs(n)}}function Zh(n){let e;for(let t=n;t&&!(e=t.pmViewDesc);t=t.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==n||e.contentDOM==n)}const Ry=function(n){return n.focusNode&&Ol(n.focusNode,n.focusOffset,n.anchorNode,n.anchorOffset)};function hl(n,e){let t=document.createEvent("Event");return t.initEvent("keydown",!0,!0),t.keyCode=n,t.key=t.code=e,t}function lX(n){let e=n.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function cX(n,e,t){if(n.caretPositionFromPoint)try{let r=n.caretPositionFromPoint(e,t);if(r)return{node:r.offsetNode,offset:Math.min(Fs(r.offsetNode),r.offset)}}catch{}if(n.caretRangeFromPoint){let r=n.caretRangeFromPoint(e,t);if(r)return{node:r.startContainer,offset:Math.min(Fs(r.startContainer),r.startOffset)}}}const Go=typeof navigator<"u"?navigator:null,jI=typeof document<"u"?document:null,qa=Go&&Go.userAgent||"",Qw=/Edge\/(\d+)/.exec(qa),_L=/MSIE \d/.exec(qa),e0=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(qa),Qr=!!(_L||e0||Qw),Ea=_L?document.documentMode:e0?+e0[1]:Qw?+Qw[1]:0,Hs=!Qr&&/gecko\/(\d+)/i.test(qa);Hs&&+(/Firefox\/(\d+)/.exec(qa)||[0,0])[1];const t0=!Qr&&/Chrome\/(\d+)/.exec(qa),Un=!!t0,ML=t0?+t0[1]:0,cr=!Qr&&!!Go&&/Apple Computer/.test(Go.vendor),sd=cr&&(/Mobile\/\w+/.test(qa)||!!Go&&Go.maxTouchPoints>2),Ls=sd||(Go?/Mac/.test(Go.platform):!1),AL=Go?/Win/.test(Go.platform):!1,Oi=/Android \d/.test(qa),Jh=!!jI&&"webkitFontSmoothing"in jI.documentElement.style,dX=Jh?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function uX(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function bi(n,e){return typeof n=="number"?n:n[e]}function hX(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function NI(n,e,t){let r=n.someProp("scrollThreshold")||0,s=n.someProp("scrollMargin")||5,o=n.dom.ownerDocument;for(let i=t||n.dom;i;){if(i.nodeType!=1){i=rd(i);continue}let a=i,l=a==o.body,c=l?uX(o):hX(a),u=0,d=0;if(e.top<c.top+bi(r,"top")?d=-(c.top-e.top+bi(s,"top")):e.bottom>c.bottom-bi(r,"bottom")&&(d=e.bottom-e.top>c.bottom-c.top?e.top+bi(s,"top")-c.top:e.bottom-c.bottom+bi(s,"bottom")),e.left<c.left+bi(r,"left")?u=-(c.left-e.left+bi(s,"left")):e.right>c.right-bi(r,"right")&&(u=e.right-c.right+bi(s,"right")),u||d)if(l)o.defaultView.scrollBy(u,d);else{let f=a.scrollLeft,g=a.scrollTop;d&&(a.scrollTop+=d),u&&(a.scrollLeft+=u);let m=a.scrollLeft-f,y=a.scrollTop-g;e={left:e.left-m,top:e.top-y,right:e.right-m,bottom:e.bottom-y}}let h=l?"fixed":getComputedStyle(i).position;if(/^(fixed|sticky)$/.test(h))break;i=h=="absolute"?i.offsetParent:rd(i)}}function pX(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,s;for(let o=(e.left+e.right)/2,i=t+1;i<Math.min(innerHeight,e.bottom);i+=5){let a=n.root.elementFromPoint(o,i);if(!a||a==n.dom||!n.dom.contains(a))continue;let l=a.getBoundingClientRect();if(l.top>=t-20){r=a,s=l.top;break}}return{refDOM:r,refTop:s,stack:DL(n.dom)}}function DL(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=rd(r));return e}function fX({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;OL(t,r==0?0:r-e)}function OL(n,e){for(let t=0;t<n.length;t++){let{dom:r,top:s,left:o}=n[t];r.scrollTop!=s+e&&(r.scrollTop=s+e),r.scrollLeft!=o&&(r.scrollLeft=o)}}let uc=null;function gX(n){if(n.setActive)return n.setActive();if(uc)return n.focus(uc);let e=DL(n);n.focus(uc==null?{get preventScroll(){return uc={preventScroll:!0},!0}}:void 0),uc||(uc=!1,OL(e,0))}function RL(n,e){let t,r=2e8,s,o=0,i=e.top,a=e.top,l,c;for(let u=n.firstChild,d=0;u;u=u.nextSibling,d++){let h;if(u.nodeType==1)h=u.getClientRects();else if(u.nodeType==3)h=ki(u).getClientRects();else continue;for(let f=0;f<h.length;f++){let g=h[f];if(g.top<=i&&g.bottom>=a){i=Math.max(g.bottom,i),a=Math.min(g.top,a);let m=g.left>e.left?g.left-e.left:g.right<e.left?e.left-g.right:0;if(m<r){t=u,r=m,s=m&&t.nodeType==3?{left:g.right<e.left?g.right:g.left,top:e.top}:e,u.nodeType==1&&m&&(o=d+(e.left>=(g.left+g.right)/2?1:0));continue}}else g.top>e.top&&!l&&g.left<=e.left&&g.right>=e.left&&(l=u,c={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top});!t&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom)&&(o=d+1)}}return!t&&l&&(t=l,s=c,r=0),t&&t.nodeType==3?mX(t,s):!t||r&&t.nodeType==1?{node:n,offset:o}:RL(t,s)}function mX(n,e){let t=n.nodeValue.length,r=document.createRange(),s;for(let o=0;o<t;o++){r.setEnd(n,o+1),r.setStart(n,o);let i=da(r,1);if(i.top!=i.bottom&&v1(e,i)){s={node:n,offset:o+(e.left>=(i.left+i.right)/2?1:0)};break}}return r.detach(),s||{node:n,offset:0}}function v1(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function yX(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left<n.getBoundingClientRect().left?t:n}function SX(n,e,t){let{node:r,offset:s}=RL(e,t),o=-1;if(r.nodeType==1&&!r.firstChild){let i=r.getBoundingClientRect();o=i.left!=i.right&&t.left>(i.left+i.right)/2?1:-1}return n.docView.posFromDOM(r,s,o)}function xX(n,e,t,r){let s=-1;for(let o=e,i=!1;o!=n.dom;){let a=n.docView.nearestDesc(o,!0),l;if(!a)return null;if(a.dom.nodeType==1&&(a.node.isBlock&&a.parent||!a.contentDOM)&&((l=a.dom.getBoundingClientRect()).width||l.height)&&(a.node.isBlock&&a.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(a.dom.nodeName)&&(!i&&l.left>r.left||l.top>r.top?s=a.posBefore:(!i&&l.right<r.left||l.bottom<r.top)&&(s=a.posAfter),i=!0),!a.contentDOM&&s<0&&!a.node.isText))return(a.node.isBlock?r.top<(l.top+l.bottom)/2:r.left<(l.left+l.right)/2)?a.posBefore:a.posAfter;o=a.dom.parentNode}return s>-1?s:n.docView.posFromDOM(e,t,-1)}function LL(n,e,t){let r=n.childNodes.length;if(r&&t.top<t.bottom)for(let s=Math.max(0,Math.min(r-1,Math.floor(r*(e.top-t.top)/(t.bottom-t.top))-2)),o=s;;){let i=n.childNodes[o];if(i.nodeType==1){let a=i.getClientRects();for(let l=0;l<a.length;l++){let c=a[l];if(v1(e,c))return LL(i,e,c)}}if((o=(o+1)%r)==s)break}return n}function bX(n,e){let t=n.dom.ownerDocument,r,s=0,o=cX(t,e.left,e.top);o&&({node:r,offset:s}=o);let i=(n.root.elementFromPoint?n.root:t).elementFromPoint(e.left,e.top),a;if(!i||!n.dom.contains(i.nodeType!=1?i.parentNode:i)){let c=n.dom.getBoundingClientRect();if(!v1(e,c)||(i=LL(n.dom,e,c),!i))return null}if(cr)for(let c=i;r&&c;c=rd(c))c.draggable&&(r=void 0);if(i=yX(i,e),r){if(Hs&&r.nodeType==1&&(s=Math.min(s,r.childNodes.length),s<r.childNodes.length)){let u=r.childNodes[s],d;u.nodeName=="IMG"&&(d=u.getBoundingClientRect()).right<=e.left&&d.bottom>e.top&&s++}let c;Jh&&s&&r.nodeType==1&&(c=r.childNodes[s-1]).nodeType==1&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&s--,r==n.dom&&s==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?a=n.state.doc.content.size:(s==0||r.nodeType!=1||r.childNodes[s-1].nodeName!="BR")&&(a=xX(n,r,s,e))}a==null&&(a=SX(n,i,e));let l=n.docView.nearestDesc(i,!0);return{pos:a,inside:l?l.posAtStart-l.border:-1}}function FI(n){return n.top<n.bottom||n.left<n.right}function da(n,e){let t=n.getClientRects();if(t.length){let r=t[e<0?0:t.length-1];if(FI(r))return r}return Array.prototype.find.call(t,FI)||n.getBoundingClientRect()}const wX=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function jL(n,e,t){let{node:r,offset:s,atom:o}=n.docView.domFromPos(e,t<0?-1:1),i=Jh||Hs;if(r.nodeType==3)if(i&&(wX.test(r.nodeValue)||(t<0?!s:s==r.nodeValue.length))){let l=da(ki(r,s,s),t);if(Hs&&s&&/\s/.test(r.nodeValue[s-1])&&s<r.nodeValue.length){let c=da(ki(r,s-1,s-1),-1);if(c.top==l.top){let u=da(ki(r,s,s+1),-1);if(u.top!=l.top)return Ud(u,u.left<c.left)}}return l}else{let l=s,c=s,u=t<0?1:-1;return t<0&&!s?(c++,u=-1):t>=0&&s==r.nodeValue.length?(l--,u=1):t<0?l--:c++,Ud(da(ki(r,l,c),u),u<0)}if(!n.state.doc.resolve(e-(o||0)).parent.inlineContent){if(o==null&&s&&(t<0||s==Fs(r))){let l=r.childNodes[s-1];if(l.nodeType==1)return sb(l.getBoundingClientRect(),!1)}if(o==null&&s<Fs(r)){let l=r.childNodes[s];if(l.nodeType==1)return sb(l.getBoundingClientRect(),!0)}return sb(r.getBoundingClientRect(),t>=0)}if(o==null&&s&&(t<0||s==Fs(r))){let l=r.childNodes[s-1],c=l.nodeType==3?ki(l,Fs(l)-(i?0:1)):l.nodeType==1&&(l.nodeName!="BR"||!l.nextSibling)?l:null;if(c)return Ud(da(c,1),!1)}if(o==null&&s<Fs(r)){let l=r.childNodes[s];for(;l.pmViewDesc&&l.pmViewDesc.ignoreForCoords;)l=l.nextSibling;let c=l?l.nodeType==3?ki(l,0,i?0:1):l.nodeType==1?l:null:null;if(c)return Ud(da(c,-1),!0)}return Ud(da(r.nodeType==3?ki(r):r,-t),t>=0)}function Ud(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function sb(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function NL(n,e,t){let r=n.state,s=n.root.activeElement;r!=e&&n.updateState(e),s!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),s!=n.dom&&s&&s.focus()}}function vX(n,e,t){let r=e.selection,s=t=="up"?r.$from:r.$to;return NL(n,e,()=>{let{node:o}=n.docView.domFromPos(s.pos,t=="up"?-1:1);for(;;){let a=n.docView.nearestDesc(o,!0);if(!a)break;if(a.node.isBlock){o=a.contentDOM||a.dom;break}o=a.dom.parentNode}let i=jL(n,s.pos,1);for(let a=o.firstChild;a;a=a.nextSibling){let l;if(a.nodeType==1)l=a.getClientRects();else if(a.nodeType==3)l=ki(a,0,a.nodeValue.length).getClientRects();else continue;for(let c=0;c<l.length;c++){let u=l[c];if(u.bottom>u.top+1&&(t=="up"?i.top-u.top>(u.bottom-i.top)*2:u.bottom-i.bottom>(i.bottom-u.top)*2))return!1}}return!0})}const CX=/[\u0590-\u08ac]/;function PX(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let s=r.parentOffset,o=!s,i=s==r.parent.content.size,a=n.domSelection();return a?!CX.test(r.parent.textContent)||!a.modify?t=="left"||t=="backward"?o:i:NL(n,e,()=>{let{focusNode:l,focusOffset:c,anchorNode:u,anchorOffset:d}=n.domSelectionRange(),h=a.caretBidiLevel;a.modify("move",t,"character");let f=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:g,focusOffset:m}=n.domSelectionRange(),y=g&&!f.contains(g.nodeType==1?g:g.parentNode)||l==g&&c==m;try{a.collapse(u,d),l&&(l!=u||c!=d)&&a.extend&&a.extend(l,c)}catch{}return h!=null&&(a.caretBidiLevel=h),y}):r.pos==r.start()||r.pos==r.end()}let BI=null,zI=null,$I=!1;function TX(n,e,t){return BI==e&&zI==t?$I:(BI=e,zI=t,$I=t=="up"||t=="down"?vX(n,e,t):PX(n,e,t))}const Us=0,HI=1,ml=2,Yo=3;class Qh{constructor(e,t,r,s){this.parent=e,this.children=t,this.dom=r,this.contentDOM=s,this.dirty=Us,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;t<this.children.length;t++)e+=this.children[t].size;return e}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let e=0;e<this.children.length;e++)this.children[e].destroy()}posBeforeChild(e){for(let t=0,r=this.posAtStart;;t++){let s=this.children[t];if(s==e)return r;r+=s.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(e,t,r){if(this.contentDOM&&this.contentDOM.contains(e.nodeType==1?e:e.parentNode))if(r<0){let o,i;if(e==this.contentDOM)o=e.childNodes[t-1];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;o=e.previousSibling}for(;o&&!((i=o.pmViewDesc)&&i.parent==this);)o=o.previousSibling;return o?this.posBeforeChild(i)+i.size:this.posAtStart}else{let o,i;if(e==this.contentDOM)o=e.childNodes[t];else{for(;e.parentNode!=this.contentDOM;)e=e.parentNode;o=e.nextSibling}for(;o&&!((i=o.pmViewDesc)&&i.parent==this);)o=o.nextSibling;return o?this.posBeforeChild(i):this.posAtEnd}let s;if(e==this.dom&&this.contentDOM)s=t>Nn(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))s=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(t==0)for(let o=e;;o=o.parentNode){if(o==this.dom){s=!1;break}if(o.previousSibling)break}if(s==null&&t==e.childNodes.length)for(let o=e;;o=o.parentNode){if(o==this.dom){s=!0;break}if(o.nextSibling)break}}return s??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,s=e;s;s=s.parentNode){let o=this.getDesc(s),i;if(o&&(!t||o.node))if(r&&(i=o.nodeDOM)&&!(i.nodeType==1?i.contains(e.nodeType==1?e:e.parentNode):i==e))r=!1;else return o}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let s=e;s;s=s.parentNode){let o=this.getDesc(s);if(o)return o.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;t<this.children.length;t++){let s=this.children[t],o=r+s.size;if(r==e&&o!=r){for(;!s.border&&s.children.length;)for(let i=0;i<s.children.length;i++){let a=s.children[i];if(a.size){s=a;break}}return s}if(e<o)return s.descAt(e-r-s.border);r=o}}domFromPos(e,t){if(!this.contentDOM)return{node:this.dom,offset:0,atom:e+1};let r=0,s=0;for(let o=0;r<this.children.length;r++){let i=this.children[r],a=o+i.size;if(a>e||i instanceof BL){s=e-o;break}o=a}if(s)return this.children[r].domFromPos(s-this.children[r].border,t);for(let o;r&&!(o=this.children[r-1]).size&&o instanceof FL&&o.side>=0;r--);if(t<=0){let o,i=!0;for(;o=r?this.children[r-1]:null,!(!o||o.dom.parentNode==this.contentDOM);r--,i=!1);return o&&t&&i&&!o.border&&!o.domAtom?o.domFromPos(o.size,t):{node:this.contentDOM,offset:o?Nn(o.dom)+1:0}}else{let o,i=!0;for(;o=r<this.children.length?this.children[r]:null,!(!o||o.dom.parentNode==this.contentDOM);r++,i=!1);return o&&i&&!o.border&&!o.domAtom?o.domFromPos(0,t):{node:this.contentDOM,offset:o?Nn(o.dom):this.contentDOM.childNodes.length}}}parseRange(e,t,r=0){if(this.children.length==0)return{node:this.contentDOM,from:e,to:t,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let s=-1,o=-1;for(let i=r,a=0;;a++){let l=this.children[a],c=i+l.size;if(s==-1&&e<=c){let u=i+l.border;if(e>=u&&t<=c-l.border&&l.node&&l.contentDOM&&this.contentDOM.contains(l.contentDOM))return l.parseRange(e,t,u);e=i;for(let d=a;d>0;d--){let h=this.children[d-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){s=Nn(h.dom)+1;break}e-=h.size}s==-1&&(s=0)}if(s>-1&&(c>t||a==this.children.length-1)){t=c;for(let u=a+1;u<this.children.length;u++){let d=this.children[u];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(-1)){o=Nn(d.dom);break}t+=d.size}o==-1&&(o=this.contentDOM.childNodes.length);break}i=c}return{node:this.contentDOM,from:e,to:t,fromOffset:s,toOffset:o}}emptyChildAt(e){if(this.border||!this.contentDOM||!this.children.length)return!1;let t=this.children[e<0?0:this.children.length-1];return t.size==0||t.emptyChildAt(e)}domAfterPos(e){let{node:t,offset:r}=this.domFromPos(e,0);if(t.nodeType!=1||r==t.childNodes.length)throw new RangeError("No node after pos "+e);return t.childNodes[r]}setSelection(e,t,r,s=!1){let o=Math.min(e,t),i=Math.max(e,t);for(let f=0,g=0;f<this.children.length;f++){let m=this.children[f],y=g+m.size;if(o>g&&i<y)return m.setSelection(e-g-m.border,t-g-m.border,r,s);g=y}let a=this.domFromPos(e,e?-1:1),l=t==e?a:this.domFromPos(t,t?-1:1),c=r.root.getSelection(),u=r.domSelectionRange(),d=!1;if((Hs||cr)&&e==t){let{node:f,offset:g}=a;if(f.nodeType==3){if(d=!!(g&&f.nodeValue[g-1]==`
200
+ `),d&&g==f.nodeValue.length)for(let m=f,y;m;m=m.parentNode){if(y=m.nextSibling){y.nodeName=="BR"&&(a=l={node:y.parentNode,offset:Nn(y)+1});break}let S=m.pmViewDesc;if(S&&S.node&&S.node.isBlock)break}}else{let m=f.childNodes[g-1];d=m&&(m.nodeName=="BR"||m.contentEditable=="false")}}if(Hs&&u.focusNode&&u.focusNode!=l.node&&u.focusNode.nodeType==1){let f=u.focusNode.childNodes[u.focusOffset];f&&f.contentEditable=="false"&&(s=!0)}if(!(s||d&&cr)&&Ol(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Ol(l.node,l.offset,u.focusNode,u.focusOffset))return;let h=!1;if((c.extend||e==t)&&!(d&&Hs)){c.collapse(a.node,a.offset);try{e!=t&&c.extend(l.node,l.offset),h=!0}catch{}}if(!h){if(e>t){let g=a;a=l,l=g}let f=document.createRange();f.setEnd(l.node,l.offset),f.setStart(a.node,a.offset),c.removeAllRanges(),c.addRange(f)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,s=0;s<this.children.length;s++){let o=this.children[s],i=r+o.size;if(r==i?e<=i&&t>=r:e<i&&t>r){let a=r+o.border,l=i-o.border;if(e>=a&&t<=l){this.dirty=e==r||t==i?ml:HI,e==a&&t==l&&(o.contentLost||o.dom.parentNode!=this.contentDOM)?o.dirty=Yo:o.markDirty(e-a,t-a);return}else o.dirty=o.dom==o.contentDOM&&o.dom.parentNode==this.contentDOM&&!o.children.length?ml:Yo}r=i}this.dirty=ml}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?ml:HI;t.dirty<r&&(t.dirty=r)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class FL extends Qh{constructor(e,t,r,s){let o,i=t.type.toDOM;if(typeof i=="function"&&(i=i(r,()=>{if(!o)return s;if(o.parent)return o.parent.posBeforeChild(o)})),!t.type.spec.raw){if(i.nodeType!=1){let a=document.createElement("span");a.appendChild(i),i=a}i.contentEditable="false",i.classList.add("ProseMirror-widget")}super(e,[],i,null),this.widget=t,this.widget=t,o=this}matchesWidget(e){return this.dirty==Us&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class IX extends Qh{constructor(e,t,r,s){super(e,[],t,null),this.textDOM=r,this.text=s}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Rl extends Qh{constructor(e,t,r,s,o){super(e,[],r,s),this.mark=t,this.spec=o}static create(e,t,r,s){let o=s.nodeViews[t.type.name],i=o&&o(t,s,r);return(!i||!i.dom)&&(i=ql.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Rl(e,t,i.dom,i.contentDOM||i.dom,i)}parseRule(){return this.dirty&Yo||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Yo&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Us){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty<this.dirty&&(r.dirty=this.dirty),this.dirty=Us}}slice(e,t,r){let s=Rl.create(this.parent,this.mark,!0,r),o=this.children,i=this.size;t<i&&(o=r0(o,t,i,r)),e>0&&(o=r0(o,0,e,r));for(let a=0;a<o.length;a++)o[a].parent=s;return s.children=o,s}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class ka extends Qh{constructor(e,t,r,s,o,i,a,l,c){super(e,[],o,i),this.node=t,this.outerDeco=r,this.innerDeco=s,this.nodeDOM=a}static create(e,t,r,s,o,i){let a=o.nodeViews[t.type.name],l,c=a&&a(t,o,()=>{if(!l)return i;if(l.parent)return l.parent.posBeforeChild(l)},r,s),u=c&&c.dom,d=c&&c.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=ql.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let h=u;return u=HL(u,r,t),c?l=new EX(e,t,r,s,u,d||null,h,c,o,i+1):t.isText?new Ly(e,t,r,s,u,h,o):new ka(e,t,r,s,u,d||null,h,o,i+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let t=this.children.length-1;t>=0;t--){let r=this.children[t];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>ne.empty)}return e}matchesNode(e,t,r){return this.dirty==Us&&e.eq(this.node)&&Qg(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,s=t,o=e.composing?this.localCompositionInfo(e,t):null,i=o&&o.pos>-1?o:null,a=o&&o.pos<0,l=new _X(this,i&&i.node,e);DX(this.node,this.innerDeco,(c,u,d)=>{c.spec.marks?l.syncToMarks(c.spec.marks,r,e,u):c.type.side>=0&&!d&&l.syncToMarks(u==this.node.childCount?wt.none:this.node.child(u).marks,r,e,u),l.placeWidget(c,e,s)},(c,u,d,h)=>{l.syncToMarks(c.marks,r,e,h);let f;l.findNodeMatch(c,u,d,h)||a&&e.state.selection.from>s&&e.state.selection.to<s+c.nodeSize&&(f=l.findIndexWithChild(o.node))>-1&&l.updateNodeAt(c,u,d,f,e)||l.updateNextNode(c,u,d,e,h,s)||l.addNode(c,u,d,e,s),s+=c.nodeSize}),l.syncToMarks([],r,e,0),this.node.isTextblock&&l.addTextblockHacks(),l.destroyRest(),(l.changed||this.dirty==ml)&&(i&&this.protectLocalComposition(e,i),zL(this.contentDOM,this.children,e),sd&&OX(this.dom))}localCompositionInfo(e,t){let{from:r,to:s}=e.state.selection;if(!(e.state.selection instanceof He)||r<t||s>t+this.node.content.size)return null;let o=e.input.compositionNode;if(!o||!this.dom.contains(o.parentNode))return null;if(this.node.inlineContent){let i=o.nodeValue,a=RX(this.node.content,i,r-t,s-t);return a<0?null:{node:o,pos:a,text:i}}else return{node:o,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:s}){if(this.getDesc(t))return;let o=t;for(;o.parentNode!=this.contentDOM;o=o.parentNode){for(;o.previousSibling;)o.parentNode.removeChild(o.previousSibling);for(;o.nextSibling;)o.parentNode.removeChild(o.nextSibling);o.pmViewDesc&&(o.pmViewDesc=void 0)}let i=new IX(this,o,t,s);e.input.compositionNodes.push(i),this.children=r0(this.children,r,r+s.length,e,i)}update(e,t,r,s){return this.dirty==Yo||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,s),!0)}updateInner(e,t,r,s){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(s,this.posAtStart),this.dirty=Us}updateOuterDeco(e){if(Qg(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=$L(this.dom,this.nodeDOM,n0(this.outerDeco,this.node,t),n0(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function UI(n,e,t,r,s){HL(r,e,n);let o=new ka(void 0,n,e,t,r,r,r,s,0);return o.contentDOM&&o.updateChildren(s,0),o}class Ly extends ka{constructor(e,t,r,s,o,i,a){super(e,t,r,s,o,null,i,a,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,s){return this.dirty==Yo||this.dirty!=Us&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=Us||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,s.trackWrites==this.nodeDOM&&(s.trackWrites=null)),this.node=e,this.dirty=Us,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let s=this.node.cut(e,t),o=document.createTextNode(s.text);return new Ly(this.parent,s,this.outerDeco,this.innerDeco,o,o,r)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=Yo)}get domAtom(){return!1}isText(e){return this.node.text==e}}class BL extends Qh{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Us&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class EX extends ka{constructor(e,t,r,s,o,i,a,l,c,u){super(e,t,r,s,o,i,a,c,u),this.spec=l}update(e,t,r,s){if(this.dirty==Yo)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let o=this.spec.update(e,t,r);return o&&this.updateInner(e,t,r,s),o}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,s)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,s){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,s)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function zL(n,e,t){let r=n.firstChild,s=!1;for(let o=0;o<e.length;o++){let i=e[o],a=i.dom;if(a.parentNode==n){for(;a!=r;)r=KI(r),s=!0;r=r.nextSibling}else s=!0,n.insertBefore(a,r);if(i instanceof Rl){let l=r?r.previousSibling:n.lastChild;zL(i.contentDOM,i.children,t),r=l?l.nextSibling:n.firstChild}}for(;r;)r=KI(r),s=!0;s&&t.trackWrites==n&&(t.trackWrites=null)}const Bu=function(n){n&&(this.nodeName=n)};Bu.prototype=Object.create(null);const yl=[new Bu];function n0(n,e,t){if(n.length==0)return yl;let r=t?yl[0]:new Bu,s=[r];for(let o=0;o<n.length;o++){let i=n[o].type.attrs;if(i){i.nodeName&&s.push(r=new Bu(i.nodeName));for(let a in i){let l=i[a];l!=null&&(t&&s.length==1&&s.push(r=new Bu(e.isInline?"span":"div")),a=="class"?r.class=(r.class?r.class+" ":"")+l:a=="style"?r.style=(r.style?r.style+";":"")+l:a!="nodeName"&&(r[a]=l))}}}return s}function $L(n,e,t,r){if(t==yl&&r==yl)return e;let s=e;for(let o=0;o<r.length;o++){let i=r[o],a=t[o];if(o){let l;a&&a.nodeName==i.nodeName&&s!=n&&(l=s.parentNode)&&l.nodeName.toLowerCase()==i.nodeName||(l=document.createElement(i.nodeName),l.pmIsDeco=!0,l.appendChild(s),a=yl[0]),s=l}kX(s,a||yl[0],i)}return s}function kX(n,e,t){for(let r in e)r!="class"&&r!="style"&&r!="nodeName"&&!(r in t)&&n.removeAttribute(r);for(let r in t)r!="class"&&r!="style"&&r!="nodeName"&&t[r]!=e[r]&&n.setAttribute(r,t[r]);if(e.class!=t.class){let r=e.class?e.class.split(" ").filter(Boolean):[],s=t.class?t.class.split(" ").filter(Boolean):[];for(let o=0;o<r.length;o++)s.indexOf(r[o])==-1&&n.classList.remove(r[o]);for(let o=0;o<s.length;o++)r.indexOf(s[o])==-1&&n.classList.add(s[o]);n.classList.length==0&&n.removeAttribute("class")}if(e.style!=t.style){if(e.style){let r=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g,s;for(;s=r.exec(e.style);)n.style.removeProperty(s[1])}t.style&&(n.style.cssText+=t.style)}}function HL(n,e,t){return $L(n,n,yl,n0(e,t,n.nodeType!=1))}function Qg(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(!n[t].type.eq(e[t].type))return!1;return!0}function KI(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class _X{constructor(e,t,r){this.lock=t,this.view=r,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=MX(e.node.content,e)}destroyBetween(e,t){if(e!=t){for(let r=e;r<t;r++)this.top.children[r].destroy();this.top.children.splice(e,t-e),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(e,t,r,s){let o=0,i=this.stack.length>>1,a=Math.min(i,e.length);for(;o<a&&(o==i-1?this.top:this.stack[o+1<<1]).matchesMark(e[o])&&e[o].type.spec.spanning!==!1;)o++;for(;o<i;)this.destroyRest(),this.top.dirty=Us,this.index=this.stack.pop(),this.top=this.stack.pop(),i--;for(;i<e.length;){this.stack.push(this.top,this.index+1);let l=-1,c=this.top.children.length;s<this.preMatch.index&&(c=Math.min(this.index+3,c));for(let u=this.index;u<c;u++){let d=this.top.children[u];if(d.matchesMark(e[i])&&!this.isLocked(d.dom)){l=u;break}}if(l>-1)l>this.index&&(this.changed=!0,this.destroyBetween(this.index,l)),this.top=this.top.children[this.index];else{let u=Rl.create(this.top,e[i],t,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,i++}}findNodeMatch(e,t,r,s){let o=-1,i;if(s>=this.preMatch.index&&(i=this.preMatch.matches[s-this.preMatch.index]).parent==this.top&&i.matchesNode(e,t,r))o=this.top.children.indexOf(i,this.index);else for(let a=this.index,l=Math.min(this.top.children.length,a+5);a<l;a++){let c=this.top.children[a];if(c.matchesNode(e,t,r)&&!this.preMatch.matched.has(c)){o=a;break}}return o<0?!1:(this.destroyBetween(this.index,o),this.index++,!0)}updateNodeAt(e,t,r,s,o){let i=this.top.children[s];return i.dirty==Yo&&i.dom==i.contentDOM&&(i.dirty=ml),i.update(e,t,r,o)?(this.destroyBetween(this.index,s),this.index++,!0):!1}findIndexWithChild(e){for(;;){let t=e.parentNode;if(!t)return-1;if(t==this.top.contentDOM){let r=e.pmViewDesc;if(r){for(let s=this.index;s<this.top.children.length;s++)if(this.top.children[s]==r)return s}return-1}e=t}}updateNextNode(e,t,r,s,o,i){for(let a=this.index;a<this.top.children.length;a++){let l=this.top.children[a];if(l instanceof ka){let c=this.preMatch.matched.get(l);if(c!=null&&c!=o)return!1;let u=l.dom,d,h=this.isLocked(u)&&!(e.isText&&l.node&&l.node.isText&&l.nodeDOM.nodeValue==e.text&&l.dirty!=Yo&&Qg(t,l.outerDeco));if(!h&&l.update(e,t,r,s))return this.destroyBetween(this.index,a),l.dom!=u&&(this.changed=!0),this.index++,!0;if(!h&&(d=this.recreateWrapper(l,e,t,r,s,i)))return this.destroyBetween(this.index,a),this.top.children[this.index]=d,d.contentDOM&&(d.dirty=ml,d.updateChildren(s,i+1),d.dirty=Us),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(e,t,r,s,o,i){if(e.dirty||t.isAtom||!e.children.length||!e.node.content.eq(t.content)||!Qg(r,e.outerDeco)||!s.eq(e.innerDeco))return null;let a=ka.create(this.top,t,r,s,o,i);if(a.contentDOM){a.children=e.children,e.children=[];for(let l of a.children)l.parent=a}return e.destroy(),a}addNode(e,t,r,s,o){let i=ka.create(this.top,e,t,r,s,o);i.contentDOM&&i.updateChildren(s,o+1),this.top.children.splice(this.index++,0,i),this.changed=!0}placeWidget(e,t,r){let s=this.index<this.top.children.length?this.top.children[this.index]:null;if(s&&s.matchesWidget(e)&&(e==s.widget||!s.widget.type.toDOM.parentNode))this.index++;else{let o=new FL(this.top,e,t,r);this.top.children.splice(this.index++,0,o),this.changed=!0}}addTextblockHacks(){let e=this.top.children[this.index-1],t=this.top;for(;e instanceof Rl;)t=e,e=t.children[t.children.length-1];(!e||!(e instanceof Ly)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((cr||Un)&&e&&e.dom.contentEditable=="false"&&this.addHackNode("IMG",t),this.addHackNode("BR",this.top))}addHackNode(e,t){if(t==this.top&&this.index<t.children.length&&t.children[this.index].matchesHack(e))this.index++;else{let r=document.createElement(e);e=="IMG"&&(r.className="ProseMirror-separator",r.alt=""),e=="BR"&&(r.className="ProseMirror-trailingBreak");let s=new BL(this.top,[],r,null);t!=this.top?t.children.push(s):t.children.splice(this.index++,0,s),this.changed=!0}}isLocked(e){return this.lock&&(e==this.lock||e.nodeType==1&&e.contains(this.lock.parentNode))}}function MX(n,e){let t=e,r=t.children.length,s=n.childCount,o=new Map,i=[];e:for(;s>0;){let a;for(;;)if(r){let c=t.children[r-1];if(c instanceof Rl)t=c,r=c.children.length;else{a=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let l=a.node;if(l){if(l!=n.child(s-1))break;--s,o.set(a,s),i.push(a)}}return{index:s,matched:o,matches:i.reverse()}}function AX(n,e){return n.type.side-e.type.side}function DX(n,e,t,r){let s=e.locals(n),o=0;if(s.length==0){for(let c=0;c<n.childCount;c++){let u=n.child(c);r(u,s,e.forChild(o,u),c),o+=u.nodeSize}return}let i=0,a=[],l=null;for(let c=0;;){let u,d;for(;i<s.length&&s[i].to==o;){let y=s[i++];y.widget&&(u?(d||(d=[u])).push(y):u=y)}if(u)if(d){d.sort(AX);for(let y=0;y<d.length;y++)t(d[y],c,!!l)}else t(u,c,!!l);let h,f;if(l)f=-1,h=l,l=null;else if(c<n.childCount)f=c,h=n.child(c++);else break;for(let y=0;y<a.length;y++)a[y].to<=o&&a.splice(y--,1);for(;i<s.length&&s[i].from<=o&&s[i].to>o;)a.push(s[i++]);let g=o+h.nodeSize;if(h.isText){let y=g;i<s.length&&s[i].from<y&&(y=s[i].from);for(let S=0;S<a.length;S++)a[S].to<y&&(y=a[S].to);y<g&&(l=h.cut(y-o),h=h.cut(0,y-o),g=y,f=-1)}else for(;i<s.length&&s[i].to<g;)i++;let m=h.isInline&&!h.isLeaf?a.filter(y=>!y.inline):a.slice();r(h,m,e.forChild(o,h),f),o=g}}function OX(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function RX(n,e,t,r){for(let s=0,o=0;s<n.childCount&&o<=r;){let i=n.child(s++),a=o;if(o+=i.nodeSize,!i.isText)continue;let l=i.text;for(;s<n.childCount;){let c=n.child(s++);if(o+=c.nodeSize,!c.isText)break;l+=c.text}if(o>=t){if(o>=r&&l.slice(r-e.length-a,r-a)==e)return r-e.length;let c=a<r?l.lastIndexOf(e,r-a-1):-1;if(c>=0&&c+e.length+a>=t)return a+c;if(t==r&&l.length>=r+e.length-a&&l.slice(r-a,r-a+e.length)==e)return r}}return-1}function r0(n,e,t,r,s){let o=[];for(let i=0,a=0;i<n.length;i++){let l=n[i],c=a,u=a+=l.size;c>=t||u<=e?o.push(l):(c<e&&o.push(l.slice(0,e-c,r)),s&&(o.push(s),s=void 0),u>t&&o.push(l.slice(t-c,l.size,r)))}return o}function C1(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let s=n.docView.nearestDesc(t.focusNode),o=s&&s.size==0,i=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(i<0)return null;let a=r.resolve(i),l,c;if(Ry(t)){for(l=i;s&&!s.node;)s=s.parent;let d=s.node;if(s&&d.isAtom&&Me.isSelectable(d)&&s.parent&&!(d.isInline&&aX(t.focusNode,t.focusOffset,s.dom))){let h=s.posBefore;c=new Me(i==h?a:r.resolve(h))}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=i,h=i;for(let f=0;f<t.rangeCount;f++){let g=t.getRangeAt(f);d=Math.min(d,n.docView.posFromDOM(g.startContainer,g.startOffset,1)),h=Math.max(h,n.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(d<0)return null;[l,i]=h==n.state.selection.anchor?[h,d]:[d,h],a=r.resolve(i)}else l=n.docView.posFromDOM(t.anchorNode,t.anchorOffset,1);if(l<0)return null}let u=r.resolve(l);if(!c){let d=e=="pointer"||n.state.selection.head<a.pos&&!o?1:-1;c=P1(n,u,a,d)}return c}function UL(n){return n.editable?n.hasFocus():WL(n)&&document.activeElement&&document.activeElement.contains(n.dom)}function Bi(n,e=!1){let t=n.state.selection;if(KL(n,t),!!UL(n)){if(!e&&n.input.mouseDown&&n.input.mouseDown.allowDefault&&Un){let r=n.domSelectionRange(),s=n.domObserver.currentSelection;if(r.anchorNode&&s.anchorNode&&Ol(r.anchorNode,r.anchorOffset,s.anchorNode,s.anchorOffset)){n.input.mouseDown.delayedSelectionSync=!0,n.domObserver.setCurSelection();return}}if(n.domObserver.disconnectSelection(),n.cursorWrapper)jX(n);else{let{anchor:r,head:s}=t,o,i;WI&&!(t instanceof He)&&(t.$from.parent.inlineContent||(o=VI(n,t.from)),!t.empty&&!t.$from.parent.inlineContent&&(i=VI(n,t.to))),n.docView.setSelection(r,s,n,e),WI&&(o&&GI(o),i&&GI(i)),t.visible?n.dom.classList.remove("ProseMirror-hideselection"):(n.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&LX(n))}n.domObserver.setCurSelection(),n.domObserver.connectSelection()}}const WI=cr||Un&&ML<63;function VI(n,e){let{node:t,offset:r}=n.docView.domFromPos(e,0),s=r<t.childNodes.length?t.childNodes[r]:null,o=r?t.childNodes[r-1]:null;if(cr&&s&&s.contentEditable=="false")return ob(s);if((!s||s.contentEditable=="false")&&(!o||o.contentEditable=="false")){if(s)return ob(s);if(o)return ob(o)}}function ob(n){return n.contentEditable="true",cr&&n.draggable&&(n.draggable=!1,n.wasDraggable=!0),n}function GI(n){n.contentEditable="false",n.wasDraggable&&(n.draggable=!0,n.wasDraggable=null)}function LX(n){let e=n.dom.ownerDocument;e.removeEventListener("selectionchange",n.input.hideSelectionGuard);let t=n.domSelectionRange(),r=t.anchorNode,s=t.anchorOffset;e.addEventListener("selectionchange",n.input.hideSelectionGuard=()=>{(t.anchorNode!=r||t.anchorOffset!=s)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!UL(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function jX(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,Nn(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&Qr&&Ea<=11&&(t.disabled=!0,t.disabled=!1)}function KL(n,e){if(e instanceof Me){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(YI(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else YI(n)}function YI(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function P1(n,e,t,r){return n.someProp("createSelectionBetween",s=>s(n,e,t))||He.between(e,t,r)}function XI(n){return n.editable&&!n.hasFocus()?!1:WL(n)}function WL(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return n.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(n.editable||n.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function NX(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return Ol(e.node,e.offset,t.anchorNode,t.anchorOffset)}function s0(n,e){let{$anchor:t,$head:r}=n.selection,s=e>0?t.max(r):t.min(r),o=s.parent.inlineContent?s.depth?n.doc.resolve(e>0?s.after():s.before()):null:s;return o&&Je.findFrom(o,e)}function ga(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function qI(n,e,t){let r=n.state.selection;if(r instanceof He)if(t.indexOf("s")>-1){let{$head:s}=r,o=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter;if(!o||o.isText||!o.isLeaf)return!1;let i=n.state.doc.resolve(s.pos+o.nodeSize*(e<0?-1:1));return ga(n,new He(r.$anchor,i))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let s=s0(n.state,e);return s&&s instanceof Me?ga(n,s):!1}else if(!(Ls&&t.indexOf("m")>-1)){let s=r.$head,o=s.textOffset?null:e<0?s.nodeBefore:s.nodeAfter,i;if(!o||o.isText)return!1;let a=e<0?s.pos-o.nodeSize:s.pos;return o.isAtom||(i=n.docView.descAt(a))&&!i.contentDOM?Me.isSelectable(o)?ga(n,new Me(e<0?n.state.doc.resolve(s.pos-o.nodeSize):s)):Jh?ga(n,new He(n.state.doc.resolve(e<0?a:a+o.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Me&&r.node.isInline)return ga(n,new He(e>0?r.$to:r.$from));{let s=s0(n.state,e);return s?ga(n,s):!1}}}function em(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function zu(n,e){let t=n.pmViewDesc;return t&&t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR")}function hc(n,e){return e<0?FX(n):BX(n)}function FX(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s,o,i=!1;for(Hs&&t.nodeType==1&&r<em(t)&&zu(t.childNodes[r],-1)&&(i=!0);;)if(r>0){if(t.nodeType!=1)break;{let a=t.childNodes[r-1];if(zu(a,-1))s=t,o=--r;else if(a.nodeType==3)t=a,r=t.nodeValue.length;else break}}else{if(VL(t))break;{let a=t.previousSibling;for(;a&&zu(a,-1);)s=t.parentNode,o=Nn(a),a=a.previousSibling;if(a)t=a,r=em(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}i?o0(n,t,r):s&&o0(n,s,o)}function BX(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let s=em(t),o,i;for(;;)if(r<s){if(t.nodeType!=1)break;let a=t.childNodes[r];if(zu(a,1))o=t,i=++r;else break}else{if(VL(t))break;{let a=t.nextSibling;for(;a&&zu(a,1);)o=a.parentNode,i=Nn(a)+1,a=a.nextSibling;if(a)t=a,r=0,s=em(t);else{if(t=t.parentNode,t==n.dom)break;r=s=0}}}o&&o0(n,o,i)}function VL(n){let e=n.pmViewDesc;return e&&e.node&&e.node.isBlock}function zX(n,e){for(;n&&e==n.childNodes.length&&!Zh(n);)e=Nn(n)+1,n=n.parentNode;for(;n&&e<n.childNodes.length;){let t=n.childNodes[e];if(t.nodeType==3)return t;if(t.nodeType==1&&t.contentEditable=="false")break;n=t,e=0}}function $X(n,e){for(;n&&!e&&!Zh(n);)e=Nn(n),n=n.parentNode;for(;n&&e;){let t=n.childNodes[e-1];if(t.nodeType==3)return t;if(t.nodeType==1&&t.contentEditable=="false")break;n=t,e=n.childNodes.length}}function o0(n,e,t){if(e.nodeType!=3){let o,i;(i=zX(e,t))?(e=i,t=0):(o=$X(e,t))&&(e=o,t=o.nodeValue.length)}let r=n.domSelection();if(!r)return;if(Ry(r)){let o=document.createRange();o.setEnd(e,t),o.setStart(e,t),r.removeAllRanges(),r.addRange(o)}else r.extend&&r.extend(e,t);n.domObserver.setCurSelection();let{state:s}=n;setTimeout(()=>{n.state==s&&Bi(n)},50)}function ZI(n,e){let t=n.state.doc.resolve(e);if(!(Un||AL)&&t.parent.inlineContent){let s=n.coordsAtPos(e);if(e>t.start()){let o=n.coordsAtPos(e-1),i=(o.top+o.bottom)/2;if(i>s.top&&i<s.bottom&&Math.abs(o.left-s.left)>1)return o.left<s.left?"ltr":"rtl"}if(e<t.end()){let o=n.coordsAtPos(e+1),i=(o.top+o.bottom)/2;if(i>s.top&&i<s.bottom&&Math.abs(o.left-s.left)>1)return o.left>s.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function JI(n,e,t){let r=n.state.selection;if(r instanceof He&&!r.empty||t.indexOf("s")>-1||Ls&&t.indexOf("m")>-1)return!1;let{$from:s,$to:o}=r;if(!s.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let i=s0(n.state,e);if(i&&i instanceof Me)return ga(n,i)}if(!s.parent.inlineContent){let i=e<0?s:o,a=r instanceof Ss?Je.near(i,e):Je.findFrom(i,e);return a?ga(n,a):!1}return!1}function QI(n,e){if(!(n.state.selection instanceof He))return!0;let{$head:t,$anchor:r,empty:s}=n.state.selection;if(!t.sameParent(r))return!0;if(!s)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let o=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(o&&!o.isText){let i=n.state.tr;return e<0?i.delete(t.pos-o.nodeSize,t.pos):i.delete(t.pos,t.pos+o.nodeSize),n.dispatch(i),!0}return!1}function eE(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function HX(n){if(!cr||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&e.nodeType==1&&t==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;eE(n,r,"true"),setTimeout(()=>eE(n,r,"false"),20)}return!1}function UX(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function KX(n,e){let t=e.keyCode,r=UX(e);if(t==8||Ls&&t==72&&r=="c")return QI(n,-1)||hc(n,-1);if(t==46&&!e.shiftKey||Ls&&t==68&&r=="c")return QI(n,1)||hc(n,1);if(t==13||t==27)return!0;if(t==37||Ls&&t==66&&r=="c"){let s=t==37?ZI(n,n.state.selection.from)=="ltr"?-1:1:-1;return qI(n,s,r)||hc(n,s)}else if(t==39||Ls&&t==70&&r=="c"){let s=t==39?ZI(n,n.state.selection.from)=="ltr"?1:-1:1;return qI(n,s,r)||hc(n,s)}else{if(t==38||Ls&&t==80&&r=="c")return JI(n,-1,r)||hc(n,-1);if(t==40||Ls&&t==78&&r=="c")return HX(n)||JI(n,1,r)||hc(n,1);if(r==(Ls?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function T1(n,e){n.someProp("transformCopied",f=>{e=f(e,n)});let t=[],{content:r,openStart:s,openEnd:o}=e;for(;s>1&&o>1&&r.childCount==1&&r.firstChild.childCount==1;){s--,o--;let f=r.firstChild;t.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let i=n.someProp("clipboardSerializer")||ql.fromSchema(n.state.schema),a=JL(),l=a.createElement("div");l.appendChild(i.serializeFragment(r,{document:a}));let c=l.firstChild,u,d=0;for(;c&&c.nodeType==1&&(u=ZL[c.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let g=a.createElement(u[f]);for(;l.firstChild;)g.appendChild(l.firstChild);l.appendChild(g),d++}c=l.firstChild}c&&c.nodeType==1&&c.setAttribute("data-pm-slice",`${s} ${o}${d?` -${d}`:""} ${JSON.stringify(t)}`);let h=n.someProp("clipboardTextSerializer",f=>f(e,n))||e.content.textBetween(0,e.content.size,`
201
+
202
+ `);return{dom:l,text:h,slice:e}}function GL(n,e,t,r,s){let o=s.parent.type.spec.code,i,a;if(!t&&!e)return null;let l=!!e&&(r||o||!t);if(l){if(n.someProp("transformPastedText",h=>{e=h(e,o||r,n)}),o)return a=new ye(ne.from(n.state.schema.text(e.replace(/\r\n?/g,`
203
+ `))),0,0),n.someProp("transformPasted",h=>{a=h(a,n,!0)}),a;let d=n.someProp("clipboardTextParser",h=>h(e,s,r,n));if(d)a=d;else{let h=s.marks(),{schema:f}=n.state,g=ql.fromSchema(f);i=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let y=i.appendChild(document.createElement("p"));m&&y.appendChild(g.serializeNode(f.text(m,h)))})}}else n.someProp("transformPastedHTML",d=>{t=d(t,n)}),i=YX(t),Jh&&XX(i);let c=i&&i.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let h=i.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;i=h}if(a||(a=(n.someProp("clipboardParser")||n.someProp("domParser")||Hc.fromSchema(n.state.schema)).parseSlice(i,{preserveWhitespace:!!(l||u),context:s,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!WX.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=qX(tE(a,+u[1],+u[2]),u[4]);else if(a=ye.maxOpen(VX(a.content,s),!0),a.openStart||a.openEnd){let d=0,h=0;for(let f=a.content.firstChild;d<a.openStart&&!f.type.spec.isolating;d++,f=f.firstChild);for(let f=a.content.lastChild;h<a.openEnd&&!f.type.spec.isolating;h++,f=f.lastChild);a=tE(a,d,h)}return n.someProp("transformPasted",d=>{a=d(a,n,l)}),a}const WX=/^(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 VX(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let s=e.node(t).contentMatchAt(e.index(t)),o,i=[];if(n.forEach(a=>{if(!i)return;let l=s.findWrapping(a.type),c;if(!l)return i=null;if(c=i.length&&o.length&&XL(l,o,a,i[i.length-1],0))i[i.length-1]=c;else{i.length&&(i[i.length-1]=qL(i[i.length-1],o.length));let u=YL(a,l);i.push(u),s=s.matchType(u.type),o=l}}),i)return ne.from(i)}return n}function YL(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,ne.from(n));return n}function XL(n,e,t,r,s){if(s<n.length&&s<e.length&&n[s]==e[s]){let o=XL(n,e,t,r.lastChild,s+1);if(o)return r.copy(r.content.replaceChild(r.childCount-1,o));if(r.contentMatchAt(r.childCount).matchType(s==n.length-1?t.type:n[s+1]))return r.copy(r.content.append(ne.from(YL(t,n,s+1))))}}function qL(n,e){if(e==0)return n;let t=n.content.replaceChild(n.childCount-1,qL(n.lastChild,e-1)),r=n.contentMatchAt(n.childCount).fillBefore(ne.empty,!0);return n.copy(t.append(r))}function i0(n,e,t,r,s,o){let i=e<0?n.firstChild:n.lastChild,a=i.content;return n.childCount>1&&(o=0),s<r-1&&(a=i0(a,e,t,r,s+1,o)),s>=t&&(a=e<0?i.contentMatchAt(0).fillBefore(a,o<=s).append(a):a.append(i.contentMatchAt(i.childCount).fillBefore(ne.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,i.copy(a))}function tE(n,e,t){return e<n.openStart&&(n=new ye(i0(n.content,-1,e,n.openStart,0,n.openEnd),e,n.openEnd)),t<n.openEnd&&(n=new ye(i0(n.content,1,t,n.openEnd,0,0),n.openStart,t)),n}const ZL={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};let nE=null;function JL(){return nE||(nE=document.implementation.createHTMLDocument("title"))}let ib=null;function GX(n){let e=window.trustedTypes;return e?(ib||(ib=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:t=>t})),ib.createHTML(n)):n}function YX(n){let e=/^(\s*<meta [^>]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=JL().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(n),s;if((s=r&&ZL[r[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"</"+o+">").reverse().join("")),t.innerHTML=GX(n),s)for(let o=0;o<s.length;o++)t=t.querySelector(s[o])||t;return t}function XX(n){let e=n.querySelectorAll(Un?"span:not([class]):not([style])":"span.Apple-converted-space");for(let t=0;t<e.length;t++){let r=e[t];r.childNodes.length==1&&r.textContent==" "&&r.parentNode&&r.parentNode.replaceChild(n.ownerDocument.createTextNode(" "),r)}}function qX(n,e){if(!n.size)return n;let t=n.content.firstChild.type.schema,r;try{r=JSON.parse(e)}catch{return n}let{content:s,openStart:o,openEnd:i}=n;for(let a=r.length-2;a>=0;a-=2){let l=t.nodes[r[a]];if(!l||l.hasRequiredAttrs())break;s=ne.from(l.create(r[a+1],s)),o++,i++}return new ye(s,o,i)}const Lr={},jr={},ZX={touchstart:!0,touchmove:!0};class JX{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 QX(n){for(let e in Lr){let t=Lr[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{tq(n,r)&&!I1(n,r)&&(n.editable||!(r.type in jr))&&t(n,r)},ZX[e]?{passive:!0}:void 0)}cr&&n.dom.addEventListener("input",()=>null),a0(n)}function Ta(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function eq(n){n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function a0(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>I1(n,r))})}function I1(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function tq(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function nq(n,e){!I1(n,e)&&Lr[e.type]&&(n.editable||!(e.type in jr))&&Lr[e.type](n,e)}jr.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!ej(n,t)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(Oi&&Un&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),sd&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",s=>s(n,hl(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||KX(n,t)?t.preventDefault():Ta(n,"key")};jr.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};jr.keypress=(n,e)=>{let t=e;if(ej(n,t)||!t.charCode||t.ctrlKey&&!t.altKey||Ls&&t.metaKey)return;if(n.someProp("handleKeyPress",s=>s(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof He)||!r.$from.sameParent(r.$to)){let s=String.fromCharCode(t.charCode),o=()=>n.state.tr.insertText(s).scrollIntoView();!/[\r\n]/.test(s)&&!n.someProp("handleTextInput",i=>i(n,r.$from.pos,r.$to.pos,s,o))&&n.dispatch(o()),t.preventDefault()}};function jy(n){return{left:n.clientX,top:n.clientY}}function rq(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function E1(n,e,t,r,s){if(r==-1)return!1;let o=n.state.doc.resolve(r);for(let i=o.depth+1;i>0;i--)if(n.someProp(e,a=>i>o.depth?a(n,t,o.nodeAfter,o.before(i),s,!0):a(n,t,o.node(i),o.before(i),s,!1)))return!0;return!1}function Kc(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function sq(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&Me.isSelectable(r)?(Kc(n,new Me(t)),!0):!1}function oq(n,e){if(e==-1)return!1;let t=n.state.selection,r,s;t instanceof Me&&(r=t.node);let o=n.state.doc.resolve(e);for(let i=o.depth+1;i>0;i--){let a=i>o.depth?o.nodeAfter:o.node(i);if(Me.isSelectable(a)){r&&t.$from.depth>0&&i>=t.$from.depth&&o.before(t.$from.depth+1)==t.$from.pos?s=o.before(t.$from.depth):s=o.before(i);break}}return s!=null?(Kc(n,Me.create(n.state.doc,s)),!0):!1}function iq(n,e,t,r,s){return E1(n,"handleClickOn",e,t,r)||n.someProp("handleClick",o=>o(n,e,r))||(s?oq(n,t):sq(n,t))}function aq(n,e,t,r){return E1(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",s=>s(n,e,r))}function lq(n,e,t,r){return E1(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",s=>s(n,e,r))||cq(n,t,r)}function cq(n,e,t){if(t.button!=0)return!1;let r=n.state.doc;if(e==-1)return r.inlineContent?(Kc(n,He.create(r,0,r.content.size)),!0):!1;let s=r.resolve(e);for(let o=s.depth+1;o>0;o--){let i=o>s.depth?s.nodeAfter:s.node(o),a=s.before(o);if(i.inlineContent)Kc(n,He.create(r,a+1,a+1+i.content.size));else if(Me.isSelectable(i))Kc(n,Me.create(r,a));else continue;return!0}}function k1(n){return tm(n)}const QL=Ls?"metaKey":"ctrlKey";Lr.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=k1(n),s=Date.now(),o="singleClick";s-n.input.lastClick.time<500&&rq(t,n.input.lastClick)&&!t[QL]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?o="doubleClick":n.input.lastClick.type=="doubleClick"&&(o="tripleClick")),n.input.lastClick={time:s,x:t.clientX,y:t.clientY,type:o,button:t.button};let i=n.posAtCoords(jy(t));i&&(o=="singleClick"?(n.input.mouseDown&&n.input.mouseDown.done(),n.input.mouseDown=new dq(n,i,t,!!r)):(o=="doubleClick"?aq:lq)(n,i.pos,i.inside,t)?t.preventDefault():Ta(n,"pointer"))};class dq{constructor(e,t,r,s){this.view=e,this.pos=t,this.event=r,this.flushed=s,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=e.state.doc,this.selectNode=!!r[QL],this.allowDefault=r.shiftKey;let o,i;if(t.inside>-1)o=e.state.doc.nodeAt(t.inside),i=t.inside;else{let u=e.state.doc.resolve(t.pos);o=u.parent,i=u.depth?u.before():0}const a=s?null:r.target,l=a?e.docView.nearestDesc(a,!0):null;this.target=l&&l.nodeDOM.nodeType==1?l.nodeDOM:null;let{selection:c}=e.state;(r.button==0&&o.type.spec.draggable&&o.type.spec.selectable!==!1||c instanceof Me&&c.from<=i&&c.to>i)&&(this.mightDrag={node:o,pos:i,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Hs&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this)),Ta(e,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),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(()=>Bi(this.view)),this.view.input.mouseDown=null}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(jy(e))),this.updateAllowDefault(e),this.allowDefault||!t?Ta(this.view,"pointer"):iq(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||cr&&this.mightDrag&&!this.mightDrag.node.isAtom||Un&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(Kc(this.view,Je.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):Ta(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ta(this.view,"pointer"),e.buttons==0&&this.done()}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}}Lr.touchstart=n=>{n.input.lastTouch=Date.now(),k1(n),Ta(n,"pointer")};Lr.touchmove=n=>{n.input.lastTouch=Date.now(),Ta(n,"pointer")};Lr.contextmenu=n=>k1(n);function ej(n,e){return n.composing?!0:cr&&Math.abs(e.timeStamp-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const uq=Oi?5e3:-1;jr.compositionstart=jr.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof He&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||Un&&AL&&hq(n)))n.markCursor=n.state.storedMarks||t.marks(),tm(n,!0),n.markCursor=null;else if(tm(n,!e.selection.empty),Hs&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let s=r.focusNode,o=r.focusOffset;s&&s.nodeType==1&&o!=0;){let i=o<0?s.lastChild:s.childNodes[o-1];if(!i)break;if(i.nodeType==3){let a=n.domSelection();a&&a.collapse(i,i.nodeValue.length);break}else s=i,o=-1}}n.input.composing=!0}tj(n,uq)};function hq(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||e.nodeType!=1||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return r.nodeType==1&&r.contentEditable=="false"}jr.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=e.timeStamp,n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,tj(n,20))};function tj(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>tm(n),e))}function nj(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=fq());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function pq(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=oX(e.focusNode,e.focusOffset),r=iX(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let s=r.pmViewDesc,o=n.domObserver.lastChangedTextNode;if(t==o||r==o)return o;if(!s||!s.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let i=t.pmViewDesc;if(!(!i||!i.isText(t.nodeValue)))return r}}return t||r}function fq(){let n=document.createEvent("Event");return n.initEvent("event",!0,!0),n.timeStamp}function tm(n,e=!1){if(!(Oi&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),nj(n),e||n.docView&&n.docView.dirty){let t=C1(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function gq(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),s=document.createRange();s.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(s),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const hh=Qr&&Ea<15||sd&&dX<604;Lr.copy=jr.cut=(n,e)=>{let t=e,r=n.state.selection,s=t.type=="cut";if(r.empty)return;let o=hh?null:t.clipboardData,i=r.content(),{dom:a,text:l}=T1(n,i);o?(t.preventDefault(),o.clearData(),o.setData("text/html",a.innerHTML),o.setData("text/plain",l)):gq(n,a),s&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function mq(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function yq(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let s=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?ph(n,r.value,null,s,e):ph(n,r.textContent,r.innerHTML,s,e)},50)}function ph(n,e,t,r,s){let o=GL(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",l=>l(n,s,o||ye.empty)))return!0;if(!o)return!1;let i=mq(o),a=i?n.state.tr.replaceSelectionWith(i,r):n.state.tr.replaceSelection(o);return n.dispatch(a.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function rj(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}jr.paste=(n,e)=>{let t=e;if(n.composing&&!Oi)return;let r=hh?null:t.clipboardData,s=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&ph(n,rj(r),r.getData("text/html"),s,t)?t.preventDefault():yq(n,t)};let sj=class{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}};const Sq=Ls?"altKey":"ctrlKey";function oj(n,e){let t=n.someProp("dragCopies",r=>!r(e));return t??!e[Sq]}Lr.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let s=n.state.selection,o=s.empty?null:n.posAtCoords(jy(t)),i;if(!(o&&o.pos>=s.from&&o.pos<=(s instanceof Me?s.to-1:s.to))){if(r&&r.mightDrag)i=Me.create(n.state.doc,r.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let d=n.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=n.docView&&(i=Me.create(n.state.doc,d.posBefore))}}let a=(i||n.state.selection).content(),{dom:l,text:c,slice:u}=T1(n,a);(!t.dataTransfer.files.length||!Un||ML>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(hh?"Text":"text/html",l.innerHTML),t.dataTransfer.effectAllowed="copyMove",hh||t.dataTransfer.setData("text/plain",c),n.dragging=new sj(u,oj(n,t),i)};Lr.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};jr.dragover=jr.dragenter=(n,e)=>e.preventDefault();jr.drop=(n,e)=>{try{xq(n,e,n.dragging)}finally{n.dragging=null}};function xq(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(jy(e));if(!r)return;let s=n.state.doc.resolve(r.pos),o=t&&t.slice;o?n.someProp("transformPasted",f=>{o=f(o,n,!1)}):o=GL(n,rj(e.dataTransfer),hh?null:e.dataTransfer.getData("text/html"),!1,s);let i=!!(t&&oj(n,e));if(n.someProp("handleDrop",f=>f(n,e,o||ye.empty,i))){e.preventDefault();return}if(!o)return;e.preventDefault();let a=o?cL(n.state.doc,s.pos,o):s.pos;a==null&&(a=s.pos);let l=n.state.tr;if(i){let{node:f}=t;f?f.replace(l):l.deleteSelection()}let c=l.mapping.map(a),u=o.openStart==0&&o.openEnd==0&&o.content.childCount==1,d=l.doc;if(u?l.replaceRangeWith(c,c,o.content.firstChild):l.replaceRange(c,c,o),l.doc.eq(d))return;let h=l.doc.resolve(c);if(u&&Me.isSelectable(o.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(o.content.firstChild))l.setSelection(new Me(h));else{let f=l.mapping.map(a);l.mapping.maps[l.mapping.maps.length-1].forEach((g,m,y,S)=>f=S),l.setSelection(P1(n,h,l.doc.resolve(f)))}n.focus(),n.dispatch(l.setMeta("uiEvent","drop"))}Lr.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&Bi(n)},20))};Lr.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};Lr.beforeinput=(n,e)=>{if(Un&&Oi&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",o=>o(n,hl(8,"Backspace")))))return;let{$cursor:s}=n.state.selection;s&&s.pos>0&&n.dispatch(n.state.tr.delete(s.pos-1,s.pos).scrollIntoView())},50)}};for(let n in jr)Lr[n]=jr[n];function fh(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class nm{constructor(e,t){this.toDOM=e,this.spec=t||Pl,this.side=this.spec.side||0}map(e,t,r,s){let{pos:o,deleted:i}=e.mapResult(t.from+s,this.side<0?-1:1);return i?null:new _r(o-r,o-r,this)}valid(){return!0}eq(e){return this==e||e instanceof nm&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&fh(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class _a{constructor(e,t){this.attrs=e,this.spec=t||Pl}map(e,t,r,s){let o=e.map(t.from+s,this.spec.inclusiveStart?-1:1)-r,i=e.map(t.to+s,this.spec.inclusiveEnd?1:-1)-r;return o>=i?null:new _r(o,i,this)}valid(e,t){return t.from<t.to}eq(e){return this==e||e instanceof _a&&fh(this.attrs,e.attrs)&&fh(this.spec,e.spec)}static is(e){return e.type instanceof _a}destroy(){}}class _1{constructor(e,t){this.attrs=e,this.spec=t||Pl}map(e,t,r,s){let o=e.mapResult(t.from+s,1);if(o.deleted)return null;let i=e.mapResult(t.to+s,-1);return i.deleted||i.pos<=o.pos?null:new _r(o.pos-r,i.pos-r,this)}valid(e,t){let{index:r,offset:s}=e.content.findIndex(t.from),o;return s==t.from&&!(o=e.child(r)).isText&&s+o.nodeSize==t.to}eq(e){return this==e||e instanceof _1&&fh(this.attrs,e.attrs)&&fh(this.spec,e.spec)}destroy(){}}class _r{constructor(e,t,r){this.from=e,this.to=t,this.type=r}copy(e,t){return new _r(e,t,this.type)}eq(e,t=0){return this.type.eq(e.type)&&this.from+t==e.from&&this.to+t==e.to}map(e,t,r){return this.type.map(e,this,t,r)}static widget(e,t,r){return new _r(e,e,new nm(t,r))}static inline(e,t,r,s){return new _r(e,t,new _a(r,s))}static node(e,t,r,s){return new _r(e,t,new _1(r,s))}get spec(){return this.type.spec}get inline(){return this.type instanceof _a}get widget(){return this.type instanceof nm}}const Pc=[],Pl={};class Nt{constructor(e,t){this.local=e.length?e:Pc,this.children=t.length?t:Pc}static create(e,t){return t.length?rm(t,e,0,Pl):rr}find(e,t,r){let s=[];return this.findInner(e??0,t??1e9,s,0,r),s}findInner(e,t,r,s,o){for(let i=0;i<this.local.length;i++){let a=this.local[i];a.from<=t&&a.to>=e&&(!o||o(a.spec))&&r.push(a.copy(a.from+s,a.to+s))}for(let i=0;i<this.children.length;i+=3)if(this.children[i]<t&&this.children[i+1]>e){let a=this.children[i]+1;this.children[i+2].findInner(e-a,t-a,r,s+a,o)}}map(e,t,r){return this==rr||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Pl)}mapInner(e,t,r,s,o){let i;for(let a=0;a<this.local.length;a++){let l=this.local[a].map(e,r,s);l&&l.type.valid(t,l)?(i||(i=[])).push(l):o.onRemove&&o.onRemove(this.local[a].spec)}return this.children.length?bq(this.children,i||[],e,t,r,s,o):i?new Nt(i.sort(Tl),Pc):rr}add(e,t){return t.length?this==rr?Nt.create(e,t):this.addInner(e,t,0):this}addInner(e,t,r){let s,o=0;e.forEach((a,l)=>{let c=l+r,u;if(u=aj(t,a,c)){for(s||(s=this.children.slice());o<s.length&&s[o]<l;)o+=3;s[o]==l?s[o+2]=s[o+2].addInner(a,u,c+1):s.splice(o,0,l,l+a.nodeSize,rm(u,a,c+1,Pl)),o+=3}});let i=ij(o?lj(t):t,-r);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||i.splice(a--,1);return new Nt(i.length?this.local.concat(i).sort(Tl):this.local,s||this.children)}remove(e){return e.length==0||this==rr?this:this.removeInner(e,0)}removeInner(e,t){let r=this.children,s=this.local;for(let o=0;o<r.length;o+=3){let i,a=r[o]+t,l=r[o+1]+t;for(let u=0,d;u<e.length;u++)(d=e[u])&&d.from>a&&d.to<l&&(e[u]=null,(i||(i=[])).push(d));if(!i)continue;r==this.children&&(r=this.children.slice());let c=r[o+2].removeInner(i,a+1);c!=rr?r[o+2]=c:(r.splice(o,3),o-=3)}if(s.length){for(let o=0,i;o<e.length;o++)if(i=e[o])for(let a=0;a<s.length;a++)s[a].eq(i,t)&&(s==this.local&&(s=this.local.slice()),s.splice(a--,1))}return r==this.children&&s==this.local?this:s.length||r.length?new Nt(s,r):rr}forChild(e,t){if(this==rr)return this;if(t.isLeaf)return Nt.empty;let r,s;for(let a=0;a<this.children.length;a+=3)if(this.children[a]>=e){this.children[a]==e&&(r=this.children[a+2]);break}let o=e+1,i=o+t.content.size;for(let a=0;a<this.local.length;a++){let l=this.local[a];if(l.from<i&&l.to>o&&l.type instanceof _a){let c=Math.max(o,l.from)-o,u=Math.min(i,l.to)-o;c<u&&(s||(s=[])).push(l.copy(c,u))}}if(s){let a=new Nt(s.sort(Tl),Pc);return r?new xa([a,r]):a}return r||rr}eq(e){if(this==e)return!0;if(!(e instanceof Nt)||this.local.length!=e.local.length||this.children.length!=e.children.length)return!1;for(let t=0;t<this.local.length;t++)if(!this.local[t].eq(e.local[t]))return!1;for(let t=0;t<this.children.length;t+=3)if(this.children[t]!=e.children[t]||this.children[t+1]!=e.children[t+1]||!this.children[t+2].eq(e.children[t+2]))return!1;return!0}locals(e){return M1(this.localsInner(e))}localsInner(e){if(this==rr)return Pc;if(e.inlineContent||!this.local.some(_a.is))return this.local;let t=[];for(let r=0;r<this.local.length;r++)this.local[r].type instanceof _a||t.push(this.local[r]);return t}forEachSet(e){e(this)}}Nt.empty=new Nt([],[]);Nt.removeOverlap=M1;const rr=Nt.empty;class xa{constructor(e){this.members=e}map(e,t){const r=this.members.map(s=>s.map(e,t,Pl));return xa.from(r)}forChild(e,t){if(t.isLeaf)return Nt.empty;let r=[];for(let s=0;s<this.members.length;s++){let o=this.members[s].forChild(e,t);o!=rr&&(o instanceof xa?r=r.concat(o.members):r.push(o))}return xa.from(r)}eq(e){if(!(e instanceof xa)||e.members.length!=this.members.length)return!1;for(let t=0;t<this.members.length;t++)if(!this.members[t].eq(e.members[t]))return!1;return!0}locals(e){let t,r=!0;for(let s=0;s<this.members.length;s++){let o=this.members[s].localsInner(e);if(o.length)if(!t)t=o;else{r&&(t=t.slice(),r=!1);for(let i=0;i<o.length;i++)t.push(o[i])}}return t?M1(r?t:t.sort(Tl)):Pc}static from(e){switch(e.length){case 0:return rr;case 1:return e[0];default:return new xa(e.every(t=>t instanceof Nt)?e:e.reduce((t,r)=>t.concat(r instanceof Nt?r:r.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}}function bq(n,e,t,r,s,o,i){let a=n.slice();for(let c=0,u=o;c<t.maps.length;c++){let d=0;t.maps[c].forEach((h,f,g,m)=>{let y=m-g-(f-h);for(let S=0;S<a.length;S+=3){let b=a[S+1];if(b<0||h>b+u-d)continue;let w=a[S]+u-d;f>=w?a[S+1]=h<=w?-2:-1:h>=u&&y&&(a[S]+=y,a[S+1]+=y)}d+=y}),u=t.maps[c].map(u,-1)}let l=!1;for(let c=0;c<a.length;c+=3)if(a[c+1]<0){if(a[c+1]==-2){l=!0,a[c+1]=-1;continue}let u=t.map(n[c]+o),d=u-s;if(d<0||d>=r.content.size){l=!0;continue}let h=t.map(n[c+1]+o,-1),f=h-s,{index:g,offset:m}=r.content.findIndex(d),y=r.maybeChild(g);if(y&&m==d&&m+y.nodeSize==f){let S=a[c+2].mapInner(t,y,u+1,n[c]+o+1,i);S!=rr?(a[c]=d,a[c+1]=f,a[c+2]=S):(a[c+1]=-2,l=!0)}else l=!0}if(l){let c=wq(a,n,e,t,s,o,i),u=rm(c,r,0,i);e=u.local;for(let d=0;d<a.length;d+=3)a[d+1]<0&&(a.splice(d,3),d-=3);for(let d=0,h=0;d<u.children.length;d+=3){let f=u.children[d];for(;h<a.length&&a[h]<f;)h+=3;a.splice(h,0,u.children[d],u.children[d+1],u.children[d+2])}}return new Nt(e.sort(Tl),a)}function ij(n,e){if(!e||!n.length)return n;let t=[];for(let r=0;r<n.length;r++){let s=n[r];t.push(new _r(s.from+e,s.to+e,s.type))}return t}function wq(n,e,t,r,s,o,i){function a(l,c){for(let u=0;u<l.local.length;u++){let d=l.local[u].map(r,s,c);d?t.push(d):i.onRemove&&i.onRemove(l.local[u].spec)}for(let u=0;u<l.children.length;u+=3)a(l.children[u+2],l.children[u]+c+1)}for(let l=0;l<n.length;l+=3)n[l+1]==-1&&a(n[l+2],e[l]+o+1);return t}function aj(n,e,t){if(e.isLeaf)return null;let r=t+e.nodeSize,s=null;for(let o=0,i;o<n.length;o++)(i=n[o])&&i.from>t&&i.to<r&&((s||(s=[])).push(i),n[o]=null);return s}function lj(n){let e=[];for(let t=0;t<n.length;t++)n[t]!=null&&e.push(n[t]);return e}function rm(n,e,t,r){let s=[],o=!1;e.forEach((a,l)=>{let c=aj(n,a,l+t);if(c){o=!0;let u=rm(c,a,t+l+1,r);u!=rr&&s.push(l,l+a.nodeSize,u)}});let i=ij(o?lj(n):n,-t).sort(Tl);for(let a=0;a<i.length;a++)i[a].type.valid(e,i[a])||(r.onRemove&&r.onRemove(i[a].spec),i.splice(a--,1));return i.length||s.length?new Nt(i,s):rr}function Tl(n,e){return n.from-e.from||n.to-e.to}function M1(n){let e=n;for(let t=0;t<e.length-1;t++){let r=e[t];if(r.from!=r.to)for(let s=t+1;s<e.length;s++){let o=e[s];if(o.from==r.from){o.to!=r.to&&(e==n&&(e=n.slice()),e[s]=o.copy(o.from,r.to),rE(e,s+1,o.copy(r.to,o.to)));continue}else{o.from<r.to&&(e==n&&(e=n.slice()),e[t]=r.copy(r.from,o.from),rE(e,s,r.copy(o.from,r.to)));break}}}return e}function rE(n,e,t){for(;e<n.length&&Tl(t,n[e])>0;)e++;n.splice(e,0,t)}function ab(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=rr&&e.push(r)}),n.cursorWrapper&&e.push(Nt.create(n.state.doc,[n.cursorWrapper.deco])),xa.from(e)}const vq={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Cq=Qr&&Ea<=11;class Pq{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Tq{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Pq,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let s=0;s<r.length;s++)this.queue.push(r[s]);Qr&&Ea<=11&&r.some(s=>s.type=="childList"&&s.removedNodes.length||s.type=="characterData"&&s.oldValue.length>s.target.nodeValue.length)?this.flushSoon():cr&&e.composing&&r.some(s=>s.type=="childList"&&s.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Cq&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,vq)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;t<e.length;t++)this.queue.push(e[t]);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(XI(this.view)){if(this.suppressingSelectionUpdates)return Bi(this.view);if(Qr&&Ea<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ol(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let o=e.focusNode;o;o=rd(o))t.add(o);for(let o=e.anchorNode;o;o=rd(o))if(t.has(o)){r=o;break}let s=r&&this.view.docView.nearestDesc(r);if(s&&s.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),s=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&XI(e)&&!this.ignoreSelectionChange(r),o=-1,i=-1,a=!1,l=[];if(e.editable)for(let u=0;u<t.length;u++){let d=this.registerMutation(t[u],l);d&&(o=o<0?d.from:Math.min(d.from,o),i=i<0?d.to:Math.max(d.to,i),d.typeOver&&(a=!0))}if(l.some(u=>u.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46)){for(let u of l)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;d&&d.nodeType==1&&d.contentEditable=="false"&&u.parentNode.removeChild(u)}}else if(Hs&&l.length){let u=l.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,h]=u;d.parentNode&&d.parentNode.parentNode==h.parentNode?h.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let h of u){let f=h.parentNode;f&&f.nodeName=="LI"&&(!d||kq(e,d)!=f)&&h.remove()}}}let c=null;o<0&&s&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)<Date.now()-300&&Ry(r)&&(c=C1(e))&&c.eq(Je.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Bi(e),this.currentSelection.set(r),e.scrollToSelection()):(o>-1||s)&&(o>-1&&(e.docView.markDirty(o,i),Iq(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,_q(e,l)),this.handleDOMChange(o,i,a,l),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Bi(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;u<e.addedNodes.length;u++){let d=e.addedNodes[u];t.push(d),d.nodeType==3&&(this.lastChangedTextNode=d)}if(r.contentDOM&&r.contentDOM!=r.dom&&!r.contentDOM.contains(e.target))return{from:r.posBefore,to:r.posAfter};let s=e.previousSibling,o=e.nextSibling;if(Qr&&Ea<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:d,nextSibling:h}=e.addedNodes[u];(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(s=d),(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(o=h)}let i=s&&s.parentNode==e.target?Nn(s)+1:0,a=r.localPosFromDOM(e.target,i,-1),l=o&&o.parentNode==e.target?Nn(o):e.target.childNodes.length,c=r.localPosFromDOM(e.target,l,1);return{from:a,to:c}}else return e.type=="attributes"?{from:r.posAtStart-r.border,to:r.posAtEnd+r.border}:(this.lastChangedTextNode=e.target,{from:r.posAtStart,to:r.posAtEnd,typeOver:e.target.nodeValue==e.oldValue})}}let sE=new WeakMap,oE=!1;function Iq(n){if(!sE.has(n)&&(sE.set(n,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(n.dom).whiteSpace)!==-1)){if(n.requiresGeckoHackNode=Hs,oE)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."),oE=!0}}function iE(n,e){let t=e.startContainer,r=e.startOffset,s=e.endContainer,o=e.endOffset,i=n.domAtPos(n.state.selection.anchor);return Ol(i.node,i.offset,s,o)&&([t,r,s,o]=[s,o,t,r]),{anchorNode:t,anchorOffset:r,focusNode:s,focusOffset:o}}function Eq(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return iE(n,s)}let t;function r(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.dom.addEventListener("beforeinput",r,!0),document.execCommand("indent"),n.dom.removeEventListener("beforeinput",r,!0),t?iE(n,t):null}function kq(n,e){for(let t=e.parentNode;t&&t!=n.dom;t=t.parentNode){let r=n.docView.nearestDesc(t,!0);if(r&&r.node.isBlock)return t}return null}function _q(n,e){var t;let{focusNode:r,focusOffset:s}=n.domSelectionRange();for(let o of e)if(((t=o.parentNode)===null||t===void 0?void 0:t.nodeName)=="TR"){let i=o.nextSibling;for(;i&&i.nodeName!="TD"&&i.nodeName!="TH";)i=i.nextSibling;if(i){let a=i;for(;;){let l=a.firstChild;if(!l||l.nodeType!=1||l.contentEditable=="false"||/^(BR|IMG)$/.test(l.nodeName))break;a=l}a.insertBefore(o,a.firstChild),r==o&&n.domSelection().collapse(o,s)}else o.parentNode.removeChild(o)}}function Mq(n,e,t){let{node:r,fromOffset:s,toOffset:o,from:i,to:a}=n.docView.parseRange(e,t),l=n.domSelectionRange(),c,u=l.anchorNode;if(u&&n.dom.contains(u.nodeType==1?u:u.parentNode)&&(c=[{node:u,offset:l.anchorOffset}],Ry(l)||c.push({node:l.focusNode,offset:l.focusOffset})),Un&&n.input.lastKeyCode===8)for(let y=o;y>s;y--){let S=r.childNodes[y-1],b=S.pmViewDesc;if(S.nodeName=="BR"&&!b){o=y;break}if(!b||b.size)break}let d=n.state.doc,h=n.someProp("domParser")||Hc.fromSchema(n.state.schema),f=d.resolve(i),g=null,m=h.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:s,to:o,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:c,ruleFromNode:Aq,context:f});if(c&&c[0].pos!=null){let y=c[0].pos,S=c[1]&&c[1].pos;S==null&&(S=y),g={anchor:y+i,head:S+i}}return{doc:m,sel:g,from:i,to:a}}function Aq(n){let e=n.pmViewDesc;if(e)return e.parseRule();if(n.nodeName=="BR"&&n.parentNode){if(cr&&/^(ul|ol)$/i.test(n.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}else if(n.parentNode.lastChild==n||cr&&/^(tr|table)$/i.test(n.parentNode.nodeName))return{ignore:!0}}else if(n.nodeName=="IMG"&&n.getAttribute("mark-placeholder"))return{ignore:!0};return null}const Dq=/^(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 Oq(n,e,t,r,s){let o=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let I=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,k=C1(n,I);if(k&&!n.state.selection.eq(k)){if(Un&&Oi&&n.input.lastKeyCode===13&&Date.now()-100<n.input.lastKeyCodeTime&&n.someProp("handleKeyDown",R=>R(n,hl(13,"Enter"))))return;let A=n.state.tr.setSelection(k);I=="pointer"?A.setMeta("pointer",!0):I=="key"&&A.scrollIntoView(),o&&A.setMeta("composition",o),n.dispatch(A)}return}let i=n.state.doc.resolve(e),a=i.sharedDepth(t);e=i.before(a+1),t=n.state.doc.resolve(t).after(a+1);let l=n.state.selection,c=Mq(n,e,t),u=n.state.doc,d=u.slice(c.from,c.to),h,f;n.input.lastKeyCode===8&&Date.now()-100<n.input.lastKeyCodeTime?(h=n.state.selection.to,f="end"):(h=n.state.selection.from,f="start"),n.input.lastKeyCode=null;let g=jq(d.content,c.doc.content,c.from,h,f);if(g&&n.input.domChangeCount++,(sd&&n.input.lastIOSEnter>Date.now()-225||Oi)&&s.some(I=>I.nodeType==1&&!Dq.test(I.nodeName))&&(!g||g.endA>=g.endB)&&n.someProp("handleKeyDown",I=>I(n,hl(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!g)if(r&&l instanceof He&&!l.empty&&l.$head.sameParent(l.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))g={start:l.from,endA:l.to,endB:l.to};else{if(c.sel){let I=aE(n,n.state.doc,c.sel);if(I&&!I.eq(n.state.selection)){let k=n.state.tr.setSelection(I);o&&k.setMeta("composition",o),n.dispatch(k)}}return}n.state.selection.from<n.state.selection.to&&g.start==g.endB&&n.state.selection instanceof He&&(g.start>n.state.selection.from&&g.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?g.start=n.state.selection.from:g.endA<n.state.selection.to&&g.endA>=n.state.selection.to-2&&n.state.selection.to<=c.to&&(g.endB+=n.state.selection.to-g.endA,g.endA=n.state.selection.to)),Qr&&Ea<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>c.from&&c.doc.textBetween(g.start-c.from-1,g.start-c.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let m=c.doc.resolveNoCache(g.start-c.from),y=c.doc.resolveNoCache(g.endB-c.from),S=u.resolve(g.start),b=m.sameParent(y)&&m.parent.inlineContent&&S.end()>=g.endA;if((sd&&n.input.lastIOSEnter>Date.now()-225&&(!b||s.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!b&&m.pos<c.doc.content.size&&(!m.sameParent(y)||!m.parent.inlineContent)&&m.pos<y.pos&&!/\S/.test(c.doc.textBetween(m.pos,y.pos,"","")))&&n.someProp("handleKeyDown",I=>I(n,hl(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>g.start&&Lq(u,g.start,g.endA,m,y)&&n.someProp("handleKeyDown",I=>I(n,hl(8,"Backspace")))){Oi&&Un&&n.domObserver.suppressSelectionUpdates();return}Un&&g.endB==g.start&&(n.input.lastChromeDelete=Date.now()),Oi&&!b&&m.start()!=y.start()&&y.parentOffset==0&&m.depth==y.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==g.endA&&(g.endB-=2,y=c.doc.resolveNoCache(g.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(I){return I(n,hl(13,"Enter"))})},20));let w=g.start,v=g.endA,P=I=>{let k=I||n.state.tr.replace(w,v,c.doc.slice(g.start-c.from,g.endB-c.from));if(c.sel){let A=aE(n,k.doc,c.sel);A&&!(Un&&n.composing&&A.empty&&(g.start!=g.endB||n.input.lastChromeDelete<Date.now()-100)&&(A.head==w||A.head==k.mapping.map(v)-1)||Qr&&A.empty&&A.head==w)&&k.setSelection(A)}return o&&k.setMeta("composition",o),k.scrollIntoView()},T;if(b)if(m.pos==y.pos){Qr&&Ea<=11&&m.parentOffset==0&&(n.domObserver.suppressSelectionUpdates(),setTimeout(()=>Bi(n),20));let I=P(n.state.tr.delete(w,v)),k=u.resolve(g.start).marksAcross(u.resolve(g.endA));k&&I.ensureMarks(k),n.dispatch(I)}else if(g.endA==g.endB&&(T=Rq(m.parent.content.cut(m.parentOffset,y.parentOffset),S.parent.content.cut(S.parentOffset,g.endA-S.start())))){let I=P(n.state.tr);T.type=="add"?I.addMark(w,v,T.mark):I.removeMark(w,v,T.mark),n.dispatch(I)}else if(m.parent.child(m.index()).isText&&m.index()==y.index()-(y.textOffset?0:1)){let I=m.parent.textBetween(m.parentOffset,y.parentOffset),k=()=>P(n.state.tr.insertText(I,w,v));n.someProp("handleTextInput",A=>A(n,w,v,I,k))||n.dispatch(k())}else n.dispatch(P());else n.dispatch(P())}function aE(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:P1(n,e.resolve(t.anchor),e.resolve(t.head))}function Rq(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,s=t,o=r,i,a,l;for(let u=0;u<r.length;u++)s=r[u].removeFromSet(s);for(let u=0;u<t.length;u++)o=t[u].removeFromSet(o);if(s.length==1&&o.length==0)a=s[0],i="add",l=u=>u.mark(a.addToSet(u.marks));else if(s.length==0&&o.length==1)a=o[0],i="remove",l=u=>u.mark(a.removeFromSet(u.marks));else return null;let c=[];for(let u=0;u<e.childCount;u++)c.push(l(e.child(u)));if(ne.from(c).eq(n))return{mark:a,type:i}}function Lq(n,e,t,r,s){if(t-e<=s.pos-r.pos||lb(r,!0,!1)<s.pos)return!1;let o=n.resolve(e);if(!r.parent.isTextblock){let a=o.nodeAfter;return a!=null&&t==e+a.nodeSize}if(o.parentOffset<o.parent.content.size||!o.parent.isTextblock)return!1;let i=n.resolve(lb(o,!0,!0));return!i.parent.isTextblock||i.pos>t||lb(i,!0,!1)<t?!1:r.parent.content.cut(r.parentOffset).eq(i.parent.content)}function lb(n,e,t){let r=n.depth,s=e?n.end():n.pos;for(;r>0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,s++,e=!1;if(t){let o=n.node(r).maybeChild(n.indexAfter(r));for(;o&&!o.isLeaf;)o=o.firstChild,s++}return s}function jq(n,e,t,r,s){let o=n.findDiffStart(e,t);if(o==null)return null;let{a:i,b:a}=n.findDiffEnd(e,t+n.size,t+e.size);if(s=="end"){let l=Math.max(0,o-Math.min(i,a));r-=i+l-o}if(i<o&&n.size<e.size){let l=r<=o&&r>=i?o-r:0;o-=l,o&&o<e.size&&lE(e.textBetween(o-1,o+1))&&(o+=l?1:-1),a=o+(a-i),i=o}else if(a<o){let l=r<=o&&r>=a?o-r:0;o-=l,o&&o<n.size&&lE(n.textBetween(o-1,o+1))&&(o+=l?1:-1),i=o+(i-a),a=o}return{start:o,endA:i,endB:a}}function lE(n){if(n.length!=2)return!1;let e=n.charCodeAt(0),t=n.charCodeAt(1);return e>=56320&&e<=57343&&t>=55296&&t<=56319}class cj{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new JX,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(pE),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=uE(this),dE(this),this.nodeViews=hE(this),this.docView=UI(this.state.doc,cE(this),ab(this),this.dom,this),this.domObserver=new Tq(this,(r,s,o,i)=>Oq(this,r,s,o,i)),this.domObserver.start(),QX(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&a0(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(pE),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let s=this.state,o=!1,i=!1;e.storedMarks&&this.composing&&(nj(this),i=!0),this.state=e;let a=s.plugins!=e.plugins||this._props.plugins!=t.plugins;if(a||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let f=hE(this);Fq(f,this.nodeViews)&&(this.nodeViews=f,o=!0)}(a||t.handleDOMEvents!=this._props.handleDOMEvents)&&a0(this),this.editable=uE(this),dE(this);let l=ab(this),c=cE(this),u=s.plugins!=e.plugins&&!s.doc.eq(e.doc)?"reset":e.scrollToSelection>s.scrollToSelection?"to selection":"preserve",d=o||!this.docView.matchesNode(e.doc,c,l);(d||!e.selection.eq(s.selection))&&(i=!0);let h=u=="preserve"&&i&&this.dom.style.overflowAnchor==null&&pX(this);if(i){this.domObserver.stop();let f=d&&(Qr||Un)&&!this.composing&&!s.selection.empty&&!e.selection.empty&&Nq(s.selection,e.selection);if(d){let g=Un?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=pq(this)),(o||!this.docView.update(e.doc,c,l,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=UI(e.doc,c,l,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&NX(this))?Bi(this,f):(KL(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(s),!((r=this.dragging)===null||r===void 0)&&r.node&&!s.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,s),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():h&&fX(h)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!this.dom.contains(e.nodeType==1?e:e.parentNode))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof Me){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&NI(this,t.getBoundingClientRect(),e)}else NI(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t<this.directPlugins.length;t++){let r=this.directPlugins[t];r.spec.view&&this.pluginViews.push(r.spec.view(this))}for(let t=0;t<this.state.plugins.length;t++){let r=this.state.plugins[t];r.spec.view&&this.pluginViews.push(r.spec.view(this))}}else for(let t=0;t<this.pluginViews.length;t++){let r=this.pluginViews[t];r.update&&r.update(this,e)}}updateDraggedNode(e,t){let r=e.node,s=-1;if(this.state.doc.nodeAt(r.from)==r.node)s=r.from;else{let o=r.from+(this.state.doc.content.size-t.doc.content.size);(o>0&&this.state.doc.nodeAt(o))==r.node&&(s=o)}this.dragging=new sj(e.slice,e.move,s<0?void 0:Me.create(this.state.doc,s))}someProp(e,t){let r=this._props&&this._props[e],s;if(r!=null&&(s=t?t(r):r))return s;for(let i=0;i<this.directPlugins.length;i++){let a=this.directPlugins[i].props[e];if(a!=null&&(s=t?t(a):a))return s}let o=this.state.plugins;if(o)for(let i=0;i<o.length;i++){let a=o[i].props[e];if(a!=null&&(s=t?t(a):a))return s}}hasFocus(){if(Qr){let e=this.root.activeElement;if(e==this.dom)return!0;if(!e||!this.dom.contains(e))return!1;for(;e&&this.dom!=e&&this.dom.contains(e);){if(e.contentEditable=="false")return!1;e=e.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&gX(this.dom),Bi(this),this.domObserver.start()}get root(){let e=this._root;if(e==null){for(let t=this.dom.parentNode;t;t=t.parentNode)if(t.nodeType==9||t.nodeType==11&&t.host)return t.getSelection||(Object.getPrototypeOf(t).getSelection=()=>t.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return bX(this,e)}coordsAtPos(e,t=1){return jL(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let s=this.docView.posFromDOM(e,t,r);if(s==null)throw new RangeError("DOM position not inside the editor");return s}endOfTextblock(e,t){return TX(this,t||this.state,e)}pasteHTML(e,t){return ph(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return ph(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return T1(this,e)}destroy(){this.docView&&(eq(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ab(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,rX())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return nq(this,e)}domSelectionRange(){let e=this.domSelection();return e?cr&&this.root.nodeType===11&&lX(this.dom.ownerDocument)==this.dom&&Eq(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}cj.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function cE(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[_r.node(0,n.state.doc.content.size,e)]}function dE(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:_r.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function uE(n){return!n.someProp("editable",e=>e(n.state)===!1)}function Nq(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function hE(n){let e=Object.create(null);function t(r){for(let s in r)Object.prototype.hasOwnProperty.call(e,s)||(e[s]=r[s])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function Fq(n,e){let t=0,r=0;for(let s in n){if(n[s]!=e[s])return!0;t++}for(let s in e)r++;return t!=r}function pE(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var La={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:"'"},sm={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Bq=typeof navigator<"u"&&/Mac/.test(navigator.platform),zq=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Fn=0;Fn<10;Fn++)La[48+Fn]=La[96+Fn]=String(Fn);for(var Fn=1;Fn<=24;Fn++)La[Fn+111]="F"+Fn;for(var Fn=65;Fn<=90;Fn++)La[Fn]=String.fromCharCode(Fn+32),sm[Fn]=String.fromCharCode(Fn);for(var cb in La)sm.hasOwnProperty(cb)||(sm[cb]=La[cb]);function $q(n){var e=Bq&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||zq&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?sm:La)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const Hq=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Uq=typeof navigator<"u"&&/Win/.test(navigator.platform);function Kq(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,s,o,i;for(let a=0;a<e.length-1;a++){let l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))s=!0;else if(/^s(hift)?$/i.test(l))o=!0;else if(/^mod$/i.test(l))Hq?i=!0:s=!0;else throw new Error("Unrecognized modifier name: "+l)}return r&&(t="Alt-"+t),s&&(t="Ctrl-"+t),i&&(t="Meta-"+t),o&&(t="Shift-"+t),t}function Wq(n){let e=Object.create(null);for(let t in n)e[Kq(t)]=n[t];return e}function db(n,e,t=!0){return e.altKey&&(n="Alt-"+n),e.ctrlKey&&(n="Ctrl-"+n),e.metaKey&&(n="Meta-"+n),t&&e.shiftKey&&(n="Shift-"+n),n}function Vq(n){return new Ht({props:{handleKeyDown:dj(n)}})}function dj(n){let e=Wq(n);return function(t,r){let s=$q(r),o,i=e[db(s,r)];if(i&&i(t.state,t.dispatch,t))return!0;if(s.length==1&&s!=" "){if(r.shiftKey){let a=e[db(s,r,!1)];if(a&&a(t.state,t.dispatch,t))return!0}if((r.altKey||r.metaKey||r.ctrlKey)&&!(Uq&&r.ctrlKey&&r.altKey)&&(o=La[r.keyCode])&&o!=s){let a=e[db(o,r)];if(a&&a(t.state,t.dispatch,t))return!0}}return!1}}var Gq=Object.defineProperty,A1=(n,e)=>{for(var t in e)Gq(n,t,{get:e[t],enumerable:!0})};function Ny(n){const{state:e,transaction:t}=n;let{selection:r}=t,{doc:s}=t,{storedMarks:o}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return o},get selection(){return r},get doc(){return s},get tr(){return r=t.selection,s=t.doc,o=t.storedMarks,t}}}var Fy=class{constructor(n){this.editor=n.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=n.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:n,editor:e,state:t}=this,{view:r}=e,{tr:s}=t,o=this.buildProps(s);return Object.fromEntries(Object.entries(n).map(([i,a])=>[i,(...c)=>{const u=a(...c)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&r.dispatch(s),u}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(n,e=!0){const{rawCommands:t,editor:r,state:s}=this,{view:o}=r,i=[],a=!!n,l=n||s.tr,c=()=>(!a&&e&&!l.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(l),i.every(d=>d===!0)),u={...Object.fromEntries(Object.entries(t).map(([d,h])=>[d,(...g)=>{const m=this.buildProps(l,e),y=h(...g)(m);return i.push(y),u}])),run:c};return u}createCan(n){const{rawCommands:e,state:t}=this,r=!1,s=n||t.tr,o=this.buildProps(s,r);return{...Object.fromEntries(Object.entries(e).map(([a,l])=>[a,(...c)=>l(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,r)}}buildProps(n,e=!0){const{rawCommands:t,editor:r,state:s}=this,{view:o}=r,i={tr:n,editor:r,view:o,state:Ny({state:s,transaction:n}),dispatch:e?()=>{}:void 0,chain:()=>this.createChain(n,e),can:()=>this.createCan(n),get commands(){return Object.fromEntries(Object.entries(t).map(([a,l])=>[a,(...c)=>l(...c)(i)]))}};return i}},uj={};A1(uj,{blur:()=>Yq,clearContent:()=>Xq,clearNodes:()=>qq,command:()=>Zq,createParagraphNear:()=>Jq,cut:()=>Qq,deleteCurrentNode:()=>eZ,deleteNode:()=>tZ,deleteRange:()=>nZ,deleteSelection:()=>rZ,enter:()=>sZ,exitCode:()=>oZ,extendMarkRange:()=>iZ,first:()=>aZ,focus:()=>cZ,forEach:()=>dZ,insertContent:()=>uZ,insertContentAt:()=>fZ,joinBackward:()=>yZ,joinDown:()=>mZ,joinForward:()=>SZ,joinItemBackward:()=>xZ,joinItemForward:()=>bZ,joinTextblockBackward:()=>wZ,joinTextblockForward:()=>vZ,joinUp:()=>gZ,keyboardShortcut:()=>PZ,lift:()=>TZ,liftEmptyBlock:()=>IZ,liftListItem:()=>EZ,newlineInCode:()=>kZ,resetAttributes:()=>_Z,scrollIntoView:()=>MZ,selectAll:()=>AZ,selectNodeBackward:()=>DZ,selectNodeForward:()=>OZ,selectParentNode:()=>RZ,selectTextblockEnd:()=>LZ,selectTextblockStart:()=>jZ,setContent:()=>NZ,setMark:()=>sJ,setMeta:()=>oJ,setNode:()=>iJ,setNodeSelection:()=>aJ,setTextDirection:()=>lJ,setTextSelection:()=>cJ,sinkListItem:()=>dJ,splitBlock:()=>uJ,splitListItem:()=>hJ,toggleList:()=>pJ,toggleMark:()=>fJ,toggleNode:()=>gJ,toggleWrap:()=>mJ,undoInputRule:()=>yJ,unsetAllMarks:()=>SJ,unsetMark:()=>xJ,unsetTextDirection:()=>bJ,updateAttributes:()=>wJ,wrapIn:()=>vJ,wrapInList:()=>CJ});var Yq=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{var t;n.isDestroyed||(e.dom.blur(),(t=window==null?void 0:window.getSelection())==null||t.removeAllRanges())}),!0),Xq=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),qq=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:s}=r;return t&&s.forEach(({$from:o,$to:i})=>{n.doc.nodesBetween(o.pos,i.pos,(a,l)=>{if(a.type.isText)return;const{doc:c,mapping:u}=e,d=c.resolve(u.map(l)),h=c.resolve(u.map(l+a.nodeSize)),f=d.blockRange(h);if(!f)return;const g=bd(f);if(a.type.isTextblock){const{defaultType:m}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(f.start,m)}(g||g===0)&&e.lift(f,g)})}),!0},Zq=n=>e=>n(e),Jq=()=>({state:n,dispatch:e})=>TL(n,e),Qq=(n,e)=>({editor:t,tr:r})=>{const{state:s}=t,o=s.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const i=r.mapping.map(e);return r.insert(i,o.content),r.setSelection(new He(r.doc.resolve(Math.max(i-1,0)))),!0},eZ=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const s=n.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===r.type){if(e){const a=s.before(o),l=s.after(o);n.delete(a,l).scrollIntoView()}return!0}return!1};function pn(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}var tZ=n=>({tr:e,state:t,dispatch:r})=>{const s=pn(n,t.schema),o=e.selection.$anchor;for(let i=o.depth;i>0;i-=1)if(o.node(i).type===s){if(r){const l=o.before(i),c=o.after(i);e.delete(l,c).scrollIntoView()}return!0}return!1},nZ=n=>({tr:e,dispatch:t})=>{const{from:r,to:s}=n;return t&&e.delete(r,s),!0},rZ=()=>({state:n,dispatch:e})=>y1(n,e),sZ=()=>({commands:n})=>n.keyboardShortcut("Enter"),oZ=()=>({state:n,dispatch:e})=>HY(n,e);function D1(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function om(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(s=>t.strict?e[s]===n[s]:D1(e[s])?e[s].test(n[s]):e[s]===n[s]):!0}function hj(n,e,t={}){return n.find(r=>r.type===e&&om(Object.fromEntries(Object.keys(t).map(s=>[s,r.attrs[s]])),t))}function fE(n,e,t={}){return!!hj(n,e,t)}function By(n,e,t){var r;if(!n||!e)return;let s=n.parent.childAfter(n.parentOffset);if((!s.node||!s.node.marks.some(u=>u.type===e))&&(s=n.parent.childBefore(n.parentOffset)),!s.node||!s.node.marks.some(u=>u.type===e)||(t=t||((r=s.node.marks[0])==null?void 0:r.attrs),!hj([...s.node.marks],e,t)))return;let i=s.index,a=n.start()+s.offset,l=i+1,c=a+s.node.nodeSize;for(;i>0&&fE([...n.parent.child(i-1).marks],e,t);)i-=1,a-=n.parent.child(i).nodeSize;for(;l<n.parent.childCount&&fE([...n.parent.child(l).marks],e,t);)c+=n.parent.child(l).nodeSize,l+=1;return{from:a,to:c}}function Gi(n,e){if(typeof n=="string"){if(!e.marks[n])throw Error(`There is no mark type named '${n}'. Maybe you forgot to add the extension?`);return e.marks[n]}return n}var iZ=(n,e={})=>({tr:t,state:r,dispatch:s})=>{const o=Gi(n,r.schema),{doc:i,selection:a}=t,{$from:l,from:c,to:u}=a;if(s){const d=By(l,o,e);if(d&&d.from<=c&&d.to>=u){const h=He.create(i,d.from,d.to);t.setSelection(h)}}return!0},aZ=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r<t.length;r+=1)if(t[r](e))return!0;return!1};function pj(n){return n instanceof He}function Sl(n=0,e=0,t=0){return Math.min(Math.max(n,e),t)}function fj(n,e=null){if(!e)return null;const t=Je.atStart(n),r=Je.atEnd(n);if(e==="start"||e===!0)return t;if(e==="end")return r;const s=t.from,o=r.to;return e==="all"?He.create(n,Sl(0,s,o),Sl(n.content.size,s,o)):He.create(n,Sl(e,s,o),Sl(e,s,o))}function gE(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function im(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function lZ(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var cZ=(n=null,e={})=>({editor:t,view:r,tr:s,dispatch:o})=>{e={scrollIntoView:!0,...e};const i=()=>{(im()||gE())&&r.dom.focus(),lZ()&&!im()&&!gE()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e!=null&&e.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(o&&n===null&&!pj(t.state.selection))return i(),!0;const a=fj(s.doc,n)||t.state.selection,l=t.state.selection.eq(a);return o&&(l||s.setSelection(a),l&&s.storedMarks&&s.setStoredMarks(s.storedMarks),i()),!0},dZ=(n,e)=>t=>n.every((r,s)=>e(r,{...t,index:s})),uZ=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),gj=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&gj(r)}return n};function fu(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`<body>${n}</body>`,t=new window.DOMParser().parseFromString(e,"text/html").body;return gj(t)}function gh(n,e,t){if(n instanceof mo||n instanceof ne)return n;t={slice:!0,parseOptions:{},...t};const r=typeof n=="object"&&n!==null,s=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return ne.fromArray(n.map(a=>e.nodeFromJSON(a)));const i=e.nodeFromJSON(n);return t.errorOnInvalidContent&&i.check(),i}catch(o){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:o});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",o),gh("",e,t)}if(s){if(t.errorOnInvalidContent){let i=!1,a="";const l=new JR({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(i=!0,a=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?Hc.fromSchema(l).parseSlice(fu(n),t.parseOptions):Hc.fromSchema(l).parse(fu(n),t.parseOptions),t.errorOnInvalidContent&&i)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const o=Hc.fromSchema(e);return t.slice?o.parseSlice(fu(n),t.parseOptions).content:o.parse(fu(n),t.parseOptions)}return gh("",e,t)}function hZ(n,e,t){const r=n.steps.length-1;if(r<e)return;const s=n.steps[r];if(!(s instanceof In||s instanceof kn))return;const o=n.mapping.maps[r];let i=0;o.forEach((a,l,c,u)=>{i===0&&(i=u)}),n.setSelection(Je.near(n.doc.resolve(i),t))}var pZ=n=>!("type"in n),fZ=(n,e,t)=>({tr:r,dispatch:s,editor:o})=>{var i;if(s){t={parseOptions:o.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let a;const l=y=>{o.emit("contentError",{editor:o,error:y,disableCollaboration:()=>{"collaboration"in o.storage&&typeof o.storage.collaboration=="object"&&o.storage.collaboration&&(o.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!o.options.enableContentCheck&&o.options.emitContentError)try{gh(e,o.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(y){l(y)}try{a=gh(e,o.schema,{parseOptions:c,errorOnInvalidContent:(i=t.errorOnInvalidContent)!=null?i:o.options.enableContentCheck})}catch(y){return l(y),!1}let{from:u,to:d}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},h=!0,f=!0;if((pZ(a)?a:[a]).forEach(y=>{y.check(),h=h?y.isText&&y.marks.length===0:!1,f=f?y.isBlock:!1}),u===d&&f){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,d+=1)}let m;if(h){if(Array.isArray(e))m=e.map(y=>y.text||"").join("");else if(e instanceof ne){let y="";e.forEach(S=>{S.text&&(y+=S.text)}),m=y}else typeof e=="object"&&e&&e.text?m=e.text:m=e;r.insertText(m,u,d)}else{m=a;const y=r.doc.resolve(u),S=y.node(),b=y.parentOffset===0,w=S.isText||S.isTextblock,v=S.content.size>0;b&&w&&v&&(u=Math.max(0,u-1)),r.replaceWith(u,d,m)}t.updateSelection&&hZ(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:m})}return!0},gZ=()=>({state:n,dispatch:e})=>BY(n,e),mZ=()=>({state:n,dispatch:e})=>zY(n,e),yZ=()=>({state:n,dispatch:e})=>SL(n,e),SZ=()=>({state:n,dispatch:e})=>vL(n,e),xZ=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ay(n.doc,n.selection.$from.pos,-1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},bZ=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Ay(n.doc,n.selection.$from.pos,1);return r==null?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},wZ=()=>({state:n,dispatch:e})=>NY(n,e),vZ=()=>({state:n,dispatch:e})=>FY(n,e);function mj(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function CZ(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,s,o,i;for(let a=0;a<e.length-1;a+=1){const l=e[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))r=!0;else if(/^(c|ctrl|control)$/i.test(l))s=!0;else if(/^s(hift)?$/i.test(l))o=!0;else if(/^mod$/i.test(l))im()||mj()?i=!0:s=!0;else throw new Error(`Unrecognized modifier name: ${l}`)}return r&&(t=`Alt-${t}`),s&&(t=`Ctrl-${t}`),i&&(t=`Meta-${t}`),o&&(t=`Shift-${t}`),t}var PZ=n=>({editor:e,view:t,tr:r,dispatch:s})=>{const o=CZ(n).split(/-(?!$)/),i=o.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),a=new KeyboardEvent("keydown",{key:i==="Space"?" ":i,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),l=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,a))});return l==null||l.steps.forEach(c=>{const u=c.map(r.mapping);u&&s&&r.maybeStep(u)}),!0};function ja(n,e,t={}){const{from:r,to:s,empty:o}=n.selection,i=e?pn(e,n.schema):null,a=[];n.doc.nodesBetween(r,s,(d,h)=>{if(d.isText)return;const f=Math.max(r,h),g=Math.min(s,h+d.nodeSize);a.push({node:d,from:f,to:g})});const l=s-r,c=a.filter(d=>i?i.name===d.node.type.name:!0).filter(d=>om(d.node.attrs,t,{strict:!1}));return o?!!c.length:c.reduce((d,h)=>d+h.to-h.from,0)>=l}var TZ=(n,e={})=>({state:t,dispatch:r})=>{const s=pn(n,t.schema);return ja(t,s,e)?$Y(t,r):!1},IZ=()=>({state:n,dispatch:e})=>IL(n,e),EZ=n=>({state:e,dispatch:t})=>{const r=pn(n,e.schema);return QY(r)(e,t)},kZ=()=>({state:n,dispatch:e})=>PL(n,e);function zy(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function mE(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,s)=>(t.includes(s)||(r[s]=n[s]),r),{})}var _Z=(n,e)=>({tr:t,state:r,dispatch:s})=>{let o=null,i=null;const a=zy(typeof n=="string"?n:n.name,r.schema);if(!a)return!1;a==="node"&&(o=pn(n,r.schema)),a==="mark"&&(i=Gi(n,r.schema));let l=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{o&&o===u.type&&(l=!0,s&&t.setNodeMarkup(d,void 0,mE(u.attrs,e))),i&&u.marks.length&&u.marks.forEach(h=>{i===h.type&&(l=!0,s&&t.addMark(d,d+u.nodeSize,i.create(mE(h.attrs,e))))})})}),l},MZ=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),AZ=()=>({tr:n,dispatch:e})=>{if(e){const t=new Ss(n.doc);n.setSelection(t)}return!0},DZ=()=>({state:n,dispatch:e})=>bL(n,e),OZ=()=>({state:n,dispatch:e})=>CL(n,e),RZ=()=>({state:n,dispatch:e})=>WY(n,e),LZ=()=>({state:n,dispatch:e})=>YY(n,e),jZ=()=>({state:n,dispatch:e})=>GY(n,e);function l0(n,e,t={},r={}){return gh(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}var NZ=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:s,tr:o,dispatch:i,commands:a})=>{const{doc:l}=o;if(r.preserveWhitespace!=="full"){const c=l0(n,s.schema,r,{errorOnInvalidContent:e??s.options.enableContentCheck});return i&&o.replaceWith(0,l.content.size,c).setMeta("preventUpdate",!t),!0}return i&&o.setMeta("preventUpdate",!t),a.insertContentAt({from:0,to:l.content.size},n,{parseOptions:r,errorOnInvalidContent:e??s.options.enableContentCheck})};function yj(n,e){const t=Gi(e,n.schema),{from:r,to:s,empty:o}=n.selection,i=[];o?(n.storedMarks&&i.push(...n.storedMarks),i.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,s,l=>{i.push(...l.marks)});const a=i.find(l=>l.type.name===t.name);return a?{...a.attrs}:{}}function Sj(n,e){const t=new fL(n);return e.forEach(r=>{r.steps.forEach(s=>{t.step(s)})}),t}function FZ(n){for(let e=0;e<n.edgeCount;e+=1){const{type:t}=n.edge(e);if(t.isTextblock&&!t.hasRequiredAttrs())return t}return null}function BZ(n,e,t){const r=[];return n.nodesBetween(e.from,e.to,(s,o)=>{t(s)&&r.push({node:s,pos:o})}),r}function zZ(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function $y(n){return e=>zZ(e.$from,n)}function Ee(n,e,t){return n.config[e]===void 0&&n.parent?Ee(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?Ee(n.parent,e,t):null}):n.config[e]}function O1(n){return n.map(e=>{const t={name:e.name,options:e.options,storage:e.storage},r=Ee(e,"addExtensions",t);return r?[e,...O1(r())]:e}).flat(10)}function Hy(n,e){const t=ql.fromSchema(e).serializeFragment(n),s=document.implementation.createHTMLDocument().createElement("div");return s.appendChild(t),s.innerHTML}function xj(n){return typeof n=="function"}function gt(n,e=void 0,...t){return xj(n)?e?n.bind(e)(...t):n(...t):n}function $Z(n={}){return Object.keys(n).length===0&&n.constructor===Object}function od(n){const e=n.filter(s=>s.type==="extension"),t=n.filter(s=>s.type==="node"),r=n.filter(s=>s.type==="mark");return{baseExtensions:e,nodeExtensions:t,markExtensions:r}}function bj(n){const e=[],{nodeExtensions:t,markExtensions:r}=od(n),s=[...t,...r],o={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},i=t.filter(c=>c.name!=="text").map(c=>c.name),a=r.map(c=>c.name),l=[...i,...a];return n.forEach(c=>{const u={name:c.name,options:c.options,storage:c.storage,extensions:s},d=Ee(c,"addGlobalAttributes",u);if(!d)return;d().forEach(f=>{let g;Array.isArray(f.types)?g=f.types:f.types==="*"?g=l:f.types==="nodes"?g=i:f.types==="marks"?g=a:g=[],g.forEach(m=>{Object.entries(f.attributes).forEach(([y,S])=>{e.push({type:m,name:y,attribute:{...o,...S}})})})})}),s.forEach(c=>{const u={name:c.name,options:c.options,storage:c.storage},d=Ee(c,"addAttributes",u);if(!d)return;const h=d();Object.entries(h).forEach(([f,g])=>{const m={...o,...g};typeof(m==null?void 0:m.default)=="function"&&(m.default=m.default()),m!=null&&m.isRequired&&(m==null?void 0:m.default)===void 0&&delete m.default,e.push({type:c.name,name:f,attribute:m})})}),e}function nn(...n){return n.filter(e=>!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([s,o])=>{if(!r[s]){r[s]=o;return}if(s==="class"){const a=o?String(o).split(" "):[],l=r[s]?r[s].split(" "):[],c=a.filter(u=>!l.includes(u));r[s]=[...l,...c].join(" ")}else if(s==="style"){const a=o?o.split(";").map(u=>u.trim()).filter(Boolean):[],l=r[s]?r[s].split(";").map(u=>u.trim()).filter(Boolean):[],c=new Map;l.forEach(u=>{const[d,h]=u.split(":").map(f=>f.trim());c.set(d,h)}),a.forEach(u=>{const[d,h]=u.split(":").map(f=>f.trim());c.set(d,h)}),r[s]=Array.from(c.entries()).map(([u,d])=>`${u}: ${d}`).join("; ")}else r[s]=o}),r},{})}function mh(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>nn(t,r),{})}function HZ(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function yE(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const s=e.reduce((o,i)=>{const a=i.attribute.parseHTML?i.attribute.parseHTML(t):HZ(t.getAttribute(i.name));return a==null?o:{...o,[i.name]:a}},{});return{...r,...s}}}}function SE(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&$Z(t)?!1:t!=null))}function xE(n){var e,t;const r={};return!((e=n==null?void 0:n.attribute)!=null&&e.isRequired)&&"default"in((n==null?void 0:n.attribute)||{})&&(r.default=n.attribute.default),((t=n==null?void 0:n.attribute)==null?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function wj(n,e){var t;const r=bj(n),{nodeExtensions:s,markExtensions:o}=od(n),i=(t=s.find(c=>Ee(c,"topNode")))==null?void 0:t.name,a=Object.fromEntries(s.map(c=>{const u=r.filter(S=>S.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((S,b)=>{const w=Ee(b,"extendNodeSchema",d);return{...S,...w?w(c):{}}},{}),f=SE({...h,content:gt(Ee(c,"content",d)),marks:gt(Ee(c,"marks",d)),group:gt(Ee(c,"group",d)),inline:gt(Ee(c,"inline",d)),atom:gt(Ee(c,"atom",d)),selectable:gt(Ee(c,"selectable",d)),draggable:gt(Ee(c,"draggable",d)),code:gt(Ee(c,"code",d)),whitespace:gt(Ee(c,"whitespace",d)),linebreakReplacement:gt(Ee(c,"linebreakReplacement",d)),defining:gt(Ee(c,"defining",d)),isolating:gt(Ee(c,"isolating",d)),attrs:Object.fromEntries(u.map(xE))}),g=gt(Ee(c,"parseHTML",d));g&&(f.parseDOM=g.map(S=>yE(S,u)));const m=Ee(c,"renderHTML",d);m&&(f.toDOM=S=>m({node:S,HTMLAttributes:mh(S,u)}));const y=Ee(c,"renderText",d);return y&&(f.toText=y),[c.name,f]})),l=Object.fromEntries(o.map(c=>{const u=r.filter(y=>y.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},h=n.reduce((y,S)=>{const b=Ee(S,"extendMarkSchema",d);return{...y,...b?b(c):{}}},{}),f=SE({...h,inclusive:gt(Ee(c,"inclusive",d)),excludes:gt(Ee(c,"excludes",d)),group:gt(Ee(c,"group",d)),spanning:gt(Ee(c,"spanning",d)),code:gt(Ee(c,"code",d)),attrs:Object.fromEntries(u.map(xE))}),g=gt(Ee(c,"parseHTML",d));g&&(f.parseDOM=g.map(y=>yE(y,u)));const m=Ee(c,"renderHTML",d);return m&&(f.toDOM=y=>m({mark:y,HTMLAttributes:mh(y,u)})),[c.name,f]}));return new JR({topNode:i,nodes:a,marks:l})}function UZ(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function $u(n){return n.sort((t,r)=>{const s=Ee(t,"priority")||100,o=Ee(r,"priority")||100;return s>o?-1:s<o?1:0})}function R1(n){const e=$u(O1(n)),t=UZ(e.map(r=>r.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Uy(n,e){const t=R1(n);return wj(t,e)}function KZ(n,e){const t=Uy(e),r=mo.fromJSON(t,n);return Hy(r.content,t)}function WZ(n,e){const t=Uy(e),r=fu(n);return Hc.fromSchema(t).parse(r).toJSON()}function vj(n,e,t){const{from:r,to:s}=e,{blockSeparator:o=`
204
+
205
+ `,textSerializers:i={}}=t||{};let a="";return n.nodesBetween(r,s,(l,c,u,d)=>{var h;l.isBlock&&c>r&&(a+=o);const f=i==null?void 0:i[l.type.name];if(f)return u&&(a+=f({node:l,pos:c,parent:u,index:d,range:e})),!1;l.isText&&(a+=(h=l==null?void 0:l.text)==null?void 0:h.slice(Math.max(r,c)-c,s-c))}),a}function Cj(n,e){const t={from:0,to:n.content.size};return vj(n,t,e)}function L1(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function VZ(n,e,t){const{blockSeparator:r=`
206
+
207
+ `,textSerializers:s={}}=t||{},o=Uy(e),i=mo.fromJSON(o,n);return Cj(i,{blockSeparator:r,textSerializers:{...L1(o),...s}})}function GZ(n,e){const t=pn(e,n.schema),{from:r,to:s}=n.selection,o=[];n.doc.nodesBetween(r,s,a=>{o.push(a)});const i=o.reverse().find(a=>a.type.name===t.name);return i?{...i.attrs}:{}}function Pj(n,e){const t=zy(typeof e=="string"?e:e.name,n.schema);return t==="node"?GZ(n,e):t==="mark"?yj(n,e):{}}function YZ(n,e=JSON.stringify){const t={};return n.filter(r=>{const s=e(r);return Object.prototype.hasOwnProperty.call(t,s)?!1:t[s]=!0})}function XZ(n){const e=YZ(n);return e.length===1?e:e.filter((t,r)=>!e.filter((o,i)=>i!==r).some(o=>t.oldRange.from>=o.oldRange.from&&t.oldRange.to<=o.oldRange.to&&t.newRange.from>=o.newRange.from&&t.newRange.to<=o.newRange.to))}function Tj(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((s,o)=>{const i=[];if(s.ranges.length)s.forEach((a,l)=>{i.push({from:a,to:l})});else{const{from:a,to:l}=t[o];if(a===void 0||l===void 0)return;i.push({from:a,to:l})}i.forEach(({from:a,to:l})=>{const c=e.slice(o).map(a,-1),u=e.slice(o).map(l),d=e.invert().map(c,-1),h=e.invert().map(u);r.push({oldRange:{from:d,to:h},newRange:{from:c,to:u}})})}),XZ(r)}function j1(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(s=>{const o=t.resolve(n),i=By(o,s.type);i&&r.push({mark:s,...i})}):t.nodesBetween(n,e,(s,o)=>{!s||(s==null?void 0:s.nodeSize)===void 0||r.push(...s.marks.map(i=>({from:o,to:o+s.nodeSize,mark:i})))}),r}var qZ=(n,e,t,r=20)=>{const s=n.doc.resolve(t);let o=r,i=null;for(;o>0&&i===null;){const a=s.node(o);(a==null?void 0:a.type.name)===e?i=a:o-=1}return[i,o]};function Kd(n,e){return e.nodes[n]||e.marks[n]||null}function Kf(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const s=n.find(o=>o.type===e&&o.name===r);return s?s.attribute.keepOnSplit:!1}))}var ZZ=(n,e=500)=>{let t="";const r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(s,o,i,a)=>{var l,c;const u=((c=(l=s.type.spec).toText)==null?void 0:c.call(l,{node:s,pos:o,parent:i,index:a}))||s.textContent||"%leaf%";t+=s.isAtom&&!s.isText?u:u.slice(0,Math.max(0,r-o))}),t};function c0(n,e,t={}){const{empty:r,ranges:s}=n.selection,o=e?Gi(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(d=>o?o.name===d.type.name:!0).find(d=>om(d.attrs,t,{strict:!1}));let i=0;const a=[];if(s.forEach(({$from:d,$to:h})=>{const f=d.pos,g=h.pos;n.doc.nodesBetween(f,g,(m,y)=>{if(o&&m.inlineContent&&!m.type.allowsMarkType(o))return!1;if(!m.isText&&!m.marks.length)return;const S=Math.max(f,y),b=Math.min(g,y+m.nodeSize),w=b-S;i+=w,a.push(...m.marks.map(v=>({mark:v,from:S,to:b})))})}),i===0)return!1;const l=a.filter(d=>o?o.name===d.mark.type.name:!0).filter(d=>om(d.mark.attrs,t,{strict:!1})).reduce((d,h)=>d+h.to-h.from,0),c=a.filter(d=>o?d.mark.type!==o&&d.mark.type.excludes(o):!0).reduce((d,h)=>d+h.to-h.from,0);return(l>0?l+c:l)>=i}function JZ(n,e,t={}){if(!e)return ja(n,null,t)||c0(n,null,t);const r=zy(e,n.schema);return r==="node"?ja(n,e,t):r==="mark"?c0(n,e,t):!1}var QZ=(n,e)=>{const{$from:t,$to:r,$anchor:s}=n.selection;if(e){const o=$y(a=>a.type.name===e)(n.selection);if(!o)return!1;const i=n.doc.resolve(o.pos+1);return s.pos+1===i.end()}return!(r.parentOffset<r.parent.nodeSize-2||t.pos!==r.pos)},eJ=n=>{const{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function bE(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function wE(n,e){const{nodeExtensions:t}=od(e),r=t.find(i=>i.name===n);if(!r)return!1;const s={name:r.name,options:r.options,storage:r.storage},o=gt(Ee(r,"group",s));return typeof o!="string"?!1:o.split(" ").includes("list")}function Ky(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){var r;if(t){if(n.type.name==="hardBreak")return!0;if(n.isText)return/^\s*$/m.test((r=n.text)!=null?r:"")}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let s=!0;return n.content.forEach(o=>{s!==!1&&(Ky(o,{ignoreWhitespace:t,checkChildren:e})||(s=!1))}),s}return!1}function Ij(n){return n instanceof Me}var Ej=class kj{constructor(e){this.position=e}static fromJSON(e){return new kj(e.position)}toJSON(){return{position:this.position}}};function tJ(n,e){const t=e.mapping.mapResult(n.position);return{position:new Ej(t.pos),mapResult:t}}function nJ(n){return new Ej(n)}function rJ(n,e,t){var r;const{selection:s}=e;let o=null;if(pj(s)&&(o=s.$cursor),o){const a=(r=n.storedMarks)!=null?r:o.marks();return o.parent.type.allowsMarkType(t)&&(!!t.isInSet(a)||!a.some(c=>c.type.excludes(t)))}const{ranges:i}=s;return i.some(({$from:a,$to:l})=>{let c=a.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(a.pos,l.pos,(u,d,h)=>{if(c)return!1;if(u.isInline){const f=!h||h.type.allowsMarkType(t),g=!!t.isInSet(u.marks)||!u.marks.some(m=>m.type.excludes(t));c=f&&g}return!c}),c})}var sJ=(n,e={})=>({tr:t,state:r,dispatch:s})=>{const{selection:o}=t,{empty:i,ranges:a}=o,l=Gi(n,r.schema);if(s)if(i){const c=yj(r,l);t.addStoredMark(l.create({...c,...e}))}else a.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(h,f)=>{const g=Math.max(f,u),m=Math.min(f+h.nodeSize,d);h.marks.find(S=>S.type===l)?h.marks.forEach(S=>{l===S.type&&t.addMark(g,m,l.create({...S.attrs,...e}))}):t.addMark(g,m,l.create(e))})});return rJ(r,t,l)},oJ=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),iJ=(n,e={})=>({state:t,dispatch:r,chain:s})=>{const o=pn(n,t.schema);let i;return t.selection.$anchor.sameParent(t.selection.$head)&&(i=t.selection.$anchor.parent.attrs),o.isTextblock?s().command(({commands:a})=>RI(o,{...i,...e})(t)?!0:a.clearNodes()).command(({state:a})=>RI(o,{...i,...e})(a,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},aJ=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,s=Sl(n,0,r.content.size),o=Me.create(r,s);e.setSelection(o)}return!0},lJ=(n,e)=>({tr:t,state:r,dispatch:s})=>{const{selection:o}=r;let i,a;return typeof e=="number"?(i=e,a=e):e&&"from"in e&&"to"in e?(i=e.from,a=e.to):(i=o.from,a=o.to),s&&t.doc.nodesBetween(i,a,(l,c)=>{l.isText||t.setNodeMarkup(c,void 0,{...l.attrs,dir:n})}),!0},cJ=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:s,to:o}=typeof n=="number"?{from:n,to:n}:n,i=He.atStart(r).from,a=He.atEnd(r).to,l=Sl(s,i,a),c=Sl(o,i,a),u=He.create(r,l,c);e.setSelection(u)}return!0},dJ=n=>({state:e,dispatch:t})=>{const r=pn(n,e.schema);return nX(r)(e,t)};function vE(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(s=>e==null?void 0:e.includes(s.type.name));n.tr.ensureMarks(r)}}var uJ=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:s})=>{const{selection:o,doc:i}=e,{$from:a,$to:l}=o,c=s.extensionManager.attributes,u=Kf(c,a.node().type.name,a.node().attrs);if(o instanceof Me&&o.node.isBlock)return!a.parentOffset||!Fi(i,a.pos)?!1:(r&&(n&&vE(t,s.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const d=l.parentOffset===l.parent.content.size,h=a.depth===0?void 0:FZ(a.node(-1).contentMatchAt(a.indexAfter(-1)));let f=d&&h?[{type:h,attrs:u}]:void 0,g=Fi(e.doc,e.mapping.map(a.pos),1,f);if(!f&&!g&&Fi(e.doc,e.mapping.map(a.pos),1,h?[{type:h}]:void 0)&&(g=!0,f=h?[{type:h,attrs:u}]:void 0),r){if(g&&(o instanceof He&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,f),h&&!d&&!a.parentOffset&&a.parent.type!==h)){const m=e.mapping.map(a.before()),y=e.doc.resolve(m);a.node(-1).canReplaceWith(y.index(),y.index()+1,h)&&e.setNodeMarkup(e.mapping.map(a.before()),h)}n&&vE(t,s.extensionManager.splittableMarks),e.scrollIntoView()}return g},hJ=(n,e={})=>({tr:t,state:r,dispatch:s,editor:o})=>{var i;const a=pn(n,r.schema),{$from:l,$to:c}=r.selection,u=r.selection.node;if(u&&u.isBlock||l.depth<2||!l.sameParent(c))return!1;const d=l.node(-1);if(d.type!==a)return!1;const h=o.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==a||l.index(-2)!==l.node(-2).childCount-1)return!1;if(s){let S=ne.empty;const b=l.index(-1)?1:l.index(-2)?2:3;for(let k=l.depth-b;k>=l.depth-3;k-=1)S=ne.from(l.node(k).copy(S));const w=l.indexAfter(-1)<l.node(-2).childCount?1:l.indexAfter(-2)<l.node(-3).childCount?2:3,v={...Kf(h,l.node().type.name,l.node().attrs),...e},P=((i=a.contentMatch.defaultType)==null?void 0:i.createAndFill(v))||void 0;S=S.append(ne.from(a.createAndFill(null,P)||void 0));const T=l.before(l.depth-(b-1));t.replace(T,l.after(-w),new ye(S,4-b,0));let I=-1;t.doc.nodesBetween(T,t.doc.content.size,(k,A)=>{if(I>-1)return!1;k.isTextblock&&k.content.size===0&&(I=A+1)}),I>-1&&t.setSelection(He.near(t.doc.resolve(I))),t.scrollIntoView()}return!0}const f=c.pos===l.end()?d.contentMatchAt(0).defaultType:null,g={...Kf(h,d.type.name,d.attrs),...e},m={...Kf(h,l.node().type.name,l.node().attrs),...e};t.delete(l.pos,c.pos);const y=f?[{type:a,attrs:g},{type:f,attrs:m}]:[{type:a,attrs:g}];if(!Fi(t.doc,l.pos,2))return!1;if(s){const{selection:S,storedMarks:b}=r,{splittableMarks:w}=o.extensionManager,v=b||S.$to.parentOffset&&S.$from.marks();if(t.split(l.pos,2,y).scrollIntoView(),!v||!s)return!0;const P=v.filter(T=>w.includes(T.type.name));t.ensureMarks(P)}return!0},ub=(n,e)=>{const t=$y(i=>i.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const s=n.doc.nodeAt(r);return t.node.type===(s==null?void 0:s.type)&&Xa(n.doc,t.pos)&&n.join(t.pos),!0},hb=(n,e)=>{const t=$y(i=>i.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const s=n.doc.nodeAt(r);return t.node.type===(s==null?void 0:s.type)&&Xa(n.doc,r)&&n.join(r),!0},pJ=(n,e,t,r={})=>({editor:s,tr:o,state:i,dispatch:a,chain:l,commands:c,can:u})=>{const{extensions:d,splittableMarks:h}=s.extensionManager,f=pn(n,i.schema),g=pn(e,i.schema),{selection:m,storedMarks:y}=i,{$from:S,$to:b}=m,w=S.blockRange(b),v=y||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const P=$y(T=>wE(T.type.name,d))(m);if(w.depth>=1&&P&&w.depth-P.depth<=1){if(P.node.type===f)return c.liftListItem(g);if(wE(P.node.type.name,d)&&f.validContent(P.node.content)&&a)return l().command(()=>(o.setNodeMarkup(P.pos,f),!0)).command(()=>ub(o,f)).command(()=>hb(o,f)).run()}return!t||!v||!a?l().command(()=>u().wrapInList(f,r)?!0:c.clearNodes()).wrapInList(f,r).command(()=>ub(o,f)).command(()=>hb(o,f)).run():l().command(()=>{const T=u().wrapInList(f,r),I=v.filter(k=>h.includes(k.type.name));return o.ensureMarks(I),T?!0:c.clearNodes()}).wrapInList(f,r).command(()=>ub(o,f)).command(()=>hb(o,f)).run()},fJ=(n,e={},t={})=>({state:r,commands:s})=>{const{extendEmptyMarkRange:o=!1}=t,i=Gi(n,r.schema);return c0(r,i,e)?s.unsetMark(i,{extendEmptyMarkRange:o}):s.setMark(i,e)},gJ=(n,e,t={})=>({state:r,commands:s})=>{const o=pn(n,r.schema),i=pn(e,r.schema),a=ja(r,o,t);let l;return r.selection.$anchor.sameParent(r.selection.$head)&&(l=r.selection.$anchor.parent.attrs),a?s.setNode(i,l):s.setNode(o,{...l,...t})},mJ=(n,e={})=>({state:t,commands:r})=>{const s=pn(n,t.schema);return ja(t,s,e)?r.lift(s):r.wrapIn(s,e)},yJ=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r<t.length;r+=1){const s=t[r];let o;if(s.spec.isInputRules&&(o=s.getState(n))){if(e){const i=n.tr,a=o.transform;for(let l=a.steps.length-1;l>=0;l-=1)i.step(a.steps[l].invert(a.docs[l]));if(o.text){const l=i.doc.resolve(o.from).marks();i.replaceWith(o.from,o.to,n.schema.text(o.text,l))}else i.delete(o.from,o.to)}return!0}}return!1},SJ=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,{empty:r,ranges:s}=t;return r||e&&s.forEach(o=>{n.removeMark(o.$from.pos,o.$to.pos)}),!0},xJ=(n,e={})=>({tr:t,state:r,dispatch:s})=>{var o;const{extendEmptyMarkRange:i=!1}=e,{selection:a}=t,l=Gi(n,r.schema),{$from:c,empty:u,ranges:d}=a;if(!s)return!0;if(u&&i){let{from:h,to:f}=a;const g=(o=c.marks().find(y=>y.type===l))==null?void 0:o.attrs,m=By(c,l,g);m&&(h=m.from,f=m.to),t.removeMark(h,f,l)}else d.forEach(h=>{t.removeMark(h.$from.pos,h.$to.pos,l)});return t.removeStoredMark(l),!0},bJ=n=>({tr:e,state:t,dispatch:r})=>{const{selection:s}=t;let o,i;return typeof n=="number"?(o=n,i=n):n&&"from"in n&&"to"in n?(o=n.from,i=n.to):(o=s.from,i=s.to),r&&e.doc.nodesBetween(o,i,(a,l)=>{if(a.isText)return;const c={...a.attrs};delete c.dir,e.setNodeMarkup(l,void 0,c)}),!0},wJ=(n,e={})=>({tr:t,state:r,dispatch:s})=>{let o=null,i=null;const a=zy(typeof n=="string"?n:n.name,r.schema);if(!a)return!1;a==="node"&&(o=pn(n,r.schema)),a==="mark"&&(i=Gi(n,r.schema));let l=!1;return t.selection.ranges.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;let h,f,g,m;t.selection.empty?r.doc.nodesBetween(u,d,(y,S)=>{o&&o===y.type&&(l=!0,g=Math.max(S,u),m=Math.min(S+y.nodeSize,d),h=S,f=y)}):r.doc.nodesBetween(u,d,(y,S)=>{S<u&&o&&o===y.type&&(l=!0,g=Math.max(S,u),m=Math.min(S+y.nodeSize,d),h=S,f=y),S>=u&&S<=d&&(o&&o===y.type&&(l=!0,s&&t.setNodeMarkup(S,void 0,{...y.attrs,...e})),i&&y.marks.length&&y.marks.forEach(b=>{if(i===b.type&&(l=!0,s)){const w=Math.max(S,u),v=Math.min(S+y.nodeSize,d);t.addMark(w,v,i.create({...b.attrs,...e}))}}))}),f&&(h!==void 0&&s&&t.setNodeMarkup(h,void 0,{...f.attrs,...e}),i&&f.marks.length&&f.marks.forEach(y=>{i===y.type&&s&&t.addMark(g,m,i.create({...y.attrs,...e}))}))}),l},vJ=(n,e={})=>({state:t,dispatch:r})=>{const s=pn(n,t.schema);return XY(s,e)(t,r)},CJ=(n,e={})=>({state:t,dispatch:r})=>{const s=pn(n,t.schema);return qY(s,e)(t,r)},PJ=class{constructor(){this.callbacks={}}on(n,e){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(e),this}emit(n,...e){const t=this.callbacks[n];return t&&t.forEach(r=>r.apply(this,e)),this}off(n,e){const t=this.callbacks[n];return t&&(e?this.callbacks[n]=t.filter(r=>r!==e):delete this.callbacks[n]),this}once(n,e){const t=(...r)=>{this.off(n,t),e.apply(this,r)};return this.on(n,t)}removeAllListeners(){this.callbacks={}}},Wy=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!=null?e:!0}},TJ=(n,e)=>{if(D1(e))return e.exec(n);const t=e(n);if(!t)return null;const r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function Qp(n){var e;const{editor:t,from:r,to:s,text:o,rules:i,plugin:a}=n,{view:l}=t;if(l.composing)return!1;const c=l.state.doc.resolve(r);if(c.parent.type.spec.code||(e=c.nodeBefore||c.nodeAfter)!=null&&e.marks.find(h=>h.type.spec.code))return!1;let u=!1;const d=ZZ(c)+o;return i.forEach(h=>{if(u)return;const f=TJ(d,h.find);if(!f)return;const g=l.state.tr,m=Ny({state:l.state,transaction:g}),y={from:r-(f[0].length-o.length),to:s},{commands:S,chain:b,can:w}=new Fy({editor:t,state:m});h.handler({state:m,range:y,match:f,commands:S,chain:b,can:w})===null||!g.steps.length||(h.undoable&&g.setMeta(a,{transform:g,from:r,to:s,text:o}),l.dispatch(g),u=!0)}),u}function IJ(n){const{editor:e,rules:t}=n,r=new Ht({state:{init(){return null},apply(s,o,i){const a=s.getMeta(r);if(a)return a;const l=s.getMeta("applyInputRules");return!!l&&setTimeout(()=>{let{text:u}=l;typeof u=="string"?u=u:u=Hy(ne.from(u),i.schema);const{from:d}=l,h=d+u.length;Qp({editor:e,from:d,to:h,text:u,rules:t,plugin:r})}),s.selectionSet||s.docChanged?null:o}},props:{handleTextInput(s,o,i,a){return Qp({editor:e,from:o,to:i,text:a,rules:t,plugin:r})},handleDOMEvents:{compositionend:s=>(setTimeout(()=>{const{$cursor:o}=s.state.selection;o&&Qp({editor:e,from:o.pos,to:o.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(s,o){if(o.key!=="Enter")return!1;const{$cursor:i}=s.state.selection;return i?Qp({editor:e,from:i.pos,to:i.pos,text:`
208
+ `,rules:t,plugin:r}):!1}},isInputRules:!0});return r}function EJ(n){return Object.prototype.toString.call(n).slice(8,-1)}function ef(n){return EJ(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function _j(n,e){const t={...n};return ef(n)&&ef(e)&&Object.keys(e).forEach(r=>{ef(e[r])&&ef(n[r])?t[r]=_j(n[r],e[r]):t[r]=e[r]}),t}var N1=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...gt(Ee(this,"addOptions",{name:this.name}))||{}}}get storage(){return{...gt(Ee(this,"addStorage",{name:this.name,options:this.options}))||{}}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>_j(this.options,n)});return e.name=this.name,e.parent=this.parent,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},Za=class Mj extends N1{constructor(){super(...arguments),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new Mj(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,s=e.state.selection.$from;if(s.pos===s.end()){const i=s.marks();if(!!!i.find(c=>(c==null?void 0:c.type.name)===t.name))return!1;const l=i.find(c=>(c==null?void 0:c.type.name)===t.name);return l&&r.removeStoredMark(l),r.insertText(" ",s.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function kJ(n){return typeof n=="number"}var _J=class{constructor(n){this.find=n.find,this.handler=n.handler}},MJ=(n,e,t)=>{if(D1(e))return[...n.matchAll(e)];const r=e(n,t);return r?r.map(s=>{const o=[s.text];return o.index=s.index,o.input=n,o.data=s.data,s.replaceWith&&(s.text.includes(s.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),o.push(s.replaceWith)),o}):[]};function AJ(n){const{editor:e,state:t,from:r,to:s,rule:o,pasteEvent:i,dropEvent:a}=n,{commands:l,chain:c,can:u}=new Fy({editor:e,state:t}),d=[];return t.doc.nodesBetween(r,s,(f,g)=>{var m,y,S,b,w;if((y=(m=f.type)==null?void 0:m.spec)!=null&&y.code||!(f.isText||f.isTextblock||f.isInline))return;const v=(w=(b=(S=f.content)==null?void 0:S.size)!=null?b:f.nodeSize)!=null?w:0,P=Math.max(r,g),T=Math.min(s,g+v);if(P>=T)return;const I=f.isText?f.text||"":f.textBetween(P-g,T-g,void 0,"");MJ(I,o.find,i).forEach(A=>{if(A.index===void 0)return;const R=P+A.index+1,D=R+A[0].length,j={from:t.tr.mapping.map(R),to:t.tr.mapping.map(D)},_=o.handler({state:t,range:j,match:A,commands:l,chain:c,can:u,pasteEvent:i,dropEvent:a});d.push(_)})}),d.every(f=>f!==null)}var tf=null,DJ=n=>{var e;const t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)==null||e.setData("text/html",n),t};function OJ(n){const{editor:e,rules:t}=n;let r=null,s=!1,o=!1,i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,a;try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}const l=({state:u,from:d,to:h,rule:f,pasteEvt:g})=>{const m=u.tr,y=Ny({state:u,transaction:m});if(!(!AJ({editor:e,state:y,from:Math.max(d-1,0),to:h.b-1,rule:f,pasteEvent:g,dropEvent:a})||!m.steps.length)){try{a=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{a=null}return i=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,m}};return t.map(u=>new Ht({view(d){const h=g=>{var m;r=(m=d.dom.parentElement)!=null&&m.contains(g.target)?d.dom.parentElement:null,r&&(tf=e)},f=()=>{tf&&(tf=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(d,h)=>{if(o=r===d.dom.parentElement,a=h,!o){const f=tf;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(d,h)=>{var f;const g=(f=h.clipboardData)==null?void 0:f.getData("text/html");return i=h,s=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(d,h,f)=>{const g=d[0],m=g.getMeta("uiEvent")==="paste"&&!s,y=g.getMeta("uiEvent")==="drop"&&!o,S=g.getMeta("applyPasteRules"),b=!!S;if(!m&&!y&&!b)return;if(b){let{text:P}=S;typeof P=="string"?P=P:P=Hy(ne.from(P),f.schema);const{from:T}=S,I=T+P.length,k=DJ(P);return l({rule:u,state:f,from:T,to:{b:I},pasteEvt:k})}const w=h.doc.content.findDiffStart(f.doc.content),v=h.doc.content.findDiffEnd(f.doc.content);if(!(!kJ(w)||!v||w===v.b))return l({rule:u,state:f,from:w,to:v,pasteEvt:i})}}))}var Vy=class{constructor(n,e){this.splittableMarks=[],this.editor=e,this.baseExtensions=n,this.extensions=R1(n),this.schema=wj(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((n,e)=>{const t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Kd(e.name,this.schema)},r=Ee(e,"addCommands",t);return r?{...n,...r()}:n},{})}get plugins(){const{editor:n}=this;return $u([...this.extensions].reverse()).flatMap(r=>{const s={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:n,type:Kd(r.name,this.schema)},o=[],i=Ee(r,"addKeyboardShortcuts",s);let a={};if(r.type==="mark"&&Ee(r,"exitable",s)&&(a.ArrowRight=()=>Za.handleExit({editor:n,mark:r})),i){const h=Object.fromEntries(Object.entries(i()).map(([f,g])=>[f,()=>g({editor:n})]));a={...a,...h}}const l=Vq(a);o.push(l);const c=Ee(r,"addInputRules",s);if(bE(r,n.options.enableInputRules)&&c){const h=c();if(h&&h.length){const f=IJ({editor:n,rules:h}),g=Array.isArray(f)?f:[f];o.push(...g)}}const u=Ee(r,"addPasteRules",s);if(bE(r,n.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const f=OJ({editor:n,rules:h});o.push(...f)}}const d=Ee(r,"addProseMirrorPlugins",s);if(d){const h=d();o.push(...h)}return o})}get attributes(){return bj(this.extensions)}get nodeViews(){const{editor:n}=this,{nodeExtensions:e}=od(this.extensions);return Object.fromEntries(e.filter(t=>!!Ee(t,"addNodeView")).map(t=>{const r=this.attributes.filter(l=>l.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:pn(t.name,this.schema)},o=Ee(t,"addNodeView",s);if(!o)return[];const i=o();if(!i)return[];const a=(l,c,u,d,h)=>{const f=mh(l,r);return i({node:l,view:c,getPos:u,decorations:d,innerDecorations:h,editor:n,extension:t,HTMLAttributes:f})};return[t.name,a]}))}dispatchTransaction(n){const{editor:e}=this;return $u([...this.extensions].reverse()).reduceRight((r,s)=>{const o={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:Kd(s.name,this.schema)},i=Ee(s,"dispatchTransaction",o);return i?a=>{i.call(o,{transaction:a,next:r})}:r},n)}transformPastedHTML(n){const{editor:e}=this;return $u([...this.extensions]).reduce((r,s)=>{const o={name:s.name,options:s.options,storage:this.editor.extensionStorage[s.name],editor:e,type:Kd(s.name,this.schema)},i=Ee(s,"transformPastedHTML",o);return i?(a,l)=>{const c=r(a,l);return i.call(o,c)}:r},n||(r=>r))}get markViews(){const{editor:n}=this,{markExtensions:e}=od(this.extensions);return Object.fromEntries(e.filter(t=>!!Ee(t,"addMarkView")).map(t=>{const r=this.attributes.filter(a=>a.type===t.name),s={name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:Gi(t.name,this.schema)},o=Ee(t,"addMarkView",s);if(!o)return[];const i=(a,l,c)=>{const u=mh(a,r);return o()({mark:a,view:l,inline:c,editor:n,extension:t,HTMLAttributes:u,updateAttributes:d=>{VJ(a,n,d)}})};return[t.name,i]}))}setupExtensions(){const n=this.extensions;this.editor.extensionStorage=Object.fromEntries(n.map(e=>[e.name,e.storage])),n.forEach(e=>{var t;const r={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Kd(e.name,this.schema)};e.type==="mark"&&((t=gt(Ee(e,"keepOnSplit",r)))==null||t)&&this.splittableMarks.push(e.name);const s=Ee(e,"onBeforeCreate",r),o=Ee(e,"onCreate",r),i=Ee(e,"onUpdate",r),a=Ee(e,"onSelectionUpdate",r),l=Ee(e,"onTransaction",r),c=Ee(e,"onFocus",r),u=Ee(e,"onBlur",r),d=Ee(e,"onDestroy",r);s&&this.editor.on("beforeCreate",s),o&&this.editor.on("create",o),i&&this.editor.on("update",i),a&&this.editor.on("selectionUpdate",a),l&&this.editor.on("transaction",l),c&&this.editor.on("focus",c),u&&this.editor.on("blur",u),d&&this.editor.on("destroy",d)})}};Vy.resolve=R1;Vy.sort=$u;Vy.flatten=O1;var Aj={};A1(Aj,{ClipboardTextSerializer:()=>Oj,Commands:()=>Rj,Delete:()=>Lj,Drop:()=>jj,Editable:()=>Nj,FocusEvents:()=>Bj,Keymap:()=>zj,Paste:()=>$j,Tabindex:()=>Hj,TextDirection:()=>Uj,focusEventsPluginKey:()=>Fj});var qt=class Dj extends N1{constructor(){super(...arguments),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new Dj(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},Oj=qt.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Ht({key:new Sn("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:s}=e,{ranges:o}=s,i=Math.min(...o.map(u=>u.$from.pos)),a=Math.max(...o.map(u=>u.$to.pos)),l=L1(t);return vj(r,{from:i,to:a},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:l})}}})]}}),Rj=qt.create({name:"commands",addCommands(){return{...uj}}}),Lj=qt.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r,s;const o=()=>{var i,a,l,c;if((c=(l=(a=(i=this.editor.options.coreExtensionOptions)==null?void 0:i.delete)==null?void 0:a.filterTransaction)==null?void 0:l.call(a,n))!=null?c:n.getMeta("y-sync$"))return;const u=Sj(n.before,[n,...e]);Tj(u).forEach(f=>{u.mapping.mapResult(f.oldRange.from).deletedAfter&&u.mapping.mapResult(f.oldRange.to).deletedBefore&&u.before.nodesBetween(f.oldRange.from,f.oldRange.to,(g,m)=>{const y=m+g.nodeSize-2,S=f.oldRange.from<=m&&y<=f.oldRange.to;this.editor.emit("delete",{type:"node",node:g,from:m,to:y,newFrom:u.mapping.map(m),newTo:u.mapping.map(y),deletedRange:f.oldRange,newRange:f.newRange,partial:!S,editor:this.editor,transaction:n,combinedTransform:u})})});const h=u.mapping;u.steps.forEach((f,g)=>{var m,y;if(f instanceof ho){const S=h.slice(g).map(f.from,-1),b=h.slice(g).map(f.to),w=h.invert().map(S,-1),v=h.invert().map(b),P=(m=u.doc.nodeAt(S-1))==null?void 0:m.marks.some(I=>I.eq(f.mark)),T=(y=u.doc.nodeAt(b))==null?void 0:y.marks.some(I=>I.eq(f.mark));this.editor.emit("delete",{type:"mark",mark:f.mark,from:f.from,to:f.to,deletedRange:{from:w,to:v},newRange:{from:S,to:b},partial:!!(T||P),editor:this.editor,transaction:n,combinedTransform:u})}})};(s=(r=(t=this.editor.options.coreExtensionOptions)==null?void 0:t.delete)==null?void 0:r.async)==null||s?setTimeout(o,0):o()}}),jj=qt.create({name:"drop",addProseMirrorPlugins(){return[new Ht({key:new Sn("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),Nj=qt.create({name:"editable",addProseMirrorPlugins(){return[new Ht({key:new Sn("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Fj=new Sn("focusEvents"),Bj=qt.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new Ht({key:Fj,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),zj=qt.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:i})=>[()=>i.undoInputRule(),()=>i.command(({tr:a})=>{const{selection:l,doc:c}=a,{empty:u,$anchor:d}=l,{pos:h,parent:f}=d,g=d.parent.isTextblock&&h>0?a.doc.resolve(h-1):d,m=g.parent.type.spec.isolating,y=d.pos-d.parentOffset,S=m&&g.parent.childCount===1?y===d.pos:Je.atStart(c).from===h;return!u||!f.type.isTextblock||f.textContent.length||!S||S&&d.parent.type.name==="paragraph"?!1:i.clearNodes()}),()=>i.deleteSelection(),()=>i.joinBackward(),()=>i.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:i})=>[()=>i.deleteSelection(),()=>i.deleteCurrentNode(),()=>i.joinForward(),()=>i.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:i})=>[()=>i.newlineInCode(),()=>i.createParagraphNear(),()=>i.liftEmptyBlock(),()=>i.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},s={...r},o={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return im()||mj()?o:s},addProseMirrorPlugins(){return[new Ht({key:new Sn("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(m=>m.getMeta("composition")))return;const r=n.some(m=>m.docChanged)&&!e.doc.eq(t.doc),s=n.some(m=>m.getMeta("preventClearDocument"));if(!r||s)return;const{empty:o,from:i,to:a}=e.selection,l=Je.atStart(e.doc).from,c=Je.atEnd(e.doc).to;if(o||!(i===l&&a===c)||!Ky(t.doc))return;const h=t.tr,f=Ny({state:t,transaction:h}),{commands:g}=new Fy({editor:this.editor,state:f});if(g.clearNodes(),!!h.steps.length)return h}})]}}),$j=qt.create({name:"paste",addProseMirrorPlugins(){return[new Ht({key:new Sn("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),Hj=qt.create({name:"tabindex",addProseMirrorPlugins(){return[new Ht({key:new Sn("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}}),Uj=qt.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=od(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new Ht({key:new Sn("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}}),RJ=class gu{constructor(e,t,r=!1,s=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=s}get name(){return this.node.type.name}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!=null?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new gu(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new gu(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new gu(e,this.editor)}get children(){const e=[];return this.node.content.forEach((t,r)=>{const s=t.isBlock&&!t.isTextblock,o=t.isAtom&&!t.isText,i=t.isInline,a=this.pos+r+(o?0:1);if(a<0||a>this.resolvedPos.doc.nodeSize-2)return;const l=this.resolvedPos.doc.resolve(a);if(!s&&!i&&l.depth<=this.depth)return;const c=new gu(l,this.editor,s,s||i?t:null);s&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,s=this.parent;for(;s&&!r;){if(s.node.type.name===e)if(Object.keys(t).length>0){const o=s.node.attrs,i=Object.keys(t);for(let a=0;a<i.length;a+=1){const l=i[a];if(o[l]!==t[l])break}}else r=s;s=s.parent}return r}querySelector(e,t={}){return this.querySelectorAll(e,t,!0)[0]||null}querySelectorAll(e,t={},r=!1){let s=[];if(!this.children||this.children.length===0)return s;const o=Object.keys(t);return this.children.forEach(i=>{r&&s.length>0||(i.node.type.name===e&&o.every(l=>t[l]===i.node.attrs[l])&&s.push(i),!(r&&s.length>0)&&(s=s.concat(i.querySelectorAll(e,t,r))))}),s}setAttribute(e){const{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}},LJ=`.ProseMirror {
209
+ position: relative;
210
+ }
211
+
212
+ .ProseMirror {
213
+ word-wrap: break-word;
214
+ white-space: pre-wrap;
215
+ white-space: break-spaces;
216
+ -webkit-font-variant-ligatures: none;
217
+ font-variant-ligatures: none;
218
+ font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
219
+ }
220
+
221
+ .ProseMirror [contenteditable="false"] {
222
+ white-space: normal;
223
+ }
224
+
225
+ .ProseMirror [contenteditable="false"] [contenteditable="true"] {
226
+ white-space: pre-wrap;
227
+ }
228
+
229
+ .ProseMirror pre {
230
+ white-space: pre-wrap;
231
+ }
232
+
233
+ img.ProseMirror-separator {
234
+ display: inline !important;
235
+ border: none !important;
236
+ margin: 0 !important;
237
+ width: 0 !important;
238
+ height: 0 !important;
239
+ }
240
+
241
+ .ProseMirror-gapcursor {
242
+ display: none;
243
+ pointer-events: none;
244
+ position: absolute;
245
+ margin: 0;
246
+ }
247
+
248
+ .ProseMirror-gapcursor:after {
249
+ content: "";
250
+ display: block;
251
+ position: absolute;
252
+ top: -2px;
253
+ width: 20px;
254
+ border-top: 1px solid black;
255
+ animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
256
+ }
257
+
258
+ @keyframes ProseMirror-cursor-blink {
259
+ to {
260
+ visibility: hidden;
261
+ }
262
+ }
263
+
264
+ .ProseMirror-hideselection *::selection {
265
+ background: transparent;
266
+ }
267
+
268
+ .ProseMirror-hideselection *::-moz-selection {
269
+ background: transparent;
270
+ }
271
+
272
+ .ProseMirror-hideselection * {
273
+ caret-color: transparent;
274
+ }
275
+
276
+ .ProseMirror-focused .ProseMirror-gapcursor {
277
+ display: block;
278
+ }`;function jJ(n,e,t){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const s=document.createElement("style");return e&&s.setAttribute("nonce",e),s.setAttribute("data-tiptap-style",""),s.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(s),s}var NJ=class extends PJ{constructor(n={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:r})=>{throw r},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:tJ,createMappablePosition:nJ},this.setOptions(n),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:r,slice:s,moved:o})=>this.options.onDrop(r,s,o)),this.on("paste",({event:r,slice:s})=>this.options.onPaste(r,s)),this.on("delete",this.options.onDelete);const e=this.createDoc(),t=fj(e,this.options.autofocus);this.editorState=Mc.create({doc:e,schema:this.schema,selection:t||void 0}),this.options.element&&this.mount(this.options.element)}mount(n){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(n),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){const n=this.editorView.dom;n!=null&&n.editor&&delete n.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(n){console.warn("Failed to remove CSS element:",n)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=jJ(LJ,this.options.injectNonce))}setOptions(n={}){this.options={...this.options,...n},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(n,e=!0){this.setOptions({editable:n}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:n=>{this.editorState=n},dispatch:n=>{this.dispatchTransaction(n)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(n,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in n)return Reflect.get(n,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(n,e){const t=xj(e)?e(n,[...this.state.plugins]):[...this.state.plugins,n],r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}unregisterPlugin(n){if(this.isDestroyed)return;const e=this.state.plugins;let t=e;if([].concat(n).forEach(s=>{const o=typeof s=="string"?`${s}$`:s.key;t=t.filter(i=>!i.key.startsWith(o))}),e.length===t.length)return;const r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}createExtensionManager(){var n,e;const r=[...this.options.enableCoreExtensions?[Nj,Oj.configure({blockSeparator:(e=(n=this.options.coreExtensionOptions)==null?void 0:n.clipboardTextSerializer)==null?void 0:e.blockSeparator}),Rj,Bj,zj,Hj,jj,$j,Lj,Uj.configure({direction:this.options.textDirection})].filter(s=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[s.name]!==!1:!0):[],...this.options.extensions].filter(s=>["extension","node","mark"].includes(s==null?void 0:s.type));this.extensionManager=new Vy(r,this)}createCommandManager(){this.commandManager=new Fy({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let n;try{n=l0(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(t=>t.name!=="collaboration"),this.createExtensionManager()}}),n=l0(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}return n}createView(n){const{editorProps:e,enableExtensionDispatchTransaction:t}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),s=t?this.extensionManager.dispatchTransaction(r):r,o=e.transformPastedHTML,i=this.extensionManager.transformPastedHTML(o);this.editorView=new cj(n,{...e,attributes:{role:"textbox",...e==null?void 0:e.attributes},dispatchTransaction:s,transformPastedHTML:i,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.prependClass(),this.injectCSS();const l=this.view.dom;l.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(n){this.isCapturingTransaction=!0,n(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(n){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=n;return}n.steps.forEach(c=>{var u;return(u=this.capturedTransaction)==null?void 0:u.step(c)});return}const{state:e,transactions:t}=this.state.applyTransaction(n),r=!this.state.selection.eq(e.selection),s=t.includes(n),o=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:n,nextState:e}),!s)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:n,appendedTransactions:t.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:n});const i=t.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),a=i==null?void 0:i.getMeta("focus"),l=i==null?void 0:i.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:i}),l&&this.emit("blur",{editor:this,event:l.event,transaction:i}),!(n.getMeta("preventUpdate")||!t.some(c=>c.docChanged)||o.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:n,appendedTransactions:t.slice(1)})}getAttributes(n){return Pj(this.state,n)}isActive(n,e){const t=typeof n=="string"?n:null,r=typeof n=="string"?e:n;return JZ(this.state,t,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Hy(this.state.doc.content,this.schema)}getText(n){const{blockSeparator:e=`
279
+
280
+ `,textSerializers:t={}}=n||{};return Cj(this.state.doc,{blockSeparator:e,textSerializers:{...L1(this.schema),...t}})}get isEmpty(){return Ky(this.state.doc)}destroy(){this.emit("destroy"),this.unmount(),this.removeAllListeners()}get isDestroyed(){var n,e;return(e=(n=this.editorView)==null?void 0:n.isDestroyed)!=null?e:!0}$node(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelector(n,e))||null}$nodes(n,e){var t;return((t=this.$doc)==null?void 0:t.querySelectorAll(n,e))||null}$pos(n){const e=this.state.doc.resolve(n);return new RJ(e,this)}get $doc(){return this.$pos(0)}};function Ll(n){return new Wy({find:n.find,handler:({state:e,range:t,match:r})=>{const s=gt(n.getAttributes,void 0,r);if(s===!1||s===null)return null;const{tr:o}=e,i=r[r.length-1],a=r[0];if(i){const l=a.search(/\S/),c=t.from+a.indexOf(i),u=c+i.length;if(j1(t.from,t.to,e.doc).filter(f=>f.mark.type.excluded.find(m=>m===n.type&&m!==f.mark.type)).filter(f=>f.to>c).length)return null;u<t.to&&o.delete(u,t.to),c>t.from&&o.delete(t.from+l,c);const h=t.from+l+i.length;o.addMark(t.from+l,h,n.type.create(s||{})),o.removeStoredMark(n.type)}},undoable:n.undoable})}function FJ(n){return new Wy({find:n.find,handler:({state:e,range:t,match:r})=>{const s=gt(n.getAttributes,void 0,r)||{},{tr:o}=e,i=t.from;let a=t.to;const l=n.type.create(s);if(r[1]){const c=r[0].lastIndexOf(r[1]);let u=i+c;u>a?u=a:a=u+r[1].length;const d=r[0][r[0].length-1];o.insertText(d,i+r[0].length-1),o.replaceWith(u,a,l)}else if(r[0]){const c=n.type.isInline?i:i-1;o.insert(c,n.type.create(s)).delete(o.mapping.map(i),o.mapping.map(a))}o.scrollIntoView()},undoable:n.undoable})}function d0(n){return new Wy({find:n.find,handler:({state:e,range:t,match:r})=>{const s=e.doc.resolve(t.from),o=gt(n.getAttributes,void 0,r)||{};if(!s.node(-1).canReplaceWith(s.index(-1),s.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,o)},undoable:n.undoable})}function id(n){return new Wy({find:n.find,handler:({state:e,range:t,match:r,chain:s})=>{const o=gt(n.getAttributes,void 0,r)||{},i=e.tr.delete(t.from,t.to),l=i.doc.resolve(t.from).blockRange(),c=l&&g1(l,n.type,o);if(!c)return null;if(i.wrap(l,c),n.keepMarks&&n.editor){const{selection:d,storedMarks:h}=e,{splittableMarks:f}=n.editor.extensionManager,g=h||d.$to.parentOffset&&d.$from.marks();if(g){const m=g.filter(y=>f.includes(y.type.name));i.ensureMarks(m)}}if(n.keepAttributes){const d=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";s().updateAttributes(d,o).run()}const u=i.doc.resolve(t.from-1).nodeBefore;u&&u.type===n.type&&Xa(i.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,u))&&i.join(t.from-1)},undoable:n.undoable})}function BJ(n,e){const{selection:t}=n,{$from:r}=t;if(t instanceof Me){const o=r.index();return r.parent.canReplaceWith(o,o+1,e)}let s=r.depth;for(;s>=0;){const o=r.index(s);if(r.node(s).contentMatchAt(o).matchType(e))return!0;s-=1}return!1}var zJ={};A1(zJ,{createAtomBlockMarkdownSpec:()=>$J,createBlockMarkdownSpec:()=>HJ,createInlineMarkdownSpec:()=>WJ,parseAttributes:()=>F1,parseIndentedBlocks:()=>u0,renderNestedMarkdownContent:()=>z1,serializeAttributes:()=>B1});function F1(n){if(!(n!=null&&n.trim()))return{};const e={},t=[],r=n.replace(/["']([^"']*)["']/g,c=>(t.push(c),`__QUOTED_${t.length-1}__`)),s=r.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);if(s){const c=s.map(u=>u.trim().slice(1));e.class=c.join(" ")}const o=r.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);o&&(e.id=o[1]);const i=/([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;Array.from(r.matchAll(i)).forEach(([,c,u])=>{var d;const h=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),f=t[h];f&&(e[c]=f.slice(1,-1))});const l=r.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g,"").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g,"").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g,"").trim();return l&&l.split(/\s+/).filter(Boolean).forEach(u=>{u.match(/^[a-zA-Z][\w-]*$/)&&(e[u]=!0)}),e}function B1(n){if(!n||Object.keys(n).length===0)return"";const e=[];return n.class&&String(n.class).split(/\s+/).filter(Boolean).forEach(r=>e.push(`.${r}`)),n.id&&e.push(`#${n.id}`),Object.entries(n).forEach(([t,r])=>{t==="class"||t==="id"||(r===!0?e.push(t):r!==!1&&r!=null&&e.push(`${t}="${String(r)}"`))}),e.join(" ")}function $J(n){const{nodeName:e,name:t,parseAttributes:r=F1,serializeAttributes:s=B1,defaultAttributes:o={},requiredAttributes:i=[],allowedAttributes:a}=n,l=t||e,c=u=>{if(!a)return u;const d={};return a.forEach(h=>{h in u&&(d[h]=u[h])}),d};return{parseMarkdown:(u,d)=>{const h={...o,...u.attributes};return d.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;const h=new RegExp(`^:::${l}(?:\\s|$)`,"m"),f=(d=u.match(h))==null?void 0:d.index;return f!==void 0?f:-1},tokenize(u,d,h){const f=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),g=u.match(f);if(!g)return;const m=g[1]||"",y=r(m);if(!i.find(b=>!(b in y)))return{type:e,raw:g[0],attributes:y}}},renderMarkdown:u=>{const d=c(u.attrs||{}),h=s(d),f=h?` {${h}}`:"";return`:::${l}${f} :::`}}}function HJ(n){const{nodeName:e,name:t,getContent:r,parseAttributes:s=F1,serializeAttributes:o=B1,defaultAttributes:i={},content:a="block",allowedAttributes:l}=n,c=t||e,u=d=>{if(!l)return d;const h={};return l.forEach(f=>{f in d&&(h[f]=d[f])}),h};return{parseMarkdown:(d,h)=>{let f;if(r){const m=r(d);f=typeof m=="string"?[{type:"text",text:m}]:m}else a==="block"?f=h.parseChildren(d.tokens||[]):f=h.parseInline(d.tokens||[]);const g={...i,...d.attributes};return h.createNode(e,g,f)},markdownTokenizer:{name:e,level:"block",start(d){var h;const f=new RegExp(`^:::${c}`,"m"),g=(h=d.match(f))==null?void 0:h.index;return g!==void 0?g:-1},tokenize(d,h,f){var g;const m=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),y=d.match(m);if(!y)return;const[S,b=""]=y,w=s(b);let v=1;const P=S.length;let T="";const I=/^:::([\w-]*)(\s.*)?/gm,k=d.slice(P);for(I.lastIndex=0;;){const A=I.exec(k);if(A===null)break;const R=A.index,D=A[1];if(!((g=A[2])!=null&&g.endsWith(":::"))){if(D)v+=1;else if(v-=1,v===0){const j=k.slice(0,R);T=j.trim();const _=d.slice(0,P+R+A[0].length);let M=[];if(T)if(a==="block")for(M=f.blockTokens(j),M.forEach(O=>{O.text&&(!O.tokens||O.tokens.length===0)&&(O.tokens=f.inlineTokens(O.text))});M.length>0;){const O=M[M.length-1];if(O.type==="paragraph"&&(!O.text||O.text.trim()===""))M.pop();else break}else M=f.inlineTokens(T);return{type:e,raw:_,attributes:w,content:T,tokens:M}}}}}},renderMarkdown:(d,h)=>{const f=u(d.attrs||{}),g=o(f),m=g?` {${g}}`:"",y=h.renderChildren(d.content||[],`
281
+
282
+ `);return`:::${c}${m}
283
+
284
+ ${y}
285
+
286
+ :::`}}}function UJ(n){if(!n.trim())return{};const e={},t=/(\w+)=(?:"([^"]*)"|'([^']*)')/g;let r=t.exec(n);for(;r!==null;){const[,s,o,i]=r;e[s]=o||i,r=t.exec(n)}return e}function KJ(n){return Object.entries(n).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(" ")}function WJ(n){const{nodeName:e,name:t,getContent:r,parseAttributes:s=UJ,serializeAttributes:o=KJ,defaultAttributes:i={},selfClosing:a=!1,allowedAttributes:l}=n,c=t||e,u=h=>{if(!l)return h;const f={};return l.forEach(g=>{const m=typeof g=="string"?g:g.name,y=typeof g=="string"?void 0:g.skipIfDefault;if(m in h){const S=h[m];if(y!==void 0&&S===y)return;f[m]=S}}),f},d=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,f)=>{const g={...i,...h.attributes};if(a)return f.createNode(e,g);const m=r?r(h):h.content||"";return m?f.createNode(e,g,[f.createTextNode(m)]):f.createNode(e,g,[])},markdownTokenizer:{name:e,level:"inline",start(h){const f=a?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),g=h.match(f),m=g==null?void 0:g.index;return m!==void 0?m:-1},tokenize(h,f,g){const m=a?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),y=h.match(m);if(!y)return;let S="",b="";if(a){const[,v]=y;b=v}else{const[,v,P]=y;b=v,S=P||""}const w=s(b.trim());return{type:e,raw:y[0],content:S.trim(),attributes:w}}},renderMarkdown:h=>{let f="";r?f=r(h):h.content&&h.content.length>0&&(f=h.content.filter(S=>S.type==="text").map(S=>S.text).join(""));const g=u(h.attrs||{}),m=o(g),y=m?` ${m}`:"";return a?`[${c}${y}]`:`[${c}${y}]${f}[/${c}]`}}}function u0(n,e,t){var r,s,o,i;const a=n.split(`
287
+ `),l=[];let c="",u=0;const d=e.baseIndentSize||2;for(;u<a.length;){const h=a[u],f=h.match(e.itemPattern);if(!f){if(l.length>0)break;if(h.trim()===""){u+=1,c=`${c}${h}
288
+ `;continue}else return}const g=e.extractItemData(f),{indentLevel:m,mainContent:y}=g;c=`${c}${h}
289
+ `;const S=[y];for(u+=1;u<a.length;){const P=a[u];if(P.trim()===""){const I=a.slice(u+1).findIndex(R=>R.trim()!=="");if(I===-1)break;if((((s=(r=a[u+1+I].match(/^(\s*)/))==null?void 0:r[1])==null?void 0:s.length)||0)>m){S.push(P),c=`${c}${P}
290
+ `,u+=1;continue}else break}if((((i=(o=P.match(/^(\s*)/))==null?void 0:o[1])==null?void 0:i.length)||0)>m)S.push(P),c=`${c}${P}
291
+ `,u+=1;else break}let b;const w=S.slice(1);if(w.length>0){const P=w.map(T=>T.slice(m+d)).join(`
292
+ `);P.trim()&&(e.customNestedParser?b=e.customNestedParser(P):b=t.blockTokens(P))}const v=e.createToken(g,b);l.push(v)}if(l.length!==0)return{items:l,raw:c}}function z1(n,e,t,r){if(!n||!Array.isArray(n.content))return"";const s=typeof t=="function"?t(r):t,[o,...i]=n.content,a=e.renderChildren([o]),l=[`${s}${a}`];return i&&i.length>0&&i.forEach(c=>{const u=e.renderChildren([c]);if(u){const d=u.split(`
293
+ `).map(h=>h?e.indent(h):"").join(`
294
+ `);l.push(d)}}),l.join(`
295
+ `)}function VJ(n,e,t={}){const{state:r}=e,{doc:s,tr:o}=r,i=n;s.descendants((a,l)=>{const c=o.mapping.map(l),u=o.mapping.map(l)+a.nodeSize;let d=null;if(a.marks.forEach(f=>{if(f!==i)return!1;d=f}),!d)return;let h=!1;if(Object.keys(t).forEach(f=>{t[f]!==d.attrs[f]&&(h=!0)}),h){const f=n.type.create({...n.attrs,...t});o.removeMark(c,u,n.type),o.addMark(c,u,f)}}),o.docChanged&&e.view.dispatch(o)}var Cs=class Kj extends N1{constructor(){super(...arguments),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new Kj(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Na(n){return new _J({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:s})=>{const o=gt(n.getAttributes,void 0,r,s);if(o===!1||o===null)return null;const{tr:i}=e,a=r[r.length-1],l=r[0];let c=t.to;if(a){const u=l.search(/\S/),d=t.from+l.indexOf(a),h=d+a.length;if(j1(t.from,t.to,e.doc).filter(g=>g.mark.type.excluded.find(y=>y===n.type&&y!==g.mark.type)).filter(g=>g.to>d).length)return null;h<t.to&&i.delete(h,t.to),d>t.from&&i.delete(t.from+u,d),c=t.from+u+a.length,i.addMark(t.from+u,c,n.type.create(o||{})),i.removeStoredMark(n.type)}}})}const GJ=new Vn;function YJ(n){return GJ.get(n,()=>Uy(n.extensions??[]))}function Gy(n,e,t){const{tipTapConfig:r,addFontsFromNode:s}=n.getTextOptions();be(r,"textOptions.tipTapConfig must be set to use rich text"),be(s,"textOptions.addFontsFromNode must be set to use rich text");const o=YJ(r),i=mo.fromJSON(o,e),a=new Set;function l(u){a.add(u)}function c(u,d){d=s(u,d,l);for(const h of u.children)c(h,d)}return c(i,t),Array.from(a)}async function XJ({shouldReload:n=!0}={}){Q4();for(const e of Wg.connectedInstances)await e.close();await Promise.all(d1().map(e=>lR(e))),J4(),n&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=XJ);function $1(n,e="_blank",t){return Bh.openWindow(n,e,t)}Wi("@tldraw/editor","4.4.0","esm");const qJ=n=>n*.65+OU(n*ht/2)*.35,ZJ=n=>({size:n,thinning:.5,streamline:xo(n,[9,16],[.64,.74],!0),smoothing:.62,easing:ar.easeOutSine,simulatePressure:!0}),JJ=n=>({size:1+n*1.2,thinning:.62,streamline:.62,smoothing:.62,simulatePressure:!1,easing:qJ}),CE=n=>({size:n,thinning:0,streamline:xo(n,[9,16],[.64,.74],!0),smoothing:.62,simulatePressure:!1,easing:ar.linear}),QJ=n=>({size:n,thinning:0,streamline:.62,smoothing:.62,simulatePressure:!1,easing:ar.linear});function H1({strokeWidth:n,showAsComplete:e}){return{size:1+n,thinning:0,streamline:.5,smoothing:.5,simulatePressure:!1,easing:ar.easeOutSine,last:e}}function Wf(n,e,t,r){const s=n.isComplete||t;return r?n.isPen?{...QJ(e),last:s}:{...CE(e),last:s}:n.dash==="draw"?n.isPen?{...JJ(e),last:s}:{...ZJ(e),last:s}:{...CE(e),last:s}}function eQ(n,e,t,r=[]){const s=ot.decodePoints(n.path);if(e!==1||t!==1)for(const o of s)o.x*=e,o.y*=t;if(n.type==="free"||s.length<2)r.push(...s.map(C.From));else{const o=Math.max(4,Math.floor(C.Dist(s[0],s[1])/16));r.push(...C.PointsBetween(s[0],s[1],o))}return r}function Ma(n,e=1,t=1){const r=[];for(const s of n)eQ(s,e,t,r);return r}function tQ(n,e,t){return{draw:"none",solid:"none",dotted:`${t} ${e*2}`,dashed:`${e*2} ${e*2}`}[n.props.dash]}class ct{constructor(){E(this,"commands",[]);E(this,"lastMoveTo",null)}static lineThroughPoints(e,t){const r=new ct;r.moveTo(e[0].x,e[0].y,{...t,offset:(t==null?void 0:t.endOffsets)??(t==null?void 0:t.offset)});for(let s=1;s<e.length;s++){const o=s===e.length-1;r.lineTo(e[s].x,e[s].y,o?{offset:t==null?void 0:t.endOffsets}:void 0)}return r}static cubicSplineThroughPoints(e,t){const r=new ct,s=e.length,o=s-2,i=1.25;r.moveTo(e[0].x,e[0].y,{...t,offset:(t==null?void 0:t.endOffsets)??(t==null?void 0:t.offset)});for(let a=0;a<s-1;a++){const l=a===0?e[0]:e[a-1],c=e[a],u=e[a+1],d=a===o?u:e[a+2];let h,f,g,m;a===0?(h=l.x,f=l.y):(h=c.x+(u.x-l.x)/6*i,f=c.y+(u.y-l.y)/6*i);let y;a===o?(g=u.x,m=u.y,y={offset:t==null?void 0:t.endOffsets}):(g=u.x-(d.x-c.x)/6*i,m=u.y-(d.y-c.y)/6*i),r.cubicBezierTo(u.x,u.y,h,f,g,m,y)}return r}assertHasMoveTo(){return be(this.lastMoveTo,"Start an SVGPathBuilder with `.moveTo()`"),this.lastMoveTo}moveTo(e,t,r){return this.lastMoveTo={type:"move",x:e,y:t,closeIdx:null,isClose:!1,opts:r},this.commands.push(this.lastMoveTo),this}lineTo(e,t,r){return this.assertHasMoveTo(),this.commands.push({type:"line",x:e,y:t,isClose:!1,opts:r}),this}circularArcTo(e,t,r,s,o,i){return this.arcTo(e,e,t,r,0,s,o,i)}arcTo(e,t,r,s,o,i,a,l){this.assertHasMoveTo();const c=this.commands[this.commands.length-1].x,u=this.commands[this.commands.length-1].y;if(c===i&&u===a)return this;if(e===0||t===0)return this.lineTo(i,a,l);const d=o,h=Math.sin(d),f=Math.cos(d);let g=Math.abs(e),m=Math.abs(t);const y=(c-i)/2,S=(u-a)/2,b=f*y+h*S,w=-h*y+f*S,v=b*b/(g*g)+w*w/(m*m);if(v>1){const te=Math.sqrt(v);g*=te,m*=te}const P=r!==s?1:-1,T=g*g*m*m-g*g*w*w-m*m*b*b,I=g*g*w*w+m*m*b*b;let k=T/I;k=k<0?0:k;const A=P*Math.sqrt(k),R=A*(g*w/m),D=A*(-(m*b)/g),j=f*R-h*D+(c+i)/2,_=h*R+f*D+(u+a)/2,M=(b-R)/g,O=(w-D)/m,N=(-b-R)/g,B=(-w-D)/m,H=Math.atan2(O,M);let z=Math.atan2(B,N);!s&&z>H?z-=2*Math.PI:s&&z<H&&(z+=2*Math.PI);const X=z-H,G=Math.max(g,m)*Math.abs(X),ae=Math.min(4,Math.ceil(Math.abs(X)/(Math.PI/2))),Ce=Math.ceil(_y(G)/ae),fe=X/ae,oe=te=>({x:j+g*Math.cos(te)*f-m*Math.sin(te)*h,y:_+g*Math.cos(te)*h+m*Math.sin(te)*f}),Te=te=>({x:-g*Math.sin(te)*f-m*Math.cos(te)*h,y:-g*Math.sin(te)*h+m*Math.cos(te)*f});for(let te=0;te<ae;te++){const re=H+te*fe,ge=H+(te+1)*fe,de=ge-re,Ne=oe(re),De=oe(ge),rt=Te(re),lt=Te(ge),pt=4/3*Math.tan(de/4),fn=Ne.x+pt*rt.x,Yn=Ne.y+pt*rt.y,Is=De.x-pt*lt.x,xn=De.y-pt*lt.y,Sr=te===0?l:{...l,mergeWithPrevious:!0};this.cubicBezierToWithResolution(De.x,De.y,fn,Yn,Is,xn,Sr,Ce)}return this}cubicBezierTo(e,t,r,s,o,i,a){return this.cubicBezierToWithResolution(e,t,r,s,o,i,a)}cubicBezierToWithResolution(e,t,r,s,o,i,a,l){return this.assertHasMoveTo(),this.commands.push({type:"cubic",x:e,y:t,cp1:{x:r,y:s},cp2:{x:o,y:i},isClose:!1,opts:a,resolution:l}),this}close(){const e=this.assertHasMoveTo(),t=this.commands[this.commands.length-1];return tn(e.x,t.x)&&tn(e.y,t.y)?t.isClose=!0:this.commands.push({type:"line",x:e.x,y:e.y,isClose:!0}),e.closeIdx=this.commands.length-1,this.lastMoveTo=null,this}toD(e={}){var u,d,h;const{startIdx:t=0,endIdx:r=this.commands.length,onlyFilled:s=!1}=e,o=[];let i=!1,a=!1,l=!1;const c=f=>{if(a||f===0)return;a=!0;const g=this.commands[f-1];o.push("M",$(g.x),$(g.y))};for(let f=t;f<r;f++){const g=this.commands[f];switch(g.type){case"move":{const m=((u=g.opts)==null?void 0:u.geometry)===!1?!1:((h=(d=g.opts)==null?void 0:d.geometry)==null?void 0:h.isFilled)??!1;s&&!m?i=!0:(i=!1,a=!0,l=!0,o.push("M",$(g.x),$(g.y)));break}case"line":if(i)break;c(f),g.isClose&&l?o.push("Z"):o.push("L",$(g.x),$(g.y));break;case"cubic":if(i)break;c(f),o.push("C",$(g.cp1.x),$(g.cp1.y),$(g.cp2.x),$(g.cp2.y),$(g.x),$(g.y));break;default:it(g,"type")}}return o.join(" ")}toSvg(e){if(e.forceSolid)return this.toSolidSvg(e);switch(e.style){case"solid":return this.toSolidSvg(e);case"dashed":case"dotted":return this.toDashedSvg(e);case"draw":return this.toDrawSvg(e);default:it(e,"style")}}toPath2D(e){return e.forceSolid||e.style==="solid"?new Path2D(this.toD({onlyFilled:e.onlyFilled})):e.style==="draw"?new Path2D(this.toDrawD(e)):new Path2D(this.toD({onlyFilled:e.onlyFilled}))}toGeometry(){var r,s,o,i,a,l,c,u;const e=[];let t=null;for(let d=0;d<this.commands.length;d++){const h=this.commands[d];h.type==="move"&&(t&&((r=t.opts)==null?void 0:r.geometry)!==!1&&e.push(new h0(this,t.startIdx,d,{...(s=t.opts)==null?void 0:s.geometry,isFilled:((i=(o=t.opts)==null?void 0:o.geometry)==null?void 0:i.isFilled)??!1,isClosed:t.moveCommand.closeIdx!==null})),t={startIdx:d,moveCommand:h,opts:h.opts,isClosed:!1}),h.isClose&&(be(t,"No current move command"),t.isClosed=!0)}return t&&((a=t.opts)==null?void 0:a.geometry)!==!1&&e.push(new h0(this,t.startIdx,this.commands.length,{...(l=t.opts)==null?void 0:l.geometry,isFilled:((u=(c=t.opts)==null?void 0:c.geometry)==null?void 0:u.isFilled)??!1,isClosed:t.moveCommand.closeIdx!==null})),be(e.length>0),e.length===1?e[0]:new es({children:e})}toSolidSvg(e){const{strokeWidth:t,props:r}=e;return p.jsx("path",{strokeWidth:t,d:this.toD({onlyFilled:e.onlyFilled}),...r})}toDashedSvg(e){var m,y,S,b,w;const{style:t,strokeWidth:r,snap:s,lengthRatio:o,props:{markerStart:i,markerEnd:a,...l}={}}=e,c=[];let u=!1,d=!1,h,f=null;const g=()=>{if(!f)return;const{startIdx:v,endIdx:P,isFirst:T,isLast:I,length:k,lineOpts:A,pathIsClosed:R}=f;if(f=null,v===P&&this.commands[v].type==="move")return;const D=(A==null?void 0:A.dashStart)??e.start,j=(A==null?void 0:A.dashEnd)??e.end,{strokeDasharray:_,strokeDashoffset:M}=HA(k,r,{style:t,snap:s,lengthRatio:o,start:T?D??(R?"outset":"none"):"outset",end:I?j??(R?"outset":"none"):"outset"}),O=this.toD({startIdx:v,endIdx:P+1});c.push(p.jsx("path",{d:O,strokeDasharray:_,strokeDashoffset:M,markerStart:T?i:void 0,markerEnd:I?a:void 0},c.length))};for(let v=0;v<this.commands.length;v++){const P=this.commands[v],T=this.commands[v-1];if(P.type==="move"){u=P.closeIdx!==null;const R=((m=P.opts)==null?void 0:m.geometry)===!1?!1:((S=(y=P.opts)==null?void 0:y.geometry)==null?void 0:S.isFilled)??!1;e.onlyFilled&&!R?d=!0:(d=!1,h=P.opts);continue}if(d)continue;const I=this.calculateSegmentLength(T,P),k=T.type==="move",A=P.isClose||v===this.commands.length-1||((b=this.commands[v+1])==null?void 0:b.type)==="move";f&&((w=P.opts)!=null&&w.mergeWithPrevious)?(f.length+=I,f.endIdx=v,f.isLast=A):(g(),f={startIdx:v,endIdx:v,isFirst:k,isLast:A,length:I,lineOpts:h,pathIsClosed:u})}return g(),p.jsx("g",{strokeWidth:r,...l,children:c})}toDrawSvg(e){return p.jsx("path",{strokeWidth:e.strokeWidth,d:this.toDrawD(e),...e.props})}toDrawD(e){var h,f,g,m,y,S,b;const{strokeWidth:t,randomSeed:r,offset:s=t/3,roundness:o=t*2,passes:i=2,onlyFilled:a=!1}=e,l=[],c=this.getCommandInfo(),u=[];let d=null;for(let w=0;w<this.commands.length;w++){const v=this.commands[w],P=((h=v.opts)==null?void 0:h.offset)??s,T=((f=v.opts)==null?void 0:f.roundness)??o;v.type==="move"&&(d=w);const I=v.isClose?Pn(d)+1:!this.commands[w+1]||this.commands[w+1].type==="move"?void 0:w+1,k=I!==void 0&&this.commands[I]&&((g=this.commands[I])==null?void 0:g.type)!=="move"?c[I]:void 0,A=PE[v.type],R=I!==void 0?PE[this.commands[I].type]:!1,D=c[w],j=D==null?void 0:D.tangentEnd,_=k==null?void 0:k.tangentStart,M=A&&R&&j&&_&&C.Len2(j)>.01&&C.Len2(_)>.01?xo(Math.abs(C.AngleBetween(j,_)),[Math.PI/2,Math.PI],[T,0],!0):0,N=Math.min((D==null?void 0:D.length)??1/0,(k==null?void 0:k.length)??1/0)-M*2,B=Fe(P,0,N/4),H=Math.min(M,((D==null?void 0:D.length)??1/0)/4),z=Math.min(M,((k==null?void 0:k.length)??1/0)/4),X={command:v,offsetAmount:B,roundnessBefore:H,roundnessAfter:z,tangentToPrev:(m=c[w])==null?void 0:m.tangentEnd,tangentToNext:k==null?void 0:k.tangentStart,moveDidClose:!1};if(u.push(X),v.isClose&&d!==null){const G=u[d];G.moveDidClose=!0,G.roundnessAfter=z}else v.type==="move"&&(d=w)}for(let w=0;w<i;w++){const v=Aa(r+w);let P={x:0,y:0},T=!1;for(const{command:I,offsetAmount:k,roundnessBefore:A,roundnessAfter:R,tangentToNext:D,tangentToPrev:j}of u){const _=I.isClose?P:{x:v()*k,y:v()*k};if(I.type==="move"){P=_;const B=((y=I.opts)==null?void 0:y.geometry)===!1?!1:((b=(S=I.opts)==null?void 0:S.geometry)==null?void 0:b.isFilled)??!1;a&&!B?T=!0:T=!1}if(T)continue;const M=C.Add(I,_),O=D&&R>0?C.Mul(D,-R).add(M):M,N=j&&A>0?C.Mul(j,A).add(M):M;if(O===M||N===M)switch(I.type){case"move":l.push("M",$(O.x),$(O.y));break;case"line":l.push("L",$(O.x),$(O.y));break;case"cubic":{const B=C.Add(I.cp1,_),H=C.Add(I.cp2,_);l.push("C",$(B.x),$(B.y),$(H.x),$(H.y),$(O.x),$(O.y));break}default:it(I,"type")}else switch(I.type){case"move":l.push("M",$(O.x),$(O.y));break;case"line":l.push("L",$(N.x),$(N.y),"Q",$(M.x),$(M.y),$(O.x),$(O.y));break;case"cubic":{const B=C.Add(I.cp1,_),H=C.Add(I.cp2,_);l.push("C",$(B.x),$(B.y),$(H.x),$(H.y),$(M.x),$(M.y));break}default:it(I,"type")}}}return l.join(" ")}calculateSegmentLength(e,t){switch(t.type){case"move":return 0;case"line":return C.Dist(e,t);case"cubic":return mu.length(e.x,e.y,t.cp1.x,t.cp1.y,t.cp2.x,t.cp2.y,t.x,t.y);default:it(t,"type")}}getCommands(){return this.commands}getCommandInfo(){const e=[];for(let t=1;t<this.commands.length;t++){const r=this.commands[t-1],s=this.commands[t];if(s._info){e[t]=s._info;continue}if(s.type==="move")continue;let o,i;switch(s.type){case"line":o=i=C.Sub(r,s).uni();break;case"cubic":{o=C.Sub(s.cp1,r).uni(),i=C.Sub(s.cp2,s).uni();break}default:it(s,"type")}s._info={tangentStart:o,tangentEnd:i,length:this.calculateSegmentLength(r,s)},e[t]=s._info}return e}}const PE={line:!0,move:!0,cubic:!1};class h0 extends Ya{constructor(t,r,s,o){super(o);E(this,"_segments",null);this.path=t,this.startIdx=r,this.endIdx=s}getSegments(){if(this._segments)return this._segments;this._segments=[];let t=this.path.commands[this.startIdx];be(t.type==="move");for(let r=this.startIdx+1;r<this.endIdx;r++){const s=this.path.commands[r];switch(be(s.type!=="move"),s.type){case"line":this._segments.push(new Qc({start:C.From(t),end:C.From(s)}));break;case"cubic":{this._segments.push(new h1({start:C.From(t),cp1:C.From(s.cp1),cp2:C.From(s.cp2),end:C.From(s),resolution:s.resolution}));break}default:it(s,"type")}t=s}return this._segments}getVertices(t){const r=this.getSegments().flatMap(s=>s.getVertices(t)).filter((s,o,i)=>{const a=i[o-1];return a?!C.Equals(a,s):!0});if(this.isClosed){const s=r[r.length-1],o=r[0];C.Equals(s,o)||r.push(o)}return r}nearestPoint(t,r){let s=null,o=1/0;for(const i of this.getSegments()){const a=i.nearestPoint(t),l=C.Dist2(t,a);l<o&&(o=l,s=a)}return be(s,"No nearest point found"),s}hitTestLineSegment(t,r,s=0,o){return super.hitTestLineSegment(t,r,s,o)}getSvgPathData(){return this.path.toD({startIdx:this.startIdx,endIdx:this.endIdx})}}/*!
296
+ * Adapted from https://github.com/adobe-webplatform/Snap.svg/tree/master
297
+ * Apache License: https://github.com/adobe-webplatform/Snap.svg/blob/master/LICENSE
298
+ * https://github.com/adobe-webplatform/Snap.svg/blob/c8e483c9694517e24b282f8f59f985629f4994ce/dist/snap.svg.js#L5786
299
+ */const mu={base3(n,e,t,r,s){const o=-3*e+9*t-9*r+3*s,i=n*o+6*e-12*t+6*r;return n*i-3*e+3*t},length(n,e,t,r,s,o,i,a,l=1){l=l>1?1:l<0?0:l;const c=l/2,u=12;let d=0;d=0;for(let h=0;h<u;h++){const f=c*mu.Tvalues[h]+c,g=mu.base3(f,n,t,s,i),m=mu.base3(f,e,r,o,a),y=g*g+m*m;d+=mu.Cvalues[h]*Math.sqrt(y)}return c*d},Tvalues:[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],Cvalues:[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472]};function Wj(){const n=Xt(),e=W("animationSpeed",()=>n==null?void 0:n.user.getAnimationSpeed(),[n]),[t,r]=x.useState(!1);return x.useEffect(()=>{if(e!==void 0){r(e===0);return}if(typeof window>"u"||!("matchMedia"in window))return;const s=window.matchMedia("(prefers-reduced-motion: reduce)"),o=()=>{r(s.matches)};return o(),s.addEventListener("change",o),()=>s.removeEventListener("change",o)},[e]),t}function Vj(n){return"richText"in n.props&&Lh.isValid(n.props.richText)}function Nr(n,e,t={}){const r=typeof e=="string"?n.getShape(e):e;if(r&&n.canEditShape(r)){if(!Vj(r))throw new Error("Shape does not have rich text");n.setEditingShape(r),n.setCurrentTool("select.editing_shape",{...t.info,target:"shape",shape:r}),t.selectAll&&n.emit("select-all-text",{shapeId:r.id})}}const p0=x.createContext(null);function nQ({children:n}){const e=md("a11y",{msg:"",priority:"assertive"}),t=x.useContext(p0),r=x.useMemo(()=>({currentMsg:e,announce(s){s&&e.set(s)}}),[e]);return t?p.jsx(p.Fragment,{children:n}):p.jsx(p0.Provider,{value:r,children:n})}function Yy(){const n=x.useContext(p0);if(!n)throw new Error("useA11y must be used within a A11yContext.Provider");return n}const Gj=x.createContext(null);function Yj({assetUrls:n,children:e}){return x.useEffect(()=>{for(const t of Object.values(n.icons)){if(!t)continue;const r=th();r.crossOrigin="anonymous",r.src=t,r.decode()}for(const t of Object.values(n.embedIcons)){if(!t)continue;const r=th();r.crossOrigin="anonymous",r.src=t,r.decode()}},[n]),p.jsx(Gj.Provider,{value:n,children:e})}function U1(){const n=x.useContext(Gj);if(!n)throw new Error("useAssetUrls must be used within an AssetUrlsProvider");return n}const f0={"action.toggle-auto-pan":"Auto (trackpad)","action.toggle-auto-zoom":"Auto (mouse)","action.toggle-auto-none":"Auto","action.toggle-mouse":"Mouse","action.toggle-trackpad":"Trackpad","action.convert-to-bookmark":"Convert to bookmark","action.convert-to-embed":"Convert to embed","action.open-embed-link":"Open link","action.align-bottom":"Align bottom","action.align-center-horizontal":"Align horizontally","action.align-center-vertical":"Align vertically","action.align-center-horizontal.short":"Align H","action.align-center-vertical.short":"Align V","action.align-left":"Align left","action.align-right":"Align right","action.align-top":"Align top","action.back-to-content":"Back to content","action.bring-forward":"Bring forward","action.bring-to-front":"Bring to front","action.copy-as-png.short":"PNG","action.copy-as-png":"Copy as PNG","action.copy-as-svg.short":"SVG","action.copy-as-svg":"Copy as SVG","action.copy":"Copy","action.cut":"Cut","action.delete":"Delete","action.unlock-all":"Unlock all","action.distribute-horizontal":"Distribute horizontally","action.distribute-vertical":"Distribute vertically","action.distribute-horizontal.short":"Distribute H","action.distribute-vertical.short":"Distribute V","action.download-original":"Download original","action.duplicate":"Duplicate","action.edit-link":"Edit link…","action.exit-pen-mode":"Exit pen mode","action.export-as-png.short":"PNG","action.export-as-png":"Export as PNG","action.export-as-svg.short":"SVG","action.export-as-svg":"Export as SVG","action.export-all-as-png.short":"PNG","action.export-all-as-png":"Export as PNG","action.export-all-as-svg.short":"SVG","action.export-all-as-svg":"Export as SVG","action.fit-frame-to-content":"Fit to content","action.flip-horizontal":"Flip horizontally","action.flip-vertical":"Flip vertically","action.flip-horizontal.short":"Flip H","action.flip-vertical.short":"Flip V","action.fork-project":"Fork this project","action.fork-project-on-tldraw":"Fork project on tldraw","action.group":"Group","action.insert-embed":"Insert embed…","action.insert-media":"Upload media…","action.leave-shared-project":"Leave shared project","action.new-project":"New project","action.new-shared-project":"New shared project","action.open-cursor-chat":"Cursor chat","action.open-kbd-shortcuts":"Keyboard shortcuts…","action.open-file":"Open file","action.pack":"Pack","action.paste":"Paste","action.paste-error-title":"Pasting failed","action.paste-error-description":"Could not paste due to missing clipboard permissions. Please enable the permissions and try again.","action.print":"Print…","action.redo":"Redo","action.remove-frame":"Remove frame","action.rename":"Rename","action.rotate-ccw":"Rotate counterclockwise","action.rotate-cw":"Rotate clockwise","action.save-copy":"Save a copy","action.select-all":"Select all","action.select-none":"Select none","action.send-backward":"Send backward","action.send-to-back":"Send to back","action.share-project":"Share this project","action.stack-horizontal":"Stack horizontally","action.stack-vertical":"Stack vertically","action.stack-horizontal.short":"Stack H","action.stack-vertical.short":"Stack V","action.stop-following":"Stop following","action.stretch-horizontal":"Stretch horizontally","action.stretch-vertical":"Stretch vertically","action.stretch-horizontal.short":"Stretch H","action.stretch-vertical.short":"Stretch V","action.toggle-auto-size":"Toggle auto size","action.toggle-dark-mode.menu":"Dark mode","action.toggle-dark-mode":"Toggle dark mode","action.toggle-paste-at-cursor.menu":"Paste at cursor","action.toggle-paste-at-cursor":"Toggle paste at cursor","action.toggle-wrap-mode.menu":"Select on wrap","action.toggle-wrap-mode":"Toggle select on wrap","action.toggle-reduce-motion.menu":"Reduce motion","action.toggle-reduce-motion":"Toggle reduce motion","action.toggle-keyboard-shortcuts.menu":"Enable keyboard shortcuts","action.toggle-keyboard-shortcuts":"Toggle keyboard shortcuts","action.enhanced-a11y-mode.menu":"Enhanced accessibility mode","action.enhanced-a11y-mode":"Toggle enhanced accessibility mode","action.toggle-edge-scrolling.menu":"Edge scrolling","action.toggle-edge-scrolling":"Toggle edge scrolling","action.toggle-invert-zoom.menu":"Invert mouse zoom","action.toggle-invert-zoom":"Toggle invert mouse zoom","action.toggle-debug-mode.menu":"Debug mode","action.toggle-debug-mode":"Toggle debug mode","action.toggle-focus-mode.menu":"Focus mode","action.toggle-focus-mode":"Toggle focus mode","action.toggle-dynamic-size-mode.menu":"Dynamic size","action.toggle-dynamic-size-mode":"Toggle dynamic size","action.toggle-grid.menu":"Show grid","action.toggle-grid":"Toggle grid","action.toggle-lock":"Toggle locked","action.flatten-to-image":"Flatten","action.toggle-snap-mode.menu":"Always snap","action.toggle-snap-mode":"Toggle always snap","action.toggle-tool-lock.menu":"Tool lock","action.toggle-tool-lock":"Toggle tool lock","action.toggle-transparent.context-menu":"Transparent","action.toggle-transparent.menu":"Transparent","action.toggle-transparent":"Toggle transparent background","action.undo":"Undo","action.ungroup":"Ungroup","action.zoom-in":"Zoom in","action.zoom-out":"Zoom out","action.zoom-to-100":"Zoom to 100%","action.zoom-to-fit":"Zoom to fit","action.zoom-to-selection":"Zoom to selection","action.zoom-quick":"Quick zoom","action.select-zoom-tool":"Zoom","assets.files.size-too-big":"File size is too big","assets.files.maximum-size":"Maximum file size is {size}","assets.files.type-not-allowed":"File type is not allowed","assets.files.upload-failed":"Upload failed","assets.files.amount-too-many":"Too many files","assets.url.failed":"Couldn’t load URL preview","theme.dark":"Dark","theme.light":"Light","theme.system":"System","color-style.white":"White","color-style.black":"Black","color-style.blue":"Blue","color-style.green":"Green","color-style.grey":"Grey","color-style.light-blue":"Light blue","color-style.light-green":"Light green","color-style.light-red":"Light red","color-style.light-violet":"Light violet","color-style.orange":"Orange","color-style.red":"Red","color-style.violet":"Violet","color-style.yellow":"Yellow","fill-style.none":"None","document.default-name":"Untitled","fill-style.semi":"Semi","fill-style.solid":"Solid","fill-style.pattern":"Pattern","fill-style.fill":"Fill","fill-style.lined-fill":"Lined fill","dash-style.dashed":"Dashed","dash-style.dotted":"Dotted","dash-style.draw":"Draw","dash-style.solid":"Solid","size-style.s":"Small","size-style.m":"Medium","size-style.l":"Large","size-style.xl":"Extra large","opacity-style.0.1":"10%","opacity-style.0.25":"25%","opacity-style.0.5":"50%","opacity-style.0.75":"75%","opacity-style.1":"100%","font-style.draw":"Draw","font-style.sans":"Sans","font-style.serif":"Serif","font-style.mono":"Mono","align-style.start":"Start","align-style.middle":"Middle","align-style.end":"End","align-style.justify":"Justify","verticalAlign-style.start":"Top","verticalAlign-style.middle":"Middle","verticalAlign-style.end":"Bottom","geo-style.arrow-down":"Arrow down","geo-style.arrow-left":"Arrow left","geo-style.arrow-right":"Arrow right","geo-style.arrow-up":"Arrow up","geo-style.cloud":"Cloud","geo-style.diamond":"Diamond","geo-style.ellipse":"Ellipse","geo-style.heart":"Heart","geo-style.hexagon":"Hexagon","geo-style.octagon":"Octagon","geo-style.oval":"Oval","geo-style.pentagon":"Pentagon","geo-style.rectangle":"Rectangle","geo-style.rhombus":"Rhombus","geo-style.rhombus-2":"Rhombus left","geo-style.star":"Star","geo-style.trapezoid":"Trapezoid","geo-style.triangle":"Triangle","geo-style.x-box":"X box","geo-style.check-box":"Check box","arrowheadStart-style.none":"None","arrowheadStart-style.arrow":"Arrow","arrowheadStart-style.bar":"Bar","arrowheadStart-style.diamond":"Diamond","arrowheadStart-style.dot":"Dot","arrowheadStart-style.inverted":"Inverted","arrowheadStart-style.pipe":"Pipe","arrowheadStart-style.square":"Square","arrowheadStart-style.triangle":"Triangle","arrowheadEnd-style.none":"None","arrowheadEnd-style.arrow":"Arrow","arrowheadEnd-style.bar":"Bar","arrowheadEnd-style.diamond":"Diamond","arrowheadEnd-style.dot":"Dot","arrowheadEnd-style.inverted":"Inverted","arrowheadEnd-style.pipe":"Pipe","arrowheadEnd-style.square":"Square","arrowheadEnd-style.triangle":"Triangle","spline-style.line":"Line","spline-style.cubic":"Cubic","arrow-kind-style.arc":"Arc","arrow-kind-style.elbow":"Elbow","tool.select":"Select","tool.hand":"Hand","tool.draw":"Draw","tool.eraser":"Eraser","tool.arrow-down":"Arrow down","tool.arrow-left":"Arrow left","tool.arrow-right":"Arrow right","tool.arrow-up":"Arrow up","tool.arrow":"Arrow","tool.cloud":"Cloud","tool.diamond":"Diamond","tool.ellipse":"Ellipse","tool.heart":"Heart","tool.hexagon":"Hexagon","tool.highlight":"Highlight","tool.line":"Line","tool.octagon":"Octagon","tool.oval":"Oval","tool.pentagon":"Pentagon","tool.rectangle":"Rectangle","tool.rhombus":"Rhombus","tool.star":"Star","tool.trapezoid":"Trapezoid","tool.triangle":"Triangle","tool.x-box":"X box","tool.check-box":"Check box","tool.media":"Media","tool.frame":"Frame","tool.note":"Note","tool.laser":"Laser","tool.embed":"Embed","tool.text":"Text","tool.pointer-down":"Pointer down","tool.image-zoom":"Zoom","tool.replace-media":"Replace media…","tool.flip-horz":"Flip horizontally","tool.flip-vert":"Flip vertically","tool.rotate-cw":"Rotate","tool.aspect-ratio":"Aspect ratio","tool.aspect-ratio.original":"Original","tool.aspect-ratio.square":"Square (1:1)","tool.aspect-ratio.circle":"Circle (1:1)","tool.aspect-ratio.landscape":"Landscape (4:3)","tool.aspect-ratio.portrait":"Portrait (3:4)","tool.aspect-ratio.wide":"Wide (16:9)","tool.image-toolbar-title":"Image tools","tool.image-crop":"Crop image","tool.image-crop-confirm":"Confirm","tool.media-alt-text":"Alternative text","tool.media-alt-text-desc":"Give a description…","tool.media-alt-text-confirm":"Confirm","tool.rich-text-bold":"Bold","tool.rich-text-italic":"Italic","tool.rich-text-code":"Code","tool.rich-text-highlight":"Highlight","tool.rich-text-strikethrough":"Strikethrough","tool.rich-text-link":"Link","tool.rich-text-link-visit":"Visit link","tool.rich-text-link-remove":"Remove link","tool.rich-text-header":"Header","tool.rich-text-bulletList":"Bulleted list","tool.rich-text-toolbar-title":"Text formatting","tool.rich-text-orderedList":"Ordered list","tool.bookmark":"Bookmark","a11y.status":"Status","a11y.skip-to-main-content":"Move focus to canvas","a11y.shape-index":"{num} of {total}","a11y.shape-image":"Image","a11y.shape-video":"Video","a11y.multiple-shapes":"{num} shapes selected","a11y.select-shape":"Select next shape","a11y.select-shape-direction":"Select shape in direction","a11y.enter-leave-container":"Enter/leave container","a11y.repeat-shape":"Repeat shape","a11y.move-shape":"Move shape","a11y.move-shape-faster":"Move shape faster","a11y.rotate-shape-cw":"Rotate shape clockwise","a11y.rotate-shape-ccw":"Rotate shape counterclockwise","a11y.rotate-shape-cw-fine":"Rotate shape clockwise (fine)","a11y.rotate-shape-ccw-fine":"Rotate shape counterclockwise (fine)","a11y.enlarge-shape":"Enlarge shape","a11y.shrink-shape":"Shrink shape","a11y.pan-camera":"Pan camera","a11y.adjust-shape-styles":"Adjust shape styles","a11y.open-context-menu":"Context menu…","a11y.open-keyboard-shortcuts":"Keyboard shortcuts…","menu.title":"Menu","menu.theme":"Theme","menu.accessibility":"Accessibility","menu.copy-as":"Copy as","menu.edit":"Edit","menu.export-as":"Export as","menu.file":"File","menu.language":"Language","menu.preferences":"Preferences","menu.view":"View","menu.input-device":"Input device","context-menu.title":"Context menu","context-menu.edit":"Edit","context-menu.arrange":"Arrange","context-menu.copy-as":"Copy as","context-menu.export-as":"Export as","context-menu.export-all-as":"Export","context-menu.move-to-page":"Move to page","context-menu.reorder":"Reorder","page-menu.title":"Pages","page-menu.create-new-page":"Create new page","page-menu.max-page-count-reached":"Max pages reached","page-menu.new-page-initial-name":"Page 1","page-menu.edit-start":"Edit","page-menu.edit-done":"Done","page-menu.go-to-page":"Go to page","page-menu.submenu.rename":"Rename","page-menu.submenu.duplicate-page":"Duplicate","page-menu.submenu.title":"Menu","page-menu.submenu.move-down":"Move down","page-menu.submenu.move-up":"Move up","page-menu.submenu.delete":"Delete","share-menu.title":"Share","share-menu.save-note":"Download this project to your computer as a .tldr file.","share-menu.fork-note":"Create a new shared project based on this snapshot.","share-menu.share-project":"Share this project","share-menu.copy-link":"Copy editor link","share-menu.create-snapshot-link":"Copy snapshot link","share-menu.snapshot-link-note":"Capture and share this project as a read-only snapshot link.","share-menu.copy-readonly-link":"Copy viewer link","share-menu.offline-note":"Create a new shared project based on your current project.","share-menu.copy-link-note":"Anyone with the link will be able to view and edit this project.","share-menu.copy-readonly-link-note":"Anyone with the link will be able to access this project.","share-menu.project-too-large":"Sorry, this project can’t be shared because it’s too large. We’re working on it!","share-menu.upload-failed":"Sorry, we couldn’t upload your project at the moment. Please try again or let us know if the problem persists.","share-menu.creating-project":"Creating the new project…","share-menu.copied":"Copied link","document-name-menu.copy-link":"Copy link","status.offline":"Offline","people-menu.title":"People","people-menu.change-name":"Change name","people-menu.avatar-color":"Avatar color","people-menu.change-color":"Change color","people-menu.follow":"Following","people-menu.following":"Following","people-menu.leading":"Following you","people-menu.user":"(You)","people-menu.invite":"Invite others","people-menu.anonymous-user":"New user","help-menu.import-tldr-file":"Import file…","help-menu.title":"Help and resources","help-menu.about":"About tldraw","help-menu.discord":"Discord","help-menu.github":"GitHub","help-menu.keyboard-shortcuts":"Keyboard shortcuts…","help-menu.twitter":"Twitter","help-menu.terms":"Terms of service","help-menu.privacy":"Privacy policy","actions-menu.title":"Actions","edit-link-dialog.title":"Edit link","edit-link-dialog.invalid-url":"A link must be a valid URL.","edit-link-dialog.detail":"Links will open in a new tab.","edit-link-dialog.url":"URL","edit-link-dialog.clear":"Clear","edit-link-dialog.save":"Continue","edit-link-dialog.cancel":"Cancel","edit-link-dialog.external-link":"External link","embed-dialog.title":"Insert embed","embed-dialog.back":"Back","embed-dialog.create":"Create","embed-dialog.cancel":"Cancel","embed-dialog.url":"URL","embed-dialog.instruction":"Paste in the site’s URL to create the embed.","embed-dialog.invalid-url":"We could not create an embed from that URL.","shortcuts-dialog.title":"Keyboard shortcuts","shortcuts-dialog.edit":"Edit","shortcuts-dialog.file":"File","shortcuts-dialog.preferences":"Preferences","shortcuts-dialog.tools":"Tools","shortcuts-dialog.transform":"Transform","shortcuts-dialog.view":"View","shortcuts-dialog.collaboration":"Collaboration","shortcuts-dialog.a11y":"Accessibility","shortcuts-dialog.text-formatting":"Text formatting","style-panel.title":"Styles","style-panel.align":"Align","style-panel.label-align":"Label align","style-panel.vertical-align":"Vertical align","style-panel.position":"Position","style-panel.arrowheads":"Arrows","style-panel.arrowhead-start":"Start","style-panel.arrowhead-end":"End","style-panel.arrow-kind":"Line","style-panel.color":"Color","style-panel.dash":"Dash","style-panel.fill":"Fill","style-panel.font":"Font","style-panel.geo":"Shape","style-panel.mixed":"Mixed","style-panel.opacity":"Opacity","style-panel.size":"Size","style-panel.spline":"Spline","style-panel.selected":"selected","tool-panel.title":"Tools","tool-panel.more":"More","navigation-zone.title":"Navigation","navigation-zone.minimap":"Minimap","navigation-zone.toggle-minimap":"Toggle minimap","navigation-zone.zoom":"Zoom","focus-mode.toggle-focus-mode":"Toggle focus mode","toast.close":"Close","toast.success":"Success","toast.error":"Error","toast.info":"Info","toast.warning":"Warning","file-system.file-open-error.title":"Could not open file","file-system.file-open-error.not-a-tldraw-file":"The file you tried to open doesn’t look like a tldraw file.","file-system.file-open-error.file-format-version-too-new":"The file you tried to open is from a newer version of tldraw. Please reload the page and try again.","file-system.file-open-error.generic-corrupted-file":"The file you tried to open is corrupted.","file-system.confirm-open.title":"Overwrite current project?","file-system.confirm-open.description":"Opening a file will replace your current project and any unsaved changes will be lost. Are you sure you want to continue?","file-system.confirm-open.cancel":"Cancel","file-system.confirm-open.open":"Open file","file-system.confirm-open.dont-show-again":"Don’t ask again","file-system.confirm-clear.title":"Clear current project?","file-system.confirm-clear.description":"Creating a new project will clear your current project and any unsaved changes will be lost. Are you sure you want to continue?","file-system.confirm-clear.cancel":"Cancel","file-system.confirm-clear.continue":"Continue","file-system.confirm-clear.dont-show-again":"Don’t ask again","file-system.shared-document-file-open-error.title":"Could not open file","file-system.shared-document-file-open-error.description":"Opening files from shared projects is not supported.","sharing.confirm-leave.title":"Leave current project?","sharing.confirm-leave.description":"Are you sure you want to leave this shared project? You can return to it by navigating to its URL.","sharing.confirm-leave.cancel":"Cancel","sharing.confirm-leave.leave":"Leave","sharing.confirm-leave.dont-show-again":"Don’t ask again","toast.error.export-fail.title":"Failed export","toast.error.export-fail.desc":"Failed to export image","toast.error.copy-fail.title":"Failed copy","toast.error.copy-fail.desc":"Failed to copy image","context.pages.new-page":"New page","vscode.file-open.desc":"We’ve updated this document to work with the current version of tldraw. If you’d like to keep the original version (which will work on old.tldraw.com), click below to create a backup.","vscode.file-open.open":"Continue","vscode.file-open.backup":"Backup","vscode.file-open.backup-saved":"Backup saved","vscode.file-open.backup-failed":"Backup failed: this is not a .tldr file.","vscode.file-open.dont-show-again":"Don’t ask again","cursor-chat.type-to-chat":"Type to chat…","app.loading":"Loading tldraw…","handle.resize-top":"Resize top","handle.resize-bottom":"Resize bottom","handle.resize-left":"Resize left","handle.resize-right":"Resize right","handle.resize-top-left":"Resize top left","handle.resize-top-right":"Resize top right","handle.resize-bottom-left":"Resize bottom left","handle.resize-bottom-right":"Resize bottom right","handle.rotate.top_left_rotate":"Rotate top left","handle.rotate.top_right_rotate":"Rotate top right","handle.rotate.bottom_left_rotate":"Rotate bottom left","handle.rotate.bottom_right_rotate":"Rotate bottom right","handle.rotate.mobile_rotate":"Rotate","handle.crop.top":"Crop top","handle.crop.bottom":"Crop bottom","handle.crop.left":"Crop left","handle.crop.right":"Crop right","handle.crop.top-left":"Crop top left","handle.crop.top-right":"Crop top right","handle.crop.bottom-left":"Crop bottom left","handle.crop.bottom-right":"Crop bottom right","ui.close":"Close","ui.checked":"Checked","ui.unchecked":"Unchecked"},rQ=new Set(["ar","fa","he","ur","ku"]),pc={locale:"en",label:"English",messages:f0,dir:"ltr"};async function sQ(n,e){if(!(await $i(e.translations.en)).ok)return console.warn("No main translations found."),pc;if(n==="en")return pc;const r=oh.find(i=>i.locale===n);if(!r)return console.warn(`No translation found for locale ${n}`),pc;const o=await(await $i(e.translations[r.locale])).json();if(!o)return console.warn(`No messages found for locale ${n}`),pc;for(const i in pc.messages)o[i];return{locale:n,label:r.label,dir:rQ.has(r.locale)?"rtl":"ltr",messages:{...pc.messages,...o}}}const K1=x.createContext(null);function oQ(){const n=x.useContext(K1);if(!n)throw new Error("useCurrentTranslation must be used inside of <TldrawUiContextProvider />");return n}function Xj({overrides:n,locale:e,children:t}){const r=U1(),[s,o]=x.useState(()=>n&&n.en?{locale:"en",label:"English",dir:"ltr",messages:{...f0,...n.en}}:{locale:"en",label:"English",dir:"ltr",messages:f0});return x.useEffect(()=>{let i=!1;async function a(){const l=await sQ(e,r);l&&!i&&(n&&n[e]?o({...l,messages:{...l.messages,...n[e]}}):o(l))}return a(),()=>{i=!0}},[r,e,n]),p.jsx(K1.Provider,{value:s,children:t})}function Se(){const n=oQ();return x.useCallback(function(t){return n.messages[t]??t},[n])}const iQ={normal:"tlui-button__normal",primary:"tlui-button__primary",danger:"tlui-button__danger",low:"tlui-button__low",icon:"tlui-button__icon",tool:"tlui-button__tool",menu:"tlui-button__menu",help:"tlui-button__help"},Ye=x.forwardRef(function({children:e,type:t,htmlButtonType:r,isActive:s,...o},i){return p.jsx("button",{ref:i,type:r||"button",draggable:!1,"data-isactive":s,...o,className:xe("tlui-button",iQ[t],o.className),children:e})});function aQ(){const n=K(),e=Se(),t=x.useRef(null),r=x.useCallback(s=>{var i;n.markEventAsHandled(s),(i=t.current)==null||i.blur();const o=n.getCurrentPageShapesInReadingOrder();o.length&&(n.setSelectedShapes([o[0].id]),n.zoomToSelectionIfOffscreen(256,{animation:{duration:n.options.animationMediumMs},inset:0}),n.timers.setTimeout(()=>n.getContainer().focus(),100))},[n]);return p.jsx(Ye,{ref:t,type:"low",tabIndex:0,className:"tl-skip-to-main-content",onClick:r,children:e("a11y.skip-to-main-content")})}const lQ=x.memo(function(){const e=Yy(),t=Se(),r=W("a11y-msg",()=>e.currentMsg.get(),[]);return dQ(r.msg),cQ(),r.msg&&p.jsx("div",{"aria-label":t("a11y.status"),"aria-live":r.priority||"assertive",role:"status","aria-hidden":"false",style:{position:"absolute",top:"-10000px",left:"-10000px"},children:r.msg})});function qj(n){const{editor:e,selectedShapeIds:t,msg:r}=n;let s="";const o=t.length;if(o>1)s=r("a11y.multiple-shapes").replace("{num}",o.toString());else if(o===1){const i=t[0],a=e.getShape(i);if(!a)return"";const l=e.getShapeUtil(a.type),c=["image","video"].includes(a.type);let u="";a.type==="geo"?u=r(`geo-style.${a.props.geo}`):c?u=r(`a11y.shape-${a.type}`):u=r(`tool.${a.type}`);const d=e.getCurrentPageShapesInReadingOrder(),h=(d.findIndex(y=>y.id===i)+1).toString(),f=d.length.toString(),g=r("a11y.shape-index").replace("{num}",h).replace("{total}",f),m=l.getAriaDescriptor(a)||l.getText(a)||"";s=(m?`${m}, `:"")+`${u}. ${g}`}return s}const cQ=()=>{const n=Xt(),e=Yy(),t=Se(),r=x.useRef([]);iy("announce selection",()=>{if(!n)return;if(n.isIn("select.idle")){const o=n.getSelectedShapeIds();o!==r.current&&(r.current=o,gl(()=>{const i=qj({editor:n,selectedShapeIds:o,msg:t});i&&e.announce({msg:i})}))}},[n,e,t])},dQ=n=>{const e=sn();x.useEffect(()=>{if(Dt.a11y.get()){const t=s=>{console.debug(`%ca11y%c: ${s}`,"color: white; background: #40C057; padding: 2px;border-radius: 3px;","font-weight: normal")},r=s=>{const o=document.activeElement;if(s.key==="Tab"&&o&&o!==document.body&&!o.classList.contains("tl-container")){const i=o.getAttribute("aria-label")||o.getAttribute("title")||o.textContent;i&&t(i)}};return n&&t(n),document.addEventListener("keyup",r),()=>document.removeEventListener("keyup",r)}},[e,n])},Wc=300,W1=320,Vf=46,uQ=101;function Zj(n,e){const t=e?n.getAsset(e):null;return t&&!t.props.image?t.props.title?uQ:Vf:W1}function TE(n,e){return{...e,props:{...e.props,h:Zj(n,e.props.assetId)}}}const hQ=n=>{try{return new URL(n).hostname.replace(/^www\./,"")}catch{return n}};function pQ(n,e){const{url:t}=e.props,r=Gl.createId(z_(t));n.getAsset(r)?e.props.assetId!==r&&n.updateShapes([{id:e.id,type:e.type,props:{assetId:r}}]):(n.updateShapes([{id:e.id,type:e.type,props:{assetId:null}}]),fQ(n,e))}const fQ=ry(async(n,e)=>{if(n.isDisposed)return;const{url:t}=e.props,r=await n.getAssetForExternalContent({type:"url",url:t});r&&n.run(()=>{n.createAssets([r]),n.updateShapes([{id:e.id,type:e.type,props:{assetId:r.id}}])})},500);async function Jj(n,{url:e,center:t=n.getViewportPageBounds().center}){try{const r=await n.getAssetForExternalContent({type:"url",url:e}),s=St(),o={id:s,type:"bookmark",x:t.x-Wc/2,y:t.y-W1/2,rotation:0,opacity:1,props:{url:e,assetId:(r==null?void 0:r.id)||null,w:Wc,h:Zj(n,r==null?void 0:r.id)}};n.run(()=>{r&&n.createAssets([r]),n.createShapes([o])});const i=n.getShape(s);return zs.ok(i)}catch(r){return zs.err(r instanceof Error?r.message:"Failed to create bookmark")}}function gQ(n,e){const t=Le(e.map(s=>n.getShape(s)).filter(s=>s&&n.isShapeOfType(s,"frame")));if(!t.length)return;const r=[];n.run(()=>{t.map(s=>{const o=n.getSortedChildIdsForParent(s.id);o.length&&(mt(n,o,{filter:i=>!t.find(a=>a.id===i.id)}),r.push(...o))}),n.setSelectedShapes(r),n.deleteShapes(e)})}const IE=50;function Qj(n,e,t={padding:IE}){const r=J.FromPoints(n.flatMap(c=>{if(!c)return[];const u=e.getShapeGeometry(c.id),d=e.getShapeLocalTransform(c);return(d==null?void 0:d.applyToPoints(u.vertices))??[]})),s=t.padding??IE,o=r.w+2*s,i=r.h+2*s,a=s-r.minX,l=s-r.minY;return{w:o,h:i,dx:a,dy:l}}function eN(n,e,t={}){const r=n.getShape(e);if(!r)return;const s=n.getSortedChildIdsForParent(r.id),o=Le(s.map(d=>n.getShape(d)));if(!o.length)return;const{w:i,h:a,dx:l,dy:c}=Qj(o,n,t);if(l===0&&c===0&&r.props.w===i&&r.props.h===a)return;const u=new C(l,c).rot(r.rotation);n.run(()=>{const d=s.map(h=>{const f=n.getShape(h);return{id:f.id,type:f.type,x:f.x+l,y:f.y+c}});d.push({id:r.id,type:r.type,x:r.x-u.x,y:r.y-u.y,props:{w:i,h:a}}),n.updateShapes(d)})}function Qt({children:n}){return p.jsx("span",{className:"tlui-button__label",children:n})}function EE(n,e){if(typeof n=="function")return n(e);n!=null&&(n.current=e)}function Xy(...n){return e=>{let t=!1;const r=n.map(s=>{const o=EE(s,e);return!t&&typeof o=="function"&&(t=!0),o});if(t)return()=>{for(let s=0;s<r.length;s++){const o=r[s];typeof o=="function"?o():EE(n[s],null)}}}}function nt(...n){return x.useCallback(Xy(...n),n)}function Fa(n){const e=mQ(n),t=x.forwardRef((r,s)=>{const{children:o,...i}=r,a=x.Children.toArray(o),l=a.find(SQ);if(l){const c=l.props.children,u=a.map(d=>d===l?x.Children.count(c)>1?x.Children.only(null):x.isValidElement(c)?c.props.children:null:d);return p.jsx(e,{...i,ref:s,children:x.isValidElement(c)?x.cloneElement(c,void 0,u):null})}return p.jsx(e,{...i,ref:s,children:o})});return t.displayName=`${n}.Slot`,t}var V1=Fa("Slot");function mQ(n){const e=x.forwardRef((t,r)=>{const{children:s,...o}=t;if(x.isValidElement(s)){const i=bQ(s),a=xQ(o,s.props);return s.type!==x.Fragment&&(a.ref=r?Xy(r,i):i),x.cloneElement(s,a)}return x.Children.count(s)>1?x.Children.only(null):null});return e.displayName=`${n}.SlotClone`,e}var tN=Symbol("radix.slottable");function yQ(n){const e=({children:t})=>p.jsx(p.Fragment,{children:t});return e.displayName=`${n}.Slottable`,e.__radixId=tN,e}function SQ(n){return x.isValidElement(n)&&typeof n.type=="function"&&"__radixId"in n.type&&n.type.__radixId===tN}function xQ(n,e){const t={...e};for(const r in e){const s=n[r],o=e[r];/^on[A-Z]/.test(r)?s&&o?t[r]=(...a)=>{const l=o(...a);return s(...a),l}:s&&(t[r]=s):r==="style"?t[r]={...s,...o}:r==="className"&&(t[r]=[s,o].filter(Boolean).join(" "))}return{...n,...t}}function bQ(n){var r,s;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(s=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:s.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var wQ=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ke=wQ.reduce((n,e)=>{const t=Fa(`Primitive.${e}`),r=x.forwardRef((s,o)=>{const{asChild:i,...a}=s,l=i?t:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,{...a,ref:o})});return r.displayName=`Primitive.${e}`,{...n,[e]:r}},{});function G1(n,e){n&&Vi.flushSync(()=>n.dispatchEvent(e))}var nN=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),vQ="VisuallyHidden",qy=x.forwardRef((n,e)=>p.jsx(ke.span,{...n,ref:e,style:{...nN,...n.style}}));qy.displayName=vQ;var CQ=qy;function PQ(n,e){const t=x.createContext(e),r=o=>{const{children:i,...a}=o,l=x.useMemo(()=>a,Object.values(a));return p.jsx(t.Provider,{value:l,children:i})};r.displayName=n+"Provider";function s(o){const i=x.useContext(t);if(i)return i;if(e!==void 0)return e;throw new Error(`\`${o}\` must be used within \`${n}\``)}return[r,s]}function rs(n,e=[]){let t=[];function r(o,i){const a=x.createContext(i),l=t.length;t=[...t,i];const c=d=>{var S;const{scope:h,children:f,...g}=d,m=((S=h==null?void 0:h[n])==null?void 0:S[l])||a,y=x.useMemo(()=>g,Object.values(g));return p.jsx(m.Provider,{value:y,children:f})};c.displayName=o+"Provider";function u(d,h){var m;const f=((m=h==null?void 0:h[n])==null?void 0:m[l])||a,g=x.useContext(f);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${o}\``)}return[c,u]}const s=()=>{const o=t.map(i=>x.createContext(i));return function(a){const l=(a==null?void 0:a[n])||o;return x.useMemo(()=>({[`__scope${n}`]:{...a,[n]:l}}),[a,l])}};return s.scopeName=n,[r,TQ(s,...e)]}function TQ(...n){const e=n[0];if(n.length===1)return e;const t=()=>{const r=n.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const d=l(o)[`__scope${c}`];return{...a,...d}},{});return x.useMemo(()=>({[`__scope${e.scopeName}`]:i}),[i])}};return t.scopeName=e.scopeName,t}function ep(n){const e=n+"CollectionProvider",[t,r]=rs(e),[s,o]=t(e,{collectionRef:{current:null},itemMap:new Map}),i=m=>{const{scope:y,children:S}=m,b=_e.useRef(null),w=_e.useRef(new Map).current;return p.jsx(s,{scope:y,itemMap:w,collectionRef:b,children:S})};i.displayName=e;const a=n+"CollectionSlot",l=Fa(a),c=_e.forwardRef((m,y)=>{const{scope:S,children:b}=m,w=o(a,S),v=nt(y,w.collectionRef);return p.jsx(l,{ref:v,children:b})});c.displayName=a;const u=n+"CollectionItemSlot",d="data-radix-collection-item",h=Fa(u),f=_e.forwardRef((m,y)=>{const{scope:S,children:b,...w}=m,v=_e.useRef(null),P=nt(y,v),T=o(u,S);return _e.useEffect(()=>(T.itemMap.set(v,{ref:v,...w}),()=>void T.itemMap.delete(v))),p.jsx(h,{[d]:"",ref:P,children:b})});f.displayName=u;function g(m){const y=o(n+"CollectionConsumer",m);return _e.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${d}]`));return Array.from(y.itemMap.values()).sort((T,I)=>w.indexOf(T.ref.current)-w.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:i,Slot:c,ItemSlot:f},g,r]}function le(n,e,{checkForDefaultPrevented:t=!0}={}){return function(s){if(n==null||n(s),t===!1||!s.defaultPrevented)return e==null?void 0:e(s)}}var Wn=globalThis!=null&&globalThis.document?x.useLayoutEffect:()=>{},IQ=L_[" useInsertionEffect ".trim().toString()]||Wn;function Ys({prop:n,defaultProp:e,onChange:t=()=>{},caller:r}){const[s,o,i]=EQ({defaultProp:e,onChange:t}),a=n!==void 0,l=a?n:s;{const u=x.useRef(n!==void 0);x.useEffect(()=>{const d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}const c=x.useCallback(u=>{var d;if(a){const h=kQ(u)?u(n):u;h!==n&&((d=i.current)==null||d.call(i,h))}else o(u)},[a,n,o,i]);return[l,c]}function EQ({defaultProp:n,onChange:e}){const[t,r]=x.useState(n),s=x.useRef(t),o=x.useRef(e);return IQ(()=>{o.current=e},[e]),x.useEffect(()=>{var i;s.current!==t&&((i=o.current)==null||i.call(o,t),s.current=t)},[t,s]),[t,r,o]}function kQ(n){return typeof n=="function"}function _Q(n,e){return x.useReducer((t,r)=>e[t][r]??t,n)}var Xs=n=>{const{present:e,children:t}=n,r=MQ(e),s=typeof t=="function"?t({present:r.isPresent}):x.Children.only(t),o=nt(r.ref,AQ(s));return typeof t=="function"||r.isPresent?x.cloneElement(s,{ref:o}):null};Xs.displayName="Presence";function MQ(n){const[e,t]=x.useState(),r=x.useRef(null),s=x.useRef(n),o=x.useRef("none"),i=n?"mounted":"unmounted",[a,l]=_Q(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return x.useEffect(()=>{const c=nf(r.current);o.current=a==="mounted"?c:"none"},[a]),Wn(()=>{const c=r.current,u=s.current;if(u!==n){const h=o.current,f=nf(c);n?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&h!==f?"ANIMATION_OUT":"UNMOUNT"),s.current=n}},[n,l]),Wn(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,d=f=>{const m=nf(r.current).includes(CSS.escape(f.animationName));if(f.target===e&&m&&(l("ANIMATION_END"),!s.current)){const y=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=y)})}},h=f=>{f.target===e&&(o.current=nf(r.current))};return e.addEventListener("animationstart",h),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",h),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:x.useCallback(c=>{r.current=c?getComputedStyle(c):null,t(c)},[])}}function nf(n){return(n==null?void 0:n.animationName)||"none"}function AQ(n){var r,s;let e=(r=Object.getOwnPropertyDescriptor(n.props,"ref"))==null?void 0:r.get,t=e&&"isReactWarning"in e&&e.isReactWarning;return t?n.ref:(e=(s=Object.getOwnPropertyDescriptor(n,"ref"))==null?void 0:s.get,t=e&&"isReactWarning"in e&&e.isReactWarning,t?n.props.ref:n.props.ref||n.ref)}var DQ=L_[" useId ".trim().toString()]||(()=>{}),OQ=0;function Ks(n){const[e,t]=x.useState(DQ());return Wn(()=>{t(r=>r??String(OQ++))},[n]),e?`radix-${e}`:""}var RQ=x.createContext(void 0);function tp(n){const e=x.useContext(RQ);return n||e||"ltr"}function dr(n){const e=x.useRef(n);return x.useEffect(()=>{e.current=n}),x.useMemo(()=>(...t)=>{var r;return(r=e.current)==null?void 0:r.call(e,...t)},[])}function LQ(n,e=globalThis==null?void 0:globalThis.document){const t=dr(n);x.useEffect(()=>{const r=s=>{s.key==="Escape"&&t(s)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[t,e])}var jQ="DismissableLayer",g0="dismissableLayer.update",NQ="dismissableLayer.pointerDownOutside",FQ="dismissableLayer.focusOutside",kE,rN=x.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Zl=x.forwardRef((n,e)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,onDismiss:a,...l}=n,c=x.useContext(rN),[u,d]=x.useState(null),h=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=x.useState({}),g=nt(e,I=>d(I)),m=Array.from(c.layers),[y]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),S=m.indexOf(y),b=u?m.indexOf(u):-1,w=c.layersWithOutsidePointerEventsDisabled.size>0,v=b>=S,P=zQ(I=>{const k=I.target,A=[...c.branches].some(R=>R.contains(k));!v||A||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},h),T=$Q(I=>{const k=I.target;[...c.branches].some(R=>R.contains(k))||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},h);return LQ(I=>{b===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},h),x.useEffect(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(kE=h.body.style.pointerEvents,h.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),_E(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(h.body.style.pointerEvents=kE)}},[u,h,t,c]),x.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),_E())},[u,c]),x.useEffect(()=>{const I=()=>f({});return document.addEventListener(g0,I),()=>document.removeEventListener(g0,I)},[]),p.jsx(ke.div,{...l,ref:g,style:{pointerEvents:w?v?"auto":"none":void 0,...n.style},onFocusCapture:le(n.onFocusCapture,T.onFocusCapture),onBlurCapture:le(n.onBlurCapture,T.onBlurCapture),onPointerDownCapture:le(n.onPointerDownCapture,P.onPointerDownCapture)})});Zl.displayName=jQ;var BQ="DismissableLayerBranch",sN=x.forwardRef((n,e)=>{const t=x.useContext(rN),r=x.useRef(null),s=nt(e,r);return x.useEffect(()=>{const o=r.current;if(o)return t.branches.add(o),()=>{t.branches.delete(o)}},[t.branches]),p.jsx(ke.div,{...n,ref:s})});sN.displayName=BQ;function zQ(n,e=globalThis==null?void 0:globalThis.document){const t=dr(n),r=x.useRef(!1),s=x.useRef(()=>{});return x.useEffect(()=>{const o=a=>{if(a.target&&!r.current){let l=function(){oN(NQ,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",s.current),s.current=l,e.addEventListener("click",s.current,{once:!0})):l()}else e.removeEventListener("click",s.current);r.current=!1},i=window.setTimeout(()=>{e.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(i),e.removeEventListener("pointerdown",o),e.removeEventListener("click",s.current)}},[e,t]),{onPointerDownCapture:()=>r.current=!0}}function $Q(n,e=globalThis==null?void 0:globalThis.document){const t=dr(n),r=x.useRef(!1);return x.useEffect(()=>{const s=o=>{o.target&&!r.current&&oN(FQ,t,{originalEvent:o},{discrete:!1})};return e.addEventListener("focusin",s),()=>e.removeEventListener("focusin",s)},[e,t]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function _E(){const n=new CustomEvent(g0);document.dispatchEvent(n)}function oN(n,e,t,{discrete:r}){const s=t.originalEvent.target,o=new CustomEvent(n,{bubbles:!1,cancelable:!0,detail:t});e&&s.addEventListener(n,e,{once:!0}),r?G1(s,o):s.dispatchEvent(o)}var HQ=Zl,UQ=sN,pb="focusScope.autoFocusOnMount",fb="focusScope.autoFocusOnUnmount",ME={bubbles:!1,cancelable:!0},KQ="FocusScope",np=x.forwardRef((n,e)=>{const{loop:t=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...i}=n,[a,l]=x.useState(null),c=dr(s),u=dr(o),d=x.useRef(null),h=nt(e,m=>l(m)),f=x.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;x.useEffect(()=>{if(r){let m=function(w){if(f.paused||!a)return;const v=w.target;a.contains(v)?d.current=v:ua(d.current,{select:!0})},y=function(w){if(f.paused||!a)return;const v=w.relatedTarget;v!==null&&(a.contains(v)||ua(d.current,{select:!0}))},S=function(w){if(document.activeElement===document.body)for(const P of w)P.removedNodes.length>0&&ua(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",y);const b=new MutationObserver(S);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",y),b.disconnect()}}},[r,a,f.paused]),x.useEffect(()=>{if(a){DE.add(f);const m=document.activeElement;if(!a.contains(m)){const S=new CustomEvent(pb,ME);a.addEventListener(pb,c),a.dispatchEvent(S),S.defaultPrevented||(WQ(qQ(iN(a)),{select:!0}),document.activeElement===m&&ua(a))}return()=>{a.removeEventListener(pb,c),setTimeout(()=>{const S=new CustomEvent(fb,ME);a.addEventListener(fb,u),a.dispatchEvent(S),S.defaultPrevented||ua(m??document.body,{select:!0}),a.removeEventListener(fb,u),DE.remove(f)},0)}}},[a,c,u,f]);const g=x.useCallback(m=>{if(!t&&!r||f.paused)return;const y=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,S=document.activeElement;if(y&&S){const b=m.currentTarget,[w,v]=VQ(b);w&&v?!m.shiftKey&&S===v?(m.preventDefault(),t&&ua(w,{select:!0})):m.shiftKey&&S===w&&(m.preventDefault(),t&&ua(v,{select:!0})):S===b&&m.preventDefault()}},[t,r,f.paused]);return p.jsx(ke.div,{tabIndex:-1,...i,ref:h,onKeyDown:g})});np.displayName=KQ;function WQ(n,{select:e=!1}={}){const t=document.activeElement;for(const r of n)if(ua(r,{select:e}),document.activeElement!==t)return}function VQ(n){const e=iN(n),t=AE(e,n),r=AE(e.reverse(),n);return[t,r]}function iN(n){const e=[],t=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function AE(n,e){for(const t of n)if(!GQ(t,{upTo:e}))return t}function GQ(n,{upTo:e}){if(getComputedStyle(n).visibility==="hidden")return!0;for(;n;){if(e!==void 0&&n===e)return!1;if(getComputedStyle(n).display==="none")return!0;n=n.parentElement}return!1}function YQ(n){return n instanceof HTMLInputElement&&"select"in n}function ua(n,{select:e=!1}={}){if(n&&n.focus){const t=document.activeElement;n.focus({preventScroll:!0}),n!==t&&YQ(n)&&e&&n.select()}}var DE=XQ();function XQ(){let n=[];return{add(e){const t=n[0];e!==t&&(t==null||t.pause()),n=OE(n,e),n.unshift(e)},remove(e){var t;n=OE(n,e),(t=n[0])==null||t.resume()}}}function OE(n,e){const t=[...n],r=t.indexOf(e);return r!==-1&&t.splice(r,1),t}function qQ(n){return n.filter(e=>e.tagName!=="A")}var ZQ="Portal",rp=x.forwardRef((n,e)=>{var a;const{container:t,...r}=n,[s,o]=x.useState(!1);Wn(()=>o(!0),[]);const i=t||s&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?k8.createPortal(p.jsx(ke.div,{...r,ref:e}),i):null});rp.displayName=ZQ;var gb=0;function Zy(){x.useEffect(()=>{const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",n[0]??RE()),document.body.insertAdjacentElement("beforeend",n[1]??RE()),gb++,()=>{gb===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),gb--}},[])}function RE(){const n=document.createElement("span");return n.setAttribute("data-radix-focus-guard",""),n.tabIndex=0,n.style.outline="none",n.style.opacity="0",n.style.position="fixed",n.style.pointerEvents="none",n}var Bo=function(){return Bo=Object.assign||function(e){for(var t,r=1,s=arguments.length;r<s;r++){t=arguments[r];for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},Bo.apply(this,arguments)};function aN(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(n);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(n,r[s])&&(t[r[s]]=n[r[s]]);return t}function JQ(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))}var Gf="right-scroll-bar-position",Yf="width-before-scroll-bar",QQ="with-scroll-bars-hidden",eee="--removed-body-scroll-bar-size";function mb(n,e){return typeof n=="function"?n(e):n&&(n.current=e),n}function tee(n,e){var t=x.useState(function(){return{value:n,callback:e,facade:{get current(){return t.value},set current(r){var s=t.value;s!==r&&(t.value=r,t.callback(r,s))}}}})[0];return t.callback=e,t.facade}var nee=typeof window<"u"?x.useLayoutEffect:x.useEffect,LE=new WeakMap;function ree(n,e){var t=tee(null,function(r){return n.forEach(function(s){return mb(s,r)})});return nee(function(){var r=LE.get(t);if(r){var s=new Set(r),o=new Set(n),i=t.current;s.forEach(function(a){o.has(a)||mb(a,null)}),o.forEach(function(a){s.has(a)||mb(a,i)})}LE.set(t,n)},[n]),t}function see(n){return n}function oee(n,e){e===void 0&&(e=see);var t=[],r=!1,s={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return t.length?t[t.length-1]:n},useMedium:function(o){var i=e(o,r);return t.push(i),function(){t=t.filter(function(a){return a!==i})}},assignSyncMedium:function(o){for(r=!0;t.length;){var i=t;t=[],i.forEach(o)}t={push:function(a){return o(a)},filter:function(){return t}}},assignMedium:function(o){r=!0;var i=[];if(t.length){var a=t;t=[],a.forEach(o),i=t}var l=function(){var u=i;i=[],u.forEach(o)},c=function(){return Promise.resolve().then(l)};c(),t={push:function(u){i.push(u),c()},filter:function(u){return i=i.filter(u),t}}}};return s}function iee(n){n===void 0&&(n={});var e=oee(null);return e.options=Bo({async:!0,ssr:!1},n),e}var lN=function(n){var e=n.sideCar,t=aN(n,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return x.createElement(r,Bo({},t))};lN.isSideCarExport=!0;function aee(n,e){return n.useMedium(e),lN}var cN=iee(),yb=function(){},Jy=x.forwardRef(function(n,e){var t=x.useRef(null),r=x.useState({onScrollCapture:yb,onWheelCapture:yb,onTouchMoveCapture:yb}),s=r[0],o=r[1],i=n.forwardProps,a=n.children,l=n.className,c=n.removeScrollBar,u=n.enabled,d=n.shards,h=n.sideCar,f=n.noRelative,g=n.noIsolation,m=n.inert,y=n.allowPinchZoom,S=n.as,b=S===void 0?"div":S,w=n.gapMode,v=aN(n,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),P=h,T=ree([t,e]),I=Bo(Bo({},v),s);return x.createElement(x.Fragment,null,u&&x.createElement(P,{sideCar:cN,removeScrollBar:c,shards:d,noRelative:f,noIsolation:g,inert:m,setCallbacks:o,allowPinchZoom:!!y,lockRef:t,gapMode:w}),i?x.cloneElement(x.Children.only(a),Bo(Bo({},I),{ref:T})):x.createElement(b,Bo({},I,{className:l,ref:T}),a))});Jy.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Jy.classNames={fullWidth:Yf,zeroRight:Gf};var lee=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function cee(){if(!document)return null;var n=document.createElement("style");n.type="text/css";var e=lee();return e&&n.setAttribute("nonce",e),n}function dee(n,e){n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}function uee(n){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(n)}var hee=function(){var n=0,e=null;return{add:function(t){n==0&&(e=cee())&&(dee(e,t),uee(e)),n++},remove:function(){n--,!n&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},pee=function(){var n=hee();return function(e,t){x.useEffect(function(){return n.add(e),function(){n.remove()}},[e&&t])}},dN=function(){var n=pee(),e=function(t){var r=t.styles,s=t.dynamic;return n(r,s),null};return e},fee={left:0,top:0,right:0,gap:0},Sb=function(n){return parseInt(n||"",10)||0},gee=function(n){var e=window.getComputedStyle(document.body),t=e[n==="padding"?"paddingLeft":"marginLeft"],r=e[n==="padding"?"paddingTop":"marginTop"],s=e[n==="padding"?"paddingRight":"marginRight"];return[Sb(t),Sb(r),Sb(s)]},mee=function(n){if(n===void 0&&(n="margin"),typeof window>"u")return fee;var e=gee(n),t=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-t+e[2]-e[0])}},yee=dN(),Vc="data-scroll-locked",See=function(n,e,t,r){var s=n.left,o=n.top,i=n.right,a=n.gap;return t===void 0&&(t="margin"),`
300
+ .`.concat(QQ,` {
301
+ overflow: hidden `).concat(r,`;
302
+ padding-right: `).concat(a,"px ").concat(r,`;
303
+ }
304
+ body[`).concat(Vc,`] {
305
+ overflow: hidden `).concat(r,`;
306
+ overscroll-behavior: contain;
307
+ `).concat([e&&"position: relative ".concat(r,";"),t==="margin"&&`
308
+ padding-left: `.concat(s,`px;
309
+ padding-top: `).concat(o,`px;
310
+ padding-right: `).concat(i,`px;
311
+ margin-left:0;
312
+ margin-top:0;
313
+ margin-right: `).concat(a,"px ").concat(r,`;
314
+ `),t==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
315
+ }
316
+
317
+ .`).concat(Gf,` {
318
+ right: `).concat(a,"px ").concat(r,`;
319
+ }
320
+
321
+ .`).concat(Yf,` {
322
+ margin-right: `).concat(a,"px ").concat(r,`;
323
+ }
324
+
325
+ .`).concat(Gf," .").concat(Gf,` {
326
+ right: 0 `).concat(r,`;
327
+ }
328
+
329
+ .`).concat(Yf," .").concat(Yf,` {
330
+ margin-right: 0 `).concat(r,`;
331
+ }
332
+
333
+ body[`).concat(Vc,`] {
334
+ `).concat(eee,": ").concat(a,`px;
335
+ }
336
+ `)},jE=function(){var n=parseInt(document.body.getAttribute(Vc)||"0",10);return isFinite(n)?n:0},xee=function(){x.useEffect(function(){return document.body.setAttribute(Vc,(jE()+1).toString()),function(){var n=jE()-1;n<=0?document.body.removeAttribute(Vc):document.body.setAttribute(Vc,n.toString())}},[])},bee=function(n){var e=n.noRelative,t=n.noImportant,r=n.gapMode,s=r===void 0?"margin":r;xee();var o=x.useMemo(function(){return mee(s)},[s]);return x.createElement(yee,{styles:See(o,!e,s,t?"":"!important")})},m0=!1;if(typeof window<"u")try{var rf=Object.defineProperty({},"passive",{get:function(){return m0=!0,!0}});window.addEventListener("test",rf,rf),window.removeEventListener("test",rf,rf)}catch{m0=!1}var fc=m0?{passive:!1}:!1,wee=function(n){return n.tagName==="TEXTAREA"},uN=function(n,e){if(!(n instanceof Element))return!1;var t=window.getComputedStyle(n);return t[e]!=="hidden"&&!(t.overflowY===t.overflowX&&!wee(n)&&t[e]==="visible")},vee=function(n){return uN(n,"overflowY")},Cee=function(n){return uN(n,"overflowX")},NE=function(n,e){var t=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=hN(n,r);if(s){var o=pN(n,r),i=o[1],a=o[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==t.body);return!1},Pee=function(n){var e=n.scrollTop,t=n.scrollHeight,r=n.clientHeight;return[e,t,r]},Tee=function(n){var e=n.scrollLeft,t=n.scrollWidth,r=n.clientWidth;return[e,t,r]},hN=function(n,e){return n==="v"?vee(e):Cee(e)},pN=function(n,e){return n==="v"?Pee(e):Tee(e)},Iee=function(n,e){return n==="h"&&e==="rtl"?-1:1},Eee=function(n,e,t,r,s){var o=Iee(n,window.getComputedStyle(e).direction),i=o*r,a=t.target,l=e.contains(a),c=!1,u=i>0,d=0,h=0;do{if(!a)break;var f=pN(n,a),g=f[0],m=f[1],y=f[2],S=m-y-o*g;(g||S)&&hN(n,a)&&(d+=S,h+=g);var b=a.parentNode;a=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&Math.abs(d)<1||!u&&Math.abs(h)<1)&&(c=!0),c},sf=function(n){return"changedTouches"in n?[n.changedTouches[0].clientX,n.changedTouches[0].clientY]:[0,0]},FE=function(n){return[n.deltaX,n.deltaY]},BE=function(n){return n&&"current"in n?n.current:n},kee=function(n,e){return n[0]===e[0]&&n[1]===e[1]},_ee=function(n){return`
337
+ .block-interactivity-`.concat(n,` {pointer-events: none;}
338
+ .allow-interactivity-`).concat(n,` {pointer-events: all;}
339
+ `)},Mee=0,gc=[];function Aee(n){var e=x.useRef([]),t=x.useRef([0,0]),r=x.useRef(),s=x.useState(Mee++)[0],o=x.useState(dN)[0],i=x.useRef(n);x.useEffect(function(){i.current=n},[n]),x.useEffect(function(){if(n.inert){document.body.classList.add("block-interactivity-".concat(s));var m=JQ([n.lockRef.current],(n.shards||[]).map(BE),!0).filter(Boolean);return m.forEach(function(y){return y.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(s))})}}},[n.inert,n.lockRef.current,n.shards]);var a=x.useCallback(function(m,y){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return!i.current.allowPinchZoom;var S=sf(m),b=t.current,w="deltaX"in m?m.deltaX:b[0]-S[0],v="deltaY"in m?m.deltaY:b[1]-S[1],P,T=m.target,I=Math.abs(w)>Math.abs(v)?"h":"v";if("touches"in m&&I==="h"&&T.type==="range")return!1;var k=window.getSelection(),A=k&&k.anchorNode,R=A?A===T||A.contains(T):!1;if(R)return!1;var D=NE(I,T);if(!D)return!0;if(D?P=I:(P=I==="v"?"h":"v",D=NE(I,T)),!D)return!1;if(!r.current&&"changedTouches"in m&&(w||v)&&(r.current=P),!P)return!0;var j=r.current||P;return Eee(j,y,m,j==="h"?w:v)},[]),l=x.useCallback(function(m){var y=m;if(!(!gc.length||gc[gc.length-1]!==o)){var S="deltaY"in y?FE(y):sf(y),b=e.current.filter(function(P){return P.name===y.type&&(P.target===y.target||y.target===P.shadowParent)&&kee(P.delta,S)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var w=(i.current.shards||[]).map(BE).filter(Boolean).filter(function(P){return P.contains(y.target)}),v=w.length>0?a(y,w[0]):!i.current.noIsolation;v&&y.cancelable&&y.preventDefault()}}},[]),c=x.useCallback(function(m,y,S,b){var w={name:m,delta:y,target:S,should:b,shadowParent:Dee(S)};e.current.push(w),setTimeout(function(){e.current=e.current.filter(function(v){return v!==w})},1)},[]),u=x.useCallback(function(m){t.current=sf(m),r.current=void 0},[]),d=x.useCallback(function(m){c(m.type,FE(m),m.target,a(m,n.lockRef.current))},[]),h=x.useCallback(function(m){c(m.type,sf(m),m.target,a(m,n.lockRef.current))},[]);x.useEffect(function(){return gc.push(o),n.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:h}),document.addEventListener("wheel",l,fc),document.addEventListener("touchmove",l,fc),document.addEventListener("touchstart",u,fc),function(){gc=gc.filter(function(m){return m!==o}),document.removeEventListener("wheel",l,fc),document.removeEventListener("touchmove",l,fc),document.removeEventListener("touchstart",u,fc)}},[]);var f=n.removeScrollBar,g=n.inert;return x.createElement(x.Fragment,null,g?x.createElement(o,{styles:_ee(s)}):null,f?x.createElement(bee,{noRelative:n.noRelative,gapMode:n.gapMode}):null)}function Dee(n){for(var e=null;n!==null;)n instanceof ShadowRoot&&(e=n.host,n=n.host),n=n.parentNode;return e}const Oee=aee(cN,Aee);var sp=x.forwardRef(function(n,e){return x.createElement(Jy,Bo({},n,{ref:e,sideCar:Oee}))});sp.classNames=Jy.classNames;var Ree=function(n){if(typeof document>"u")return null;var e=Array.isArray(n)?n[0]:n;return e.ownerDocument.body},mc=new WeakMap,of=new WeakMap,af={},xb=0,fN=function(n){return n&&(n.host||fN(n.parentNode))},Lee=function(n,e){return e.map(function(t){if(n.contains(t))return t;var r=fN(t);return r&&n.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",n,". Doing nothing"),null)}).filter(function(t){return!!t})},jee=function(n,e,t,r){var s=Lee(e,Array.isArray(n)?n:[n]);af[t]||(af[t]=new WeakMap);var o=af[t],i=[],a=new Set,l=new Set(s),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};s.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(h){if(a.has(h))u(h);else try{var f=h.getAttribute(r),g=f!==null&&f!=="false",m=(mc.get(h)||0)+1,y=(o.get(h)||0)+1;mc.set(h,m),o.set(h,y),i.push(h),m===1&&g&&of.set(h,!0),y===1&&h.setAttribute(t,"true"),g||h.setAttribute(r,"true")}catch(S){console.error("aria-hidden: cannot operate on ",h,S)}})};return u(e),a.clear(),xb++,function(){i.forEach(function(d){var h=mc.get(d)-1,f=o.get(d)-1;mc.set(d,h),o.set(d,f),h||(of.has(d)||d.removeAttribute(r),of.delete(d)),f||d.removeAttribute(t)}),xb--,xb||(mc=new WeakMap,mc=new WeakMap,of=new WeakMap,af={})}},Qy=function(n,e,t){t===void 0&&(t="data-aria-hidden");var r=Array.from(Array.isArray(n)?n:[n]),s=Ree(n);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live], script"))),jee(r,s,t,"aria-hidden")):function(){return null}},eS="Dialog",[gN]=rs(eS),[Nee,To]=gN(eS),mN=n=>{const{__scopeDialog:e,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!0}=n,a=x.useRef(null),l=x.useRef(null),[c,u]=Ys({prop:r,defaultProp:s??!1,onChange:o,caller:eS});return p.jsx(Nee,{scope:e,triggerRef:a,contentRef:l,contentId:Ks(),titleId:Ks(),descriptionId:Ks(),open:c,onOpenChange:u,onOpenToggle:x.useCallback(()=>u(d=>!d),[u]),modal:i,children:t})};mN.displayName=eS;var yN="DialogTrigger",Fee=x.forwardRef((n,e)=>{const{__scopeDialog:t,...r}=n,s=To(yN,t),o=nt(e,s.triggerRef);return p.jsx(ke.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":q1(s.open),...r,ref:o,onClick:le(n.onClick,s.onOpenToggle)})});Fee.displayName=yN;var Y1="DialogPortal",[Bee,SN]=gN(Y1,{forceMount:void 0}),xN=n=>{const{__scopeDialog:e,forceMount:t,children:r,container:s}=n,o=To(Y1,e);return p.jsx(Bee,{scope:e,forceMount:t,children:x.Children.map(r,i=>p.jsx(Xs,{present:t||o.open,children:p.jsx(rp,{asChild:!0,container:s,children:i})}))})};xN.displayName=Y1;var am="DialogOverlay",bN=x.forwardRef((n,e)=>{const t=SN(am,n.__scopeDialog),{forceMount:r=t.forceMount,...s}=n,o=To(am,n.__scopeDialog);return o.modal?p.jsx(Xs,{present:r||o.open,children:p.jsx($ee,{...s,ref:e})}):null});bN.displayName=am;var zee=Fa("DialogOverlay.RemoveScroll"),$ee=x.forwardRef((n,e)=>{const{__scopeDialog:t,...r}=n,s=To(am,t);return p.jsx(sp,{as:zee,allowPinchZoom:!0,shards:[s.contentRef],children:p.jsx(ke.div,{"data-state":q1(s.open),...r,ref:e,style:{pointerEvents:"auto",...r.style}})})}),jl="DialogContent",wN=x.forwardRef((n,e)=>{const t=SN(jl,n.__scopeDialog),{forceMount:r=t.forceMount,...s}=n,o=To(jl,n.__scopeDialog);return p.jsx(Xs,{present:r||o.open,children:o.modal?p.jsx(Hee,{...s,ref:e}):p.jsx(Uee,{...s,ref:e})})});wN.displayName=jl;var Hee=x.forwardRef((n,e)=>{const t=To(jl,n.__scopeDialog),r=x.useRef(null),s=nt(e,t.contentRef,r);return x.useEffect(()=>{const o=r.current;if(o)return Qy(o)},[]),p.jsx(vN,{...n,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:le(n.onCloseAutoFocus,o=>{var i;o.preventDefault(),(i=t.triggerRef.current)==null||i.focus()}),onPointerDownOutside:le(n.onPointerDownOutside,o=>{const i=o.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&o.preventDefault()}),onFocusOutside:le(n.onFocusOutside,o=>o.preventDefault())})}),Uee=x.forwardRef((n,e)=>{const t=To(jl,n.__scopeDialog),r=x.useRef(!1),s=x.useRef(!1);return p.jsx(vN,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=n.onCloseAutoFocus)==null||i.call(n,o),o.defaultPrevented||(r.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var l,c;(l=n.onInteractOutside)==null||l.call(n,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const i=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(i))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),vN=x.forwardRef((n,e)=>{const{__scopeDialog:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...i}=n,a=To(jl,t),l=x.useRef(null),c=nt(e,l);return Zy(),p.jsxs(p.Fragment,{children:[p.jsx(np,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:p.jsx(Zl,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":q1(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),p.jsxs(p.Fragment,{children:[p.jsx(Wee,{titleId:a.titleId}),p.jsx(Gee,{contentRef:l,descriptionId:a.descriptionId})]})]})}),X1="DialogTitle",CN=x.forwardRef((n,e)=>{const{__scopeDialog:t,...r}=n,s=To(X1,t);return p.jsx(ke.h2,{id:s.titleId,...r,ref:e})});CN.displayName=X1;var PN="DialogDescription",Kee=x.forwardRef((n,e)=>{const{__scopeDialog:t,...r}=n,s=To(PN,t);return p.jsx(ke.p,{id:s.descriptionId,...r,ref:e})});Kee.displayName=PN;var TN="DialogClose",IN=x.forwardRef((n,e)=>{const{__scopeDialog:t,...r}=n,s=To(TN,t);return p.jsx(ke.button,{type:"button",...r,ref:e,onClick:le(n.onClick,()=>s.onOpenChange(!1))})});IN.displayName=TN;function q1(n){return n?"open":"closed"}var EN="DialogTitleWarning",[kye,kN]=PQ(EN,{contentName:jl,titleName:X1,docsSlug:"dialog"}),Wee=({titleId:n})=>{const e=kN(EN),t=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.
340
+
341
+ If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
342
+
343
+ For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return x.useEffect(()=>{n&&(document.getElementById(n)||console.error(t))},[t,n]),null},Vee="DialogDescriptionWarning",Gee=({contentRef:n,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${kN(Vee).contentName}}.`;return x.useEffect(()=>{var o;const s=(o=n.current)==null?void 0:o.getAttribute("aria-describedby");e&&s&&(document.getElementById(e)||console.warn(r))},[r,n,e]),null},Yee=mN,Xee=xN,qee=bN,Zee=wN,Jee=CN;function _N(n){const e=x.useRef({value:n,previous:n});return x.useMemo(()=>(e.current.value!==n&&(e.current.previous=e.current.value,e.current.value=n),e.current.previous),[n])}function MN(n){const[e,t]=x.useState(void 0);return Wn(()=>{if(n){t({width:n.offsetWidth,height:n.offsetHeight});const r=new ResizeObserver(s=>{if(!Array.isArray(s)||!s.length)return;const o=s[0];let i,a;if("borderBoxSize"in o){const l=o.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=n.offsetWidth,a=n.offsetHeight;t({width:i,height:a})});return r.observe(n,{box:"border-box"}),()=>r.unobserve(n)}else t(void 0)},[n]),e}const Qee=["top","right","bottom","left"],Ba=Math.min,hs=Math.max,lm=Math.round,lf=Math.floor,Wo=n=>({x:n,y:n}),ete={left:"right",right:"left",bottom:"top",top:"bottom"},tte={start:"end",end:"start"};function y0(n,e,t){return hs(n,Ba(e,t))}function Ui(n,e){return typeof n=="function"?n(e):n}function Ki(n){return n.split("-")[0]}function wd(n){return n.split("-")[1]}function Z1(n){return n==="x"?"y":"x"}function J1(n){return n==="y"?"height":"width"}const nte=new Set(["top","bottom"]);function Ho(n){return nte.has(Ki(n))?"y":"x"}function Q1(n){return Z1(Ho(n))}function rte(n,e,t){t===void 0&&(t=!1);const r=wd(n),s=Q1(n),o=J1(s);let i=s==="x"?r===(t?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[o]>e.floating[o]&&(i=cm(i)),[i,cm(i)]}function ste(n){const e=cm(n);return[S0(n),e,S0(e)]}function S0(n){return n.replace(/start|end/g,e=>tte[e])}const zE=["left","right"],$E=["right","left"],ote=["top","bottom"],ite=["bottom","top"];function ate(n,e,t){switch(n){case"top":case"bottom":return t?e?$E:zE:e?zE:$E;case"left":case"right":return e?ote:ite;default:return[]}}function lte(n,e,t,r){const s=wd(n);let o=ate(Ki(n),t==="start",r);return s&&(o=o.map(i=>i+"-"+s),e&&(o=o.concat(o.map(S0)))),o}function cm(n){return n.replace(/left|right|bottom|top/g,e=>ete[e])}function cte(n){return{top:0,right:0,bottom:0,left:0,...n}}function AN(n){return typeof n!="number"?cte(n):{top:n,right:n,bottom:n,left:n}}function dm(n){const{x:e,y:t,width:r,height:s}=n;return{width:r,height:s,top:t,left:e,right:e+r,bottom:t+s,x:e,y:t}}function HE(n,e,t){let{reference:r,floating:s}=n;const o=Ho(e),i=Q1(e),a=J1(i),l=Ki(e),c=o==="y",u=r.x+r.width/2-s.width/2,d=r.y+r.height/2-s.height/2,h=r[a]/2-s[a]/2;let f;switch(l){case"top":f={x:u,y:r.y-s.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:d};break;case"left":f={x:r.x-s.width,y:d};break;default:f={x:r.x,y:r.y}}switch(wd(e)){case"start":f[i]-=h*(t&&c?-1:1);break;case"end":f[i]+=h*(t&&c?-1:1);break}return f}async function dte(n,e){var t;e===void 0&&(e={});const{x:r,y:s,platform:o,rects:i,elements:a,strategy:l}=n,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:h=!1,padding:f=0}=Ui(e,n),g=AN(f),y=a[h?d==="floating"?"reference":"floating":d],S=dm(await o.getClippingRect({element:(t=await(o.isElement==null?void 0:o.isElement(y)))==null||t?y:y.contextElement||await(o.getDocumentElement==null?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),b=d==="floating"?{x:r,y:s,width:i.floating.width,height:i.floating.height}:i.reference,w=await(o.getOffsetParent==null?void 0:o.getOffsetParent(a.floating)),v=await(o.isElement==null?void 0:o.isElement(w))?await(o.getScale==null?void 0:o.getScale(w))||{x:1,y:1}:{x:1,y:1},P=dm(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:b,offsetParent:w,strategy:l}):b);return{top:(S.top-P.top+g.top)/v.y,bottom:(P.bottom-S.bottom+g.bottom)/v.y,left:(S.left-P.left+g.left)/v.x,right:(P.right-S.right+g.right)/v.x}}const ute=async(n,e,t)=>{const{placement:r="bottom",strategy:s="absolute",middleware:o=[],platform:i}=t,a=o.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(e));let c=await i.getElementRects({reference:n,floating:e,strategy:s}),{x:u,y:d}=HE(c,r,l),h=r,f={},g=0;for(let y=0;y<a.length;y++){var m;const{name:S,fn:b}=a[y],{x:w,y:v,data:P,reset:T}=await b({x:u,y:d,initialPlacement:r,placement:h,strategy:s,middlewareData:f,rects:c,platform:{...i,detectOverflow:(m=i.detectOverflow)!=null?m:dte},elements:{reference:n,floating:e}});u=w??u,d=v??d,f={...f,[S]:{...f[S],...P}},T&&g<=50&&(g++,typeof T=="object"&&(T.placement&&(h=T.placement),T.rects&&(c=T.rects===!0?await i.getElementRects({reference:n,floating:e,strategy:s}):T.rects),{x:u,y:d}=HE(c,h,l)),y=-1)}return{x:u,y:d,placement:h,strategy:s,middlewareData:f}},hte=n=>({name:"arrow",options:n,async fn(e){const{x:t,y:r,placement:s,rects:o,platform:i,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=Ui(n,e)||{};if(c==null)return{};const d=AN(u),h={x:t,y:r},f=Q1(s),g=J1(f),m=await i.getDimensions(c),y=f==="y",S=y?"top":"left",b=y?"bottom":"right",w=y?"clientHeight":"clientWidth",v=o.reference[g]+o.reference[f]-h[f]-o.floating[g],P=h[f]-o.reference[f],T=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=T?T[w]:0;(!I||!await(i.isElement==null?void 0:i.isElement(T)))&&(I=a.floating[w]||o.floating[g]);const k=v/2-P/2,A=I/2-m[g]/2-1,R=Ba(d[S],A),D=Ba(d[b],A),j=R,_=I-m[g]-D,M=I/2-m[g]/2+k,O=y0(j,M,_),N=!l.arrow&&wd(s)!=null&&M!==O&&o.reference[g]/2-(M<j?R:D)-m[g]/2<0,B=N?M<j?M-j:M-_:0;return{[f]:h[f]+B,data:{[f]:O,centerOffset:M-O-B,...N&&{alignmentOffset:B}},reset:N}}}),pte=function(n){return n===void 0&&(n={}),{name:"flip",options:n,async fn(e){var t,r;const{placement:s,middlewareData:o,rects:i,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:h,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...y}=Ui(n,e);if((t=o.arrow)!=null&&t.alignmentOffset)return{};const S=Ki(s),b=Ho(a),w=Ki(a)===a,v=await(l.isRTL==null?void 0:l.isRTL(c.floating)),P=h||(w||!m?[cm(a)]:ste(a)),T=g!=="none";!h&&T&&P.push(...lte(a,m,g,v));const I=[a,...P],k=await l.detectOverflow(e,y),A=[];let R=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&A.push(k[S]),d){const M=rte(s,i,v);A.push(k[M[0]],k[M[1]])}if(R=[...R,{placement:s,overflows:A}],!A.every(M=>M<=0)){var D,j;const M=(((D=o.flip)==null?void 0:D.index)||0)+1,O=I[M];if(O&&(!(d==="alignment"?b!==Ho(O):!1)||R.every(H=>Ho(H.placement)===b?H.overflows[0]>0:!0)))return{data:{index:M,overflows:R},reset:{placement:O}};let N=(j=R.filter(B=>B.overflows[0]<=0).sort((B,H)=>B.overflows[1]-H.overflows[1])[0])==null?void 0:j.placement;if(!N)switch(f){case"bestFit":{var _;const B=(_=R.filter(H=>{if(T){const z=Ho(H.placement);return z===b||z==="y"}return!0}).map(H=>[H.placement,H.overflows.filter(z=>z>0).reduce((z,X)=>z+X,0)]).sort((H,z)=>H[1]-z[1])[0])==null?void 0:_[0];B&&(N=B);break}case"initialPlacement":N=a;break}if(s!==N)return{reset:{placement:N}}}return{}}}};function UE(n,e){return{top:n.top-e.height,right:n.right-e.width,bottom:n.bottom-e.height,left:n.left-e.width}}function KE(n){return Qee.some(e=>n[e]>=0)}const fte=function(n){return n===void 0&&(n={}),{name:"hide",options:n,async fn(e){const{rects:t,platform:r}=e,{strategy:s="referenceHidden",...o}=Ui(n,e);switch(s){case"referenceHidden":{const i=await r.detectOverflow(e,{...o,elementContext:"reference"}),a=UE(i,t.reference);return{data:{referenceHiddenOffsets:a,referenceHidden:KE(a)}}}case"escaped":{const i=await r.detectOverflow(e,{...o,altBoundary:!0}),a=UE(i,t.floating);return{data:{escapedOffsets:a,escaped:KE(a)}}}default:return{}}}}},DN=new Set(["left","top"]);async function gte(n,e){const{placement:t,platform:r,elements:s}=n,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),i=Ki(t),a=wd(t),l=Ho(t)==="y",c=DN.has(i)?-1:1,u=o&&l?-1:1,d=Ui(e,n);let{mainAxis:h,crossAxis:f,alignmentAxis:g}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof g=="number"&&(f=a==="end"?g*-1:g),l?{x:f*u,y:h*c}:{x:h*c,y:f*u}}const mte=function(n){return n===void 0&&(n=0),{name:"offset",options:n,async fn(e){var t,r;const{x:s,y:o,placement:i,middlewareData:a}=e,l=await gte(e,n);return i===((t=a.offset)==null?void 0:t.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:s+l.x,y:o+l.y,data:{...l,placement:i}}}}},yte=function(n){return n===void 0&&(n={}),{name:"shift",options:n,async fn(e){const{x:t,y:r,placement:s,platform:o}=e,{mainAxis:i=!0,crossAxis:a=!1,limiter:l={fn:S=>{let{x:b,y:w}=S;return{x:b,y:w}}},...c}=Ui(n,e),u={x:t,y:r},d=await o.detectOverflow(e,c),h=Ho(Ki(s)),f=Z1(h);let g=u[f],m=u[h];if(i){const S=f==="y"?"top":"left",b=f==="y"?"bottom":"right",w=g+d[S],v=g-d[b];g=y0(w,g,v)}if(a){const S=h==="y"?"top":"left",b=h==="y"?"bottom":"right",w=m+d[S],v=m-d[b];m=y0(w,m,v)}const y=l.fn({...e,[f]:g,[h]:m});return{...y,data:{x:y.x-t,y:y.y-r,enabled:{[f]:i,[h]:a}}}}}},Ste=function(n){return n===void 0&&(n={}),{options:n,fn(e){const{x:t,y:r,placement:s,rects:o,middlewareData:i}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=Ui(n,e),u={x:t,y:r},d=Ho(s),h=Z1(d);let f=u[h],g=u[d];const m=Ui(a,e),y=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const w=h==="y"?"height":"width",v=o.reference[h]-o.floating[w]+y.mainAxis,P=o.reference[h]+o.reference[w]-y.mainAxis;f<v?f=v:f>P&&(f=P)}if(c){var S,b;const w=h==="y"?"width":"height",v=DN.has(Ki(s)),P=o.reference[d]-o.floating[w]+(v&&((S=i.offset)==null?void 0:S[d])||0)+(v?0:y.crossAxis),T=o.reference[d]+o.reference[w]+(v?0:((b=i.offset)==null?void 0:b[d])||0)-(v?y.crossAxis:0);g<P?g=P:g>T&&(g=T)}return{[h]:f,[d]:g}}}},xte=function(n){return n===void 0&&(n={}),{name:"size",options:n,async fn(e){var t,r;const{placement:s,rects:o,platform:i,elements:a}=e,{apply:l=()=>{},...c}=Ui(n,e),u=await i.detectOverflow(e,c),d=Ki(s),h=wd(s),f=Ho(s)==="y",{width:g,height:m}=o.floating;let y,S;d==="top"||d==="bottom"?(y=d,S=h===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(S=d,y=h==="end"?"top":"bottom");const b=m-u.top-u.bottom,w=g-u.left-u.right,v=Ba(m-u[y],b),P=Ba(g-u[S],w),T=!e.middlewareData.shift;let I=v,k=P;if((t=e.middlewareData.shift)!=null&&t.enabled.x&&(k=w),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(I=b),T&&!h){const R=hs(u.left,0),D=hs(u.right,0),j=hs(u.top,0),_=hs(u.bottom,0);f?k=g-2*(R!==0||D!==0?R+D:hs(u.left,u.right)):I=m-2*(j!==0||_!==0?j+_:hs(u.top,u.bottom))}await l({...e,availableWidth:k,availableHeight:I});const A=await i.getDimensions(a.floating);return g!==A.width||m!==A.height?{reset:{rects:!0}}:{}}}};function tS(){return typeof window<"u"}function vd(n){return ON(n)?(n.nodeName||"").toLowerCase():"#document"}function xs(n){var e;return(n==null||(e=n.ownerDocument)==null?void 0:e.defaultView)||window}function Qo(n){var e;return(e=(ON(n)?n.ownerDocument:n.document)||window.document)==null?void 0:e.documentElement}function ON(n){return tS()?n instanceof Node||n instanceof xs(n).Node:!1}function wo(n){return tS()?n instanceof Element||n instanceof xs(n).Element:!1}function Xo(n){return tS()?n instanceof HTMLElement||n instanceof xs(n).HTMLElement:!1}function WE(n){return!tS()||typeof ShadowRoot>"u"?!1:n instanceof ShadowRoot||n instanceof xs(n).ShadowRoot}const bte=new Set(["inline","contents"]);function op(n){const{overflow:e,overflowX:t,overflowY:r,display:s}=vo(n);return/auto|scroll|overlay|hidden|clip/.test(e+r+t)&&!bte.has(s)}const wte=new Set(["table","td","th"]);function vte(n){return wte.has(vd(n))}const Cte=[":popover-open",":modal"];function nS(n){return Cte.some(e=>{try{return n.matches(e)}catch{return!1}})}const Pte=["transform","translate","scale","rotate","perspective"],Tte=["transform","translate","scale","rotate","perspective","filter"],Ite=["paint","layout","strict","content"];function eC(n){const e=tC(),t=wo(n)?vo(n):n;return Pte.some(r=>t[r]?t[r]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!e&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!e&&(t.filter?t.filter!=="none":!1)||Tte.some(r=>(t.willChange||"").includes(r))||Ite.some(r=>(t.contain||"").includes(r))}function Ete(n){let e=za(n);for(;Xo(e)&&!ad(e);){if(eC(e))return e;if(nS(e))return null;e=za(e)}return null}function tC(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}const kte=new Set(["html","body","#document"]);function ad(n){return kte.has(vd(n))}function vo(n){return xs(n).getComputedStyle(n)}function rS(n){return wo(n)?{scrollLeft:n.scrollLeft,scrollTop:n.scrollTop}:{scrollLeft:n.scrollX,scrollTop:n.scrollY}}function za(n){if(vd(n)==="html")return n;const e=n.assignedSlot||n.parentNode||WE(n)&&n.host||Qo(n);return WE(e)?e.host:e}function RN(n){const e=za(n);return ad(e)?n.ownerDocument?n.ownerDocument.body:n.body:Xo(e)&&op(e)?e:RN(e)}function yh(n,e,t){var r;e===void 0&&(e=[]),t===void 0&&(t=!0);const s=RN(n),o=s===((r=n.ownerDocument)==null?void 0:r.body),i=xs(s);if(o){const a=x0(i);return e.concat(i,i.visualViewport||[],op(s)?s:[],a&&t?yh(a):[])}return e.concat(s,yh(s,[],t))}function x0(n){return n.parent&&Object.getPrototypeOf(n.parent)?n.frameElement:null}function LN(n){const e=vo(n);let t=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const s=Xo(n),o=s?n.offsetWidth:t,i=s?n.offsetHeight:r,a=lm(t)!==o||lm(r)!==i;return a&&(t=o,r=i),{width:t,height:r,$:a}}function nC(n){return wo(n)?n:n.contextElement}function Gc(n){const e=nC(n);if(!Xo(e))return Wo(1);const t=e.getBoundingClientRect(),{width:r,height:s,$:o}=LN(e);let i=(o?lm(t.width):t.width)/r,a=(o?lm(t.height):t.height)/s;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const _te=Wo(0);function jN(n){const e=xs(n);return!tC()||!e.visualViewport?_te:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function Mte(n,e,t){return e===void 0&&(e=!1),!t||e&&t!==xs(n)?!1:e}function Nl(n,e,t,r){e===void 0&&(e=!1),t===void 0&&(t=!1);const s=n.getBoundingClientRect(),o=nC(n);let i=Wo(1);e&&(r?wo(r)&&(i=Gc(r)):i=Gc(n));const a=Mte(o,t,r)?jN(o):Wo(0);let l=(s.left+a.x)/i.x,c=(s.top+a.y)/i.y,u=s.width/i.x,d=s.height/i.y;if(o){const h=xs(o),f=r&&wo(r)?xs(r):r;let g=h,m=x0(g);for(;m&&r&&f!==g;){const y=Gc(m),S=m.getBoundingClientRect(),b=vo(m),w=S.left+(m.clientLeft+parseFloat(b.paddingLeft))*y.x,v=S.top+(m.clientTop+parseFloat(b.paddingTop))*y.y;l*=y.x,c*=y.y,u*=y.x,d*=y.y,l+=w,c+=v,g=xs(m),m=x0(g)}}return dm({width:u,height:d,x:l,y:c})}function sS(n,e){const t=rS(n).scrollLeft;return e?e.left+t:Nl(Qo(n)).left+t}function NN(n,e){const t=n.getBoundingClientRect(),r=t.left+e.scrollLeft-sS(n,t),s=t.top+e.scrollTop;return{x:r,y:s}}function Ate(n){let{elements:e,rect:t,offsetParent:r,strategy:s}=n;const o=s==="fixed",i=Qo(r),a=e?nS(e.floating):!1;if(r===i||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Wo(1);const u=Wo(0),d=Xo(r);if((d||!d&&!o)&&((vd(r)!=="body"||op(i))&&(l=rS(r)),Xo(r))){const f=Nl(r);c=Gc(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const h=i&&!d&&!o?NN(i,l):Wo(0);return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x+h.x,y:t.y*c.y-l.scrollTop*c.y+u.y+h.y}}function Dte(n){return Array.from(n.getClientRects())}function Ote(n){const e=Qo(n),t=rS(n),r=n.ownerDocument.body,s=hs(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),o=hs(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-t.scrollLeft+sS(n);const a=-t.scrollTop;return vo(r).direction==="rtl"&&(i+=hs(e.clientWidth,r.clientWidth)-s),{width:s,height:o,x:i,y:a}}const VE=25;function Rte(n,e){const t=xs(n),r=Qo(n),s=t.visualViewport;let o=r.clientWidth,i=r.clientHeight,a=0,l=0;if(s){o=s.width,i=s.height;const u=tC();(!u||u&&e==="fixed")&&(a=s.offsetLeft,l=s.offsetTop)}const c=sS(r);if(c<=0){const u=r.ownerDocument,d=u.body,h=getComputedStyle(d),f=u.compatMode==="CSS1Compat"&&parseFloat(h.marginLeft)+parseFloat(h.marginRight)||0,g=Math.abs(r.clientWidth-d.clientWidth-f);g<=VE&&(o-=g)}else c<=VE&&(o+=c);return{width:o,height:i,x:a,y:l}}const Lte=new Set(["absolute","fixed"]);function jte(n,e){const t=Nl(n,!0,e==="fixed"),r=t.top+n.clientTop,s=t.left+n.clientLeft,o=Xo(n)?Gc(n):Wo(1),i=n.clientWidth*o.x,a=n.clientHeight*o.y,l=s*o.x,c=r*o.y;return{width:i,height:a,x:l,y:c}}function GE(n,e,t){let r;if(e==="viewport")r=Rte(n,t);else if(e==="document")r=Ote(Qo(n));else if(wo(e))r=jte(e,t);else{const s=jN(n);r={x:e.x-s.x,y:e.y-s.y,width:e.width,height:e.height}}return dm(r)}function FN(n,e){const t=za(n);return t===e||!wo(t)||ad(t)?!1:vo(t).position==="fixed"||FN(t,e)}function Nte(n,e){const t=e.get(n);if(t)return t;let r=yh(n,[],!1).filter(a=>wo(a)&&vd(a)!=="body"),s=null;const o=vo(n).position==="fixed";let i=o?za(n):n;for(;wo(i)&&!ad(i);){const a=vo(i),l=eC(i);!l&&a.position==="fixed"&&(s=null),(o?!l&&!s:!l&&a.position==="static"&&!!s&&Lte.has(s.position)||op(i)&&!l&&FN(n,i))?r=r.filter(u=>u!==i):s=a,i=za(i)}return e.set(n,r),r}function Fte(n){let{element:e,boundary:t,rootBoundary:r,strategy:s}=n;const i=[...t==="clippingAncestors"?nS(e)?[]:Nte(e,this._c):[].concat(t),r],a=i[0],l=i.reduce((c,u)=>{const d=GE(e,u,s);return c.top=hs(d.top,c.top),c.right=Ba(d.right,c.right),c.bottom=Ba(d.bottom,c.bottom),c.left=hs(d.left,c.left),c},GE(e,a,s));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Bte(n){const{width:e,height:t}=LN(n);return{width:e,height:t}}function zte(n,e,t){const r=Xo(e),s=Qo(e),o=t==="fixed",i=Nl(n,!0,o,e);let a={scrollLeft:0,scrollTop:0};const l=Wo(0);function c(){l.x=sS(s)}if(r||!r&&!o)if((vd(e)!=="body"||op(s))&&(a=rS(e)),r){const f=Nl(e,!0,o,e);l.x=f.x+e.clientLeft,l.y=f.y+e.clientTop}else s&&c();o&&!r&&s&&c();const u=s&&!r&&!o?NN(s,a):Wo(0),d=i.left+a.scrollLeft-l.x-u.x,h=i.top+a.scrollTop-l.y-u.y;return{x:d,y:h,width:i.width,height:i.height}}function bb(n){return vo(n).position==="static"}function YE(n,e){if(!Xo(n)||vo(n).position==="fixed")return null;if(e)return e(n);let t=n.offsetParent;return Qo(n)===t&&(t=t.ownerDocument.body),t}function BN(n,e){const t=xs(n);if(nS(n))return t;if(!Xo(n)){let s=za(n);for(;s&&!ad(s);){if(wo(s)&&!bb(s))return s;s=za(s)}return t}let r=YE(n,e);for(;r&&vte(r)&&bb(r);)r=YE(r,e);return r&&ad(r)&&bb(r)&&!eC(r)?t:r||Ete(n)||t}const $te=async function(n){const e=this.getOffsetParent||BN,t=this.getDimensions,r=await t(n.floating);return{reference:zte(n.reference,await e(n.floating),n.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Hte(n){return vo(n).direction==="rtl"}const Ute={convertOffsetParentRelativeRectToViewportRelativeRect:Ate,getDocumentElement:Qo,getClippingRect:Fte,getOffsetParent:BN,getElementRects:$te,getClientRects:Dte,getDimensions:Bte,getScale:Gc,isElement:wo,isRTL:Hte};function zN(n,e){return n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height}function Kte(n,e){let t=null,r;const s=Qo(n);function o(){var a;clearTimeout(r),(a=t)==null||a.disconnect(),t=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),o();const c=n.getBoundingClientRect(),{left:u,top:d,width:h,height:f}=c;if(a||e(),!h||!f)return;const g=lf(d),m=lf(s.clientWidth-(u+h)),y=lf(s.clientHeight-(d+f)),S=lf(u),w={rootMargin:-g+"px "+-m+"px "+-y+"px "+-S+"px",threshold:hs(0,Ba(1,l))||1};let v=!0;function P(T){const I=T[0].intersectionRatio;if(I!==l){if(!v)return i();I?i(!1,I):r=setTimeout(()=>{i(!1,1e-7)},1e3)}I===1&&!zN(c,n.getBoundingClientRect())&&i(),v=!1}try{t=new IntersectionObserver(P,{...w,root:s.ownerDocument})}catch{t=new IntersectionObserver(P,w)}t.observe(n)}return i(!0),o}function Wte(n,e,t,r){r===void 0&&(r={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=nC(n),u=s||o?[...c?yh(c):[],...yh(e)]:[];u.forEach(S=>{s&&S.addEventListener("scroll",t,{passive:!0}),o&&S.addEventListener("resize",t)});const d=c&&a?Kte(c,t):null;let h=-1,f=null;i&&(f=new ResizeObserver(S=>{let[b]=S;b&&b.target===c&&f&&(f.unobserve(e),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(e)})),t()}),c&&!l&&f.observe(c),f.observe(e));let g,m=l?Nl(n):null;l&&y();function y(){const S=Nl(n);m&&!zN(m,S)&&t(),m=S,g=requestAnimationFrame(y)}return t(),()=>{var S;u.forEach(b=>{s&&b.removeEventListener("scroll",t),o&&b.removeEventListener("resize",t)}),d==null||d(),(S=f)==null||S.disconnect(),f=null,l&&cancelAnimationFrame(g)}}const Vte=mte,Gte=yte,Yte=pte,Xte=xte,qte=fte,XE=hte,Zte=Ste,Jte=(n,e,t)=>{const r=new Map,s={platform:Ute,...t},o={...s.platform,_c:r};return ute(n,e,{...s,platform:o})};var Qte=typeof document<"u",ene=function(){},Xf=Qte?x.useLayoutEffect:ene;function um(n,e){if(n===e)return!0;if(typeof n!=typeof e)return!1;if(typeof n=="function"&&n.toString()===e.toString())return!0;let t,r,s;if(n&&e&&typeof n=="object"){if(Array.isArray(n)){if(t=n.length,t!==e.length)return!1;for(r=t;r--!==0;)if(!um(n[r],e[r]))return!1;return!0}if(s=Object.keys(n),t=s.length,t!==Object.keys(e).length)return!1;for(r=t;r--!==0;)if(!{}.hasOwnProperty.call(e,s[r]))return!1;for(r=t;r--!==0;){const o=s[r];if(!(o==="_owner"&&n.$$typeof)&&!um(n[o],e[o]))return!1}return!0}return n!==n&&e!==e}function $N(n){return typeof window>"u"?1:(n.ownerDocument.defaultView||window).devicePixelRatio||1}function qE(n,e){const t=$N(n);return Math.round(e*t)/t}function wb(n){const e=x.useRef(n);return Xf(()=>{e.current=n}),e}function tne(n){n===void 0&&(n={});const{placement:e="bottom",strategy:t="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=n,[u,d]=x.useState({x:0,y:0,strategy:t,placement:e,middlewareData:{},isPositioned:!1}),[h,f]=x.useState(r);um(h,r)||f(r);const[g,m]=x.useState(null),[y,S]=x.useState(null),b=x.useCallback(H=>{H!==T.current&&(T.current=H,m(H))},[]),w=x.useCallback(H=>{H!==I.current&&(I.current=H,S(H))},[]),v=o||g,P=i||y,T=x.useRef(null),I=x.useRef(null),k=x.useRef(u),A=l!=null,R=wb(l),D=wb(s),j=wb(c),_=x.useCallback(()=>{if(!T.current||!I.current)return;const H={placement:e,strategy:t,middleware:h};D.current&&(H.platform=D.current),Jte(T.current,I.current,H).then(z=>{const X={...z,isPositioned:j.current!==!1};M.current&&!um(k.current,X)&&(k.current=X,Vi.flushSync(()=>{d(X)}))})},[h,e,t,D,j]);Xf(()=>{c===!1&&k.current.isPositioned&&(k.current.isPositioned=!1,d(H=>({...H,isPositioned:!1})))},[c]);const M=x.useRef(!1);Xf(()=>(M.current=!0,()=>{M.current=!1}),[]),Xf(()=>{if(v&&(T.current=v),P&&(I.current=P),v&&P){if(R.current)return R.current(v,P,_);_()}},[v,P,_,R,A]);const O=x.useMemo(()=>({reference:T,floating:I,setReference:b,setFloating:w}),[b,w]),N=x.useMemo(()=>({reference:v,floating:P}),[v,P]),B=x.useMemo(()=>{const H={position:t,left:0,top:0};if(!N.floating)return H;const z=qE(N.floating,u.x),X=qE(N.floating,u.y);return a?{...H,transform:"translate("+z+"px, "+X+"px)",...$N(N.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:z,top:X}},[t,a,N.floating,u.x,u.y]);return x.useMemo(()=>({...u,update:_,refs:O,elements:N,floatingStyles:B}),[u,_,O,N,B])}const nne=n=>{function e(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:n,fn(t){const{element:r,padding:s}=typeof n=="function"?n(t):n;return r&&e(r)?r.current!=null?XE({element:r.current,padding:s}).fn(t):{}:r?XE({element:r,padding:s}).fn(t):{}}}},rne=(n,e)=>({...Vte(n),options:[n,e]}),sne=(n,e)=>({...Gte(n),options:[n,e]}),one=(n,e)=>({...Zte(n),options:[n,e]}),ine=(n,e)=>({...Yte(n),options:[n,e]}),ane=(n,e)=>({...Xte(n),options:[n,e]}),lne=(n,e)=>({...qte(n),options:[n,e]}),cne=(n,e)=>({...nne(n),options:[n,e]});var dne="Arrow",HN=x.forwardRef((n,e)=>{const{children:t,width:r=10,height:s=5,...o}=n;return p.jsx(ke.svg,{...o,ref:e,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:n.asChild?t:p.jsx("polygon",{points:"0,0 30,0 15,10"})})});HN.displayName=dne;var une=HN,rC="Popper",[UN,Ja]=rs(rC),[hne,KN]=UN(rC),WN=n=>{const{__scopePopper:e,children:t}=n,[r,s]=x.useState(null);return p.jsx(hne,{scope:e,anchor:r,onAnchorChange:s,children:t})};WN.displayName=rC;var VN="PopperAnchor",GN=x.forwardRef((n,e)=>{const{__scopePopper:t,virtualRef:r,...s}=n,o=KN(VN,t),i=x.useRef(null),a=nt(e,i),l=x.useRef(null);return x.useEffect(()=>{const c=l.current;l.current=(r==null?void 0:r.current)||i.current,c!==l.current&&o.onAnchorChange(l.current)}),r?null:p.jsx(ke.div,{...s,ref:a})});GN.displayName=VN;var sC="PopperContent",[pne,fne]=UN(sC),YN=x.forwardRef((n,e)=>{var te,re,ge,de,Ne,De;const{__scopePopper:t,side:r="bottom",sideOffset:s=0,align:o="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:h=!1,updatePositionStrategy:f="optimized",onPlaced:g,...m}=n,y=KN(sC,t),[S,b]=x.useState(null),w=nt(e,rt=>b(rt)),[v,P]=x.useState(null),T=MN(v),I=(T==null?void 0:T.width)??0,k=(T==null?void 0:T.height)??0,A=r+(o!=="center"?"-"+o:""),R=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},D=Array.isArray(c)?c:[c],j=D.length>0,_={padding:R,boundary:D.filter(mne),altBoundary:j},{refs:M,floatingStyles:O,placement:N,isPositioned:B,middlewareData:H}=tne({strategy:"fixed",placement:A,whileElementsMounted:(...rt)=>Wte(...rt,{animationFrame:f==="always"}),elements:{reference:y.anchor},middleware:[rne({mainAxis:s+k,alignmentAxis:i}),l&&sne({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?one():void 0,..._}),l&&ine({..._}),ane({..._,apply:({elements:rt,rects:lt,availableWidth:pt,availableHeight:fn})=>{const{width:Yn,height:Is}=lt.reference,xn=rt.floating.style;xn.setProperty("--radix-popper-available-width",`${pt}px`),xn.setProperty("--radix-popper-available-height",`${fn}px`),xn.setProperty("--radix-popper-anchor-width",`${Yn}px`),xn.setProperty("--radix-popper-anchor-height",`${Is}px`)}}),v&&cne({element:v,padding:a}),yne({arrowWidth:I,arrowHeight:k}),h&&lne({strategy:"referenceHidden",..._})]}),[z,X]=ZN(N),G=dr(g);Wn(()=>{B&&(G==null||G())},[B,G]);const ae=(te=H.arrow)==null?void 0:te.x,Ce=(re=H.arrow)==null?void 0:re.y,fe=((ge=H.arrow)==null?void 0:ge.centerOffset)!==0,[oe,Te]=x.useState();return Wn(()=>{S&&Te(window.getComputedStyle(S).zIndex)},[S]),p.jsx("div",{ref:M.setFloating,"data-radix-popper-content-wrapper":"",style:{...O,transform:B?O.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:oe,"--radix-popper-transform-origin":[(de=H.transformOrigin)==null?void 0:de.x,(Ne=H.transformOrigin)==null?void 0:Ne.y].join(" "),...((De=H.hide)==null?void 0:De.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:n.dir,children:p.jsx(pne,{scope:t,placedSide:z,onArrowChange:P,arrowX:ae,arrowY:Ce,shouldHideArrow:fe,children:p.jsx(ke.div,{"data-side":z,"data-align":X,...m,ref:w,style:{...m.style,animation:B?void 0:"none"}})})})});YN.displayName=sC;var XN="PopperArrow",gne={top:"bottom",right:"left",bottom:"top",left:"right"},qN=x.forwardRef(function(e,t){const{__scopePopper:r,...s}=e,o=fne(XN,r),i=gne[o.placedSide];return p.jsx("span",{ref:o.onArrowChange,style:{position:"absolute",left:o.arrowX,top:o.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[o.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[o.placedSide],visibility:o.shouldHideArrow?"hidden":void 0},children:p.jsx(une,{...s,ref:t,style:{...s.style,display:"block"}})})});qN.displayName=XN;function mne(n){return n!==null}var yne=n=>({name:"transformOrigin",options:n,fn(e){var y,S,b;const{placement:t,rects:r,middlewareData:s}=e,i=((y=s.arrow)==null?void 0:y.centerOffset)!==0,a=i?0:n.arrowWidth,l=i?0:n.arrowHeight,[c,u]=ZN(t),d={start:"0%",center:"50%",end:"100%"}[u],h=(((S=s.arrow)==null?void 0:S.x)??0)+a/2,f=(((b=s.arrow)==null?void 0:b.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?d:`${h}px`,m=`${-l}px`):c==="top"?(g=i?d:`${h}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?d:`${f}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?d:`${f}px`),{data:{x:g,y:m}}}});function ZN(n){const[e,t="center"]=n.split("-");return[e,t]}var oS=WN,ip=GN,iS=YN,aS=qN,vb="rovingFocusGroup.onEntryFocus",Sne={bubbles:!1,cancelable:!0},ap="RovingFocusGroup",[b0,JN,xne]=ep(ap),[bne,Cd]=rs(ap,[xne]),[wne,vne]=bne(ap),QN=x.forwardRef((n,e)=>p.jsx(b0.Provider,{scope:n.__scopeRovingFocusGroup,children:p.jsx(b0.Slot,{scope:n.__scopeRovingFocusGroup,children:p.jsx(Cne,{...n,ref:e})})}));QN.displayName=ap;var Cne=x.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:t,orientation:r,loop:s=!1,dir:o,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=n,h=x.useRef(null),f=nt(e,h),g=tp(o),[m,y]=Ys({prop:i,defaultProp:a??null,onChange:l,caller:ap}),[S,b]=x.useState(!1),w=dr(c),v=JN(t),P=x.useRef(!1),[T,I]=x.useState(0);return x.useEffect(()=>{const k=h.current;if(k)return k.addEventListener(vb,w),()=>k.removeEventListener(vb,w)},[w]),p.jsx(wne,{scope:t,orientation:r,dir:g,loop:s,currentTabStopId:m,onItemFocus:x.useCallback(k=>y(k),[y]),onItemShiftTab:x.useCallback(()=>b(!0),[]),onFocusableItemAdd:x.useCallback(()=>I(k=>k+1),[]),onFocusableItemRemove:x.useCallback(()=>I(k=>k-1),[]),children:p.jsx(ke.div,{tabIndex:S||T===0?-1:0,"data-orientation":r,...d,ref:f,style:{outline:"none",...n.style},onMouseDown:le(n.onMouseDown,()=>{P.current=!0}),onFocus:le(n.onFocus,k=>{const A=!P.current;if(k.target===k.currentTarget&&A&&!S){const R=new CustomEvent(vb,Sne);if(k.currentTarget.dispatchEvent(R),!R.defaultPrevented){const D=v().filter(N=>N.focusable),j=D.find(N=>N.active),_=D.find(N=>N.id===m),O=[j,_,...D].filter(Boolean).map(N=>N.ref.current);nF(O,u)}}P.current=!1}),onBlur:le(n.onBlur,()=>b(!1))})})}),eF="RovingFocusGroupItem",tF=x.forwardRef((n,e)=>{const{__scopeRovingFocusGroup:t,focusable:r=!0,active:s=!1,tabStopId:o,children:i,...a}=n,l=Ks(),c=o||l,u=vne(eF,t),d=u.currentTabStopId===c,h=JN(t),{onFocusableItemAdd:f,onFocusableItemRemove:g,currentTabStopId:m}=u;return x.useEffect(()=>{if(r)return f(),()=>g()},[r,f,g]),p.jsx(b0.ItemSlot,{scope:t,id:c,focusable:r,active:s,children:p.jsx(ke.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:le(n.onMouseDown,y=>{r?u.onItemFocus(c):y.preventDefault()}),onFocus:le(n.onFocus,()=>u.onItemFocus(c)),onKeyDown:le(n.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){u.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const S=Ine(y,u.orientation,u.dir);if(S!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let w=h().filter(v=>v.focusable).map(v=>v.ref.current);if(S==="last")w.reverse();else if(S==="prev"||S==="next"){S==="prev"&&w.reverse();const v=w.indexOf(y.currentTarget);w=u.loop?Ene(w,v+1):w.slice(v+1)}setTimeout(()=>nF(w))}}),children:typeof i=="function"?i({isCurrentTabStop:d,hasTabStop:m!=null}):i})})});tF.displayName=eF;var Pne={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Tne(n,e){return e!=="rtl"?n:n==="ArrowLeft"?"ArrowRight":n==="ArrowRight"?"ArrowLeft":n}function Ine(n,e,t){const r=Tne(n.key,t);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Pne[r]}function nF(n,e=!1){const t=document.activeElement;for(const r of n)if(r===t||(r.focus({preventScroll:e}),document.activeElement!==t))return}function Ene(n,e){return n.map((t,r)=>n[(e+r)%n.length])}var oC=QN,lS=tF,w0=["Enter"," "],kne=["ArrowDown","PageUp","Home"],rF=["ArrowUp","PageDown","End"],_ne=[...kne,...rF],Mne={ltr:[...w0,"ArrowRight"],rtl:[...w0,"ArrowLeft"]},Ane={ltr:["ArrowLeft"],rtl:["ArrowRight"]},lp="Menu",[Sh,Dne,One]=ep(lp),[Jl,cS]=rs(lp,[One,Ja,Cd]),cp=Ja(),sF=Cd(),[oF,Qa]=Jl(lp),[Rne,dp]=Jl(lp),iF=n=>{const{__scopeMenu:e,open:t=!1,children:r,dir:s,onOpenChange:o,modal:i=!0}=n,a=cp(e),[l,c]=x.useState(null),u=x.useRef(!1),d=dr(o),h=tp(s);return x.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},g=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),p.jsx(oS,{...a,children:p.jsx(oF,{scope:e,open:t,onOpenChange:d,content:l,onContentChange:c,children:p.jsx(Rne,{scope:e,onClose:x.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:h,modal:i,children:r})})})};iF.displayName=lp;var Lne="MenuAnchor",iC=x.forwardRef((n,e)=>{const{__scopeMenu:t,...r}=n,s=cp(t);return p.jsx(ip,{...s,...r,ref:e})});iC.displayName=Lne;var aC="MenuPortal",[jne,aF]=Jl(aC,{forceMount:void 0}),lF=n=>{const{__scopeMenu:e,forceMount:t,children:r,container:s}=n,o=Qa(aC,e);return p.jsx(jne,{scope:e,forceMount:t,children:p.jsx(Xs,{present:t||o.open,children:p.jsx(rp,{asChild:!0,container:s,children:r})})})};lF.displayName=aC;var Ws="MenuContent",[Nne,lC]=Jl(Ws),cF=x.forwardRef((n,e)=>{const t=aF(Ws,n.__scopeMenu),{forceMount:r=t.forceMount,...s}=n,o=Qa(Ws,n.__scopeMenu),i=dp(Ws,n.__scopeMenu);return p.jsx(Sh.Provider,{scope:n.__scopeMenu,children:p.jsx(Xs,{present:r||o.open,children:p.jsx(Sh.Slot,{scope:n.__scopeMenu,children:i.modal?p.jsx(Fne,{...s,ref:e}):p.jsx(Bne,{...s,ref:e})})})})}),Fne=x.forwardRef((n,e)=>{const t=Qa(Ws,n.__scopeMenu),r=x.useRef(null),s=nt(e,r);return x.useEffect(()=>{const o=r.current;if(o)return Qy(o)},[]),p.jsx(cC,{...n,ref:s,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:le(n.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),Bne=x.forwardRef((n,e)=>{const t=Qa(Ws,n.__scopeMenu);return p.jsx(cC,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),zne=Fa("MenuContent.ScrollLock"),cC=x.forwardRef((n,e)=>{const{__scopeMenu:t,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,onDismiss:f,disableOutsideScroll:g,...m}=n,y=Qa(Ws,t),S=dp(Ws,t),b=cp(t),w=sF(t),v=Dne(t),[P,T]=x.useState(null),I=x.useRef(null),k=nt(e,I,y.onContentChange),A=x.useRef(0),R=x.useRef(""),D=x.useRef(0),j=x.useRef(null),_=x.useRef("right"),M=x.useRef(0),O=g?sp:x.Fragment,N=g?{as:zne,allowPinchZoom:!0}:void 0,B=z=>{var te,re;const X=R.current+z,G=v().filter(ge=>!ge.disabled),ae=document.activeElement,Ce=(te=G.find(ge=>ge.ref.current===ae))==null?void 0:te.textValue,fe=G.map(ge=>ge.textValue),oe=Jne(fe,X,Ce),Te=(re=G.find(ge=>ge.textValue===oe))==null?void 0:re.ref.current;(function ge(de){R.current=de,window.clearTimeout(A.current),de!==""&&(A.current=window.setTimeout(()=>ge(""),1e3))})(X),Te&&setTimeout(()=>Te.focus())};x.useEffect(()=>()=>window.clearTimeout(A.current),[]),Zy();const H=x.useCallback(z=>{var G,ae;return _.current===((G=j.current)==null?void 0:G.side)&&ere(z,(ae=j.current)==null?void 0:ae.area)},[]);return p.jsx(Nne,{scope:t,searchRef:R,onItemEnter:x.useCallback(z=>{H(z)&&z.preventDefault()},[H]),onItemLeave:x.useCallback(z=>{var X;H(z)||((X=I.current)==null||X.focus(),T(null))},[H]),onTriggerLeave:x.useCallback(z=>{H(z)&&z.preventDefault()},[H]),pointerGraceTimerRef:D,onPointerGraceIntentChange:x.useCallback(z=>{j.current=z},[]),children:p.jsx(O,{...N,children:p.jsx(np,{asChild:!0,trapped:s,onMountAutoFocus:le(o,z=>{var X;z.preventDefault(),(X=I.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:p.jsx(Zl,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,onDismiss:f,children:p.jsx(oC,{asChild:!0,...w,dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:T,onEntryFocus:le(l,z=>{S.isUsingKeyboardRef.current||z.preventDefault()}),preventScrollOnEntryFocus:!0,children:p.jsx(iS,{role:"menu","aria-orientation":"vertical","data-state":IF(y.open),"data-radix-menu-content":"",dir:S.dir,...b,...m,ref:k,style:{outline:"none",...m.style},onKeyDown:le(m.onKeyDown,z=>{const G=z.target.closest("[data-radix-menu-content]")===z.currentTarget,ae=z.ctrlKey||z.altKey||z.metaKey,Ce=z.key.length===1;G&&(z.key==="Tab"&&z.preventDefault(),!ae&&Ce&&B(z.key));const fe=I.current;if(z.target!==fe||!_ne.includes(z.key))return;z.preventDefault();const Te=v().filter(te=>!te.disabled).map(te=>te.ref.current);rF.includes(z.key)&&Te.reverse(),qne(Te)}),onBlur:le(n.onBlur,z=>{z.currentTarget.contains(z.target)||(window.clearTimeout(A.current),R.current="")}),onPointerMove:le(n.onPointerMove,xh(z=>{const X=z.target,G=M.current!==z.clientX;if(z.currentTarget.contains(X)&&G){const ae=z.clientX>M.current?"right":"left";_.current=ae,M.current=z.clientX}}))})})})})})})});cF.displayName=Ws;var $ne="MenuGroup",dC=x.forwardRef((n,e)=>{const{__scopeMenu:t,...r}=n;return p.jsx(ke.div,{role:"group",...r,ref:e})});dC.displayName=$ne;var Hne="MenuLabel",dF=x.forwardRef((n,e)=>{const{__scopeMenu:t,...r}=n;return p.jsx(ke.div,{...r,ref:e})});dF.displayName=Hne;var hm="MenuItem",ZE="menu.itemSelect",dS=x.forwardRef((n,e)=>{const{disabled:t=!1,onSelect:r,...s}=n,o=x.useRef(null),i=dp(hm,n.__scopeMenu),a=lC(hm,n.__scopeMenu),l=nt(e,o),c=x.useRef(!1),u=()=>{const d=o.current;if(!t&&d){const h=new CustomEvent(ZE,{bubbles:!0,cancelable:!0});d.addEventListener(ZE,f=>r==null?void 0:r(f),{once:!0}),G1(d,h),h.defaultPrevented?c.current=!1:i.onClose()}};return p.jsx(uF,{...s,ref:l,disabled:t,onClick:le(n.onClick,u),onPointerDown:d=>{var h;(h=n.onPointerDown)==null||h.call(n,d),c.current=!0},onPointerUp:le(n.onPointerUp,d=>{var h;c.current||(h=d.currentTarget)==null||h.click()}),onKeyDown:le(n.onKeyDown,d=>{const h=a.searchRef.current!=="";t||h&&d.key===" "||w0.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});dS.displayName=hm;var uF=x.forwardRef((n,e)=>{const{__scopeMenu:t,disabled:r=!1,textValue:s,...o}=n,i=lC(hm,t),a=sF(t),l=x.useRef(null),c=nt(e,l),[u,d]=x.useState(!1),[h,f]=x.useState("");return x.useEffect(()=>{const g=l.current;g&&f((g.textContent??"").trim())},[o.children]),p.jsx(Sh.ItemSlot,{scope:t,disabled:r,textValue:s??h,children:p.jsx(lS,{asChild:!0,...a,focusable:!r,children:p.jsx(ke.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:c,onPointerMove:le(n.onPointerMove,xh(g=>{r?i.onItemLeave(g):(i.onItemEnter(g),g.defaultPrevented||g.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:le(n.onPointerLeave,xh(g=>i.onItemLeave(g))),onFocus:le(n.onFocus,()=>d(!0)),onBlur:le(n.onBlur,()=>d(!1))})})})}),Une="MenuCheckboxItem",hF=x.forwardRef((n,e)=>{const{checked:t=!1,onCheckedChange:r,...s}=n;return p.jsx(yF,{scope:n.__scopeMenu,checked:t,children:p.jsx(dS,{role:"menuitemcheckbox","aria-checked":pm(t)?"mixed":t,...s,ref:e,"data-state":pC(t),onSelect:le(s.onSelect,()=>r==null?void 0:r(pm(t)?!0:!t),{checkForDefaultPrevented:!1})})})});hF.displayName=Une;var pF="MenuRadioGroup",[Kne,Wne]=Jl(pF,{value:void 0,onValueChange:()=>{}}),fF=x.forwardRef((n,e)=>{const{value:t,onValueChange:r,...s}=n,o=dr(r);return p.jsx(Kne,{scope:n.__scopeMenu,value:t,onValueChange:o,children:p.jsx(dC,{...s,ref:e})})});fF.displayName=pF;var gF="MenuRadioItem",mF=x.forwardRef((n,e)=>{const{value:t,...r}=n,s=Wne(gF,n.__scopeMenu),o=t===s.value;return p.jsx(yF,{scope:n.__scopeMenu,checked:o,children:p.jsx(dS,{role:"menuitemradio","aria-checked":o,...r,ref:e,"data-state":pC(o),onSelect:le(r.onSelect,()=>{var i;return(i=s.onValueChange)==null?void 0:i.call(s,t)},{checkForDefaultPrevented:!1})})})});mF.displayName=gF;var uC="MenuItemIndicator",[yF,Vne]=Jl(uC,{checked:!1}),SF=x.forwardRef((n,e)=>{const{__scopeMenu:t,forceMount:r,...s}=n,o=Vne(uC,t);return p.jsx(Xs,{present:r||pm(o.checked)||o.checked===!0,children:p.jsx(ke.span,{...s,ref:e,"data-state":pC(o.checked)})})});SF.displayName=uC;var Gne="MenuSeparator",xF=x.forwardRef((n,e)=>{const{__scopeMenu:t,...r}=n;return p.jsx(ke.div,{role:"separator","aria-orientation":"horizontal",...r,ref:e})});xF.displayName=Gne;var Yne="MenuArrow",bF=x.forwardRef((n,e)=>{const{__scopeMenu:t,...r}=n,s=cp(t);return p.jsx(aS,{...s,...r,ref:e})});bF.displayName=Yne;var hC="MenuSub",[Xne,wF]=Jl(hC),vF=n=>{const{__scopeMenu:e,children:t,open:r=!1,onOpenChange:s}=n,o=Qa(hC,e),i=cp(e),[a,l]=x.useState(null),[c,u]=x.useState(null),d=dr(s);return x.useEffect(()=>(o.open===!1&&d(!1),()=>d(!1)),[o.open,d]),p.jsx(oS,{...i,children:p.jsx(oF,{scope:e,open:r,onOpenChange:d,content:c,onContentChange:u,children:p.jsx(Xne,{scope:e,contentId:Ks(),triggerId:Ks(),trigger:a,onTriggerChange:l,children:t})})})};vF.displayName=hC;var yu="MenuSubTrigger",CF=x.forwardRef((n,e)=>{const t=Qa(yu,n.__scopeMenu),r=dp(yu,n.__scopeMenu),s=wF(yu,n.__scopeMenu),o=lC(yu,n.__scopeMenu),i=x.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=o,c={__scopeMenu:n.__scopeMenu},u=x.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return x.useEffect(()=>u,[u]),x.useEffect(()=>{const d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),p.jsx(iC,{asChild:!0,...c,children:p.jsx(uF,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":s.contentId,"data-state":IF(t.open),...n,ref:Xy(e,s.onTriggerChange),onClick:d=>{var h;(h=n.onClick)==null||h.call(n,d),!(n.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:le(n.onPointerMove,xh(d=>{o.onItemEnter(d),!d.defaultPrevented&&!n.disabled&&!t.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{t.onOpenChange(!0),u()},100))})),onPointerLeave:le(n.onPointerLeave,xh(d=>{var f,g;u();const h=(f=t.content)==null?void 0:f.getBoundingClientRect();if(h){const m=(g=t.content)==null?void 0:g.dataset.side,y=m==="right",S=y?-5:5,b=h[y?"left":"right"],w=h[y?"right":"left"];o.onPointerGraceIntentChange({area:[{x:d.clientX+S,y:d.clientY},{x:b,y:h.top},{x:w,y:h.top},{x:w,y:h.bottom},{x:b,y:h.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(d),d.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:le(n.onKeyDown,d=>{var f;const h=o.searchRef.current!=="";n.disabled||h&&d.key===" "||Mne[r.dir].includes(d.key)&&(t.onOpenChange(!0),(f=t.content)==null||f.focus(),d.preventDefault())})})})});CF.displayName=yu;var PF="MenuSubContent",TF=x.forwardRef((n,e)=>{const t=aF(Ws,n.__scopeMenu),{forceMount:r=t.forceMount,...s}=n,o=Qa(Ws,n.__scopeMenu),i=dp(Ws,n.__scopeMenu),a=wF(PF,n.__scopeMenu),l=x.useRef(null),c=nt(e,l);return p.jsx(Sh.Provider,{scope:n.__scopeMenu,children:p.jsx(Xs,{present:r||o.open,children:p.jsx(Sh.Slot,{scope:n.__scopeMenu,children:p.jsx(cC,{id:a.contentId,"aria-labelledby":a.triggerId,...s,ref:c,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var d;i.isUsingKeyboardRef.current&&((d=l.current)==null||d.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:le(n.onFocusOutside,u=>{u.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:le(n.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:le(n.onKeyDown,u=>{var f;const d=u.currentTarget.contains(u.target),h=Ane[i.dir].includes(u.key);d&&h&&(o.onOpenChange(!1),(f=a.trigger)==null||f.focus(),u.preventDefault())})})})})})});TF.displayName=PF;function IF(n){return n?"open":"closed"}function pm(n){return n==="indeterminate"}function pC(n){return pm(n)?"indeterminate":n?"checked":"unchecked"}function qne(n){const e=document.activeElement;for(const t of n)if(t===e||(t.focus(),document.activeElement!==e))return}function Zne(n,e){return n.map((t,r)=>n[(e+r)%n.length])}function Jne(n,e,t){const s=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,o=t?n.indexOf(t):-1;let i=Zne(n,Math.max(o,0));s.length===1&&(i=i.filter(c=>c!==t));const l=i.find(c=>c.toLowerCase().startsWith(s.toLowerCase()));return l!==t?l:void 0}function Qne(n,e){const{x:t,y:r}=n;let s=!1;for(let o=0,i=e.length-1;o<e.length;i=o++){const a=e[o],l=e[i],c=a.x,u=a.y,d=l.x,h=l.y;u>r!=h>r&&t<(d-c)*(r-u)/(h-u)+c&&(s=!s)}return s}function ere(n,e){if(!e)return!1;const t={x:n.clientX,y:n.clientY};return Qne(t,e)}function xh(n){return e=>e.pointerType==="mouse"?n(e):void 0}var EF=iF,kF=iC,_F=lF,MF=cF,AF=dC,DF=dF,OF=dS,RF=hF,LF=fF,jF=mF,NF=SF,FF=xF,BF=bF,zF=vF,$F=CF,HF=TF,fC="ContextMenu",[tre]=rs(fC,[cS]),fr=cS(),[nre,UF]=tre(fC),KF=n=>{const{__scopeContextMenu:e,children:t,onOpenChange:r,dir:s,modal:o=!0}=n,[i,a]=x.useState(!1),l=fr(e),c=dr(r),u=x.useCallback(d=>{a(d),c(d)},[c]);return p.jsx(nre,{scope:e,open:i,onOpenChange:u,modal:o,children:p.jsx(EF,{...l,dir:s,open:i,onOpenChange:u,modal:o,children:t})})};KF.displayName=fC;var WF="ContextMenuTrigger",VF=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,disabled:r=!1,...s}=n,o=UF(WF,t),i=fr(t),a=x.useRef({x:0,y:0}),l=x.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),c=x.useRef(0),u=x.useCallback(()=>window.clearTimeout(c.current),[]),d=h=>{a.current={x:h.clientX,y:h.clientY},o.onOpenChange(!0)};return x.useEffect(()=>u,[u]),x.useEffect(()=>void(r&&u()),[r,u]),p.jsxs(p.Fragment,{children:[p.jsx(kF,{...i,virtualRef:l}),p.jsx(ke.span,{"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,...s,ref:e,style:{WebkitTouchCallout:"none",...n.style},onContextMenu:r?n.onContextMenu:le(n.onContextMenu,h=>{u(),d(h),h.preventDefault()}),onPointerDown:r?n.onPointerDown:le(n.onPointerDown,cf(h=>{u(),c.current=window.setTimeout(()=>d(h),700)})),onPointerMove:r?n.onPointerMove:le(n.onPointerMove,cf(u)),onPointerCancel:r?n.onPointerCancel:le(n.onPointerCancel,cf(u)),onPointerUp:r?n.onPointerUp:le(n.onPointerUp,cf(u))})]})});VF.displayName=WF;var rre="ContextMenuPortal",gC=n=>{const{__scopeContextMenu:e,...t}=n,r=fr(e);return p.jsx(_F,{...r,...t})};gC.displayName=rre;var GF="ContextMenuContent",YF=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=UF(GF,t),o=fr(t),i=x.useRef(!1);return p.jsx(MF,{...o,...r,ref:e,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:a=>{var l;(l=n.onCloseAutoFocus)==null||l.call(n,a),!a.defaultPrevented&&i.current&&a.preventDefault(),i.current=!1},onInteractOutside:a=>{var l;(l=n.onInteractOutside)==null||l.call(n,a),!a.defaultPrevented&&!s.modal&&(i.current=!0)},style:{...n.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});YF.displayName=GF;var sre="ContextMenuGroup",ore=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(AF,{...s,...r,ref:e})});ore.displayName=sre;var ire="ContextMenuLabel",are=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(DF,{...s,...r,ref:e})});are.displayName=ire;var lre="ContextMenuItem",XF=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(OF,{...s,...r,ref:e})});XF.displayName=lre;var cre="ContextMenuCheckboxItem",qF=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(RF,{...s,...r,ref:e})});qF.displayName=cre;var dre="ContextMenuRadioGroup",ure=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(LF,{...s,...r,ref:e})});ure.displayName=dre;var hre="ContextMenuRadioItem",pre=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(jF,{...s,...r,ref:e})});pre.displayName=hre;var fre="ContextMenuItemIndicator",gre=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(NF,{...s,...r,ref:e})});gre.displayName=fre;var mre="ContextMenuSeparator",yre=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(FF,{...s,...r,ref:e})});yre.displayName=mre;var Sre="ContextMenuArrow",xre=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(BF,{...s,...r,ref:e})});xre.displayName=Sre;var ZF="ContextMenuSub",JF=n=>{const{__scopeContextMenu:e,children:t,onOpenChange:r,open:s,defaultOpen:o}=n,i=fr(e),[a,l]=Ys({prop:s,defaultProp:o??!1,onChange:r,caller:ZF});return p.jsx(zF,{...i,open:a,onOpenChange:l,children:t})};JF.displayName=ZF;var bre="ContextMenuSubTrigger",QF=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx($F,{...s,...r,ref:e})});QF.displayName=bre;var wre="ContextMenuSubContent",e3=x.forwardRef((n,e)=>{const{__scopeContextMenu:t,...r}=n,s=fr(t);return p.jsx(HF,{...s,...r,ref:e,style:{...n.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});e3.displayName=wre;function cf(n){return e=>e.pointerType!=="mouse"?n(e):void 0}var vre=KF,Cre=VF,Pre=gC,Tre=YF,Ire=XF,Ere=qF,uS="DropdownMenu",[kre]=rs(uS,[cS]),gr=cS(),[_re,t3]=kre(uS),n3=n=>{const{__scopeDropdownMenu:e,children:t,dir:r,open:s,defaultOpen:o,onOpenChange:i,modal:a=!0}=n,l=gr(e),c=x.useRef(null),[u,d]=Ys({prop:s,defaultProp:o??!1,onChange:i,caller:uS});return p.jsx(_re,{scope:e,triggerId:Ks(),triggerRef:c,contentId:Ks(),open:u,onOpenChange:d,onOpenToggle:x.useCallback(()=>d(h=>!h),[d]),modal:a,children:p.jsx(EF,{...l,open:u,onOpenChange:d,dir:r,modal:a,children:t})})};n3.displayName=uS;var r3="DropdownMenuTrigger",s3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,disabled:r=!1,...s}=n,o=t3(r3,t),i=gr(t);return p.jsx(kF,{asChild:!0,...i,children:p.jsx(ke.button,{type:"button",id:o.triggerId,"aria-haspopup":"menu","aria-expanded":o.open,"aria-controls":o.open?o.contentId:void 0,"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...s,ref:Xy(e,o.triggerRef),onPointerDown:le(n.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:le(n.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});s3.displayName=r3;var Mre="DropdownMenuPortal",o3=n=>{const{__scopeDropdownMenu:e,...t}=n,r=gr(e);return p.jsx(_F,{...r,...t})};o3.displayName=Mre;var i3="DropdownMenuContent",a3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=t3(i3,t),o=gr(t),i=x.useRef(!1);return p.jsx(MF,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:e,onCloseAutoFocus:le(n.onCloseAutoFocus,a=>{var l;i.current||(l=s.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:le(n.onInteractOutside,a=>{const l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;(!s.modal||u)&&(i.current=!0)}),style:{...n.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});a3.displayName=i3;var Are="DropdownMenuGroup",Dre=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(AF,{...s,...r,ref:e})});Dre.displayName=Are;var Ore="DropdownMenuLabel",Rre=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(DF,{...s,...r,ref:e})});Rre.displayName=Ore;var Lre="DropdownMenuItem",l3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(OF,{...s,...r,ref:e})});l3.displayName=Lre;var jre="DropdownMenuCheckboxItem",c3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(RF,{...s,...r,ref:e})});c3.displayName=jre;var Nre="DropdownMenuRadioGroup",Fre=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(LF,{...s,...r,ref:e})});Fre.displayName=Nre;var Bre="DropdownMenuRadioItem",zre=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(jF,{...s,...r,ref:e})});zre.displayName=Bre;var $re="DropdownMenuItemIndicator",d3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(NF,{...s,...r,ref:e})});d3.displayName=$re;var Hre="DropdownMenuSeparator",Ure=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(FF,{...s,...r,ref:e})});Ure.displayName=Hre;var Kre="DropdownMenuArrow",Wre=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(BF,{...s,...r,ref:e})});Wre.displayName=Kre;var Vre=n=>{const{__scopeDropdownMenu:e,children:t,open:r,onOpenChange:s,defaultOpen:o}=n,i=gr(e),[a,l]=Ys({prop:r,defaultProp:o??!1,onChange:s,caller:"DropdownMenuSub"});return p.jsx(zF,{...i,open:a,onOpenChange:l,children:t})},Gre="DropdownMenuSubTrigger",u3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx($F,{...s,...r,ref:e})});u3.displayName=Gre;var Yre="DropdownMenuSubContent",h3=x.forwardRef((n,e)=>{const{__scopeDropdownMenu:t,...r}=n,s=gr(t);return p.jsx(HF,{...s,...r,ref:e,style:{...n.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});h3.displayName=Yre;var mC=n3,yC=s3,hS=o3,SC=a3,Xre=l3,p3=c3,qre=d3,Zre=Vre,Jre=u3,Qre=h3;function fm(n,[e,t]){return Math.min(t,Math.max(e,n))}var pS="Popover",[f3]=rs(pS,[Ja]),up=Ja(),[ese,el]=f3(pS),g3=n=>{const{__scopePopover:e,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=n,a=up(e),l=x.useRef(null),[c,u]=x.useState(!1),[d,h]=Ys({prop:r,defaultProp:s??!1,onChange:o,caller:pS});return p.jsx(oS,{...a,children:p.jsx(ese,{scope:e,contentId:Ks(),triggerRef:l,open:d,onOpenChange:h,onOpenToggle:x.useCallback(()=>h(f=>!f),[h]),hasCustomAnchor:c,onCustomAnchorAdd:x.useCallback(()=>u(!0),[]),onCustomAnchorRemove:x.useCallback(()=>u(!1),[]),modal:i,children:t})})};g3.displayName=pS;var m3="PopoverAnchor",tse=x.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,s=el(m3,t),o=up(t),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return x.useEffect(()=>(i(),()=>a()),[i,a]),p.jsx(ip,{...o,...r,ref:e})});tse.displayName=m3;var y3="PopoverTrigger",S3=x.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,s=el(y3,t),o=up(t),i=nt(e,s.triggerRef),a=p.jsx(ke.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":C3(s.open),...r,ref:i,onClick:le(n.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:p.jsx(ip,{asChild:!0,...o,children:a})});S3.displayName=y3;var xC="PopoverPortal",[nse,rse]=f3(xC,{forceMount:void 0}),x3=n=>{const{__scopePopover:e,forceMount:t,children:r,container:s}=n,o=el(xC,e);return p.jsx(nse,{scope:e,forceMount:t,children:p.jsx(Xs,{present:t||o.open,children:p.jsx(rp,{asChild:!0,container:s,children:r})})})};x3.displayName=xC;var ld="PopoverContent",b3=x.forwardRef((n,e)=>{const t=rse(ld,n.__scopePopover),{forceMount:r=t.forceMount,...s}=n,o=el(ld,n.__scopePopover);return p.jsx(Xs,{present:r||o.open,children:o.modal?p.jsx(ose,{...s,ref:e}):p.jsx(ise,{...s,ref:e})})});b3.displayName=ld;var sse=Fa("PopoverContent.RemoveScroll"),ose=x.forwardRef((n,e)=>{const t=el(ld,n.__scopePopover),r=x.useRef(null),s=nt(e,r),o=x.useRef(!1);return x.useEffect(()=>{const i=r.current;if(i)return Qy(i)},[]),p.jsx(sp,{as:sse,allowPinchZoom:!0,children:p.jsx(w3,{...n,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:le(n.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:le(n.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;o.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:le(n.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),ise=x.forwardRef((n,e)=>{const t=el(ld,n.__scopePopover),r=x.useRef(!1),s=x.useRef(!1);return p.jsx(w3,{...n,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=n.onCloseAutoFocus)==null||i.call(n,o),o.defaultPrevented||(r.current||(a=t.triggerRef.current)==null||a.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var l,c;(l=n.onInteractOutside)==null||l.call(n,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const i=o.target;((c=t.triggerRef.current)==null?void 0:c.contains(i))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),w3=x.forwardRef((n,e)=>{const{__scopePopover:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=n,h=el(ld,t),f=up(t);return Zy(),p.jsx(np,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:p.jsx(Zl,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>h.onOpenChange(!1),children:p.jsx(iS,{"data-state":C3(h.open),role:"dialog",id:h.contentId,...f,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),v3="PopoverClose",ase=x.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,s=el(v3,t);return p.jsx(ke.button,{type:"button",...r,ref:e,onClick:le(n.onClick,()=>s.onOpenChange(!1))})});ase.displayName=v3;var lse="PopoverArrow",cse=x.forwardRef((n,e)=>{const{__scopePopover:t,...r}=n,s=up(t);return p.jsx(aS,{...s,...r,ref:e})});cse.displayName=lse;function C3(n){return n?"open":"closed"}var bC=g3,wC=S3,vC=x3,CC=b3,dse=[" ","Enter","ArrowUp","ArrowDown"],use=[" ","Enter"],fS="Select",[PC,gS,hse]=ep(fS),[Pd]=rs(fS,[hse,Ja]),TC=Ja(),[_ye,tl]=Pd(fS),[Mye,pse]=Pd(fS),P3="SelectTrigger",T3=x.forwardRef((n,e)=>{const{__scopeSelect:t,disabled:r=!1,...s}=n,o=TC(t),i=tl(P3,t),a=i.disabled||r,l=nt(e,i.onTriggerChange),c=gS(t),u=x.useRef("touch"),[d,h,f]=N3(m=>{const y=c().filter(w=>!w.disabled),S=y.find(w=>w.value===i.value),b=F3(y,m,S);b!==void 0&&i.onValueChange(b.value)}),g=m=>{a||(i.onOpenChange(!0),f()),m&&(i.triggerPointerDownPosRef.current={x:Math.round(m.pageX),y:Math.round(m.pageY)})};return p.jsx(ip,{asChild:!0,...o,children:p.jsx(ke.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":j3(i.value)?"":void 0,...s,ref:l,onClick:le(s.onClick,m=>{m.currentTarget.focus(),u.current!=="mouse"&&g(m)}),onPointerDown:le(s.onPointerDown,m=>{u.current=m.pointerType;const y=m.target;y.hasPointerCapture(m.pointerId)&&y.releasePointerCapture(m.pointerId),m.button===0&&m.ctrlKey===!1&&m.pointerType==="mouse"&&(g(m),m.preventDefault())}),onKeyDown:le(s.onKeyDown,m=>{const y=d.current!=="";!(m.ctrlKey||m.altKey||m.metaKey)&&m.key.length===1&&h(m.key),!(y&&m.key===" ")&&dse.includes(m.key)&&(g(),m.preventDefault())})})})});T3.displayName=P3;var I3="SelectValue",fse=x.forwardRef((n,e)=>{const{__scopeSelect:t,className:r,style:s,children:o,placeholder:i="",...a}=n,l=tl(I3,t),{onValueNodeHasChildrenChange:c}=l,u=o!==void 0,d=nt(e,l.onValueNodeChange);return Wn(()=>{c(u)},[c,u]),p.jsx(ke.span,{...a,ref:d,style:{pointerEvents:"none"},children:j3(l.value)?p.jsx(p.Fragment,{children:i}):o})});fse.displayName=I3;var gse="SelectIcon",E3=x.forwardRef((n,e)=>{const{__scopeSelect:t,children:r,...s}=n;return p.jsx(ke.span,{"aria-hidden":!0,...s,ref:e,children:r||"▼"})});E3.displayName=gse;var Fl="SelectContent",mse=x.forwardRef((n,e)=>{const t=tl(Fl,n.__scopeSelect),[r,s]=x.useState();if(Wn(()=>{s(new DocumentFragment)},[]),!t.open){const o=r;return o?Vi.createPortal(p.jsx(k3,{scope:n.__scopeSelect,children:p.jsx(PC.Slot,{scope:n.__scopeSelect,children:p.jsx("div",{children:n.children})})}),o):null}return p.jsx(_3,{...n,ref:e})});mse.displayName=Fl;var oo=10,[k3,nl]=Pd(Fl),yse="SelectContentImpl",Sse=Fa("SelectContent.RemoveScroll"),_3=x.forwardRef((n,e)=>{const{__scopeSelect:t,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:h,collisionPadding:f,sticky:g,hideWhenDetached:m,avoidCollisions:y,...S}=n,b=tl(Fl,t),[w,v]=x.useState(null),[P,T]=x.useState(null),I=nt(e,te=>v(te)),[k,A]=x.useState(null),[R,D]=x.useState(null),j=gS(t),[_,M]=x.useState(!1),O=x.useRef(!1);x.useEffect(()=>{if(w)return Qy(w)},[w]),Zy();const N=x.useCallback(te=>{const[re,...ge]=j().map(De=>De.ref.current),[de]=ge.slice(-1),Ne=document.activeElement;for(const De of te)if(De===Ne||(De==null||De.scrollIntoView({block:"nearest"}),De===re&&P&&(P.scrollTop=0),De===de&&P&&(P.scrollTop=P.scrollHeight),De==null||De.focus(),document.activeElement!==Ne))return},[j,P]),B=x.useCallback(()=>N([k,w]),[N,k,w]);x.useEffect(()=>{_&&B()},[_,B]);const{onOpenChange:H,triggerPointerDownPosRef:z}=b;x.useEffect(()=>{if(w){let te={x:0,y:0};const re=de=>{var Ne,De;te={x:Math.abs(Math.round(de.pageX)-(((Ne=z.current)==null?void 0:Ne.x)??0)),y:Math.abs(Math.round(de.pageY)-(((De=z.current)==null?void 0:De.y)??0))}},ge=de=>{te.x<=10&&te.y<=10?de.preventDefault():w.contains(de.target)||H(!1),document.removeEventListener("pointermove",re),z.current=null};return z.current!==null&&(document.addEventListener("pointermove",re),document.addEventListener("pointerup",ge,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",re),document.removeEventListener("pointerup",ge,{capture:!0})}}},[w,H,z]),x.useEffect(()=>{const te=()=>H(!1);return window.addEventListener("blur",te),window.addEventListener("resize",te),()=>{window.removeEventListener("blur",te),window.removeEventListener("resize",te)}},[H]);const[X,G]=N3(te=>{const re=j().filter(Ne=>!Ne.disabled),ge=re.find(Ne=>Ne.ref.current===document.activeElement),de=F3(re,te,ge);de&&setTimeout(()=>de.ref.current.focus())}),ae=x.useCallback((te,re,ge)=>{const de=!O.current&&!ge;(b.value!==void 0&&b.value===re||de)&&(A(te),de&&(O.current=!0))},[b.value]),Ce=x.useCallback(()=>w==null?void 0:w.focus(),[w]),fe=x.useCallback((te,re,ge)=>{const de=!O.current&&!ge;(b.value!==void 0&&b.value===re||de)&&D(te)},[b.value]),oe=r==="popper"?v0:M3,Te=oe===v0?{side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:h,collisionPadding:f,sticky:g,hideWhenDetached:m,avoidCollisions:y}:{};return p.jsx(k3,{scope:t,content:w,viewport:P,onViewportChange:T,itemRefCallback:ae,selectedItem:k,onItemLeave:Ce,itemTextRefCallback:fe,focusSelectedItem:B,selectedItemText:R,position:r,isPositioned:_,searchRef:X,children:p.jsx(sp,{as:Sse,allowPinchZoom:!0,children:p.jsx(np,{asChild:!0,trapped:b.open,onMountAutoFocus:te=>{te.preventDefault()},onUnmountAutoFocus:le(s,te=>{var re;(re=b.trigger)==null||re.focus({preventScroll:!0}),te.preventDefault()}),children:p.jsx(Zl,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:te=>te.preventDefault(),onDismiss:()=>b.onOpenChange(!1),children:p.jsx(oe,{role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:te=>te.preventDefault(),...S,...Te,onPlaced:()=>M(!0),ref:I,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:le(S.onKeyDown,te=>{const re=te.ctrlKey||te.altKey||te.metaKey;if(te.key==="Tab"&&te.preventDefault(),!re&&te.key.length===1&&G(te.key),["ArrowUp","ArrowDown","Home","End"].includes(te.key)){let de=j().filter(Ne=>!Ne.disabled).map(Ne=>Ne.ref.current);if(["ArrowUp","End"].includes(te.key)&&(de=de.slice().reverse()),["ArrowUp","ArrowDown"].includes(te.key)){const Ne=te.target,De=de.indexOf(Ne);de=de.slice(De+1)}setTimeout(()=>N(de)),te.preventDefault()}})})})})})})});_3.displayName=yse;var xse="SelectItemAlignedPosition",M3=x.forwardRef((n,e)=>{const{__scopeSelect:t,onPlaced:r,...s}=n,o=tl(Fl,t),i=nl(Fl,t),[a,l]=x.useState(null),[c,u]=x.useState(null),d=nt(e,I=>u(I)),h=gS(t),f=x.useRef(!1),g=x.useRef(!0),{viewport:m,selectedItem:y,selectedItemText:S,focusSelectedItem:b}=i,w=x.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&c&&m&&y&&S){const I=o.trigger.getBoundingClientRect(),k=c.getBoundingClientRect(),A=o.valueNode.getBoundingClientRect(),R=S.getBoundingClientRect();if(o.dir!=="rtl"){const Ne=R.left-k.left,De=A.left-Ne,rt=I.left-De,lt=I.width+rt,pt=Math.max(lt,k.width),fn=window.innerWidth-oo,Yn=fm(De,[oo,Math.max(oo,fn-pt)]);a.style.minWidth=lt+"px",a.style.left=Yn+"px"}else{const Ne=k.right-R.right,De=window.innerWidth-A.right-Ne,rt=window.innerWidth-I.right-De,lt=I.width+rt,pt=Math.max(lt,k.width),fn=window.innerWidth-oo,Yn=fm(De,[oo,Math.max(oo,fn-pt)]);a.style.minWidth=lt+"px",a.style.right=Yn+"px"}const D=h(),j=window.innerHeight-oo*2,_=m.scrollHeight,M=window.getComputedStyle(c),O=parseInt(M.borderTopWidth,10),N=parseInt(M.paddingTop,10),B=parseInt(M.borderBottomWidth,10),H=parseInt(M.paddingBottom,10),z=O+N+_+H+B,X=Math.min(y.offsetHeight*5,z),G=window.getComputedStyle(m),ae=parseInt(G.paddingTop,10),Ce=parseInt(G.paddingBottom,10),fe=I.top+I.height/2-oo,oe=j-fe,Te=y.offsetHeight/2,te=y.offsetTop+Te,re=O+N+te,ge=z-re;if(re<=fe){const Ne=D.length>0&&y===D[D.length-1].ref.current;a.style.bottom="0px";const De=c.clientHeight-m.offsetTop-m.offsetHeight,rt=Math.max(oe,Te+(Ne?Ce:0)+De+B),lt=re+rt;a.style.height=lt+"px"}else{const Ne=D.length>0&&y===D[0].ref.current;a.style.top="0px";const rt=Math.max(fe,O+m.offsetTop+(Ne?ae:0)+Te)+ge;a.style.height=rt+"px",m.scrollTop=re-fe+m.offsetTop}a.style.margin=`${oo}px 0`,a.style.minHeight=X+"px",a.style.maxHeight=j+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[h,o.trigger,o.valueNode,a,c,m,y,S,o.dir,r]);Wn(()=>w(),[w]);const[v,P]=x.useState();Wn(()=>{c&&P(window.getComputedStyle(c).zIndex)},[c]);const T=x.useCallback(I=>{I&&g.current===!0&&(w(),b==null||b(),g.current=!1)},[w,b]);return p.jsx(wse,{scope:t,contentWrapper:a,shouldExpandOnScrollRef:f,onScrollButtonChange:T,children:p.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:v},children:p.jsx(ke.div,{...s,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});M3.displayName=xse;var bse="SelectPopperPosition",v0=x.forwardRef((n,e)=>{const{__scopeSelect:t,align:r="start",collisionPadding:s=oo,...o}=n,i=TC(t);return p.jsx(iS,{...i,...o,ref:e,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});v0.displayName=bse;var[wse,IC]=Pd(Fl,{}),C0="SelectViewport",vse=x.forwardRef((n,e)=>{const{__scopeSelect:t,nonce:r,...s}=n,o=nl(C0,t),i=IC(C0,t),a=nt(e,o.onViewportChange),l=x.useRef(0);return p.jsxs(p.Fragment,{children:[p.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),p.jsx(PC.Slot,{scope:t,children:p.jsx(ke.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:le(s.onScroll,c=>{const u=c.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&d){const f=Math.abs(l.current-u.scrollTop);if(f>0){const g=window.innerHeight-oo*2,m=parseFloat(d.style.minHeight),y=parseFloat(d.style.height),S=Math.max(m,y);if(S<g){const b=S+f,w=Math.min(g,b),v=b-w;d.style.height=w+"px",d.style.bottom==="0px"&&(u.scrollTop=v>0?v:0,d.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});vse.displayName=C0;var A3="SelectGroup",[Cse,Pse]=Pd(A3),Tse=x.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,s=Ks();return p.jsx(Cse,{scope:t,id:s,children:p.jsx(ke.div,{role:"group","aria-labelledby":s,...r,ref:e})})});Tse.displayName=A3;var D3="SelectLabel",Ise=x.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,s=Pse(D3,t);return p.jsx(ke.div,{id:s.id,...r,ref:e})});Ise.displayName=D3;var gm="SelectItem",[Ese,O3]=Pd(gm),kse=x.forwardRef((n,e)=>{const{__scopeSelect:t,value:r,disabled:s=!1,textValue:o,...i}=n,a=tl(gm,t),l=nl(gm,t),c=a.value===r,[u,d]=x.useState(o??""),[h,f]=x.useState(!1),g=nt(e,b=>{var w;return(w=l.itemRefCallback)==null?void 0:w.call(l,b,r,s)}),m=Ks(),y=x.useRef("touch"),S=()=>{s||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return p.jsx(Ese,{scope:t,value:r,disabled:s,textId:m,isSelected:c,onItemTextChange:x.useCallback(b=>{d(w=>w||((b==null?void 0:b.textContent)??"").trim())},[]),children:p.jsx(PC.ItemSlot,{scope:t,value:r,disabled:s,textValue:u,children:p.jsx(ke.div,{role:"option","aria-labelledby":m,"data-highlighted":h?"":void 0,"aria-selected":c&&h,"data-state":c?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...i,ref:g,onFocus:le(i.onFocus,()=>f(!0)),onBlur:le(i.onBlur,()=>f(!1)),onClick:le(i.onClick,()=>{y.current!=="mouse"&&S()}),onPointerUp:le(i.onPointerUp,()=>{y.current==="mouse"&&S()}),onPointerDown:le(i.onPointerDown,b=>{y.current=b.pointerType}),onPointerMove:le(i.onPointerMove,b=>{var w;y.current=b.pointerType,s?(w=l.onItemLeave)==null||w.call(l):y.current==="mouse"&&b.currentTarget.focus({preventScroll:!0})}),onPointerLeave:le(i.onPointerLeave,b=>{var w;b.currentTarget===document.activeElement&&((w=l.onItemLeave)==null||w.call(l))}),onKeyDown:le(i.onKeyDown,b=>{var v;((v=l.searchRef)==null?void 0:v.current)!==""&&b.key===" "||(use.includes(b.key)&&S(),b.key===" "&&b.preventDefault())})})})})});kse.displayName=gm;var Su="SelectItemText",_se=x.forwardRef((n,e)=>{const{__scopeSelect:t,className:r,style:s,...o}=n,i=tl(Su,t),a=nl(Su,t),l=O3(Su,t),c=pse(Su,t),[u,d]=x.useState(null),h=nt(e,S=>d(S),l.onItemTextChange,S=>{var b;return(b=a.itemTextRefCallback)==null?void 0:b.call(a,S,l.value,l.disabled)}),f=u==null?void 0:u.textContent,g=x.useMemo(()=>p.jsx("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:m,onNativeOptionRemove:y}=c;return Wn(()=>(m(g),()=>y(g)),[m,y,g]),p.jsxs(p.Fragment,{children:[p.jsx(ke.span,{id:l.textId,...o,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Vi.createPortal(o.children,i.valueNode):null]})});_se.displayName=Su;var R3="SelectItemIndicator",Mse=x.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n;return O3(R3,t).isSelected?p.jsx(ke.span,{"aria-hidden":!0,...r,ref:e}):null});Mse.displayName=R3;var P0="SelectScrollUpButton",Ase=x.forwardRef((n,e)=>{const t=nl(P0,n.__scopeSelect),r=IC(P0,n.__scopeSelect),[s,o]=x.useState(!1),i=nt(e,r.onScrollButtonChange);return Wn(()=>{if(t.viewport&&t.isPositioned){let a=function(){const c=l.scrollTop>0;o(c)};const l=t.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[t.viewport,t.isPositioned]),s?p.jsx(L3,{...n,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=t;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});Ase.displayName=P0;var T0="SelectScrollDownButton",Dse=x.forwardRef((n,e)=>{const t=nl(T0,n.__scopeSelect),r=IC(T0,n.__scopeSelect),[s,o]=x.useState(!1),i=nt(e,r.onScrollButtonChange);return Wn(()=>{if(t.viewport&&t.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,u=Math.ceil(l.scrollTop)<c;o(u)};const l=t.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[t.viewport,t.isPositioned]),s?p.jsx(L3,{...n,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=t;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Dse.displayName=T0;var L3=x.forwardRef((n,e)=>{const{__scopeSelect:t,onAutoScroll:r,...s}=n,o=nl("SelectScrollButton",t),i=x.useRef(null),a=gS(t),l=x.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return x.useEffect(()=>()=>l(),[l]),Wn(()=>{var u;const c=a().find(d=>d.ref.current===document.activeElement);(u=c==null?void 0:c.ref.current)==null||u.scrollIntoView({block:"nearest"})},[a]),p.jsx(ke.div,{"aria-hidden":!0,...s,ref:e,style:{flexShrink:0,...s.style},onPointerDown:le(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:le(s.onPointerMove,()=>{var c;(c=o.onItemLeave)==null||c.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:le(s.onPointerLeave,()=>{l()})})}),Ose="SelectSeparator",Rse=x.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n;return p.jsx(ke.div,{"aria-hidden":!0,...r,ref:e})});Rse.displayName=Ose;var I0="SelectArrow",Lse=x.forwardRef((n,e)=>{const{__scopeSelect:t,...r}=n,s=TC(t),o=tl(I0,t),i=nl(I0,t);return o.open&&i.position==="popper"?p.jsx(aS,{...s,...r,ref:e}):null});Lse.displayName=I0;var jse="SelectBubbleInput",Nse=x.forwardRef(({__scopeSelect:n,value:e,...t},r)=>{const s=x.useRef(null),o=nt(r,s),i=_N(e);return x.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==e&&u){const d=new Event("change",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[i,e]),p.jsx(ke.select,{...t,style:{...nN,...t.style},ref:o,defaultValue:e})});Nse.displayName=jse;function j3(n){return n===""||n===void 0}function N3(n){const e=dr(n),t=x.useRef(""),r=x.useRef(0),s=x.useCallback(i=>{const a=t.current+i;e(a),(function l(c){t.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))})(a)},[e]),o=x.useCallback(()=>{t.current="",window.clearTimeout(r.current)},[]);return x.useEffect(()=>()=>window.clearTimeout(r.current),[]),[t,s,o]}function F3(n,e,t){const s=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,o=t?n.indexOf(t):-1;let i=Fse(n,Math.max(o,0));s.length===1&&(i=i.filter(c=>c!==t));const l=i.find(c=>c.textValue.toLowerCase().startsWith(s.toLowerCase()));return l!==t?l:void 0}function Fse(n,e){return n.map((t,r)=>n[(e+r)%n.length])}var Bse=T3,zse=E3,$se="Separator",JE="horizontal",Hse=["horizontal","vertical"],B3=x.forwardRef((n,e)=>{const{decorative:t,orientation:r=JE,...s}=n,o=Use(r)?r:JE,a=t?{role:"none"}:{"aria-orientation":o==="vertical"?o:void 0,role:"separator"};return p.jsx(ke.div,{"data-orientation":o,...a,...s,ref:e})});B3.displayName=$se;function Use(n){return Hse.includes(n)}var Kse=B3,z3=["PageUp","PageDown"],$3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],H3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Td="Slider",[E0,Wse,Vse]=ep(Td),[U3]=rs(Td,[Vse]),[Gse,mS]=U3(Td),K3=x.forwardRef((n,e)=>{const{name:t,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:d=()=>{},onValueCommit:h=()=>{},inverted:f=!1,form:g,...m}=n,y=x.useRef(new Set),S=x.useRef(0),w=i==="horizontal"?Yse:Xse,[v=[],P]=Ys({prop:u,defaultProp:c,onChange:D=>{var _;(_=[...y.current][S.current])==null||_.focus(),d(D)}}),T=x.useRef(v);function I(D){const j=eoe(v,D);R(D,j)}function k(D){R(D,S.current)}function A(){const D=T.current[S.current];v[S.current]!==D&&h(v)}function R(D,j,{commit:_}={commit:!1}){const M=soe(o),O=ooe(Math.round((D-r)/o)*o+r,M),N=fm(O,[r,s]);P((B=[])=>{const H=Jse(B,N,j);if(roe(H,l*o)){S.current=H.indexOf(N);const z=String(H)!==String(B);return z&&_&&h(H),z?H:B}else return B})}return p.jsx(Gse,{scope:n.__scopeSlider,name:t,disabled:a,min:r,max:s,valueIndexToChangeRef:S,thumbs:y.current,values:v,orientation:i,form:g,children:p.jsx(E0.Provider,{scope:n.__scopeSlider,children:p.jsx(E0.Slot,{scope:n.__scopeSlider,children:p.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...m,ref:e,onPointerDown:le(m.onPointerDown,()=>{a||(T.current=v)}),min:r,max:s,inverted:f,onSlideStart:a?void 0:I,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:A,onHomeKeyDown:()=>!a&&R(r,0,{commit:!0}),onEndKeyDown:()=>!a&&R(s,v.length-1,{commit:!0}),onStepKeyDown:({event:D,direction:j})=>{if(!a){const O=z3.includes(D.key)||D.shiftKey&&$3.includes(D.key)?10:1,N=S.current,B=v[N],H=o*O*j;R(B+H,N,{commit:!0})}}})})})})});K3.displayName=Td;var[W3,V3]=U3(Td,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Yse=x.forwardRef((n,e)=>{const{min:t,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=n,[d,h]=x.useState(null),f=nt(e,w=>h(w)),g=x.useRef(void 0),m=tp(s),y=m==="ltr",S=y&&!o||!y&&o;function b(w){const v=g.current||d.getBoundingClientRect(),P=[0,v.width],I=EC(P,S?[t,r]:[r,t]);return g.current=v,I(w-v.left)}return p.jsx(W3,{scope:n.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width",children:p.jsx(G3,{dir:m,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const v=b(w.clientX);i==null||i(v)},onSlideMove:w=>{const v=b(w.clientX);a==null||a(v)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:w=>{const P=H3[S?"from-left":"from-right"].includes(w.key);c==null||c({event:w,direction:P?-1:1})}})})}),Xse=x.forwardRef((n,e)=>{const{min:t,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=n,u=x.useRef(null),d=nt(e,u),h=x.useRef(void 0),f=!s;function g(m){const y=h.current||u.current.getBoundingClientRect(),S=[0,y.height],w=EC(S,f?[r,t]:[t,r]);return h.current=y,w(m-y.top)}return p.jsx(W3,{scope:n.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:p.jsx(G3,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{const y=g(m.clientY);o==null||o(y)},onSlideMove:m=>{const y=g(m.clientY);i==null||i(y)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:m=>{const S=H3[f?"from-bottom":"from-top"].includes(m.key);l==null||l({event:m,direction:S?-1:1})}})})}),G3=x.forwardRef((n,e)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=n,u=mS(Td,t);return p.jsx(ke.span,{...c,ref:e,onKeyDown:le(n.onKeyDown,d=>{d.key==="Home"?(i(d),d.preventDefault()):d.key==="End"?(a(d),d.preventDefault()):z3.concat($3).includes(d.key)&&(l(d),d.preventDefault())}),onPointerDown:le(n.onPointerDown,d=>{const h=d.target;h.setPointerCapture(d.pointerId),d.preventDefault(),u.thumbs.has(h)?h.focus():r(d)}),onPointerMove:le(n.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&s(d)}),onPointerUp:le(n.onPointerUp,d=>{const h=d.target;h.hasPointerCapture(d.pointerId)&&(h.releasePointerCapture(d.pointerId),o(d))})})}),Y3="SliderTrack",X3=x.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,s=mS(Y3,t);return p.jsx(ke.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:e})});X3.displayName=Y3;var k0="SliderRange",q3=x.forwardRef((n,e)=>{const{__scopeSlider:t,...r}=n,s=mS(k0,t),o=V3(k0,t),i=x.useRef(null),a=nt(e,i),l=s.values.length,c=s.values.map(h=>Q3(h,s.min,s.max)),u=l>1?Math.min(...c):0,d=100-Math.max(...c);return p.jsx(ke.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...n.style,[o.startEdge]:u+"%",[o.endEdge]:d+"%"}})});q3.displayName=k0;var _0="SliderThumb",Z3=x.forwardRef((n,e)=>{const t=Wse(n.__scopeSlider),[r,s]=x.useState(null),o=nt(e,a=>s(a)),i=x.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return p.jsx(qse,{...n,ref:o,index:i})}),qse=x.forwardRef((n,e)=>{const{__scopeSlider:t,index:r,name:s,...o}=n,i=mS(_0,t),a=V3(_0,t),[l,c]=x.useState(null),u=nt(e,b=>c(b)),d=l?i.form||!!l.closest("form"):!0,h=MN(l),f=i.values[r],g=f===void 0?0:Q3(f,i.min,i.max),m=Qse(r,i.values.length),y=h==null?void 0:h[a.size],S=y?toe(y,g,a.direction):0;return x.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),p.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${S}px)`},children:[p.jsx(E0.ItemSlot,{scope:n.__scopeSlider,children:p.jsx(ke.span,{role:"slider","aria-label":n["aria-label"]||m,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:u,style:f===void 0?{display:"none"}:n.style,onFocus:le(n.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),d&&p.jsx(J3,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},r)]})});Z3.displayName=_0;var Zse="RadioBubbleInput",J3=x.forwardRef(({__scopeSlider:n,value:e,...t},r)=>{const s=x.useRef(null),o=nt(s,r),i=_N(e);return x.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==e&&u){const d=new Event("input",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[i,e]),p.jsx(ke.input,{style:{display:"none"},...t,ref:o,defaultValue:e})});J3.displayName=Zse;function Jse(n=[],e,t){const r=[...n];return r[t]=e,r.sort((s,o)=>s-o)}function Q3(n,e,t){const o=100/(t-e)*(n-e);return fm(o,[0,100])}function Qse(n,e){return e>2?`Value ${n+1} of ${e}`:e===2?["Minimum","Maximum"][n]:void 0}function eoe(n,e){if(n.length===1)return 0;const t=n.map(s=>Math.abs(s-e)),r=Math.min(...t);return t.indexOf(r)}function toe(n,e,t){const r=n/2,o=EC([0,50],[0,r]);return(r-o(e)*t)*t}function noe(n){return n.slice(0,-1).map((e,t)=>n[t+1]-e)}function roe(n,e){if(e>0){const t=noe(n);return Math.min(...t)>=e}return!0}function EC(n,e){return t=>{if(n[0]===n[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(n[1]-n[0]);return e[0]+r*(t-n[0])}}function soe(n){return(String(n).split(".")[1]||"").length}function ooe(n,e){const t=Math.pow(10,e);return Math.round(n*t)/t}var ioe=K3,aoe=X3,loe=q3,coe=Z3,kC="ToastProvider",[_C,doe,uoe]=ep("Toast"),[eB]=rs("Toast",[uoe]),[hoe,yS]=eB(kC),tB=n=>{const{__scopeToast:e,label:t="Notification",duration:r=5e3,swipeDirection:s="right",swipeThreshold:o=50,children:i}=n,[a,l]=x.useState(null),[c,u]=x.useState(0),d=x.useRef(!1),h=x.useRef(!1);return t.trim()||console.error(`Invalid prop \`label\` supplied to \`${kC}\`. Expected non-empty \`string\`.`),p.jsx(_C.Provider,{scope:e,children:p.jsx(hoe,{scope:e,label:t,duration:r,swipeDirection:s,swipeThreshold:o,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:x.useCallback(()=>u(f=>f+1),[]),onToastRemove:x.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:d,isClosePausedRef:h,children:i})})};tB.displayName=kC;var nB="ToastViewport",poe=["F8"],M0="toast.viewportPause",A0="toast.viewportResume",rB=x.forwardRef((n,e)=>{const{__scopeToast:t,hotkey:r=poe,label:s="Notifications ({hotkey})",...o}=n,i=yS(nB,t),a=doe(t),l=x.useRef(null),c=x.useRef(null),u=x.useRef(null),d=x.useRef(null),h=nt(e,d,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=i.toastCount>0;x.useEffect(()=>{const y=S=>{var w;r.length!==0&&r.every(v=>S[v]||S.code===v)&&((w=d.current)==null||w.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[r]),x.useEffect(()=>{const y=l.current,S=d.current;if(g&&y&&S){const b=()=>{if(!i.isClosePausedRef.current){const T=new CustomEvent(M0);S.dispatchEvent(T),i.isClosePausedRef.current=!0}},w=()=>{if(i.isClosePausedRef.current){const T=new CustomEvent(A0);S.dispatchEvent(T),i.isClosePausedRef.current=!1}},v=T=>{!y.contains(T.relatedTarget)&&w()},P=()=>{y.contains(document.activeElement)||w()};return y.addEventListener("focusin",b),y.addEventListener("focusout",v),y.addEventListener("pointermove",b),y.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",w),()=>{y.removeEventListener("focusin",b),y.removeEventListener("focusout",v),y.removeEventListener("pointermove",b),y.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",w)}}},[g,i.isClosePausedRef]);const m=x.useCallback(({tabbingDirection:y})=>{const b=a().map(w=>{const v=w.ref.current,P=[v,...Ioe(v)];return y==="forwards"?P:P.reverse()});return(y==="forwards"?b.reverse():b).flat()},[a]);return x.useEffect(()=>{const y=d.current;if(y){const S=b=>{var P,T,I;const w=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!w){const k=document.activeElement,A=b.shiftKey;if(b.target===y&&A){(P=c.current)==null||P.focus();return}const j=m({tabbingDirection:A?"backwards":"forwards"}),_=j.findIndex(M=>M===k);Cb(j.slice(_+1))?b.preventDefault():A?(T=c.current)==null||T.focus():(I=u.current)==null||I.focus()}};return y.addEventListener("keydown",S),()=>y.removeEventListener("keydown",S)}},[a,m]),p.jsxs(UQ,{ref:l,role:"region","aria-label":s.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&p.jsx(D0,{ref:c,onFocusFromOutsideViewport:()=>{const y=m({tabbingDirection:"forwards"});Cb(y)}}),p.jsx(_C.Slot,{scope:t,children:p.jsx(ke.ol,{tabIndex:-1,...o,ref:h})}),g&&p.jsx(D0,{ref:u,onFocusFromOutsideViewport:()=>{const y=m({tabbingDirection:"backwards"});Cb(y)}})]})});rB.displayName=nB;var sB="ToastFocusProxy",D0=x.forwardRef((n,e)=>{const{__scopeToast:t,onFocusFromOutsideViewport:r,...s}=n,o=yS(sB,t);return p.jsx(qy,{tabIndex:0,...s,ref:e,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=o.viewport)!=null&&c.contains(a))&&r()}})});D0.displayName=sB;var hp="Toast",foe="toast.swipeStart",goe="toast.swipeMove",moe="toast.swipeCancel",yoe="toast.swipeEnd",oB=x.forwardRef((n,e)=>{const{forceMount:t,open:r,defaultOpen:s,onOpenChange:o,...i}=n,[a,l]=Ys({prop:r,defaultProp:s??!0,onChange:o,caller:hp});return p.jsx(Xs,{present:t||a,children:p.jsx(boe,{open:a,...i,ref:e,onClose:()=>l(!1),onPause:dr(n.onPause),onResume:dr(n.onResume),onSwipeStart:le(n.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:le(n.onSwipeMove,c=>{const{x:u,y:d}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${d}px`)}),onSwipeCancel:le(n.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:le(n.onSwipeEnd,c=>{const{x:u,y:d}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${d}px`),l(!1)})})})});oB.displayName=hp;var[Soe,xoe]=eB(hp,{onClose(){}}),boe=x.forwardRef((n,e)=>{const{__scopeToast:t,type:r="foreground",duration:s,open:o,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:d,onSwipeCancel:h,onSwipeEnd:f,...g}=n,m=yS(hp,t),[y,S]=x.useState(null),b=nt(e,M=>S(M)),w=x.useRef(null),v=x.useRef(null),P=s||m.duration,T=x.useRef(0),I=x.useRef(P),k=x.useRef(0),{onToastAdd:A,onToastRemove:R}=m,D=dr(()=>{var O;(y==null?void 0:y.contains(document.activeElement))&&((O=m.viewport)==null||O.focus()),i()}),j=x.useCallback(M=>{!M||M===1/0||(window.clearTimeout(k.current),T.current=new Date().getTime(),k.current=window.setTimeout(D,M))},[D]);x.useEffect(()=>{const M=m.viewport;if(M){const O=()=>{j(I.current),c==null||c()},N=()=>{const B=new Date().getTime()-T.current;I.current=I.current-B,window.clearTimeout(k.current),l==null||l()};return M.addEventListener(M0,N),M.addEventListener(A0,O),()=>{M.removeEventListener(M0,N),M.removeEventListener(A0,O)}}},[m.viewport,P,l,c,j]),x.useEffect(()=>{o&&!m.isClosePausedRef.current&&j(P)},[o,P,m.isClosePausedRef,j]),x.useEffect(()=>(A(),()=>R()),[A,R]);const _=x.useMemo(()=>y?hB(y):null,[y]);return m.viewport?p.jsxs(p.Fragment,{children:[_&&p.jsx(woe,{__scopeToast:t,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:_}),p.jsx(Soe,{scope:t,onClose:D,children:Vi.createPortal(p.jsx(_C.ItemSlot,{scope:t,children:p.jsx(HQ,{asChild:!0,onEscapeKeyDown:le(a,()=>{m.isFocusedToastEscapeKeyDownRef.current||D(),m.isFocusedToastEscapeKeyDownRef.current=!1}),children:p.jsx(ke.li,{tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":m.swipeDirection,...g,ref:b,style:{userSelect:"none",touchAction:"none",...n.style},onKeyDown:le(n.onKeyDown,M=>{M.key==="Escape"&&(a==null||a(M.nativeEvent),M.nativeEvent.defaultPrevented||(m.isFocusedToastEscapeKeyDownRef.current=!0,D()))}),onPointerDown:le(n.onPointerDown,M=>{M.button===0&&(w.current={x:M.clientX,y:M.clientY})}),onPointerMove:le(n.onPointerMove,M=>{if(!w.current)return;const O=M.clientX-w.current.x,N=M.clientY-w.current.y,B=!!v.current,H=["left","right"].includes(m.swipeDirection),z=["left","up"].includes(m.swipeDirection)?Math.min:Math.max,X=H?z(0,O):0,G=H?0:z(0,N),ae=M.pointerType==="touch"?10:2,Ce={x:X,y:G},fe={originalEvent:M,delta:Ce};B?(v.current=Ce,df(goe,d,fe,{discrete:!1})):QE(Ce,m.swipeDirection,ae)?(v.current=Ce,df(foe,u,fe,{discrete:!1}),M.target.setPointerCapture(M.pointerId)):(Math.abs(O)>ae||Math.abs(N)>ae)&&(w.current=null)}),onPointerUp:le(n.onPointerUp,M=>{const O=v.current,N=M.target;if(N.hasPointerCapture(M.pointerId)&&N.releasePointerCapture(M.pointerId),v.current=null,w.current=null,O){const B=M.currentTarget,H={originalEvent:M,delta:O};QE(O,m.swipeDirection,m.swipeThreshold)?df(yoe,f,H,{discrete:!0}):df(moe,h,H,{discrete:!0}),B.addEventListener("click",z=>z.preventDefault(),{once:!0})}})})})}),m.viewport)})]}):null}),woe=n=>{const{__scopeToast:e,children:t,...r}=n,s=yS(hp,e),[o,i]=x.useState(!1),[a,l]=x.useState(!1);return Poe(()=>i(!0)),x.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:p.jsx(rp,{asChild:!0,children:p.jsx(qy,{...r,children:o&&p.jsxs(p.Fragment,{children:[s.label," ",t]})})})},voe="ToastTitle",iB=x.forwardRef((n,e)=>{const{__scopeToast:t,...r}=n;return p.jsx(ke.div,{...r,ref:e})});iB.displayName=voe;var Coe="ToastDescription",aB=x.forwardRef((n,e)=>{const{__scopeToast:t,...r}=n;return p.jsx(ke.div,{...r,ref:e})});aB.displayName=Coe;var lB="ToastAction",cB=x.forwardRef((n,e)=>{const{altText:t,...r}=n;return t.trim()?p.jsx(uB,{altText:t,asChild:!0,children:p.jsx(MC,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${lB}\`. Expected non-empty \`string\`.`),null)});cB.displayName=lB;var dB="ToastClose",MC=x.forwardRef((n,e)=>{const{__scopeToast:t,...r}=n,s=xoe(dB,t);return p.jsx(uB,{asChild:!0,children:p.jsx(ke.button,{type:"button",...r,ref:e,onClick:le(n.onClick,s.onClose)})})});MC.displayName=dB;var uB=x.forwardRef((n,e)=>{const{__scopeToast:t,altText:r,...s}=n;return p.jsx(ke.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...s,ref:e})});function hB(n){const e=[];return Array.from(n.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),Toe(r)){const s=r.ariaHidden||r.hidden||r.style.display==="none",o=r.dataset.radixToastAnnounceExclude==="";if(!s)if(o){const i=r.dataset.radixToastAnnounceAlt;i&&e.push(i)}else e.push(...hB(r))}}),e}function df(n,e,t,{discrete:r}){const s=t.originalEvent.currentTarget,o=new CustomEvent(n,{bubbles:!0,cancelable:!0,detail:t});e&&s.addEventListener(n,e,{once:!0}),r?G1(s,o):s.dispatchEvent(o)}var QE=(n,e,t=0)=>{const r=Math.abs(n.x),s=Math.abs(n.y),o=r>s;return e==="left"||e==="right"?o&&r>t:!o&&s>t};function Poe(n=()=>{}){const e=dr(n);Wn(()=>{let t=0,r=0;return t=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(t),window.cancelAnimationFrame(r)}},[e])}function Toe(n){return n.nodeType===n.ELEMENT_NODE}function Ioe(n){const e=[],t=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const s=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||s?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)e.push(t.currentNode);return e}function Cb(n){const e=document.activeElement;return n.some(t=>t===e?!0:(t.focus(),document.activeElement!==e))}var Eoe=tB,koe=oB,_oe=iB,Moe=aB,Aoe=cB,ek=MC,pB="Toggle",fB=x.forwardRef((n,e)=>{const{pressed:t,defaultPressed:r,onPressedChange:s,...o}=n,[i,a]=Ys({prop:t,onChange:s,defaultProp:r??!1,caller:pB});return p.jsx(ke.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":n.disabled?"":void 0,...o,ref:e,onClick:le(n.onClick,()=>{n.disabled||a(!i)})})});fB.displayName=pB;var rl="ToggleGroup",[gB,mB]=rs(rl,[Cd]),yB=Cd(),AC=_e.forwardRef((n,e)=>{const{type:t,...r}=n;if(t==="single"){const s=r;return p.jsx(Doe,{...s,ref:e})}if(t==="multiple"){const s=r;return p.jsx(Ooe,{...s,ref:e})}throw new Error(`Missing prop \`type\` expected on \`${rl}\``)});AC.displayName=rl;var[SB,xB]=gB(rl),Doe=_e.forwardRef((n,e)=>{const{value:t,defaultValue:r,onValueChange:s=()=>{},...o}=n,[i,a]=Ys({prop:t,defaultProp:r??"",onChange:s,caller:rl});return p.jsx(SB,{scope:n.__scopeToggleGroup,type:"single",value:_e.useMemo(()=>i?[i]:[],[i]),onItemActivate:a,onItemDeactivate:_e.useCallback(()=>a(""),[a]),children:p.jsx(bB,{...o,ref:e})})}),Ooe=_e.forwardRef((n,e)=>{const{value:t,defaultValue:r,onValueChange:s=()=>{},...o}=n,[i,a]=Ys({prop:t,defaultProp:r??[],onChange:s,caller:rl}),l=_e.useCallback(u=>a((d=[])=>[...d,u]),[a]),c=_e.useCallback(u=>a((d=[])=>d.filter(h=>h!==u)),[a]);return p.jsx(SB,{scope:n.__scopeToggleGroup,type:"multiple",value:i,onItemActivate:l,onItemDeactivate:c,children:p.jsx(bB,{...o,ref:e})})});AC.displayName=rl;var[Roe,Loe]=gB(rl),bB=_e.forwardRef((n,e)=>{const{__scopeToggleGroup:t,disabled:r=!1,rovingFocus:s=!0,orientation:o,dir:i,loop:a=!0,...l}=n,c=yB(t),u=tp(i),d={role:"group",dir:u,...l};return p.jsx(Roe,{scope:t,rovingFocus:s,disabled:r,children:s?p.jsx(oC,{asChild:!0,...c,orientation:o,dir:u,loop:a,children:p.jsx(ke.div,{...d,ref:e})}):p.jsx(ke.div,{...d,ref:e})})}),mm="ToggleGroupItem",wB=_e.forwardRef((n,e)=>{const t=xB(mm,n.__scopeToggleGroup),r=Loe(mm,n.__scopeToggleGroup),s=yB(n.__scopeToggleGroup),o=t.value.includes(n.value),i=r.disabled||n.disabled,a={...n,pressed:o,disabled:i},l=_e.useRef(null);return r.rovingFocus?p.jsx(lS,{asChild:!0,...s,focusable:!i,active:o,ref:l,children:p.jsx(tk,{...a,ref:e})}):p.jsx(tk,{...a,ref:e})});wB.displayName=mm;var tk=_e.forwardRef((n,e)=>{const{__scopeToggleGroup:t,value:r,...s}=n,o=xB(mm,t),i={role:"radio","aria-checked":n.pressed,"aria-pressed":void 0},a=o.type==="single"?i:void 0;return p.jsx(fB,{...a,...s,ref:e,onPressedChange:l=>{l?o.onItemActivate(r):o.onItemDeactivate(r)}})}),joe=AC,Noe=wB,DC="Toolbar",[Foe]=rs(DC,[Cd,mB]),OC=Cd(),vB=mB(),[Boe,CB]=Foe(DC),PB=x.forwardRef((n,e)=>{const{__scopeToolbar:t,orientation:r="horizontal",dir:s,loop:o=!0,...i}=n,a=OC(t),l=tp(s);return p.jsx(Boe,{scope:t,orientation:r,dir:l,children:p.jsx(oC,{asChild:!0,...a,orientation:r,dir:l,loop:o,children:p.jsx(ke.div,{role:"toolbar","aria-orientation":r,dir:l,...i,ref:e})})})});PB.displayName=DC;var TB="ToolbarSeparator",zoe=x.forwardRef((n,e)=>{const{__scopeToolbar:t,...r}=n,s=CB(TB,t);return p.jsx(Kse,{orientation:s.orientation==="horizontal"?"vertical":"horizontal",...r,ref:e})});zoe.displayName=TB;var $oe="ToolbarButton",RC=x.forwardRef((n,e)=>{const{__scopeToolbar:t,...r}=n,s=OC(t);return p.jsx(lS,{asChild:!0,...s,focusable:!n.disabled,children:p.jsx(ke.button,{type:"button",...r,ref:e})})});RC.displayName=$oe;var Hoe="ToolbarLink",Uoe=x.forwardRef((n,e)=>{const{__scopeToolbar:t,...r}=n,s=OC(t);return p.jsx(lS,{asChild:!0,...s,focusable:!0,children:p.jsx(ke.a,{...r,ref:e,onKeyDown:le(n.onKeyDown,o=>{o.key===" "&&o.currentTarget.click()})})})});Uoe.displayName=Hoe;var IB="ToolbarToggleGroup",EB=x.forwardRef((n,e)=>{const{__scopeToolbar:t,...r}=n,s=CB(IB,t),o=vB(t);return p.jsx(joe,{"data-orientation":s.orientation,dir:s.dir,...o,...r,ref:e,rovingFocus:!1})});EB.displayName=IB;var Koe="ToolbarToggleItem",kB=x.forwardRef((n,e)=>{const{__scopeToolbar:t,...r}=n,s=vB(t),o={__scopeToolbar:n.__scopeToolbar};return p.jsx(RC,{asChild:!0,...o,children:p.jsx(Noe,{...s,...r,ref:e})})});kB.displayName=Koe;var Woe=PB,Voe=RC,Goe=EB,Yoe=kB,[SS]=rs("Tooltip",[Ja]),xS=Ja(),_B="TooltipProvider",Xoe=700,O0="tooltip.open",[qoe,LC]=SS(_B),MB=n=>{const{__scopeTooltip:e,delayDuration:t=Xoe,skipDelayDuration:r=300,disableHoverableContent:s=!1,children:o}=n,i=x.useRef(!0),a=x.useRef(!1),l=x.useRef(0);return x.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),p.jsx(qoe,{scope:e,isOpenDelayedRef:i,delayDuration:t,onOpen:x.useCallback(()=>{window.clearTimeout(l.current),i.current=!1},[]),onClose:x.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:x.useCallback(c=>{a.current=c},[]),disableHoverableContent:s,children:o})};MB.displayName=_B;var bh="Tooltip",[Zoe,bS]=SS(bh),AB=n=>{const{__scopeTooltip:e,children:t,open:r,defaultOpen:s,onOpenChange:o,disableHoverableContent:i,delayDuration:a}=n,l=LC(bh,n.__scopeTooltip),c=xS(e),[u,d]=x.useState(null),h=Ks(),f=x.useRef(0),g=i??l.disableHoverableContent,m=a??l.delayDuration,y=x.useRef(!1),[S,b]=Ys({prop:r,defaultProp:s??!1,onChange:I=>{I?(l.onOpen(),document.dispatchEvent(new CustomEvent(O0))):l.onClose(),o==null||o(I)},caller:bh}),w=x.useMemo(()=>S?y.current?"delayed-open":"instant-open":"closed",[S]),v=x.useCallback(()=>{window.clearTimeout(f.current),f.current=0,y.current=!1,b(!0)},[b]),P=x.useCallback(()=>{window.clearTimeout(f.current),f.current=0,b(!1)},[b]),T=x.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{y.current=!0,b(!0),f.current=0},m)},[m,b]);return x.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),p.jsx(oS,{...c,children:p.jsx(Zoe,{scope:e,contentId:h,open:S,stateAttribute:w,trigger:u,onTriggerChange:d,onTriggerEnter:x.useCallback(()=>{l.isOpenDelayedRef.current?T():v()},[l.isOpenDelayedRef,T,v]),onTriggerLeave:x.useCallback(()=>{g?P():(window.clearTimeout(f.current),f.current=0)},[P,g]),onOpen:v,onClose:P,disableHoverableContent:g,children:t})})};AB.displayName=bh;var R0="TooltipTrigger",DB=x.forwardRef((n,e)=>{const{__scopeTooltip:t,...r}=n,s=bS(R0,t),o=LC(R0,t),i=xS(t),a=x.useRef(null),l=nt(e,a,s.onTriggerChange),c=x.useRef(!1),u=x.useRef(!1),d=x.useCallback(()=>c.current=!1,[]);return x.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),p.jsx(ip,{asChild:!0,...i,children:p.jsx(ke.button,{"aria-describedby":s.open?s.contentId:void 0,"data-state":s.stateAttribute,...r,ref:l,onPointerMove:le(n.onPointerMove,h=>{h.pointerType!=="touch"&&!u.current&&!o.isPointerInTransitRef.current&&(s.onTriggerEnter(),u.current=!0)}),onPointerLeave:le(n.onPointerLeave,()=>{s.onTriggerLeave(),u.current=!1}),onPointerDown:le(n.onPointerDown,()=>{s.open&&s.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:le(n.onFocus,()=>{c.current||s.onOpen()}),onBlur:le(n.onBlur,s.onClose),onClick:le(n.onClick,s.onClose)})})});DB.displayName=R0;var Joe="TooltipPortal",[Aye,Qoe]=SS(Joe,{forceMount:void 0}),cd="TooltipContent",OB=x.forwardRef((n,e)=>{const t=Qoe(cd,n.__scopeTooltip),{forceMount:r=t.forceMount,side:s="top",...o}=n,i=bS(cd,n.__scopeTooltip);return p.jsx(Xs,{present:r||i.open,children:i.disableHoverableContent?p.jsx(RB,{side:s,...o,ref:e}):p.jsx(eie,{side:s,...o,ref:e})})}),eie=x.forwardRef((n,e)=>{const t=bS(cd,n.__scopeTooltip),r=LC(cd,n.__scopeTooltip),s=x.useRef(null),o=nt(e,s),[i,a]=x.useState(null),{trigger:l,onClose:c}=t,u=s.current,{onPointerInTransitChange:d}=r,h=x.useCallback(()=>{a(null),d(!1)},[d]),f=x.useCallback((g,m)=>{const y=g.currentTarget,S={x:g.clientX,y:g.clientY},b=sie(S,y.getBoundingClientRect()),w=oie(S,b),v=iie(m.getBoundingClientRect()),P=lie([...w,...v]);a(P),d(!0)},[d]);return x.useEffect(()=>()=>h(),[h]),x.useEffect(()=>{if(l&&u){const g=y=>f(y,u),m=y=>f(y,l);return l.addEventListener("pointerleave",g),u.addEventListener("pointerleave",m),()=>{l.removeEventListener("pointerleave",g),u.removeEventListener("pointerleave",m)}}},[l,u,f,h]),x.useEffect(()=>{if(i){const g=m=>{const y=m.target,S={x:m.clientX,y:m.clientY},b=(l==null?void 0:l.contains(y))||(u==null?void 0:u.contains(y)),w=!aie(S,i);b?h():w&&(h(),c())};return document.addEventListener("pointermove",g),()=>document.removeEventListener("pointermove",g)}},[l,u,i,c,h]),p.jsx(RB,{...n,ref:o})}),[tie,nie]=SS(bh,{isInside:!1}),rie=yQ("TooltipContent"),RB=x.forwardRef((n,e)=>{const{__scopeTooltip:t,children:r,"aria-label":s,onEscapeKeyDown:o,onPointerDownOutside:i,...a}=n,l=bS(cd,t),c=xS(t),{onClose:u}=l;return x.useEffect(()=>(document.addEventListener(O0,u),()=>document.removeEventListener(O0,u)),[u]),x.useEffect(()=>{if(l.trigger){const d=h=>{const f=h.target;f!=null&&f.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),p.jsx(Zl,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:p.jsxs(iS,{"data-state":l.stateAttribute,...c,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[p.jsx(rie,{children:r}),p.jsx(tie,{scope:t,isInside:!0,children:p.jsx(CQ,{id:l.contentId,role:"tooltip",children:s||r})})]})})});OB.displayName=cd;var LB="TooltipArrow",jB=x.forwardRef((n,e)=>{const{__scopeTooltip:t,...r}=n,s=xS(t);return nie(LB,t).isInside?null:p.jsx(aS,{...s,...r,ref:e})});jB.displayName=LB;function sie(n,e){const t=Math.abs(e.top-n.y),r=Math.abs(e.bottom-n.y),s=Math.abs(e.right-n.x),o=Math.abs(e.left-n.x);switch(Math.min(t,r,s,o)){case o:return"left";case s:return"right";case t:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function oie(n,e,t=5){const r=[];switch(e){case"top":r.push({x:n.x-t,y:n.y+t},{x:n.x+t,y:n.y+t});break;case"bottom":r.push({x:n.x-t,y:n.y-t},{x:n.x+t,y:n.y-t});break;case"left":r.push({x:n.x+t,y:n.y-t},{x:n.x+t,y:n.y+t});break;case"right":r.push({x:n.x-t,y:n.y-t},{x:n.x-t,y:n.y+t});break}return r}function iie(n){const{top:e,right:t,bottom:r,left:s}=n;return[{x:s,y:e},{x:t,y:e},{x:t,y:r},{x:s,y:r}]}function aie(n,e){const{x:t,y:r}=n;let s=!1;for(let o=0,i=e.length-1;o<e.length;i=o++){const a=e[o],l=e[i],c=a.x,u=a.y,d=l.x,h=l.y;u>r!=h>r&&t<(d-c)*(r-u)/(h-u)+c&&(s=!s)}return s}function lie(n){const e=n.slice();return e.sort((t,r)=>t.x<r.x?-1:t.x>r.x?1:t.y<r.y?-1:t.y>r.y?1:0),cie(e)}function cie(n){if(n.length<=1)return n.slice();const e=[];for(let r=0;r<n.length;r++){const s=n[r];for(;e.length>=2;){const o=e[e.length-1],i=e[e.length-2];if((o.x-i.x)*(s.y-i.y)>=(o.y-i.y)*(s.x-i.x))e.pop();else break}e.push(s)}e.pop();const t=[];for(let r=n.length-1;r>=0;r--){const s=n[r];for(;t.length>=2;){const o=t[t.length-1],i=t[t.length-2];if((o.x-i.x)*(s.y-i.y)>=(o.y-i.y)*(s.x-i.x))t.pop();else break}t.push(s)}return t.pop(),e.length===1&&t.length===1&&e[0].x===t[0].x&&e[0].y===t[0].y?e:e.concat(t)}var die=MB,NB=AB,FB=DB,BB=OB,zB=jB;const Co=x.memo(function({label:e,small:t,invertIcon:r,icon:s,color:o,className:i,...a}){return typeof s=="string"?p.jsx(uie,{label:e,small:t,invertIcon:r,icon:s,color:o,className:i,...a}):x.cloneElement(s,{...a,className:xe({"tlui-icon__small":t},i,s.props.className),"aria-label":e,style:{color:o,transform:r?"scale(-1, 1)":void 0,...s.props.style}})});function uie({label:n,small:e,invertIcon:t,icon:r,color:s,className:o,...i}){const a=U1(),l=a.icons[r]??a.icons["question-mark-circle"],c=x.useRef(null);return x.useLayoutEffect(()=>{l||console.error(`Icon not found: ${r}. Add it to the assetUrls.icons object.`),c!=null&&c.current&&(c.current.style.webkitMask=`url(${l}) center 100% / 100% no-repeat`)},[c,l,r]),r==="none"?p.jsx("div",{className:xe("tlui-icon tlui-icon__placeholder",{"tlui-icon__small":e},o),...i}):p.jsx("div",{...i,ref:c,"aria-label":n,role:"img",className:xe("tlui-icon",{"tlui-icon__small":e},o),style:{color:s,mask:`url(${l}) center 100% / 100% no-repeat`,transform:t?"scale(-1, 1)":void 0}})}function Ae({icon:n,small:e,invertIcon:t}){return p.jsx(Co,{"aria-hidden":"true",label:"",className:"tlui-button__icon",icon:n,small:e,invertIcon:t})}function wS({className:n,children:e}){return p.jsx("div",{className:xe("tlui-dialog__header",n),children:e})}function vS({className:n,children:e,style:t}){return p.jsx(Jee,{dir:"ltr",className:xe("tlui-dialog__header__title",n),style:t,children:e})}function CS(){const n=Se();return p.jsx("div",{className:"tlui-dialog__header__close",children:p.jsx(IN,{"data-testid":"dialog.close",dir:"ltr",asChild:!0,children:p.jsx(Ye,{type:"icon","aria-label":n("ui.close"),onTouchEnd:e=>e.target.click(),children:p.jsx(Ae,{small:!0,icon:"cross-2"})})})})}function wh({className:n,children:e,style:t}){return p.jsx("div",{className:xe("tlui-dialog__body",n),style:t,tabIndex:0,children:e})}function jC({className:n,children:e}){return p.jsx("div",{className:xe("tlui-dialog__footer",n),children:e})}const Id=x.forwardRef(function({className:e,label:t,icon:r,iconLeft:s,iconLabel:o,autoSelect:i=!1,autoFocus:a=!1,defaultValue:l,placeholder:c,onComplete:u,onValueChange:d,onCancel:h,onFocus:f,onBlur:g,shouldManuallyMaintainScrollPositionWhenFocused:m=!1,children:y,value:S,"data-testid":b,disabled:w,"aria-label":v},P){const T=Xt(),I=x.useRef(null);x.useImperativeHandle(P,()=>I.current);const k=Se(),A=x.useRef(l??""),R=x.useRef(l??""),D=x.useRef(!1),[j,_]=x.useState(!1),M=x.useCallback(X=>{_(!0);const G=X.currentTarget;R.current=G.value,T?T.timers.requestAnimationFrame(()=>{i&&G.select()}):Ug.requestAnimationFrame("anon",()=>{i&&G.select()}),f==null||f()},[i,T,f]),O=x.useCallback(X=>{const G=X.currentTarget.value;R.current=G,d==null||d(G)},[d]),N=x.useCallback(X=>{switch(X.key){case"Enter":{if(D.current)return;X.currentTarget.blur(),X.stopPropagation(),u==null||u(X.currentTarget.value);break}case"Escape":{X.currentTarget.value=A.current,h==null||h(X.currentTarget.value),X.currentTarget.blur(),X.stopPropagation();break}}},[u,h]),B=x.useCallback(X=>{_(!1);const G=X.currentTarget.value;g==null||g(G)},[g]),H=x.useCallback(()=>D.current=!0,[]),z=x.useCallback(()=>D.current=!1,[]);return x.useEffect(()=>{if(!dt.isIos)return;const X=window.visualViewport;if(j&&m&&X){const G=()=>{var ae;(ae=I.current)==null||ae.scrollIntoView({block:"center"})};return X.addEventListener("resize",G),X.addEventListener("scroll",G),T?T.timers.requestAnimationFrame(()=>{var ae;(ae=I.current)==null||ae.scrollIntoView({block:"center"})}):Ug.requestAnimationFrame("anon",()=>{var ae;(ae=I.current)==null||ae.scrollIntoView({block:"center"})}),()=>{X.removeEventListener("resize",G),X.removeEventListener("scroll",G)}}},[j,T,m]),p.jsxs("div",{draggable:!1,className:"tlui-input__wrapper",children:[y,t&&p.jsx("label",{children:k(t)}),s&&p.jsx(Co,{label:o?k(o):"",icon:s,className:"tlui-icon-left",small:!0}),p.jsx("input",{ref:I,className:xe("tlui-input",e),type:"text",defaultValue:l,onKeyDownCapture:N,onChange:O,onFocus:M,onBlur:B,onCompositionStart:H,onCompositionEnd:z,autoFocus:a,"aria-label":v,placeholder:c,value:S,"data-testid":b,disabled:w}),r&&p.jsx(Co,{label:o?k(o):"",icon:r,small:!!t})]})});function nk(n){return bs.isValid(n)?{isValid:!0,hasProtocol:!0}:bs.isValid("https://"+n)?{isValid:!0,hasProtocol:!1}:{isValid:!1,hasProtocol:!1}}function $B(n){return!!(n&&"url"in n.props&&typeof n.props.url=="string")}function rk(n){if(!$B(n))throw new Error("Shape is not a valid ShapeWithUrl")}const hie=rn(function({onClose:e}){const r=K().getOnlySelectedShape();return $B(r)?p.jsx(pie,{onClose:e,selectedShape:r}):null}),pie=rn(function({onClose:e,selectedShape:t}){const r=K(),s=Se(),o=x.useRef(null);x.useEffect(()=>{r.timers.requestAnimationFrame(()=>{var g;return(g=o.current)==null?void 0:g.focus()})},[r]);const i=x.useRef(t.props.url),[a,l]=x.useState(()=>{const g=nk(t.props.url),m=g.isValid===!0?g.hasProtocol?t.props.url:"https://"+t.props.url:"https://";return{actual:m,safe:m,valid:!0}}),c=x.useCallback(g=>{const m=g.replace(/https?:\/\/(https?:\/\/)/,(b,w)=>w),y=nk(m),S=y.isValid===!0?y.hasProtocol?m:"https://"+m:"https://";l({actual:m,safe:S,valid:y.isValid})},[]),u=x.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(rk(g),r.updateShapes([{id:g.id,type:g.type,props:{url:""}}]),e())},[r,e]),d=x.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(rk(g),g&&"url"in g.props&&g.props.url!==a.safe&&r.updateShapes([{id:g.id,type:g.type,props:{url:a.safe}}]),e())},[r,e,a]),h=x.useCallback(()=>{e()},[e]);if(!t)return e(),null;const f=i.current&&!a.valid;return p.jsxs(p.Fragment,{children:[p.jsxs(wS,{children:[p.jsx(vS,{children:s("edit-link-dialog.title")}),p.jsx(CS,{})]}),p.jsx(wh,{children:p.jsxs("div",{className:"tlui-edit-link-dialog",children:[p.jsx(Id,{ref:o,className:"tlui-edit-link-dialog__input",label:"edit-link-dialog.url",autoFocus:!0,autoSelect:!0,placeholder:"https://example.com",value:a.actual,onValueChange:c,onComplete:d,onCancel:h}),p.jsx("div",{children:a.valid?s("edit-link-dialog.detail"):s("edit-link-dialog.invalid-url")})]})}),p.jsxs(jC,{className:"tlui-dialog__footer__actions",children:[p.jsx(Ye,{type:"normal",onClick:h,onTouchEnd:h,children:p.jsx(Qt,{children:s("edit-link-dialog.cancel")})}),f?p.jsx(Ye,{type:"danger",onTouchEnd:u,onClick:u,children:p.jsx(Qt,{children:s("edit-link-dialog.clear")})}):p.jsx(Ye,{type:"primary",disabled:!a.valid,onTouchEnd:d,onClick:d,children:p.jsx(Qt,{children:s("edit-link-dialog.save")})})]})]})});var fie={};const sk=/(^\/[f|p|r|ro|s|v]\/[^/]+\/?$)/,NC=[{type:"tldraw",title:"tldraw",hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,overridePermissions:{"allow-top-navigation":!0},toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(sk))return e.searchParams.append("embed","true"),n},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(sk))return e.searchParams.delete("embed"),n},embedOnPaste:!1},{type:"figma",title:"Figma",hostnames:["figma.com"],width:720,height:500,doesResize:!0,toEmbedUrl:n=>{if(n.match(/https:\/\/([\w\.-]+\.)?figma.com\/(file|proto|design)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/)&&!n.includes("figma.com/embed"))return`https://www.figma.com/embed?embed_host=share&url=${n}`},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/?$/)){const t=e.searchParams.get("url");if(t)return t}},embedOnPaste:!0},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,overridePermissions:{"allow-presentation":!0},toEmbedUrl:n=>{if(n.includes("/maps/embed?"))return n;if(n.includes("/maps/")){const e=n.match(/@(.*?),(.*?),(.*?)(z|m)/);let t;if(e){const[,r,s,o,i]=e,a=i==="z"?"roadmap":"satellite",l=a==="roadmap"?o:-Math.log2(parseInt(o)/14772321)/.8;t=`https://${new URL(n).host.replace("www.","")}/maps/embed/v1/view?key=${fie.NEXT_PUBLIC_GC_API_KEY}&center=${r},${s}&zoom=${l}&maptype=${a}`}else t="";return t}},fromEmbedUrl:n=>{const e=ze(n);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom")??"12",s=e.searchParams.get("maptype")??"roadmap",o=s==="roadmap"?r:14772321*Math.pow(2,parseInt(r)*-.8),[i,a]=e.searchParams.get("center").split(",");return`https://www.google.com/maps/@${i},${a},${o}${s==="roadmap"?"z":"m"}`}},embedOnPaste:!0},{type:"val_town",title:"Val Town",hostnames:["val.town"],minWidth:260,minHeight:100,width:720,height:500,doesResize:!0,toEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/v\/(.+)\/?/);if(t)return`https://www.val.town/embed/${t[1]}`},fromEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(t)return`https://www.val.town/v/${t[1]}`},embedOnPaste:!0},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/s\/([^/]+)\/?/);if(t)return`https://codesandbox.io/embed/${t[1]}`},fromEmbedUrl:n=>{const e=ze(n),t=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(t)return`https://codesandbox.io/s/${t[1]}`},embedOnPaste:!0},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:n=>{const e=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,t=n.match(e);if(t){const[r,s,o]=t;return`https://codepen.io/${s}/embed/${o}`}},fromEmbedUrl:n=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,t=n.match(e);if(t){const[r,s,o]=t;return`https://codepen.io/${s}/pen/${o}`}},embedOnPaste:!0},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,embedOnPaste:!0,toEmbedUrl:n=>{const e=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,t=n.match(e);if(t){const[r,s]=t;return`https://scratch.mit.edu/projects/embed/${s}`}},fromEmbedUrl:n=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,t=n.match(e);if(t){const[r,s]=t;return`https://scratch.mit.edu/projects/${s}`}}},{type:"youtube",title:"YouTube",hostnames:["*.youtube.com","youtube.com","youtu.be"],width:800,height:450,doesResize:!0,overridePermissions:{"allow-presentation":!0,"allow-popups-to-escape-sandbox":!0},isAspectRatioLocked:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(!e)return;const t=e.hostname.replace(/^www./,"");if(t==="youtu.be"){const r=e.pathname.split("/").filter(Boolean)[0],s=new URLSearchParams(e.search),o=s.get("t");o&&(s.set("start",o),s.delete("t"));const i=s.toString()?"?"+s.toString():"";return`https://www.youtube.com/embed/${r}${i}`}else if((t==="youtube.com"||t==="m.youtube.com")&&e.pathname.match(/^\/watch/)){const r=e.searchParams.get("v"),s=new URLSearchParams(e.search);s.delete("v");const o=s.get("t");o&&(s.set("start",o),s.delete("t"));const i=s.toString()?"?"+s.toString():"";return`https://www.youtube.com/embed/${r}${i}`}},fromEmbedUrl:n=>{const e=ze(n);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r){const s=new URLSearchParams(e.search);s.set("v",(r==null?void 0:r[1])??"");const o=s.get("start");return o&&(s.set("t",o),s.delete("start")),`https://www.youtube.com/watch?${s.toString()}`}}}},{type:"google_calendar",title:"Google Calendar",hostnames:["calendar.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,instructionLink:"https://support.google.com/calendar/answer/41207?hl=en",overridePermissions:{"allow-popups-to-escape-sandbox":!0},embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n),t=e==null?void 0:e.searchParams.get("cid");if(e!=null&&e.pathname.match(/\/calendar\/u\/0/)&&t){e.pathname="/calendar/embed";const r=Array.from(e.searchParams.keys());for(const s of r)e.searchParams.delete(s);return e.searchParams.set("src",t),e.href}},fromEmbedUrl:n=>{const e=ze(n),t=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&t){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const s of r)e.searchParams.delete(s);return e.searchParams.set("cid",t),e.href}}},{type:"google_slides",title:"Google Slides",hostnames:["docs.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,overridePermissions:{"allow-popups-to-escape-sandbox":!0},embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/pub\/?$/))){e.pathname=e.pathname.replace(/\/pub$/,"/embed");const t=Array.from(e.searchParams.keys());for(const r of t)e.searchParams.delete(r);return e.href}},fromEmbedUrl:n=>{const e=ze(n);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const t=Array.from(e.searchParams.keys());for(const r of t)e.searchParams.delete(r);return e.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/([^/]+)\/([0-9a-f]+)$/))return n.split("/").pop()?n:void 0},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/([^/]+)\/([0-9a-f]+)$/))return n.split("/").pop()?n:void 0}},{type:"replit",title:"Replit",hostnames:["replit.com"],width:720,height:500,doesResize:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/))return e.searchParams.append("embed","true"),e.href},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/map\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/(artist|album)\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="vimeo.com"&&e.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+e.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="player.vimeo.com"){const t=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(t)return"https://vimeo.com/"+t[1]}}},{type:"observable",title:"Observable",hostnames:["observablehq.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!1,backgroundColor:"#fff",embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}/embed${e.pathname}?cell=*`;if(e&&e.pathname.match(/^\/d\/([^/]+)\/?$/)){const t=e.pathname.replace(/^\/d/,"");return`${e.origin}/embed${t}?cell=*`}},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{type:"desmos",title:"Desmos",hostnames:["desmos.com"],width:700,height:450,doesResize:!0,embedOnPaste:!0,toEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search===""&&e.hash==="")return`${n}?embed`},fromEmbedUrl:n=>{const e=ze(n);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return n.replace("?embed","")}}],gie={"allow-downloads-without-user-activation":!1,"allow-downloads":!1,"allow-modals":!1,"allow-orientation-lock":!1,"allow-pointer-lock":!1,"allow-popups":!0,"allow-popups-to-escape-sandbox":!1,"allow-presentation":!1,"allow-storage-access-by-user-activation":!1,"allow-top-navigation":!1,"allow-top-navigation-by-user-activation":!1,"allow-scripts":!0,"allow-same-origin":!0,"allow-forms":!0},mie=NC.map(n=>n.type);function yie(n){return mie.includes(n)}function Sie(n){return"icon"in n}function HB(){const n=Xt();if(n&&n.hasShapeUtil("embed"))return n.getShapeUtil("embed")}function FC(){const n=HB();return e=>n?n.getEmbedDefinition(e):void 0}function xie(){const n=HB();return n?n.getEmbedDefinitions():[]}const UB=rn(function({onClose:e}){const t=K(),r=Se(),s=U1(),[o,i]=x.useState(null),[a,l]=x.useState(""),[c,u]=x.useState(null),[d,h]=x.useState(!1),f=x.useRef(-1),g=xie(),m=FC();return p.jsxs(p.Fragment,{children:[p.jsxs(wS,{children:[p.jsx(vS,{children:o?`${r("embed-dialog.title")} — ${o.title}`:r("embed-dialog.title")}),p.jsx(CS,{})]}),o?p.jsxs(p.Fragment,{children:[p.jsxs(wh,{className:"tlui-embed-dialog__enter",children:[p.jsx(Id,{className:"tlui-embed-dialog__input",label:"embed-dialog.url",placeholder:"https://example.com",autoFocus:!0,onValueChange:y=>{l(y);const S=m(y);u(S&&S.definition.type===o.type?S:null),h(!1),clearTimeout(f.current),f.current=t.timers.setTimeout(()=>h(!S),320)}}),a===""?p.jsxs("div",{className:"tlui-embed-dialog__instruction",children:[p.jsx("span",{children:r("embed-dialog.instruction")})," ",o.instructionLink&&p.jsxs(p.Fragment,{children:[p.jsx("a",{target:"_blank",rel:"noopener noreferrer",href:o.instructionLink,className:"tlui-embed-dialog__instruction__link",children:"Learn more"}),"."]})]}):p.jsx("div",{className:"tlui-embed-dialog__warning",children:d?r("embed-dialog.invalid-url"):" "})]}),p.jsxs(jC,{className:"tlui-dialog__footer__actions",children:[p.jsx(Ye,{type:"normal",onClick:()=>{i(null),u(null),l("")},children:p.jsx(Qt,{children:r("embed-dialog.back")})}),p.jsx("div",{className:"tlui-embed__spacer"}),p.jsx(Ye,{type:"normal",onClick:e,children:p.jsx(Qt,{children:r("embed-dialog.cancel")})}),p.jsx(Ye,{type:"primary",disabled:!c,onClick:()=>{c&&(t.putExternalContent({type:"embed",url:a,point:t.getViewportPageBounds().center,embed:c.definition}),e())},children:p.jsx(Qt,{children:r("embed-dialog.create")})})]})]}):p.jsx(p.Fragment,{children:p.jsx(wh,{className:"tlui-embed-dialog__list",children:g.map(y=>{const S=yie(y.type)?s.embedIcons[y.type]:Sie(y)?y.icon:void 0;return p.jsxs(Ye,{type:"menu",onClick:()=>i(y),children:[p.jsx(Qt,{children:y.title}),S&&p.jsx("div",{className:"tlui-embed-dialog__item__image",style:{backgroundImage:`url(${S})`}})]},y.type)})})})]})}),qf=[0,389,436,476,580,640,840,1023];var Ot=(n=>(n[n.ZERO=0]="ZERO",n[n.MOBILE_XXS=1]="MOBILE_XXS",n[n.MOBILE_XS=2]="MOBILE_XS",n[n.MOBILE_SM=3]="MOBILE_SM",n[n.MOBILE=4]="MOBILE",n[n.TABLET_SM=5]="TABLET_SM",n[n.TABLET=6]="TABLET",n[n.DESKTOP=7]="DESKTOP",n))(Ot||{});const KB=_e.createContext(null);function bie({forceMobile:n=!1,children:e}){const t=Xt(),r=W("breakpoint",()=>{const{width:s}=(t==null?void 0:t.getViewportScreenBounds())??{width:window.innerWidth},o=n?Ot.MOBILE_SM:qf.length-1;for(let i=0;i<o;i++)if(s>qf[i]&&s<=qf[i+1])return i;return o},[t]);return p.jsx(KB.Provider,{value:r,children:e})}function Gn(){const n=x.useContext(KB);if(n===null)throw new Error("useBreakpoint must be used inside of the <BreakpointProvider /> component");return n}const WB=x.createContext(null);function PS(){const n=x.useContext(WB);if(!n)throw new Error("useTldrawUiMenuContext must be used within a TldrawUiMenuContextProvider");return n}function Fr({type:n,sourceId:e,children:t}){return p.jsx(WB.Provider,{value:{type:n,sourceId:e},children:t})}function TS(){const n=Xt();return(n==null?void 0:n.store.props.collaboration)!==void 0}function wie(){const n=Xt();return W("sync status",()=>{var e;return(e=n==null?void 0:n.store.props.collaboration)!=null&&e.status?n.store.props.collaboration.status.get():null},[n])}function Ps(){const n=Xt();return W("isReadonlyMode",()=>!!(n!=null&&n.getIsReadonly()),[n])}const ok=dt.isDarwin?"⌘":"__CTRL__",vie=dt.isDarwin?"⌃":"__CTRL__",ik=dt.isDarwin?"⌥":"__ALT__";function VB(n){return n===","?[","]:n.split(",")[0].split(/(\[\[[^\]]+\]\])/g).map(e=>e.startsWith("[[")?e.replace(/[[\]]/g,""):e.replace(/cmd\+/g,ok).replace(/ctrl\+/g,vie).replace(/alt\+/g,ik).replace(/shift\+/g,"⇧").replace(/\$/g,ok).replace(/\?/g,ik).replace(/!/g,"⇧").match(/__CTRL__|__ALT__|./g)||[]).flat().map((e,t)=>{if(e[0]==="+")return[];let r;return e==="__CTRL__"?r="Ctrl":e==="__ALT__"?r="Alt":r=e[0].toUpperCase()+e.slice(1),dt.isDarwin||!t?r:["+",r]}).flat()}function ym(n){return"— "+VB(n).join(" ")}function GB(n){const e=Se();return p.jsx(xR,{"aria-label":e("app.loading"),...n})}const YB=()=>{},XB=x.createContext(null);function Cie({onEvent:n,children:e}){return p.jsx(XB.Provider,{value:n??YB,children:e})}function Rt(){return x.useContext(XB)??YB}function Yi(n,e){const t=Xt(),r=x.useCallback(i=>{i&&(t==null||t.complete()),e==null||e(i)},[t,e]),s=Rt(),o=x.useCallback(i=>{s(i,{source:"unknown",id:n})},[n,s]);return RG(t?`${n}-${t.contextId}`:n,r,o)}function IS({id:n,children:e,modal:t=!1,debugOpen:r=!1}){const[s,o]=Yi(n);return p.jsx(mC,{open:r||s,dir:"ltr",modal:t,onOpenChange:o,children:e})}function ES({children:n,...e}){return p.jsx(yC,{dir:"ltr",asChild:!0,onTouchEnd:t=>je(t),...e,children:n})}function kS({className:n,side:e="bottom",align:t="start",sideOffset:r=8,alignOffset:s=8,children:o}){const i=sn();return p.jsx(hS,{container:i,children:p.jsx(SC,{className:xe("tlui-menu",n),side:e,sideOffset:r,align:t,alignOffset:s,collisionPadding:4,children:o})})}function Pie({id:n,children:e}){const[t,r]=Yi(n);return p.jsx(Zre,{open:t,onOpenChange:r,children:e})}function Tie({id:n,label:e,title:t,disabled:r}){return p.jsx(Jre,{dir:"ltr",asChild:!0,disabled:r,children:p.jsxs(Ye,{"data-testid":n,type:"menu",className:"tlui-menu__submenu__trigger",disabled:r,title:t,children:[p.jsx(Qt,{children:e}),p.jsx(Ae,{icon:"chevron-right",small:!0})]})})}function Iie({id:n,alignOffset:e=-1,sideOffset:t=-6,size:r="small",children:s}){const o=sn();return p.jsx(hS,{container:o,children:p.jsx(Qre,{"data-testid":n,className:"tlui-menu tlui-menu__submenu__content",alignOffset:e,sideOffset:t,collisionPadding:4,"data-size":r,children:s})})}function Eie({className:n,children:e}){return p.jsx("div",{dir:"ltr",className:xe("tlui-menu__group",n),children:e})}function kie({noClose:n,children:e}){return p.jsx(Xre,{dir:"ltr",asChild:!0,onClick:n?je:void 0,children:e})}function _ie({children:n,onSelect:e,...t}){const r=Se();return p.jsxs(p3,{dir:"ltr",className:"tlui-button tlui-button__menu tlui-button__checkbox",onSelect:s=>{e==null||e(s),je(s)},...t,children:[p.jsx("div",{className:"tlui-button__checkbox__indicator",children:p.jsx(qre,{dir:"ltr",children:p.jsx(Co,{label:r("ui.checked"),icon:"check",small:!0})})}),n]})}function Hu({children:n,visibleOnMobileLayout:e=!1}){const t=Gn();return!e&&t<Ot.MOBILE?null:p.jsx("kbd",{className:"tlui-kbd",children:VB(n).map((r,s)=>p.jsx("span",{children:r},s))})}const qB=x.createContext({orientation:"horizontal",tooltipSide:"bottom"});function _S({children:n,orientation:e,tooltipSide:t}){const r=pp(),s=t??(e===r.orientation?r.tooltipSide:e==="horizontal"?"bottom":"right");return p.jsx(qB.Provider,{value:{orientation:e,tooltipSide:s},children:n})}function pp(){return x.useContext(qB)}const Ql=x.forwardRef(({asChild:n,className:e,tooltipSide:t,...r},s)=>{const o=n?V1:"div";return p.jsx(_S,{orientation:"horizontal",tooltipSide:t,children:p.jsx(o,{ref:s,className:xe("tlui-row",e),...r})})}),BC=x.forwardRef(({asChild:n,className:e,tooltipSide:t,...r},s)=>{const o=n?V1:"div";return p.jsx(_S,{orientation:"vertical",tooltipSide:t,children:p.jsx(o,{ref:s,className:xe("tlui-column",e),...r})})}),MS=x.forwardRef(({asChild:n,className:e,tooltipSide:t,...r},s)=>{const o=n?V1:"div";return p.jsx(_S,{orientation:"horizontal",tooltipSide:t,children:p.jsx(o,{ref:s,className:xe("tlui-grid",e),...r})})}),Mie=700,fl=class fl{constructor(){E(this,"state",We("tooltip state",{name:"idle"}))}static getInstance(){return fl.instance||(fl.instance=new fl),fl.instance}hideAllTooltips(){this.handleEvent({type:"hide_all"})}handleEvent(e){const t=this.state.get();switch(e.type){case"pointer_down":{t.name==="waiting_to_hide"&&clearTimeout(t.timeoutId),this.state.set({name:"pointer_down"});break}case"pointer_up":{t.name==="pointer_down"&&this.state.set({name:"idle"});break}case"show":{if(t.name==="pointer_down")return;t.name==="waiting_to_hide"&&clearTimeout(t.timeoutId),this.state.set({name:"showing",tooltip:e.tooltip});break}case"hide":{const{tooltipId:r,editor:s,instant:o}=e;if(t.name==="showing"&&t.tooltip.id===r)if(s&&!o){const i=s.timers.setTimeout(()=>{const a=this.state.get();a.name==="waiting_to_hide"&&a.tooltip.id===r&&this.state.set({name:"idle"})},300);this.state.set({name:"waiting_to_hide",tooltip:t.tooltip,timeoutId:i})}else this.state.set({name:"idle"});else t.name==="waiting_to_hide"&&t.tooltip.id===r&&o&&(clearTimeout(t.timeoutId),this.state.set({name:"idle"}));break}case"hide_all":{if(t.name==="waiting_to_hide"&&clearTimeout(t.timeoutId),t.name==="pointer_down")return;this.state.set({name:"idle"});break}}}getCurrentTooltipData(){const e=this.state.get();let t=null;return(e.name==="showing"||e.name==="waiting_to_hide")&&(t=e.tooltip),!t||Lu.get().isCoarsePointer&&!t.showOnMobile?null:t}};E(fl,"instance",null);let L0=fl;const ao=L0.getInstance();function zC(){ao.hideAllTooltips()}const ZB=x.createContext(!1);function Aie({children:n}){return p.jsx(die,{skipDelayDuration:700,children:p.jsxs(ZB.Provider,{value:!0,children:[n,p.jsx(Die,{})]})})}function Die(){const[n,e]=x.useState(!1),t=x.useRef(null),r=x.useRef(!0),s=Xt(),o=W("current tooltip",()=>ao.getCurrentTooltipData(),[]),i=W("camera state",()=>s==null?void 0:s.getCameraState(),[s]);return x.useEffect(()=>{i==="moving"&&n&&o&&ao.handleEvent({type:"hide",tooltipId:o.id,editor:s,instant:!0})},[i,n,o,s]),x.useEffect(()=>{function a(l){l.key==="Escape"&&o&&n&&(zC(),l.stopPropagation())}return document.addEventListener("keydown",a,{capture:!0}),()=>{document.removeEventListener("keydown",a,{capture:!0})}},[o,n]),x.useEffect(()=>{function a(){ao.handleEvent({type:"pointer_down"})}function l(){ao.handleEvent({type:"pointer_up"})}return document.addEventListener("pointerdown",a,{capture:!0}),document.addEventListener("pointerup",l,{capture:!0}),document.addEventListener("pointercancel",l,{capture:!0}),()=>{document.removeEventListener("pointerdown",a,{capture:!0}),document.removeEventListener("pointerup",l,{capture:!0}),document.removeEventListener("pointercancel",l,{capture:!0}),ao.handleEvent({type:"pointer_up"})}},[]),x.useEffect(()=>{let a=null;if(o&&t.current){const l=o.targetElement.getBoundingClientRect(),c=t.current;c.style.position="fixed",c.style.left=`${l.left}px`,c.style.top=`${l.top}px`,c.style.width=`${l.width}px`,c.style.height=`${l.height}px`,c.style.pointerEvents="none",c.style.zIndex="9999",r.current?a=setTimeout(()=>{e(!0),r.current=!1},o.delayDuration):e(!0)}else e(!1),r.current=!0;return()=>{a!==null&&clearTimeout(a)}},[o]),o?p.jsxs(NB,{open:n,delayDuration:0,children:[p.jsx(FB,{asChild:!0,children:p.jsx("div",{ref:t})}),p.jsxs(BB,{className:"tlui-tooltip",side:o.side,sideOffset:o.sideOffset,avoidCollisions:!0,collisionPadding:8,dir:"ltr",children:[o.content,p.jsx(zB,{className:"tlui-tooltip__arrow"})]})]}):null}const fp=x.forwardRef(({children:n,content:e,side:t,sideOffset:r=5,disabled:s=!1,showOnMobile:o=!1,delayDuration:i},a)=>{const l=Xt(),c=x.useRef(at()),u=x.useContext(ZB),d=W("enhancedA11yMode",()=>l==null?void 0:l.user.getEnhancedA11yMode(),[l]),h=pp(),f=t??h.tooltipSide;if(x.useEffect(()=>{const T=c.current;return()=>{u&&ao.handleEvent({type:"hide",tooltipId:T,editor:l,instant:!0})}},[l,u]),s||!e)return p.jsx(p.Fragment,{children:n});let g;if(d?g=0:g=i??((l==null?void 0:l.options.tooltipDelayMs)||Mie),!u||d)return p.jsxs(NB,{delayDuration:g,disableHoverableContent:!d,children:[p.jsx(FB,{asChild:!0,ref:a,children:n}),p.jsxs(BB,{className:"tlui-tooltip",side:f,sideOffset:r,avoidCollisions:!0,collisionPadding:8,dir:"ltr",children:[e,p.jsx(zB,{className:"tlui-tooltip__arrow"})]})]});const m=_e.Children.only(n);be(_e.isValidElement(m),"TldrawUiTooltip children must be a single element");const y=m,S=T=>{var I,k;(k=(I=y.props).onMouseEnter)==null||k.call(I,T),ao.handleEvent({type:"show",tooltip:{id:c.current,content:e,targetElement:T.currentTarget,side:f,sideOffset:r,showOnMobile:o,delayDuration:g}})},b=T=>{var I,k;(k=(I=y.props).onMouseLeave)==null||k.call(I,T),ao.handleEvent({type:"hide",tooltipId:c.current,editor:l,instant:!1})},w=T=>{var I,k;(k=(I=y.props).onFocus)==null||k.call(I,T),ao.handleEvent({type:"show",tooltip:{id:c.current,content:e,targetElement:T.currentTarget,side:f,sideOffset:r,showOnMobile:o,delayDuration:g}})},v=T=>{var I,k;(k=(I=y.props).onBlur)==null||k.call(I,T),ao.handleEvent({type:"hide",tooltipId:c.current,editor:l,instant:!1})};return _e.cloneElement(y,{onMouseEnter:S,onMouseLeave:b,onFocus:w,onBlur:v})}),Oie={horizontal:Ql,vertical:BC,grid:MS},ur=_e.forwardRef(({children:n,className:e,label:t,orientation:r="horizontal",tooltipSide:s,...o},i)=>{const a=Oie[r];return p.jsx(a,{asChild:!0,tooltipSide:s,children:p.jsx(Woe,{ref:i,...o,className:xe("tlui-toolbar",e),"aria-label":t,orientation:r==="grid"?"horizontal":r,children:n})})}),bt=_e.forwardRef(({asChild:n,children:e,type:t,isActive:r,tooltip:s,...o},i)=>{const a=p.jsx(Voe,{ref:i,asChild:n,draggable:!1,"data-isactive":r,...o,"aria-label":o.title,title:void 0,className:xe("tlui-button",`tlui-button__${t}`,o.className),children:e}),l=s||o.title;return p.jsx(fp,{content:l,children:a})}),Rie=({children:n,className:e,type:t,asChild:r,...s})=>p.jsx(Goe,{asChild:r,type:t,...s,role:"radiogroup",className:xe("tlui-toolbar-toggle-group",e),children:n}),Lie=({children:n,className:e,type:t,value:r,tooltip:s,...o})=>{const i=p.jsx(Yoe,{...o,title:void 0,className:xe("tlui-button",`tlui-button__${t}`,"tlui-toolbar-toggle-group-item",e),value:r,children:n}),a=s||o.title;return p.jsx(fp,{content:a,children:i})};function Ze({disabled:n=!1,spinner:e=!1,readonlyOk:t=!1,id:r,kbd:s,label:o,icon:i,iconLeft:a,onSelect:l,noClose:c,isSelected:u,onDragStart:d}){const{type:h,sourceId:f}=PS(),g=Se(),[m,y]=x.useState(!1);if(Ps()&&!t)return null;const b=Ih(o,h),w=s?ym(s):void 0,v=b?g(b):void 0,P=v&&w?`${v} ${w}`:v;switch(h){case"menu":return p.jsx(kie,{children:p.jsxs(Ye,{type:"menu","data-testid":`${f}.${r}`,disabled:n,onClick:T=>{c&&je(T),m?y(!1):l(f)},children:[a&&p.jsx(Ae,{icon:a,small:!0}),p.jsx(Qt,{children:v}),s&&p.jsx(Hu,{children:s})]})});case"context-menu":return n?null:p.jsxs(Ire,{dir:"ltr",draggable:!1,className:"tlui-button tlui-button__menu","data-testid":`${f}.${r}`,onSelect:T=>{c&&je(T),m?y(!1):l(f)},children:[p.jsx("span",{className:"tlui-button__label",draggable:!1,children:v}),a&&p.jsx(Ae,{icon:a,small:!0}),s&&p.jsx(Hu,{children:s}),e&&p.jsx(GB,{})]});case"small-icons":case"icons":return p.jsx(bt,{"data-testid":`${f}.${r}`,type:"icon",title:P,disabled:n,onClick:()=>l(f),children:p.jsx(Ae,{icon:i,small:!0})});case"keyboard-shortcuts":return s?p.jsxs("div",{className:"tlui-shortcuts-dialog__key-pair","data-testid":`${f}.${r}`,children:[p.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__key",children:v}),p.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__value",children:p.jsx(Hu,{visibleOnMobileLayout:!0,children:s})})]}):(console.warn(`Menu item '${o}' isn't shown in the keyboard shortcuts dialog because it doesn't have a keyboard shortcut.`),null);case"helper-buttons":return p.jsxs(Ye,{type:"low","data-testid":`${f}.${r}`,onClick:()=>l(f),children:[p.jsx(Ae,{icon:i}),p.jsx(Qt,{children:v})]});case"toolbar":return d?p.jsx(ak,{id:r,icon:i,onSelect:l,onDragStart:d,labelStr:v,titleStr:P,disabled:n,isSelected:u}):p.jsx(bt,{"aria-label":v,"aria-pressed":u?"true":"false","data-testid":`tools.${r}`,"data-value":r,disabled:n,onClick:()=>l("toolbar"),onTouchStart:T=>{je(T),l("toolbar")},title:P,type:"tool",children:p.jsx(Ae,{icon:i})});case"toolbar-overflow":return d?p.jsx(ak,{id:r,icon:i,onSelect:l,onDragStart:d,labelStr:v,titleStr:P,disabled:n,isSelected:u,overflow:!0}):p.jsx(bt,{"aria-label":v,"aria-pressed":u?"true":"false",isActive:u,"data-testid":`tools.more.${r}`,"data-value":r,disabled:n,onClick:()=>l("toolbar"),title:P,type:"icon",children:p.jsx(Ae,{icon:i})});default:throw it(h)}}function jie(n,e){const t=K();return x.useMemo(()=>{let s={name:"idle"};function o(c){s={name:"pointing",screenSpaceStart:{x:c.clientX,y:c.clientY}},c.currentTarget.setPointerCapture(c.pointerId)}function i(c){if(!c.isSpecialRedispatchedEvent&&s.name==="pointing"&&C.Dist2(s.screenSpaceStart,{x:c.clientX,y:c.clientY})>(t.getInstanceState().isCoarsePointer?t.options.uiCoarseDragDistanceSquared:t.options.uiDragDistanceSquared)){const d=s.screenSpaceStart;s={name:"dragging",screenSpaceStart:d},t.run(()=>{t.setCurrentTool("select"),t.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...$n(t,c),point:d}),t.selectNone(),n==null||n("toolbar",{type:"pointer",target:"canvas",name:"pointer_move",...$n(t,c),point:d}),zC(),t.getContainer().focus()})}}function a(c){c.isSpecialRedispatchedEvent||(c.currentTarget.releasePointerCapture(c.pointerId),t.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...$n(t,c)}))}function l(){if(s.name==="dragging"||s.name==="dragged")return s={name:"idle"},!0;s={name:"idle"},e==null||e("toolbar")}return{onPointerDown:o,onPointerMove:i,onPointerUp:a,onClick:l}},[n,t,e])}function ak({id:n,labelStr:e,titleStr:t,disabled:r,isSelected:s,icon:o,onSelect:i,onDragStart:a,overflow:l}){const c=jie(a,i);return l?p.jsx(bt,{"aria-label":e,"aria-pressed":s?"true":"false",isActive:s,className:"tlui-button-grid__button","data-testid":`tools.more.${n}`,"data-value":n,disabled:r,title:t,type:"icon",...c,children:p.jsx(Ae,{icon:o})}):p.jsx(bt,{"aria-label":e,"aria-pressed":s?"true":"false","data-testid":`tools.${n}`,"data-value":n,disabled:r,onTouchStart:u=>{je(u),i("toolbar")},title:t,type:"tool",...c,children:p.jsx(Ae,{icon:o})})}function Z({actionId:n="",...e}){const r=ni()[n];return r?p.jsx(Ze,{...r,...e}):null}function $e({id:n,label:e,className:t,children:r}){const s=PS(),{orientation:o}=pp(),i=Se(),a=Ih(e,s.type),l=a?i(a):void 0;switch(s.type){case"menu":return p.jsx(Eie,{className:t,"data-testid":`${s.sourceId}-group.${n}`,children:r});case"context-menu":return p.jsx("div",{dir:"ltr",className:xe("tlui-menu__group",t),"data-testid":`${s.sourceId}-group.${n}`,children:r});case"keyboard-shortcuts":return p.jsxs("div",{className:"tlui-shortcuts-dialog__group","data-testid":`${s.sourceId}-group.${n}`,children:[p.jsx("h2",{className:"tlui-shortcuts-dialog__group__title",children:l}),p.jsx("div",{className:"tlui-shortcuts-dialog__group__content",children:r})]});case"toolbar":{const c=o==="horizontal"?Ql:BC;return p.jsx(c,{className:"tlui-main-toolbar__group","data-testid":`${s.sourceId}-group.${n}`,children:r})}case"toolbar-overflow":return p.jsx(MS,{className:"tlui-main-toolbar__group","data-testid":`${s.sourceId}-group.${n}`,children:r});default:return r}}const j0=x.createContext(null);function Nie({context:n,children:e}){const t=x.useContext(j0),r=Rt(),s=md("dialogs",[]),o=x.useMemo(()=>({dialogs:s,addDialog(i){const a=i.id??at();return s.update(l=>[...l.filter(c=>c.id!==i.id),{...i,id:a}]),r("open-menu",{source:"dialog",id:a}),Tr.addOpenMenu(a,n),a},removeDialog(i){var l;const a=s.get().find(c=>c.id===i);return a&&((l=a.onClose)==null||l.call(a),r("close-menu",{source:"dialog",id:i}),Tr.deleteOpenMenu(i,n),s.update(c=>c.filter(u=>u!==a))),i},clearDialogs(){const i=s.get();i.length!==0&&(i.forEach(a=>{var l;(l=a.onClose)==null||l.call(a),r("close-menu",{source:"dialog",id:a.id}),Tr.deleteOpenMenu(a.id,n)}),s.set([]))}}),[r,s,n]);return t?p.jsx(p.Fragment,{children:e}):p.jsx(j0.Provider,{value:o,children:e})}function gp(){const n=x.useContext(j0);if(!n)throw new Error("useDialogs must be used within a DialogsProvider");return n}const N0=x.createContext(null);function Fie({children:n}){const e=md("toasts",[]),t=x.useContext(N0),r=x.useMemo(()=>({toasts:e,addToast(s){const o=s.id??at();return e.update(i=>[...i.filter(a=>a.id!==s.id),{...s,id:o}]),o},removeToast(s){return e.update(o=>o.filter(i=>i.id!==s)),s},clearToasts(){e.set([])}}),[e]);return t?p.jsx(p.Fragment,{children:n}):p.jsx(Eoe,{children:p.jsx(N0.Provider,{value:r,children:n})})}function Xi(){const n=x.useContext(N0);if(!n)throw new Error("useToasts must be used within a ToastsProvider");return n}function lk(n){return new Promise(e=>{const{allowMultiple:t=!0,mimeTypes:r=[]}=n||{},s=document.createElement("input");s.type="file",s.accept=r==null?void 0:r.join(","),s.multiple=t,s.style.display="none";function o(){s.removeEventListener("change",i),s.removeEventListener("cancel",a),s.remove()}async function i(l){const c=l.target.files;if(!c||c.length===0){e([]),o();return}const u=Array.from(c);s.value="",e(u),o()}function a(){e([]),o()}document.body.appendChild(s),s.addEventListener("cancel",a),s.addEventListener("change",i),s==null||s.click()})}var Pb={exports:{}},ck;function Bie(){return ck||(ck=1,(function(n){var e=(function(){var t=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",o={};function i(l,c){if(!o[l]){o[l]={};for(var u=0;u<l.length;u++)o[l][l.charAt(u)]=u}return o[l][c]}var a={compressToBase64:function(l){if(l==null)return"";var c=a._compress(l,6,function(u){return r.charAt(u)});switch(c.length%4){default:case 0:return c;case 1:return c+"===";case 2:return c+"==";case 3:return c+"="}},decompressFromBase64:function(l){return l==null?"":l==""?null:a._decompress(l.length,32,function(c){return i(r,l.charAt(c))})},compressToUTF16:function(l){return l==null?"":a._compress(l,15,function(c){return t(c+32)})+" "},decompressFromUTF16:function(l){return l==null?"":l==""?null:a._decompress(l.length,16384,function(c){return l.charCodeAt(c)-32})},compressToUint8Array:function(l){for(var c=a.compress(l),u=new Uint8Array(c.length*2),d=0,h=c.length;d<h;d++){var f=c.charCodeAt(d);u[d*2]=f>>>8,u[d*2+1]=f%256}return u},decompressFromUint8Array:function(l){if(l==null)return a.decompress(l);for(var c=new Array(l.length/2),u=0,d=c.length;u<d;u++)c[u]=l[u*2]*256+l[u*2+1];var h=[];return c.forEach(function(f){h.push(t(f))}),a.decompress(h.join(""))},compressToEncodedURIComponent:function(l){return l==null?"":a._compress(l,6,function(c){return s.charAt(c)})},decompressFromEncodedURIComponent:function(l){return l==null?"":l==""?null:(l=l.replace(/ /g,"+"),a._decompress(l.length,32,function(c){return i(s,l.charAt(c))}))},compress:function(l){return a._compress(l,16,function(c){return t(c)})},_compress:function(l,c,u){if(l==null)return"";var d,h,f={},g={},m="",y="",S="",b=2,w=3,v=2,P=[],T=0,I=0,k;for(k=0;k<l.length;k+=1)if(m=l.charAt(k),Object.prototype.hasOwnProperty.call(f,m)||(f[m]=w++,g[m]=!0),y=S+m,Object.prototype.hasOwnProperty.call(f,y))S=y;else{if(Object.prototype.hasOwnProperty.call(g,S)){if(S.charCodeAt(0)<256){for(d=0;d<v;d++)T=T<<1,I==c-1?(I=0,P.push(u(T)),T=0):I++;for(h=S.charCodeAt(0),d=0;d<8;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1}else{for(h=1,d=0;d<v;d++)T=T<<1|h,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=0;for(h=S.charCodeAt(0),d=0;d<16;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1}b--,b==0&&(b=Math.pow(2,v),v++),delete g[S]}else for(h=f[S],d=0;d<v;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1;b--,b==0&&(b=Math.pow(2,v),v++),f[y]=w++,S=String(m)}if(S!==""){if(Object.prototype.hasOwnProperty.call(g,S)){if(S.charCodeAt(0)<256){for(d=0;d<v;d++)T=T<<1,I==c-1?(I=0,P.push(u(T)),T=0):I++;for(h=S.charCodeAt(0),d=0;d<8;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1}else{for(h=1,d=0;d<v;d++)T=T<<1|h,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=0;for(h=S.charCodeAt(0),d=0;d<16;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1}b--,b==0&&(b=Math.pow(2,v),v++),delete g[S]}else for(h=f[S],d=0;d<v;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1;b--,b==0&&(b=Math.pow(2,v),v++)}for(h=2,d=0;d<v;d++)T=T<<1|h&1,I==c-1?(I=0,P.push(u(T)),T=0):I++,h=h>>1;for(;;)if(T=T<<1,I==c-1){P.push(u(T));break}else I++;return P.join("")},decompress:function(l){return l==null?"":l==""?null:a._decompress(l.length,32768,function(c){return l.charCodeAt(c)})},_decompress:function(l,c,u){var d=[],h=4,f=4,g=3,m="",y=[],S,b,w,v,P,T,I,k={val:u(0),position:c,index:1};for(S=0;S<3;S+=1)d[S]=S;for(w=0,P=Math.pow(2,2),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;switch(w){case 0:for(w=0,P=Math.pow(2,8),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;I=t(w);break;case 1:for(w=0,P=Math.pow(2,16),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;I=t(w);break;case 2:return""}for(d[3]=I,b=I,y.push(I);;){if(k.index>l)return"";for(w=0,P=Math.pow(2,g),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;switch(I=w){case 0:for(w=0,P=Math.pow(2,8),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;d[f++]=t(w),I=f-1,h--;break;case 1:for(w=0,P=Math.pow(2,16),T=1;T!=P;)v=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),w|=(v>0?1:0)*T,T<<=1;d[f++]=t(w),I=f-1,h--;break;case 2:return y.join("")}if(h==0&&(h=Math.pow(2,g),g++),d[I])m=d[I];else if(I===f)m=b+b.charAt(0);else return null;y.push(m),d[f++]=b+m.charAt(0),h--,b=m,h==0&&(h=Math.pow(2,g),g++)}}};return a})();n!=null?n.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(Pb)),Pb.exports}var zie=Bie();const F0=Ua(zie),$C="web image/vnd.tldraw+png",$ie={png:$C},Hie={[$C]:"image/png"};function Uie(n){return un($ie,n)??null}function Kie(n){return un(Hie,n)??n}function Wie(n){return typeof ClipboardItem<"u"&&"supports"in ClipboardItem&&ClipboardItem.supports(n)}function Vie(n){const e=Object.entries(n);for(const[t,r]of e)r.catch(s=>console.error(s));return navigator.clipboard.write([new ClipboardItem(n)]).catch(t=>(console.error(t),Promise.all(e.map(async([r,s])=>[r,await s])).then(r=>{const s=W_(r);return navigator.clipboard.write([new ClipboardItem(s)])})))}async function Gie(n,e,t,r){const s=e.map(o=>o instanceof File?o:new File([o],"tldrawFile",{type:o.type}));n.markHistoryStoppingPoint("paste"),await n.putExternalContent({type:"files",files:s,point:t,sources:r})}async function B0(n,e,t,r){return n.markHistoryStoppingPoint("paste"),await n.putExternalContent({type:"url",point:t,url:e,sources:r})}const Yie=[$C,"image/png","image/jpeg","image/webp","image/svg+xml"];function Tb(n){const e=document.implementation.createHTMLDocument("");return e.documentElement.innerHTML=n.trim(),e.body.textContent||e.body.innerText||""}const Xie=n=>{try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}},qie=n=>{const e=n.split(/[\n\s]/);for(const t of e)try{const r=new URL(t);if(!(r.protocol==="http:"||r.protocol==="https:"))return}catch{return}return DR(e)},Zie=n=>/^<svg/.test(n),Jie=["input","select","textarea"];function Ib(n){const{activeElement:e}=document;return n.menus.hasAnyOpenMenus()||e&&(e.isContentEditable||Jie.indexOf(e.tagName.toLowerCase())>-1)}const uf=(n,e,t,r)=>{const s=qie(e);if(s)for(const o of s)B0(n,o,t);else Xie(e)?B0(n,e,t):Zie(e)?(n.markHistoryStoppingPoint("paste"),n.putExternalContent({type:"svg-text",text:e,point:t,sources:r})):(n.markHistoryStoppingPoint("paste"),n.putExternalContent({type:"text",text:e,point:t,sources:r}))},Qie=async(n,e,t)=>{if(n.getEditingShapeId()!==null)return;if(!e)throw Error("No clipboard data");const r=[];for(const s of Object.values(e.items))switch(s.kind){case"file":{r.push({type:"file",source:new Promise(o=>o(s.getAsFile()))});break}case"string":{s.type==="text/html"?r.push({type:"html",source:new Promise(o=>s.getAsString(o))}):s.type==="text/plain"?r.push({type:"text",source:new Promise(o=>s.getAsString(o))}):r.push({type:s.type,source:new Promise(o=>s.getAsString(o))});break}}QB(n,r,t)},JB=async({editor:n,clipboardItems:e,point:t,fallbackFiles:r})=>{const s=[];for(const o of e){for(const i of Yie)if(o.types.includes(i)){const a=o.getType(i).then(l=>ir.rewriteMimeType(l,Kie(i)));s.push({type:"blob",source:a});break}o.types.includes("text/html")&&s.push({type:"html",source:(async()=>{const i=await o.getType("text/html");return await ir.blobToText(i)})()}),o.types.includes("text/uri-list")&&s.push({type:"url",source:(async()=>{const i=await o.getType("text/uri-list");return await ir.blobToText(i)})()}),o.types.includes("text/plain")&&s.push({type:"text",source:(async()=>{const i=await o.getType("text/plain");return await ir.blobToText(i)})()})}return r!=null&&r.length&&s.length===1&&s[0].type==="text"?(s.pop(),s.push(...r.map(o=>({type:"file",source:Promise.resolve(o)})))):r!=null&&r.length&&s.length===0&&s.push(...r.map(o=>({type:"file",source:Promise.resolve(o)}))),await QB(n,s,t)};async function QB(n,e,t){const r=e.filter(o=>(o.type==="file"||o.type==="blob")&&o.source!==null);if(r.length){if(r.length>n.options.maxFilesAtOnce)throw Error("Too many files");const o=Le(await Promise.all(r.map(i=>i.source)));return await Gie(n,o,t)}const s=await Promise.all(e.filter(o=>o.type!=="file").map(o=>new Promise(i=>{const a=o;if(a.type==="file"){i({type:"error",data:null,reason:"unexpected file"});return}a.source.then(l=>{var u;const c=(u=l.match(/<div data-tldraw[^>]*>(.*)<\/div>/))==null?void 0:u[1];if(c)try{let d;try{d=JSON.parse(c)}catch{const h=F0.decompressFromBase64(c);if(h===null){i({type:"error",data:null,reason:"found tldraw data comment but could not parse"});return}d=JSON.parse(h)}if(d.type!=="application/tldraw"){i({type:"error",data:d,reason:`found tldraw data comment but JSON was of a different type: ${d.type}`});return}if(d.version===3)try{const h=JSON.parse(F0.decompressFromBase64(d.data.otherCompressed)||"{}"),f={assets:d.data.assets||[],...h};i({type:"tldraw",data:f});return}catch(h){i({type:"error",data:d,reason:`failed to decompress version 2 clipboard data: ${h}`});return}if(d.version===2)i({type:"tldraw",data:d.data});else{if(typeof d.data=="string"){i({type:"error",data:d,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}i({type:"tldraw",data:d.data});return}}catch{i({type:"error",data:c,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}else{if(a.type==="html"){i({type:"text",data:l,subtype:"html"});return}if(a.type==="url"){i({type:"text",data:l,subtype:"url"});return}try{const d=JSON.parse(l);if(d.type==="excalidraw/clipboard"){i({type:"excalidraw",data:d});return}else{i({type:"text",data:l,subtype:"json"});return}}catch{i({type:"text",data:l,subtype:"text"});return}}i({type:"error",data:l,reason:"unhandled case"})})})));for(const o of s)if(o.type==="tldraw"){n.markHistoryStoppingPoint("paste"),n.putExternalContent({type:"tldraw",content:o.data,point:t});return}for(const o of s)if(o.type==="excalidraw"){n.markHistoryStoppingPoint("paste"),n.putExternalContent({type:"excalidraw",content:o.data,point:t});return}for(const o of s){if(o.type==="text"&&o.subtype==="html"){const a=new DOMParser().parseFromString(o.data,"text/html").querySelector("body");if(a&&Array.from(a.children).filter(c=>c.nodeType===1).length===1&&a.firstElementChild&&a.firstElementChild.tagName==="A"&&a.firstElementChild.hasAttribute("href")&&a.firstElementChild.getAttribute("href")!==""){const c=a.firstElementChild.getAttribute("href");uf(n,c,t,s);return}if(!s.some(c=>c.type==="text"&&c.subtype!=="html")&&o.data.trim()&&(Tb(o.data)??"")){uf(n,Tb(o.data),t,s);return}if(s.some(c=>c.type==="text"&&c.subtype!=="html")){const c=Tb(o.data)??"";if(c){n.markHistoryStoppingPoint("paste"),n.putExternalContent({type:"text",text:c,html:o.data,point:t,sources:s});return}}}if(o.type==="text"&&o.subtype==="text"&&o.data.startsWith("<iframe ")){const a=new DOMParser().parseFromString(o.data,"text/html").querySelector("body");if(a&&Array.from(a.children).filter(c=>c.nodeType===1).length===1&&a.firstElementChild&&a.firstElementChild.tagName==="IFRAME"&&a.firstElementChild.hasAttribute("src")&&a.firstElementChild.getAttribute("src")!==""){const c=a.firstElementChild.getAttribute("src");uf(n,c,t,s);return}}}for(const o of s)if(o.type==="text"&&o.subtype==="url"){B0(n,o.data,t,s);return}for(const o of s)if(o.type==="text"&&o.subtype==="text"&&o.data.trim()){uf(n,o.data,t,s);return}}const Sm=async n=>{var a,l,c;const e=((l=(a=n.getContainer().ownerDocument)==null?void 0:a.defaultView)==null?void 0:l.navigator)??globalThis.navigator,t=await n.resolveAssetsInContent(n.getContentFromCurrentPage(n.getSelectedShapeIds()));if(!t){e&&e.clipboard&&e.clipboard.writeText("");return}const{assets:r,...s}=t,o={type:"application/tldraw",kind:"content",version:3,data:{assets:r||[],otherCompressed:F0.compressToBase64(JSON.stringify(s))}},i=JSON.stringify(o);if(!(typeof e>"u")){const u=t.shapes.map(d=>n.getShapeUtil(d).getText(d)).filter(s6);if((c=e.clipboard)!=null&&c.write){const d=new Blob([`<div data-tldraw>${i}</div>`],{type:"text/html"});let h=u.join(" ");h===""&&(h=" "),e.clipboard.write([new ClipboardItem({"text/html":d,"text/plain":new Blob([h],{type:"text/plain"})})])}else e.clipboard.writeText&&e.clipboard.writeText(`<div data-tldraw>${i}</div>`)}};function eae(){const n=Xt(),e=Rt(),t=x.useCallback(async function(i){be(n,"editor is required for copy"),n.getSelectedShapeIds().length!==0&&(await Sm(n),e("copy",{source:i}))},[n,e]),r=x.useCallback(async function(i){n&&n.getSelectedShapeIds().length!==0&&(await Sm(n),n.deleteShapes(n.getSelectedShapeIds()),e("cut",{source:i}))},[n,e]),s=x.useCallback(async function(i,a,l){n&&n.getEditingShapeId()===null&&(Array.isArray(i)&&i[0]instanceof ClipboardItem?(JB({editor:n,clipboardItems:i,point:l}),e("paste",{source:"menu"})):navigator.clipboard.read().then(c=>{s(c,a,l)}))},[n,e]);return{copy:t,cut:r,paste:s}}function tae(){const n=K(),e=n.getContainer().ownerDocument,t=Rt(),r=W("editor.isFocused",()=>n.getInstanceState().isFocused,[n]);x.useEffect(()=>{if(!r)return;const s=async c=>{n.getSelectedShapeIds().length===0||n.getEditingShapeId()!==null||Ib(n)||(je(c),await Sm(n),t("copy",{source:"kbd"}))};async function o(c){n.getSelectedShapeIds().length===0||n.getEditingShapeId()!==null||Ib(n)||(je(c),await Sm(n),n.deleteShapes(n.getSelectedShapeIds()),t("cut",{source:"kbd"}))}let i=!1;const a=c=>{c.button===1&&(i=!0,n.timers.requestAnimationFrame(()=>{i=!1}))},l=c=>{var f,g;if(i){n.markEventAsHandled(c);return}if(n.getEditingShapeId()!==null||Ib(n))return;let u,d=!1;n.inputs.getShiftKey()&&(d=!0),n.user.getIsPasteAtCursorMode()&&(d=!d),d&&(u=n.inputs.getCurrentPagePoint());const h=()=>{c.clipboardData&&Qie(n,c.clipboardData,u)};if((f=navigator.clipboard)!=null&&f.read){const m=Array.from(((g=c.clipboardData)==null?void 0:g.files)||[]);navigator.clipboard.read().then(y=>{Array.isArray(y)&&y[0]instanceof ClipboardItem&&JB({editor:n,clipboardItems:y,point:u,fallbackFiles:m})},()=>{h()})}else h();je(c),t("paste",{source:"kbd"})};return e==null||e.addEventListener("copy",s),e==null||e.addEventListener("cut",o),e==null||e.addEventListener("paste",l),e==null||e.addEventListener("pointerup",a),()=>{e==null||e.removeEventListener("copy",s),e==null||e.removeEventListener("cut",o),e==null||e.removeEventListener("paste",l),e==null||e.removeEventListener("pointerup",a)}},[n,t,r,e])}const dk={jpeg:"image/jpeg",png:"image/png",webp:"image/webp",svg:"text/plain"};function nae(n,e,t={}){const r=e!=null&&e.length?e:[...n.getCurrentPageShapeIds()],s=t.format??"png";return{blobPromise:n.toImage(r,t).then(o=>ir.rewriteMimeType(o.blob,dk[s])),mimeType:dk[s]}}function rae(n,e,t){if(!navigator.clipboard)return Promise.reject(new Error("Copy not supported"));if(navigator.clipboard.write){const{blobPromise:r,mimeType:s}=nae(n,e,t),o={[s]:r},i=Uie(t.format);return i&&Wie(i)&&(o[i]=r.then(a=>ir.rewriteMimeType(a,i))),Vie(o)}switch(t.format){case"svg":return sae(async()=>{const r=await n.getSvgString(e,t);if(!r)throw new Error("Failed to copy");return r.svg});case"png":throw new Error("Copy not supported");default:it(t.format)}}async function sae(n){var e,t;await((t=(e=navigator.clipboard)==null?void 0:e.writeText)==null?void 0:t.call(e,await n()))}function oae(){const n=Xt(),{addToast:e}=Xi(),t=Se();return x.useCallback((r,s="svg")=>{be(n,"useCopyAs: editor is required"),rae(n,r,{format:s}).catch(()=>{e({id:"copy-fail",severity:"warning",title:t("toast.error.copy-fail.title"),description:t("toast.error.copy-fail.desc")})})},[n,e,t])}async function iae(n,e,t){let r=t.name;if(!r&&(r=`shapes at ${uk()}`,e.length===1)){const i=n.getShape(e[0]);n.isShapeOfType(i,"frame")?r=i.props.name||"frame":r=`${py(i.id)} at ${uk()}`}r+=`.${t.format}`;const{blob:s}=await n.toImage(e,t),o=new File([s],r,{type:s.type});aae(o)}function uk(){const n=new Date,e=String(n.getFullYear()).slice(2),t=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0"),s=String(n.getHours()).padStart(2,"0"),o=String(n.getMinutes()).padStart(2,"0"),i=String(n.getSeconds()).padStart(2,"0");return`${e}-${t}-${r} ${s}.${o}.${i}`}function aae(n){const e=document.createElement("a"),t=URL.createObjectURL(n);e.href=t,e.download=n.name,e.click(),URL.revokeObjectURL(t)}function lae(){const n=Xt(),{addToast:e}=Xi(),t=Se();return x.useCallback((r,s={})=>{be(n,"useExportAs: editor is required");const{format:o="png",name:i,scale:a=1}=s;iae(n,r,{format:o,name:i,scale:a}).catch(l=>{console.error(l.message),e({id:"export-fail",title:t("toast.error.export-fail.title"),description:t("toast.error.export-fail.desc"),severity:"error"})})},[n,e,t])}function cae(){const n=Xt(),e=x.useRef(null),t=x.useRef(null);return x.useCallback(async function(){be(n,"usePrint: editor is required");const s=document.createElement("div"),o=document.createElement("style"),i=(S,b)=>{S&&(S.innerHTML=""),b&&document.head.contains(b)&&document.head.removeChild(b),S&&document.body.contains(S)&&document.body.removeChild(S)};i(e.current,t.current),e.current=s,t.current=o;const a=`tl-print-surface-${at()}`;s.className=a,o.innerHTML=`
344
+ .${a} {
345
+ display: none;
346
+ }
347
+
348
+ .${a} svg {
349
+ max-width: 100%;
350
+ height: 100%;
351
+ display: block;
352
+ }
353
+
354
+ @media print {
355
+ html, body {
356
+ min-height: 100%;
357
+ height: 100%;
358
+ margin: 0;
359
+ }
360
+
361
+ body {
362
+ position: relative;
363
+ }
364
+
365
+ body > * {
366
+ display: none;
367
+ }
368
+
369
+ .tldraw__editor {
370
+ display: none;
371
+ }
372
+
373
+ .${a} {
374
+ display: block !important;
375
+ background: white;
376
+ min-height: 100%;
377
+ height: 100%;
378
+ max-width: 100%;
379
+ }
380
+
381
+ .${a}__item {
382
+ padding: 10mm;
383
+ display: flex;
384
+ min-height: 100%;
385
+ flex-direction: column;
386
+ page-break-after: always;
387
+ position: relative;
388
+ overflow: hidden;
389
+ height: 100%;
390
+ }
391
+
392
+ .${a}__item__main {
393
+ flex: 1;
394
+ display: flex;
395
+ align-items: center;
396
+ justify-content: center;
397
+ max-height: 100%;
398
+ }
399
+
400
+ .${a}__item__header {
401
+ display: none;
402
+ }
403
+
404
+ .${a}__item__footer {
405
+ display: none;
406
+ text-align: right;
407
+ }
408
+
409
+ .${a}__item__footer__hide {
410
+ display: none;
411
+ }
412
+
413
+
414
+ }
415
+
416
+ `;const l=()=>{document.head.appendChild(o),document.body.appendChild(s)},c=()=>{n.once("tick",()=>{i(s,o)})};window.addEventListener("beforeprint",l),window.addEventListener("afterprint",c);function u(S,b,w){try{s.innerHTML+=`<div class="${a}__item">
417
+ <div class="${a}__item__header">
418
+ ${S.replace(/</g,"&lt;").replace(/>/g,"&gt;")}
419
+ </div>
420
+ <div class="${a}__item__main">
421
+ ${w}
422
+ </div>
423
+ <div class="${a}__item__footer ${a}__item__footer__${b?"":"hide"}">
424
+ ${b??""}
425
+ </div>
426
+ </div>`}catch(v){console.error(v)}}function d(){dt.isChromeForIos?(l(),window.print()):dt.isSafari?(l(),document.execCommand("print",!1)):window.print()}const h=n.getSelectedShapeIds(),f=n.getCurrentPageId(),g=n.getPages(),y={scale:1,background:!1,darkMode:!1,preserveAspectRatio:"xMidYMid meet"};if(n.getSelectedShapeIds().length>0){const S=await n.getSvgString(h,y);if(S){const b=g.find(w=>w.id===f);u(`tldraw — ${b==null?void 0:b.name}`,null,S.svg),d()}}else{const S=n.getCurrentPage(),b=await n.getSvgString(n.getSortedChildIdsForParent(S.id),y);b&&(u(`tldraw — ${S.name}`,null,b.svg),d())}window.removeEventListener("beforeprint",l),window.removeEventListener("afterprint",c)},[n])}const e5=x.createContext([]);function HC(){const n=Xt(),{addToast:e,removeToast:t,clearToasts:r}=Xi(),{addDialog:s,clearDialogs:o,removeDialog:i}=gp(),a=Se(),l=cae(),{cut:c,copy:u,paste:d}=eae(),h=oae(),f=lae(),g=FC(),y=Gn()<Ot.TABLET_SM,S=Sa(x.useContext(e5)),b=x.useCallback(async()=>{if(!n)return;const T=await lk({allowMultiple:!0,mimeTypes:S});T.length&&(n.markHistoryStoppingPoint("insert media"),n.putExternalContent({type:"files",files:T,point:n.getViewportPageBounds().center}))},[n,S]),w=x.useCallback(async T=>{if(!n)return;const I=await lk({allowMultiple:!1,mimeTypes:S==null?void 0:S.filter(R=>T?R.startsWith("image/"):R.startsWith("video/"))});if(!I.length)return;const k=n.getOnlySelectedShape();if(!k||T&&k.type!=="image"||!T&&k.type!=="video")return;n.markHistoryStoppingPoint("replace media");const A=I[0];n.replaceExternalContent({type:"file-replace",file:A,shapeId:k.id,isImage:T})},[n,S]),v=x.useCallback(()=>w(!0),[w]),P=x.useCallback(()=>w(!1),[w]);return x.useMemo(()=>({addToast:e,removeToast:t,clearToasts:r,addDialog:s,removeDialog:i,clearDialogs:o,msg:a,isMobile:y,insertMedia:b,replaceImage:v,replaceVideo:P,printSelectionOrPages:l,cut:c,copy:u,paste:d,copyAs:h,exportAs:f,getEmbedDefinition:g}),[e,t,r,s,i,o,a,y,b,v,P,l,c,u,d,h,f,g])}function dae(n,e){const t={};for(const r of n)if(r.translations)for(const[s,o]of $s(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return{actions:(r,s,o)=>{for(const i of n)i.actions&&(s=i.actions(r,s,o));return s},tools:(r,s,o)=>{for(const i of n)i.tools&&(s=i.tools(r,s,{...e,...o}));return s},translations:t}}function t5(n){return x.useMemo(()=>n,n)}function n5(n){const e=t5(n==null?[]:Array.isArray(n)?n:[n]);return x.useMemo(()=>{const t={};for(const r of e)if(r.translations)for(const[s,o]of $s(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return t},[e])}function uae(n){const e=HC(),t=t5(n==null?[]:Array.isArray(n)?n:[n]);return x.useMemo(()=>dae(t,e),[t,e])}const r5=x.createContext(null);function hae({overrides:n,children:e}){const t=Xt(),r=Rt(),s=Yy(),o=Se(),i=HC(),a=x.useCallback((c,u,d)=>{s.announce({msg:o(u.label)}),r("select-tool",{source:c,id:d??u.id})},[s,o,r]),l=x.useMemo(()=>{if(!t)return{};const c=[{id:"select",label:"tool.select",icon:"tool-pointer",kbd:"v",readonlyOk:!0,onSelect(d){if(t.isIn("select")){const h=t.root.getCurrent();h.exit({},h.id),h.enter({},h.id)}t.setCurrentTool("select"),a(d,this)}},{id:"hand",label:"tool.hand",icon:"tool-hand",kbd:"h",readonlyOk:!0,onSelect(d){t.setCurrentTool("hand"),a(d,this)}},{id:"eraser",label:"tool.eraser",icon:"tool-eraser",kbd:"e",onSelect(d){t.setCurrentTool("eraser"),a(d,this)}},{id:"draw",label:"tool.draw",icon:"tool-pencil",kbd:"d,b,x",onSelect(d){t.setCurrentTool("draw"),a(d,this)}},...[...$o.values].map(d=>({id:d,label:`tool.${d}`,meta:{geo:d},kbd:d==="rectangle"?"r":d==="ellipse"?"o":void 0,icon:"geo-"+d,onSelect(h){t.run(()=>{t.setStyleForNextShapes($o,d),t.setCurrentTool("geo"),a(h,this,`geo-${d}`)})},onDragStart(h,f){yc(t,f,{createShape:g=>t.createShape({id:g,type:"geo",props:{w:200,h:200,geo:d}})}),r("drag-tool",{source:h,id:"geo"})}})),{id:"arrow",label:"tool.arrow",icon:"tool-arrow",kbd:"a",onSelect(d){t.setCurrentTool("arrow"),a(d,this)},onDragStart(d,h){yc(t,h,{createShape:f=>t.createShape({id:f,type:"arrow",props:{start:{x:0,y:200},end:{x:200,y:0}}})}),r("drag-tool",{source:d,id:"arrow"})}},{id:"line",label:"tool.line",icon:"tool-line",kbd:"l",onSelect(d){t.setCurrentTool("line"),a(d,this)},onDragStart(d,h){yc(t,h,{createShape:f=>{const[g,m]=El(null,null,2);t.createShape({id:f,type:"line",props:{points:{[g]:{id:g,index:g,x:0,y:200},[m]:{id:m,index:m,x:200,y:0}}}})}}),r("drag-tool",{source:d,id:"line"})}},{id:"frame",label:"tool.frame",icon:"tool-frame",kbd:"f",onSelect(d){t.setCurrentTool("frame"),a(d,this)},onDragStart(d,h){yc(t,h,{createShape:f=>t.createShape({id:f,type:"frame"})}),r("drag-tool",{source:d,id:"frame"})}},{id:"text",label:"tool.text",icon:"tool-text",kbd:"t",onSelect(d){t.setCurrentTool("text"),a(d,this)},onDragStart(d,h){yc(t,h,{createShape:f=>t.createShape({id:f,type:"text",props:{richText:Kn("Text")}}),onDragEnd:f=>{Nr(t,f,{selectAll:!0})}}),r("drag-tool",{source:d,id:"text"})}},{id:"asset",label:"tool.media",icon:"tool-media",kbd:"cmd+u,ctrl+u",onSelect(d){i.insertMedia(),a(d,this,"media")}},{id:"note",label:"tool.note",icon:"tool-note",kbd:"n",onSelect(d){t.setCurrentTool("note"),a(d,this)},onDragStart(d,h){yc(t,h,{createShape:f=>t.createShape({id:f,type:"note"}),onDragEnd:f=>{Nr(t,f,{selectAll:!0})}}),r("drag-tool",{source:d,id:"note"})}},{id:"laser",label:"tool.laser",readonlyOk:!0,icon:"tool-laser",kbd:"k",onSelect(d){t.setCurrentTool("laser"),a(d,this)}},{id:"embed",label:"tool.embed",icon:"dot",onSelect(d){i.addDialog({component:UB}),a(d,this)}},{id:"highlight",label:"tool.highlight",icon:"tool-highlight",kbd:"shift+d",onSelect(d){t.setCurrentTool("highlight"),a(d,this)}}];c.forEach(d=>d.onSelect=d.onSelect.bind(d));const u=Object.fromEntries(c.map(d=>[d.id,d]));return n?n(t,u,i):u},[n,t,i,a,r]);return p.jsx(r5.Provider,{value:l,children:e})}function UC(){const n=x.useContext(r5);if(!n)throw new Error("useTools must be used within a ToolProvider");return n}function yc(n,e,t){const{x:r,y:s}=n.inputs.getCurrentPagePoint(),o=n.markHistoryStoppingPoint("drag shape tool");n.setCurrentTool("select.translating");const i=St();t.createShape(i);const a=Pn(n.getShape(i),"Shape not found"),{w:l,h:c}=n.getShapePageBounds(i);n.updateShape({id:i,type:a.type,x:r-l/2,y:s-c/2}),n.select(i),n.setCurrentTool("select.translating",{...e,target:"shape",shape:n.getShape(i),isCreating:!0,creatingMarkId:o,onCreate(){var u;n.setCurrentTool("select.idle"),n.select(i),(u=t.onDragEnd)==null||u.call(t,i)}}),n.getCurrentTool().setCurrentToolIdMask(a.type)}function Ur({toolId:n="",...e}){const r=UC()[n];return r?p.jsx(Ze,{...r,...e}):null}function pae(){const n=TS();return p.jsxs(p.Fragment,{children:[p.jsxs($e,{label:"shortcuts-dialog.tools",id:"tools",children:[p.jsx(Z,{actionId:"toggle-tool-lock"}),p.jsx(Z,{actionId:"insert-media"}),p.jsx(Ur,{toolId:"select"}),p.jsx(Ur,{toolId:"draw"}),p.jsx(Ur,{toolId:"eraser"}),p.jsx(Ur,{toolId:"hand"}),p.jsx(Ur,{toolId:"rectangle"}),p.jsx(Ur,{toolId:"ellipse"}),p.jsx(Ur,{toolId:"arrow"}),p.jsx(Ur,{toolId:"line"}),p.jsx(Ur,{toolId:"text"}),p.jsx(Ur,{toolId:"frame"}),p.jsx(Ur,{toolId:"note"}),p.jsx(Ur,{toolId:"laser"}),p.jsx(Ze,{id:"pointer-down",label:"tool.pointer-down",kbd:",",onSelect:()=>{}})]}),p.jsxs($e,{label:"shortcuts-dialog.preferences",id:"preferences",children:[p.jsx(Z,{actionId:"toggle-dark-mode"}),p.jsx(Z,{actionId:"toggle-focus-mode"}),p.jsx(Z,{actionId:"toggle-grid"})]}),p.jsxs($e,{label:"shortcuts-dialog.edit",id:"edit",children:[p.jsx(Z,{actionId:"undo"}),p.jsx(Z,{actionId:"redo"}),p.jsx(Z,{actionId:"cut"}),p.jsx(Z,{actionId:"copy"}),p.jsx(Z,{actionId:"paste"}),p.jsx(Z,{actionId:"select-all"}),p.jsx(Z,{actionId:"delete"}),p.jsx(Z,{actionId:"duplicate"})]}),p.jsxs($e,{label:"shortcuts-dialog.view",id:"view",children:[p.jsx(Z,{actionId:"select-zoom-tool"}),p.jsx(Z,{actionId:"zoom-in"}),p.jsx(Z,{actionId:"zoom-out"}),p.jsx(Z,{actionId:"zoom-to-100"}),p.jsx(Z,{actionId:"zoom-to-fit"}),p.jsx(Z,{actionId:"zoom-to-selection"}),p.jsx(Ze,{id:"zoom-quick",label:"action.zoom-quick",kbd:"shift+z",onSelect:()=>{}})]}),p.jsxs($e,{label:"shortcuts-dialog.transform",id:"transform",children:[p.jsx(Z,{actionId:"bring-to-front"}),p.jsx(Z,{actionId:"bring-forward"}),p.jsx(Z,{actionId:"send-backward"}),p.jsx(Z,{actionId:"send-to-back"}),p.jsx(Z,{actionId:"group"}),p.jsx(Z,{actionId:"ungroup"}),p.jsx(Z,{actionId:"flip-horizontal"}),p.jsx(Z,{actionId:"flip-vertical"}),p.jsx(Z,{actionId:"align-top"}),p.jsx(Z,{actionId:"align-center-vertical"}),p.jsx(Z,{actionId:"align-bottom"}),p.jsx(Z,{actionId:"align-left"}),p.jsx(Z,{actionId:"align-center-horizontal"}),p.jsx(Z,{actionId:"align-right"})]}),p.jsxs($e,{label:"shortcuts-dialog.text-formatting",id:"text",children:[p.jsx(Ze,{id:"text-bold",label:"tool.rich-text-bold",kbd:"cmd+b",onSelect:()=>{}}),p.jsx(Ze,{id:"text-italic",label:"tool.rich-text-italic",kbd:"cmd+i",onSelect:()=>{}}),p.jsx(Ze,{id:"text-code",label:"tool.rich-text-code",kbd:"cmd+e",onSelect:()=>{}}),p.jsx(Ze,{id:"text-highlight",label:"tool.rich-text-highlight",kbd:"cmd+shift+h",onSelect:()=>{}}),p.jsx(Ze,{id:"text-strikethrough",label:"tool.rich-text-strikethrough",kbd:"cmd+shift+s",onSelect:()=>{}}),p.jsx(Ze,{id:"text-link",label:"tool.rich-text-link",kbd:"cmd+shift+k",onSelect:()=>{}}),p.jsx(Ze,{id:"text-header",label:"tool.rich-text-header",kbd:"cmd+alt+[[1-6]]",onSelect:()=>{}}),p.jsx(Ze,{id:"text-orderedList",label:"tool.rich-text-orderedList",kbd:"cmd+shift+7",onSelect:()=>{}}),p.jsx(Ze,{id:"text-bulletedlist",label:"tool.rich-text-bulletList",kbd:"cmd+shift+8",onSelect:()=>{}})]}),p.jsxs($e,{label:"shortcuts-dialog.a11y",id:"a11y",children:[p.jsx(Ze,{id:"a11y-select-next-shape",label:"a11y.select-shape",kbd:"[[Tab]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-select-next-shape-direction",label:"a11y.select-shape-direction",kbd:"cmd+[[↑→↓←]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-select-next-shape-container",label:"a11y.enter-leave-container",kbd:"cmd+shift+[[↑↓]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-pan-camera",label:"a11y.pan-camera",kbd:"[[Space]]+[[↑→↓←]]",onSelect:()=>{}}),p.jsx(Ze,{id:"adjust-shape-styles",label:"a11y.adjust-shape-styles",kbd:"cmd+[[Enter]]",onSelect:()=>{}}),p.jsx(Ze,{id:"open-context-menu",label:"a11y.open-context-menu",kbd:"cmd+shift+[[Enter]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-move-shape",label:"a11y.move-shape",kbd:"[[↑→↓←]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-move-shape-faster",label:"a11y.move-shape-faster",kbd:"shift+[[↑→↓←]]",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-rotate-shape-cw",label:"a11y.rotate-shape-cw",kbd:"shift+﹥",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-rotate-shape-cw-fine",label:"a11y.rotate-shape-cw-fine",kbd:"shift+alt+﹥",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-rotate-shape-ccw",label:"a11y.rotate-shape-ccw",kbd:"shift+﹤",onSelect:()=>{}}),p.jsx(Ze,{id:"a11y-rotate-shape-ccw-fine",label:"a11y.rotate-shape-ccw-fine",kbd:"shift+alt+﹤",onSelect:()=>{}}),p.jsx(Z,{actionId:"enlarge-shapes"}),p.jsx(Z,{actionId:"shrink-shapes"}),p.jsx(Z,{actionId:"a11y-repeat-shape-announce"}),p.jsx(Ze,{id:"a11y-open-keyboard-shortcuts",label:"a11y.open-keyboard-shortcuts",kbd:"cmd+alt+/",onSelect:()=>{}})]}),n&&p.jsx($e,{label:"shortcuts-dialog.collaboration",id:"collaboration",children:p.jsx(Z,{actionId:"open-cursor-chat"})})]})}const s5=x.memo(function({children:e}){const t=Se(),r=Gn(),s=e??p.jsx(pae,{});return p.jsxs(p.Fragment,{children:[p.jsxs(wS,{className:"tlui-shortcuts-dialog__header",children:[p.jsx(vS,{children:t("shortcuts-dialog.title")}),p.jsx(CS,{})]}),p.jsx(wh,{className:xe("tlui-shortcuts-dialog__body",{"tlui-shortcuts-dialog__body__mobile":r<=Ot.MOBILE_XS,"tlui-shortcuts-dialog__body__tablet":r<=Ot.TABLET}),children:p.jsx(Fr,{type:"keyboard-shortcuts",sourceId:"kbd",children:s})}),p.jsx("div",{className:"tlui-dialog__scrim"})]})});async function fae(n,e,t){const r=Le(e.map(a=>{const l=n.getShape(a);if(!(!l||n.getShapeUtil(l.type).toSvg===void 0))return l}));if(r.length===0)return;if(r.length===1){const a=r[0];if(!a||n.isShapeOfType(a,"image"))return}const s=[];if(t!==void 0){const a=r.map(l=>({shape:l,bounds:n.getShapeMaskedPageBounds(l).clone().expandBy(t)}));for(let l=0;l<a.length;l++){const c=a[l];if(l===0){s[0]={shapes:[c.shape],bounds:c.bounds};continue}let u=!1;for(const d of s)if(d.bounds.includes(c.bounds)){d.shapes.push(c.shape),d.bounds.expand(c.bounds),u=!0;break}u||s.push({shapes:[c.shape],bounds:c.bounds})}}else{const a=J.Common(r.map(l=>n.getShapeMaskedPageBounds(l)));s.push({shapes:r,bounds:a})}const o=n.options.flattenImageBoundsPadding;for(const a of s){t!==void 0&&a.bounds.expandBy(-t);const l=await n.getSvgString(a.shapes,{padding:o,background:!1});if(!(l!=null&&l.svg))continue;const c=await n.getAssetForExternalContent({type:"file",file:new File([l.svg],"asset.svg",{type:"image/svg+xml"})});c&&(a.asset=c)}const i=[];return ms(()=>{for(const a of s){const{asset:l,bounds:c,shapes:u}=a;if(!l)continue;const d=n.findCommonAncestor(u)??n.getCurrentPageId();if(!d)continue;let h="a1";for(const S of u)if(S.parentId===d){S.index>h&&(h=S.index);break}let f,g,m;if(Pr(d)){const S=n.getShape(d);if(!S)continue;const b=n.getPointInShapeSpace(S,{x:c.x,y:c.y});m=n.getShapePageTransform(d).rotation(),b.sub(new C(o,o).rot(-m)),f=b.x,g=b.y}else f=c.x-o,g=c.y-o,m=0;n.deleteShapes(u),n.createAssets([{...l,id:l.id}]);const y=St();n.createShape({id:y,type:"image",index:h,parentId:d,x:f,y:g,rotation:-m,props:{assetId:l.id,w:c.w+o*2,h:c.h+o*2}}),i.push(y)}}),i}function Bl({id:n,children:e,onOpenChange:t,open:r,className:s}){const[o,i]=Yi(n,t);return p.jsx(bC,{onOpenChange:i,open:r||o,children:p.jsx("div",{className:xe("tlui-popover",s),children:e})})}function zl({children:n}){return p.jsx(wC,{asChild:!0,dir:"ltr",children:n})}function $l({side:n,children:e,align:t="center",sideOffset:r=8,alignOffset:s=0,disableEscapeKeyDown:o=!1,autoFocusFirstButton:i=!0}){const a=sn(),l=_e.useRef(null),c=_e.useCallback(()=>{var f;if(!i)return;const h=[...((f=l.current)==null?void 0:f.querySelectorAll("button:not([disabled])"))??[]].filter(g=>g.offsetWidth||g.offsetHeight)[0];h&&h.focus()},[i]);return p.jsx(vC,{container:a,children:p.jsx(CC,{className:"tlui-popover__content",side:n,sideOffset:r,align:t,alignOffset:s,dir:"ltr",ref:l,onOpenAutoFocus:c,onEscapeKeyDown:u=>o&&u.preventDefault(),children:e})})}function xm(n,e,t){const{arrowheadStart:r,arrowheadEnd:s}=e.props,o=pl(n,e,t),i=o.start.clone(),a=o.end.clone(),l=C.Med(i,a);if(C.Equals(i,a))return{bindings:t,type:"straight",start:{handle:i,point:i,arrowhead:e.props.arrowheadStart},end:{handle:a,point:a,arrowhead:e.props.arrowheadEnd},middle:l,isValid:!1,length:0};const c=C.Sub(a,i).uni(),u=wm(n,e,"start"),d=wm(n,e,"end"),h=n.getShapePageTransform(e);hk(a,o.start,h,d),hk(i,o.end,h,u);let f=0,g=0,m=0,y=0,S=Dc*e.props.scale;const b=u&&d&&u.shape===d.shape,w=u&&d?KC(n,u.shape.id,d.shape.id):"safe";w==="safe"&&u&&d&&!b&&!u.isExact&&!d.isExact&&(d.didIntersect&&!u.didIntersect?u.isClosed&&i.setTo(a.clone().add(c.clone().mul(Dc*e.props.scale))):d.didIntersect||d.isClosed&&a.setTo(i.clone().sub(c.clone().mul(Dc*e.props.scale))));const v=C.Sub(a,i),P=C.Len(v)?v.uni():C.From(v),T=!C.Equals(P,c);b||(w!=="start-contains-end"&&u&&r!=="none"&&!u.isExact&&(m=qr[e.props.size]/2+("size"in u.shape.props?qr[u.shape.props.size]/2:0),f=(Ch+m)*e.props.scale,S+=m*e.props.scale),w!=="end-contains-start"&&d&&s!=="none"&&!d.isExact&&(y=qr[e.props.size]/2+("size"in d.shape.props?qr[d.shape.props.size]/2:0),g=(Ch+y)*e.props.scale,S+=y*e.props.scale));const I=i.clone().add(P.clone().mul(f*(T?-1:1))),k=a.clone().sub(P.clone().mul(g*(T?-1:1)));C.DistMin(I,k,S)&&(f!==0&&g!==0?(f*=-1.5,g*=-1.5):f!==0?f*=-1:g!==0&&(g*=-1)),i.add(P.clone().mul(f*(T?-1:1))),a.sub(P.clone().mul(g*(T?-1:1))),T?(u&&d&&a.setTo(C.Add(i,P.clone().mul(-Dc*e.props.scale))),l.setTo(C.Med(o.start,o.end))):l.setTo(C.Med(i,a));const A=C.Dist(i,a);return{bindings:t,type:"straight",start:{handle:o.start,point:i,arrowhead:e.props.arrowheadStart},end:{handle:o.end,point:a,arrowhead:e.props.arrowheadEnd},middle:l,isValid:A>0,length:A}}function hk(n,e,t,r){if(r===void 0||r.isExact)return;const s=Q.applyToPoint(t,e),o=Q.applyToPoint(t,n),i=Q.applyToPoint(Q.Inverse(r.transform),s),a=Q.applyToPoint(Q.Inverse(r.transform),o),l=Array.from(r.geometry.intersectLineSegment(i,a,{includeLabels:!1,includeInternal:!1}));let c;if(l.length&&(c=l.sort((h,f)=>C.Dist2(h,i)-C.Dist2(f,i))[0]??(r.isClosed?void 0:a)),c===void 0&&(c=r.geometry.nearestPoint(a,{includeLabels:!1,includeInternal:!1}),!C.DistMin(c,a,1)))return;const u=Q.applyToPoint(r.transform,c),d=Q.applyToPoint(Q.Inverse(t),u);n.setTo(d),r.didIntersect=!0}function gae(n,e,t){const{arrowheadEnd:r,arrowheadStart:s}=e.props,o=e.props.bend;if(Math.abs(o)>Math.abs(e.props.bend*(Fae*e.props.scale)))return xm(n,e,t);const i=pl(n,e,t),a=C.Med(i.start,i.end),l=C.Sub(i.end,i.start),c=C.Len(l)?l.uni():C.From(l),u=C.Add(a,c.per().mul(-o)),d=wm(n,e,"start"),h=wm(n,e,"end"),f=i.start.clone(),g=i.end.clone(),m=u.clone();if(C.Equals(f,g))return{bindings:t,type:"straight",start:{handle:f,point:f,arrowhead:e.props.arrowheadStart},end:{handle:g,point:g,arrowhead:e.props.arrowheadEnd},middle:m,isValid:!1,length:0};const y=e.props.bend<0,S=y?Hv:LU,b=pk(f,g,m),w=C.Angle(b.center,f),v=C.Angle(b.center,g),P=S(w,v);if(b.length===0||b.size===0||!gT(b.length)||!gT(b.size))return xm(n,e,t);const T=f.clone(),I=g.clone(),k=m.clone(),A=n.getShapePageTransform(e);let R=0,D=0,j=Dc*e.props.scale;if(d&&!d.isExact){const X=Q.applyToPoint(A,T),G=Q.applyToPoint(A,b.center),ae=Q.applyToPoint(A,I),Ce=Q.Inverse(d.transform),fe=Q.applyToPoint(Ce,X),oe=Q.applyToPoint(Ce,G),Te=Q.applyToPoint(Ce,ae),{isClosed:te}=d;let re,ge=Array.from(d.geometry.intersectCircle(oe,b.radius,{includeLabels:!1,includeInternal:!1}));if(ge.length){const de=oe.angle(fe),Ne=oe.angle(Te),De=S(de,Ne);ge=ge.filter(lt=>S(de,oe.angle(lt))<=De);const rt=De*.25;ge.sort(te?(lt,pt)=>Math.abs(S(de,oe.angle(lt))-rt)<Math.abs(S(de,oe.angle(pt))-rt)?-1:1:(lt,pt)=>S(de,oe.angle(lt))<S(de,oe.angle(pt))?-1:1),re=ge[0]}if(!re)if(te){const de=d.geometry.nearestPoint(fe,{includeInternal:!1,includeLabels:!1});C.DistMin(de,fe,1)&&(re=de)}else re=fe;if(re&&(T.setTo(n.getPointInShapeSpace(e,Q.applyToPoint(d.transform,re))),d.didIntersect=!0,s!=="none")){const de=qr[e.props.size]/2+("size"in d.shape.props?qr[d.shape.props.size]/2:0);R=(Ch+de)*e.props.scale,j+=de*e.props.scale}}if(h&&!h.isExact){const X=Q.applyToPoint(A,T),G=Q.applyToPoint(A,I),ae=Q.applyToPoint(A,b.center),Ce=Q.Inverse(h.transform),fe=Q.applyToPoint(Ce,X),oe=Q.applyToPoint(Ce,ae),Te=Q.applyToPoint(Ce,G),te=h.isClosed;let re,ge=Array.from(h.geometry.intersectCircle(oe,b.radius,{includeLabels:!1,includeInternal:!1}));if(ge.length){const de=oe.angle(fe),Ne=oe.angle(Te),De=S(de,Ne),rt=De*.75;ge=ge.filter(lt=>S(de,oe.angle(lt))<=De),ge.sort(te?(lt,pt)=>Math.abs(S(de,oe.angle(lt))-rt)<Math.abs(S(de,oe.angle(pt))-rt)?-1:1:(lt,pt)=>S(de,oe.angle(lt))<S(de,oe.angle(pt))?-1:1),re=ge[0]}if(!re)if(te){const de=h.geometry.nearestPoint(Te,{includeInternal:!1,includeLabels:!1});C.DistMin(de,Te,1)&&(re=de)}else re=Te;if(re&&(I.setTo(n.getPointInShapeSpace(e,Q.applyToPoint(h.transform,re))),h.didIntersect=!0,r!=="none")){const de=qr[e.props.size]/2+("size"in h.shape.props?qr[h.shape.props.size]/2:0);D=(Ch+de)*e.props.scale,j+=de*e.props.scale}}let _=C.Angle(b.center,T),M=C.Angle(b.center,I),O=S(_,M),N=O*b.radius;const B=T.clone(),H=I.clone();if(R!==0&&B.setTo(b.center).add(C.FromAngle(_+O*(R/N*(y?1:-1))).mul(b.radius)),D!==0&&H.setTo(b.center).add(C.FromAngle(M+O*(D/N*(y?-1:1))).mul(b.radius)),C.DistMin(B,H,j)){R!==0&&D!==0?(R*=-1.5,D*=-1.5):R!==0?R*=-2:D!==0&&(D*=-2);const X=.1-S(w,_)*b.radius,G=.1-S(M,v)*b.radius;R=Math.max(R,X),D=Math.max(D,G)}if(R!==0&&T.setTo(b.center).add(C.FromAngle(_+O*(R/N*(y?1:-1))).mul(b.radius)),D!==0&&I.setTo(b.center).add(C.FromAngle(M+O*(D/N*(y?-1:1))).mul(b.radius)),d&&h&&!d.isExact&&!h.isExact){_=C.Angle(b.center,T),M=C.Angle(b.center,I),O=S(_,M),N=O*b.radius;const X=KC(n,d.shape.id,h.shape.id);X==="double-bound"&&N<30?(T.setTo(f),I.setTo(g),k.setTo(m)):X==="safe"&&(d&&!d.didIntersect&&T.setTo(f),(h&&!h.didIntersect||S(w,_)>S(w,M))&&I.setTo(b.center).add(C.FromAngle(_+O*(Math.min(.9,Dc*e.props.scale/N)*(y?1:-1))).mul(b.radius)))}mae(b.center,b.radius,T,I,k,P,y),T.equals(I)&&(T.setTo(k.clone().addXY(1,1)),I.setTo(k.clone().subXY(1,1))),f.setTo(T),g.setTo(I),m.setTo(k);const z=pk(f,g,m);return{bindings:t,type:"arc",start:{point:f,handle:i.start,arrowhead:e.props.arrowheadStart},end:{point:g,handle:i.end,arrowhead:e.props.arrowheadEnd},middle:m,handleArc:b,bodyArc:z,isValid:z.length!==0&&isFinite(z.center.x)&&isFinite(z.center.y)}}function pk(n,e,t){const r=gA(n,e,t)??C.Med(n,e),s=C.Dist(r,n),o=+C.Clockwise(n,t,e),i=((n.y-e.y)**2+(n.x-e.x)**2)**.5,a=((e.y-t.y)**2+(e.x-t.x)**2)**.5,l=((t.y-n.y)**2+(t.x-n.x)**2)**.5,c=Math.acos((a*a+l*l-i*i)/(2*a*l))*2,u=+(ht>c),d=(vt-c)*(o?1:-1),h=d*s;return{center:r,radius:s,size:d,length:h,largeArcFlag:u,sweepFlag:o}}function mae(n,e,t,r,s,o,i){const a=C.Angle(n,t),l=C.Angle(n,r);let c=Hv(a,l);if(i||(c=vt-c),s.setTo(n).add(C.FromAngle(a+c*(.5*(i?1:-1))).mul(e)),c>o){s.rotWith(n,ht);const u=r.clone();r.setTo(t),t.setTo(u)}}const fk=["right","bottom","left","top"],yae={top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}},Sae={left:"x",right:"x",top:"y",bottom:"y"},Sc={top:"bottom",right:"left",bottom:"top",left:"right"},vh={x:{v:(n,e)=>new C(n,e),loEdge:"left",hiEdge:"right",crossMid:"midY",gap:"gapX",midRange:"midXRange",self:"x",cross:"y",size:"width"},y:{v:(n,e)=>new C(e,n),loEdge:"top",hiEdge:"bottom",crossMid:"midX",gap:"gapY",midRange:"midYRange",self:"y",cross:"x",size:"height"}};function xae(n,e){const t={min:n.min-e,max:n.max+e};return t.min>t.max?null:t}function bae(n,e){return be(n.min<=n.max&&e.min<=e.max),n.min<=e.min&&e.max<=n.max?[{min:n.min,max:e.min},{min:e.max,max:n.max}]:e.max<=n.min||e.min>=n.max?[n]:e.min<=n.min&&n.max<=e.max?[]:bm(n.min,e)?[{min:e.max,max:n.max}]:bm(n.max,e)?[{min:n.min,max:e.min}]:[]}function Eb(n,e){return{min:Math.min(n,e),max:Math.max(n,e)}}function bm(n,e){return n>=e.min&&n<=e.max}function gk(n){return n.max-n.min}function hf(n){if(!n)return;const e=n.cross.min;n.cross.min=-n.cross.max,n.cross.max=-e,n.crossTarget=-n.crossTarget}function pf(n){n&&(n.value=-n.value,n.expanded=n.expanded===null?null:-n.expanded)}const cn={Identity:{x:1,y:1,transpose:!1},Rotate90:{x:-1,y:1,transpose:!0},Rotate180:{x:-1,y:-1,transpose:!1},Rotate270:{x:1,y:-1,transpose:!0},FlipY:{x:1,y:-1,transpose:!1}};function wae(n){return n.transpose?{x:n.y,y:n.x,transpose:!0}:n}function vae(n,e){const t={...n};return e.transpose&&(Ia(t,"x","y"),t.transpose=!t.transpose),e.x===-1&&(t.x=-t.x),e.y===-1&&(t.y=-t.y),t}function Ia(n,e,t){const r=n[e];n[e]=n[t],n[t]=r}function mk(n,e){e.x=n.x*e.x,e.y=n.y*e.y,n.transpose&&Ia(e,"x","y")}function xc(n,e){n.x===-1&&(e.x=-(e.x+e.width)),n.y===-1&&(e.y=-(e.y+e.height)),n.transpose&&(Ia(e,"x","y"),Ia(e,"width","height"))}function yk(n,e){n.x===-1&&(Ia(e,"left","right"),hf(e.top),hf(e.bottom),pf(e.left),pf(e.right)),n.y===-1&&(Ia(e,"top","bottom"),hf(e.left),hf(e.right),pf(e.top),pf(e.bottom)),n.transpose&&(Ia(e,"left","top"),Ia(e,"right","bottom"))}class Cae{constructor(e){E(this,"options");E(this,"A");E(this,"B");E(this,"common");E(this,"gapX");E(this,"gapY");E(this,"midX");E(this,"midY");E(this,"bias");E(this,"transform",cn.Identity);E(this,"inverse",cn.Identity);this.options=e.options,this.A=e.A,this.B=e.B,this.common=e.common,this.midX=e.midX,this.midY=e.midY,this.gapX=e.gapX,this.gapY=e.gapY,this.bias=new C(1,1)}apply(e){if(this.transform=vae(e,this.transform),this.inverse=wae(this.transform),xc(e,this.A.original),xc(e,this.B.original),xc(e,this.common.original),xc(e,this.A.expanded),xc(e,this.B.expanded),xc(e,this.common.expanded),yk(e,this.A.edges),yk(e,this.B.edges),mk(e,this.bias),e.x===-1&&(this.gapX=-this.gapX,this.midX=this.midX===null?null:-this.midX),e.y===-1&&(this.gapY=-this.gapY,this.midY=this.midY===null?null:-this.midY),e.transpose){let t=this.midX;this.midX=this.midY,this.midY=t,t=this.gapX,this.gapX=this.gapY,this.gapY=t}}reset(){this.apply(this.inverse)}vec(e,t){const r=new C(e,t);return mk(this.inverse,r),r}}const bc=.01;class Gr{constructor(e,t){E(this,"points",[]);E(this,"_midpointHandle",null);this.info=e,this.name=t}add(e,t){return this.points.push(this.info.vec(e,t)),this}midpointHandle(e){be(this._midpointHandle===null,"midX/midY called multiple times");const t=C.Lrp(this.points[this.points.length-2],this.points[this.points.length-1],.5);return this._midpointHandle={axis:this.info.transform.transpose?e==="x"?"y":"x":e,point:t,segmentStart:this.points[this.points.length-2].clone(),segmentEnd:this.points[this.points.length-1].clone()},this}build(){const e=[];for(let t=0;t<this.points.length;t++){const r=this.points[t],s=e[e.length-1],o=e[e.length-2];if(!s||!o)e.push(r);else{const i=Math.abs(r.x-s.x),a=Math.abs(r.y-s.y),l=Math.abs(r.x-o.x),c=Math.abs(r.y-o.y);i<bc&&a<bc||(i<bc&&l<bc?s.y=r.y:a<bc&&c<bc?s.x=r.x:e.push(r))}}return{name:this.name,points:e,distance:Pae(e),aEdgePicking:"manual",bEdgePicking:"manual",skipPointsWhenDrawing:new Set,midpointHandle:this._midpointHandle}}}function Pae(n){let e=0;for(let t=0;t<n.length-1;t++){const r=n[t],s=n[t+1];e+=Math.abs(s.x-r.x)+Math.abs(s.y-r.y)}return e}function ff(n){const e=n.A.edges.right,t=n.B.edges.left;if(!e||!t)return null;if(e.crossTarget>t.crossTarget&&n.apply(cn.FlipY),n.gapX>0&&n.midX!==null)return new Gr(n,"to left 1").add(e.value,e.crossTarget).add(n.midX,e.crossTarget).add(n.midX,t.crossTarget).midpointHandle("x").add(t.value,t.crossTarget).build();if(e.expanded===null||t.expanded===null)return null;if(n.midY!==null)return new Gr(n,"to left 2").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.midY).add(t.expanded,n.midY).midpointHandle("y").add(t.expanded,t.crossTarget).add(t.value,t.crossTarget).build();const r=Math.abs(e.value-n.common.expanded.right)+Math.abs(e.crossTarget-n.common.expanded.bottom)+Math.abs(n.common.expanded.right-t.expanded)+Math.abs(n.common.expanded.bottom-t.crossTarget)+n.options.expandElbowLegLength+6,s=n.options.expandElbowLegLength+Math.abs(e.crossTarget-n.common.expanded.top)+Math.abs(e.expanded-n.common.expanded.left)+Math.abs(n.common.expanded.top-t.crossTarget)+Math.abs(n.common.expanded.left-t.value)+6+n.bias.y,o=n.gapX<0&&n.midX!==null?n.options.expandElbowLegLength+Math.abs(e.crossTarget-n.A.expanded.bottom)+n.common.expanded.width+Math.abs(n.A.expanded.bottom-n.B.expanded.top)+Math.abs(n.B.expanded.top-t.crossTarget)+n.options.expandElbowLegLength+8:1/0;return r<s&&r<o?new Gr(n,"to left 3").add(e.value,e.crossTarget).add(n.common.expanded.right,e.crossTarget).add(n.common.expanded.right,n.common.expanded.bottom).add(t.expanded,n.common.expanded.bottom).add(t.expanded,t.crossTarget).add(t.value,t.crossTarget).build():s<o?new Gr(n,"to left 4").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.common.expanded.top).add(n.common.expanded.left,n.common.expanded.top).add(n.common.expanded.left,t.crossTarget).add(t.value,t.crossTarget).build():n.midX!==null?new Gr(n,"to left 5").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.A.expanded.bottom).add(n.midX,n.A.expanded.bottom).add(n.midX,n.B.expanded.top).midpointHandle("y").add(t.expanded,n.B.expanded.top).add(t.expanded,t.crossTarget).add(t.value,t.crossTarget).build():null}function xu(n){const e=n.A.edges.right,t=n.B.edges.top;if(!e||!t)return null;if(e.crossTarget<(t.expanded??t.value)&&t.crossTarget>(e.expanded??e.value)||n.A.isPoint&&n.B.expanded.containsPoint(n.A.original.center))return new Gr(n,"to top 1").add(e.value,e.crossTarget).add(t.crossTarget,e.crossTarget).add(t.crossTarget,t.value).build();if(n.gapX>0&&n.midX!==null&&t.expanded!==null)return new Gr(n,"to top 2").add(e.value,e.crossTarget).add(n.midX,e.crossTarget).add(n.midX,t.expanded).midpointHandle("x").add(t.crossTarget,t.expanded).add(t.crossTarget,t.value).build();if(n.gapY>0&&e.expanded!==null&&t.crossTarget<e.expanded&&n.midY!==null)return new Gr(n,"to top 3").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.midY).add(t.crossTarget,n.midY).midpointHandle("y").add(t.crossTarget,t.value).build();const r=Math.abs(e.value-n.common.expanded.right)+Math.abs(e.crossTarget-n.common.expanded.top)+Math.abs(t.crossTarget-n.common.expanded.right)+Math.abs(t.value-n.common.expanded.top),s=e.expanded!==null&&n.midY!==null&&t.expanded!==null?Math.abs(e.value-e.expanded)+Math.abs(n.B.expanded.left-e.expanded)+Math.abs(n.B.expanded.left-t.crossTarget)+Math.abs(e.crossTarget-n.B.expanded.top)+Math.abs(t.value-t.expanded):1/0,o=e.expanded!==null&&n.midX!==null&&t.expanded!==null?Math.abs(e.value-n.common.expanded.right)+Math.abs(e.crossTarget-n.A.expanded.bottom)+Math.abs(e.expanded-t.crossTarget)+Math.abs(n.A.expanded.bottom-t.expanded)+Math.abs(t.expanded-t.value):1/0;return r<s&&r<o?new Gr(n,"to top 4").add(e.value,e.crossTarget).add(n.common.expanded.right,e.crossTarget).add(n.common.expanded.right,n.common.expanded.top).add(t.crossTarget,n.common.expanded.top).add(t.crossTarget,t.value).build():t.expanded!==null&&e.expanded!==null&&n.midY!==null&&s<o?new Gr(n,"to top 5").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.midY).add(n.B.expanded.left,n.midY).midpointHandle("y").add(n.B.expanded.left,t.expanded).add(t.crossTarget,t.expanded).add(t.crossTarget,t.value).build():t.expanded!==null&&e.expanded!==null&&n.midX!==null?new Gr(n,"to top 6").add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.A.expanded.bottom).add(n.midX,n.A.expanded.bottom).add(n.midX,t.expanded).midpointHandle("x").add(t.crossTarget,t.expanded).add(t.crossTarget,t.value).build():null}function gf(n){return n.apply(cn.FlipY),xu(n)}function mf(n){const e=n.A.edges.right,t=n.B.edges.right;if(!e||!t)return null;if((n.gapX<=0||e.crossTarget>n.B.expanded.bottom||e.crossTarget<n.B.expanded.top)&&(t.value>n.A.original.left||t.crossTarget>n.A.expanded.bottom||t.crossTarget<n.A.expanded.top))return new Gr(n,"to right 1").add(e.value,e.crossTarget).add(n.common.expanded.right,e.crossTarget).add(n.common.expanded.right,t.crossTarget).add(t.value,t.crossTarget).build();if(n.midX===null)return null;if(t.expanded!==null&&n.gapX>=0){const r=Math.abs(t.crossTarget-n.B.expanded.bottom)+Math.abs(e.crossTarget-n.B.expanded.bottom),s=Math.abs(t.crossTarget-n.B.expanded.top)+Math.abs(e.crossTarget-n.B.expanded.top),o=r<s?"bottom":"top";return new Gr(n,`to right 2 via ${o}`).add(e.value,e.crossTarget).add(n.midX,e.crossTarget).add(n.midX,n.B.expanded[o]).midpointHandle("x").add(t.expanded,n.B.expanded[o]).add(t.expanded,t.crossTarget).add(t.value,t.crossTarget).build()}if(e.expanded!==null&&n.gapX<=0){const r=Math.abs(t.crossTarget-n.A.expanded.bottom)+Math.abs(e.crossTarget-n.A.expanded.bottom),s=Math.abs(t.crossTarget-n.A.expanded.top)+Math.abs(e.crossTarget-n.A.expanded.top),o=r<s?"bottom":"top";return new Gr(n,`to right 3 via ${o}`).add(e.value,e.crossTarget).add(e.expanded,e.crossTarget).add(e.expanded,n.A.expanded[o]).add(n.midX,n.A.expanded[o]).add(n.midX,t.crossTarget).midpointHandle("x").add(t.value,t.crossTarget).build()}return null}const Tae={top:{top:[cn.Rotate270,mf],left:[cn.Rotate270,xu],bottom:[cn.Rotate270,ff],right:[cn.Rotate270,gf]},right:{top:[cn.Identity,xu],right:[cn.Identity,mf],bottom:[cn.Identity,gf],left:[cn.Identity,ff]},bottom:{top:[cn.Rotate90,ff],left:[cn.Rotate90,gf],bottom:[cn.Rotate90,mf],right:[cn.Rotate90,xu]},left:{top:[cn.Rotate180,gf],left:[cn.Rotate180,mf],bottom:[cn.Rotate180,xu],right:[cn.Rotate180,ff]}};function dn(n,e,t){const[r,s]=Tae[e][t];n.apply(r);const o=s(n);return n.reset(),o}function Iae(n,e){let t=null;if(Math.abs(n.gapX)+1>Math.abs(n.gapY)&&n.midX!==null)n.gapX>0?t=dn(n,"right","left"):t=dn(n,"left","right");else{const i=n.A.edges.right,a=n.A.edges.left,l=n.B.edges.top,c=n.B.edges.bottom;n.A.isPoint&&n.B.isPoint?n.gapY>0?t=dn(n,"bottom","top"):t=dn(n,"top","bottom"):i&&l&&(i.expanded??i.value)<=l.crossTarget&&i.crossTarget<=(l.expanded??l.value)?t=dn(n,"right","top"):i&&c&&(i.expanded??i.value)<=c.crossTarget&&i.crossTarget>=(c.expanded??c.value)?t=dn(n,"right","bottom"):a&&l&&(a.expanded??a.value)>=l.crossTarget&&a.crossTarget<=(l.expanded??l.value)?t=dn(n,"left","top"):a&&c&&(a.expanded??a.value)>=c.crossTarget&&a.crossTarget>=(c.expanded??c.value)?t=dn(n,"left","bottom"):n.gapY>0&&n.midY!==null?t=dn(n,"bottom","top"):n.gapY<0&&n.midY!==null&&(t=dn(n,"top","bottom"))}if(t)return t.aEdgePicking=e,t.bEdgePicking=e,t;const r=fk.filter(i=>n.A.edges[i]),s=fk.filter(i=>n.B.edges[i]),o=r.flatMap(i=>s.map(a=>[i,a,e,e]));return Ac(n,o)}function Eae(n,e){let t=null;const r=n.A.edges.right,s=n.A.edges.left,o=n.B.edges.top,i=n.B.edges.bottom;switch(e){case"right":n.gapX>0&&n.gapX>Math.abs(n.gapY)&&n.midX!==null?t=dn(n,"right","left"):r&&o&&(r.expanded??r.value)<=o.crossTarget&&r.crossTarget<=(o.expanded??o.value)?t=dn(n,"right","top"):r&&i&&(r.expanded??r.value)<=i.crossTarget&&r.crossTarget>=(i.expanded??i.value)&&(t=dn(n,"right","bottom"));break;case"left":n.gapX<0&&Math.abs(n.gapX)>Math.abs(n.gapY)&&n.midX!==null?t=dn(n,"left","right"):s&&o&&(s.expanded??s.value)>=o.crossTarget&&s.crossTarget<=(o.expanded??o.value)?t=dn(n,"left","top"):s&&i&&(s.expanded??s.value)>=i.crossTarget&&s.crossTarget>=(i.expanded??i.value)&&(t=dn(n,"left","bottom"));break;case"top":case"bottom":break;default:it(e)}if(t)return t.aEdgePicking="manual",t.bEdgePicking="auto",t;switch(e){case"top":return Ac(n,[["top","bottom","manual","auto"],["top","right","manual","auto"],["top","left","manual","auto"],["top","top","manual","auto"]]);case"bottom":return Ac(n,[["bottom","top","manual","auto"],["bottom","right","manual","auto"],["bottom","left","manual","auto"],["bottom","bottom","manual","auto"]]);case"left":return Ac(n,[["left","right","manual","auto"],["left","bottom","manual","auto"],["left","left","manual","auto"],["left","top","manual","auto"]]);case"right":return Ac(n,[["right","left","manual","auto"],["right","bottom","manual","auto"],["right","right","manual","auto"],["right","top","manual","auto"]])}}function kae(n,e,t){const r=dn(n,e,t);return r||(n.A.isPoint&&n.B.isPoint?Ac(n,[[Sc[e],Sc[t],"manual","manual"],[e,Sc[t],"manual","auto"],[Sc[e],t,"auto","manual"]]):n.A.isPoint?dn(n,Sc[e],t):n.B.isPoint?dn(n,e,Sc[t]):null)}function Ac(n,e){let t=null,r=1/0,s=1/0,o=0;for(const[i,a,l,c]of e){o+=1;const u=dn(n,i,a);u&&(u.aEdgePicking=l,u.bEdgePicking=c,u.points.length<r?(r=u.points.length,s=u.distance,t=u):u.points.length===r&&u.distance+o<s&&(s=u.distance,t=u))}return t}function o5(n,e,t){const r=n.getShapeUtil(e.type).options,s={elbowMidpoint:e.props.elbowMidPoint,expandElbowLegLength:r.expandElbowLegLength[e.props.size]*e.props.scale,minElbowLegLength:r.minElbowLegLength[e.props.size]*e.props.scale};let o=Sk(n,e,t.start,e.props.start),i=Sk(n,e,t.end,e.props.end);o=vk(o,i,s),i=vk(i,o,s);const a=!!(!o.side&&i.side);let{aTerminal:l,bTerminal:c}=a?{aTerminal:i,bTerminal:o}:{aTerminal:o,bTerminal:i},u={top:er(l,c,"top",s),right:er(l,c,"right",s),bottom:er(l,c,"bottom",s),left:er(l,c,"left",s)},d={top:er(c,l,"top",s),right:er(c,l,"right",s),bottom:er(c,l,"bottom",s),left:er(c,l,"left",s)};const h=xk(u,l.side),f=xk(d,c.side);let g=!1;(!h||!f)&&(g=!0,h||(c=bu(c)),f||(l=bu(l)),c.bounds.containsPoint(l.target,s.expandElbowLegLength)&&(c=bu(c)),l.bounds.containsPoint(c.target,s.expandElbowLegLength)&&(l=bu(l))),g&&(u={top:er(l,c,"top",s),right:er(l,c,"right",s),bottom:er(l,c,"bottom",s),left:er(l,c,"left",s)},d={top:er(c,l,"top",s),right:er(c,l,"right",s),bottom:er(c,l,"bottom",s),left:er(c,l,"left",s)});const m=l.isPoint?l.bounds:l.bounds.clone().expandBy(s.expandElbowLegLength),y=c.isPoint?c.bounds:c.bounds.clone().expandBy(s.expandElbowLegLength),S={original:J.Common([l.bounds,c.bounds]),expanded:J.Common([m,y])};let b=c.bounds.minX-l.bounds.maxX;b<0&&(b=l.bounds.minX-c.bounds.maxX,b<0&&(b=0),b=-b);let w=c.bounds.minY-l.bounds.maxY;w<0&&(w=l.bounds.minY-c.bounds.maxY,w<0&&(w=0),w=-w);const v=l.minEndSegmentLength*3,P=c.minEndSegmentLength*3,T=(l.isPoint?v:s.minElbowLegLength)+(c.isPoint?P:s.minElbowLegLength);let I=null;b>T?I={a:l.isPoint?l.bounds.maxX+v:m.maxX,b:c.isPoint?c.bounds.minX-P:y.minX}:b<-T&&(I={a:l.isPoint?l.bounds.minX-v:m.minX,b:c.isPoint?c.bounds.maxX+P:y.maxX});let k=null;w>T?k={a:l.isPoint?l.bounds.maxY+v:m.maxY,b:c.isPoint?c.bounds.minY-P:y.minY}:w<-T&&(k={a:l.isPoint?l.bounds.minY-v:m.minY,b:c.isPoint?c.bounds.maxY+P:y.maxY});const A=a?1-s.elbowMidpoint:s.elbowMidpoint,R=I?Ue(I.a,I.b,A):null,D=k?Ue(k.a,k.b,A):null,j={options:s,swapOrder:a,A:{isPoint:l.isPoint,target:l.target,isExact:l.isExact,arrowheadOffset:l.arrowheadOffset,minEndSegmentLength:l.minEndSegmentLength,original:l.bounds,expanded:m,edges:u,geometry:l.geometry},B:{isPoint:c.isPoint,target:c.target,isExact:c.isExact,arrowheadOffset:c.arrowheadOffset,minEndSegmentLength:c.minEndSegmentLength,original:c.bounds,expanded:y,edges:d,geometry:c.geometry},common:S,gapX:b,gapY:w,midX:R,midY:D},_=new Cae(j),M=bk(l,c,j.A.edges),O=bk(c,l,j.B.edges);let N;return M&&O?N=kae(_,M,O):M&&!O&&(N=Eae(_,M)),N||(N=Iae(_,M||O?"fallback":"auto")),N&&(wk("first",j.A,j.B,N),wk("last",j.B,j.A,N),Oae(N,l,c),a&&N.points.reverse()),{...j,route:N,midXRange:I?a?{lo:I.b,hi:I.a}:{lo:I.a,hi:I.b}:null,midYRange:k?a?{lo:k.b,hi:k.a}:{lo:k.a,hi:k.b}:null}}function _ae(n,e){const t=n.swapOrder?n.B.target:n.A.target,r=n.swapOrder?n.A.target:n.B.target,s=C.ManhattanDist(e.points[0],e.points[1]),o=C.ManhattanDist(e.points[e.points.length-2],e.points[e.points.length-1]),i=C.ManhattanDist(t,e.points[1]),a=C.ManhattanDist(e.points[e.points.length-2],r),l=s-i,c=o-a,u=[t,...e.points,r];return{name:e.name,distance:e.distance+l+c,points:u.filter(d=>!e.skipPointsWhenDrawing.has(d)),aEdgePicking:e.aEdgePicking,bEdgePicking:e.bEdgePicking,skipPointsWhenDrawing:e.skipPointsWhenDrawing,midpointHandle:e.midpointHandle}}function Mae(n){return tn(n.x,.5)&&tn(n.y,.5)?null:Math.abs(n.x-.5)>Math.abs(n.y-.5)-1e-4?n.x<.5?"left":"right":n.y<.5?"top":"bottom"}function Sk(n,e,t,r){const s=qr[e.props.size]*e.props.scale/2,o=s*3;if(t){const i=n.getShape(t.toId),a=Aae(n,e,t.toId,t.props);if(a&&i){let l=0;const c=t.props.terminal==="start"?"arrowheadStart":"arrowheadEnd";if(e.props[c]!=="none"){const h="scale"in i.props?i.props.scale:1,f="size"in i.props?(qr[i.props.size]??0)*h/2:0;l=s+f+Ch*e.props.scale}let u=null;const d=a.target;return t.props.isPrecise&&(u=Mae(C.RotWith(t.props.normalizedAnchor,{x:.5,y:.5},a.shapeToArrowTransform.rotation()))),{targetShapeId:t.toId,isPoint:!1,isExact:t.props.isExact,bounds:a.bounds,geometry:a.geometry,target:d,arrowheadOffset:l,minEndSegmentLength:o,side:u,snap:t.props.snap}}}return{targetShapeId:null,bounds:J.FromCenter(r,{x:0,y:0}),geometry:null,isExact:!1,isPoint:!0,target:C.From(r),arrowheadOffset:0,minEndSegmentLength:o,side:null,snap:"none"}}function Aae(n,e,t,r){const s=r.terminal==="start"?e.props.arrowheadStart!=="none":e.props.arrowheadEnd!=="none",o=n.getShapeGeometry(t,s?void 0:{context:"@tldraw/arrow-without-arrowhead"});if(!o)return null;const i=n.getShapePageTransform(e.id),a=n.getShapePageTransform(t),l=i.clone().invert().multiply(a),c=o.transform(l),u={x:.5,y:.5},d=r.isPrecise?r.normalizedAnchor:u,h={x:Ue(o.bounds.minX,o.bounds.maxX,d.x),y:Ue(o.bounds.minY,o.bounds.maxY,d.y)},f={x:Ue(o.bounds.minX,o.bounds.maxX,u.x),y:Ue(o.bounds.minY,o.bounds.maxY,u.y)},g=Q.applyToPoint(l,h),m=Q.applyToPoint(l,f);return{bounds:c.bounds,geometry:c,target:g,center:m,shapeToArrowTransform:l}}const Dae={top:{expand:-1,main:"minY",opposite:"maxY",crossMid:"midX",crossMin:"minX",crossMax:"maxX",bRangeExpand:"max",crossAxis:"x"},bottom:{expand:1,main:"maxY",opposite:"minY",crossMid:"midX",crossMin:"minX",crossMax:"maxX",bRangeExpand:"min",crossAxis:"x"},left:{expand:-1,main:"minX",opposite:"maxX",crossMid:"midY",crossMin:"minY",crossMax:"maxY",bRangeExpand:"max",crossAxis:"y"},right:{expand:1,main:"maxX",opposite:"minX",crossMid:"midY",crossMin:"minY",crossMax:"maxY",bRangeExpand:"min",crossAxis:"y"}};function er(n,e,t,r){const s=Dae[t],o=n.targetShapeId===e.targetShapeId&&n.targetShapeId!==null&&(n.snap==="edge"||n.snap==="edge-point")&&(e.snap==="edge"||e.snap==="edge-point"),i=n.bounds[s.main],a=n.isPoint?null:i+s.expand*r.expandElbowLegLength,l=Eb(n.bounds[s.crossMin],n.bounds[s.crossMax]);let c=l;if(!c)return null;be(l);const u=Eb(e.bounds[s.main],e.bounds[s.opposite]);e.isPoint||(u[s.bRangeExpand]-=r.minElbowLegLength*2*s.expand);const d=xae(Eb(e.bounds[s.crossMin],e.bounds[s.crossMax]),r.expandElbowLegLength);be(u&&d);let h=!1;if(bm(i,u)&&!n.isPoint&&!e.isPoint&&!o){const g=bae(c,d);switch(g.length){case 0:return null;case 1:h=g[0]!==c,c=g[0];break;case 2:h=!0,c=gk(g[0])>gk(g[1])?g[0]:g[1];break;default:it(g)}}if(!bm(n.target[s.crossAxis],c))return null;const f=n.target[s.crossAxis];return{value:i,expanded:a,cross:c,crossTarget:f,isPartial:h}}function xk(n,e){return e===null?!!(n.bottom||n.left||n.right||n.top):e==="x"?!!n.left||!!n.right:e==="y"?!!n.top||!!n.bottom:!!n[e]}function bk(n,e,t){switch(n.side){case null:return null;case"x":return n.bounds.center.x>e.bounds.center.x&&(t!=null&&t.left)?"left":t!=null&&t.right?"right":null;case"y":return n.bounds.center.y>e.bounds.center.y&&(t!=null&&t.top)?"top":t!=null&&t.bottom?"bottom":null;default:return n.side}}function bu(n){if(n.isPoint)return n;let e=null,t=0;return(n.snap==="edge"||n.snap==="edge-point")&&(t=n.arrowheadOffset,(n.side==="x"||n.side==="left"||n.side==="right")&&(e="x"),(n.side==="y"||n.side==="top"||n.side==="bottom")&&(e="y")),{targetShapeId:n.targetShapeId,side:e,bounds:new J(n.target.x,n.target.y,0,0),geometry:n.geometry,target:n.target,arrowheadOffset:t,minEndSegmentLength:n.minEndSegmentLength,isExact:n.isExact,isPoint:!0,snap:n.snap}}function wk(n,e,t,r){if(!e.geometry)return;const s=n==="first"?r.points[0]:r.points[r.points.length-1],o=n==="first"?r.points[1]:r.points[r.points.length-2],i=e.geometry.isClosed?o:e.target,a=C.ManhattanDist(s,i);let l=null,c=1/0;if(e.isExact)l=e.target;else if(e.geometry){const u=e.geometry.intersectLineSegment(o,e.target,{includeLabels:!1,includeInternal:!1});e.geometry.hitTestPoint(e.target,Math.max(1,e.arrowheadOffset),!0,Ko.EXCLUDE_NON_STANDARD)&&u.push(e.target);for(const d of u){const h=C.ManhattanDist(i,d);h<c&&(c=h,l=d)}}if(l){let u=e.arrowheadOffset;const d=C.ManhattanDist(o,l),h=e.arrowheadOffset*2;if(d<h){const y=h-e.arrowheadOffset;u=d-y}u<e.minEndSegmentLength&&(e.geometry.bounds.containsPoint(t.target)?u=Math.max(0,u):u=-e.arrowheadOffset);let f=l,g=!1;if(!e.isExact&&u!==0){const y=C.Nudge(l,o,u);f=y,u<0&&!e.geometry.hitTestPoint(y,0,!0,Ko.EXCLUDE_NON_STANDARD)?f=l:(u<0&&(g=!0),f=y)}const m=C.ManhattanDist(o,f);if(r.distance+=m-a,s.x=f.x,s.y=f.y,g){const y=C.Lrp(o,s,.5);r.skipPointsWhenDrawing.add(y),r.points.splice(n==="first"?1:r.points.length-1,0,y)}}}function Oae(n,e,t){if(n){if(n.points.length>=3){const r=n.points[0],s=n.points[1];if(C.ManhattanDist(r,s)<e.minEndSegmentLength&&(n.points.splice(1,1),n.points.length>=3)){const i=tn(r.x,s.x)?"y":"x";n.points[1][i]=r[i]}}if(n.points.length>=3){const r=n.points[n.points.length-1],s=n.points[n.points.length-2];if(C.ManhattanDist(r,s)<t.minEndSegmentLength&&(n.points.splice(n.points.length-2,1),n.points.length>=3)){const i=tn(r.x,s.x)?"y":"x";n.points[n.points.length-2][i]=r[i]}}}}function vk(n,e,t){if(!n.geometry||n.geometry.isClosed)return n;const r=n.geometry.uninterpolateAlongEdge(n.target,Ko.EXCLUDE_NON_STANDARD),s=n.geometry.interpolateAlongEdge(r-.01/n.geometry.length),i=n.geometry.interpolateAlongEdge(r+.01/n.geometry.length).sub(s).per().uni(),a=Math.abs(i.x)>Math.abs(i.y)?vh.x:vh.y;if(n.geometry.bounds.containsPoint(e.target,t.expandElbowLegLength))return n.side=a.self,bu(n);const l=a.v(n.target[a.self]-n.bounds[a.size]*2,n.target[a.cross]),c=a.v(n.target[a.self]+n.bounds[a.size]*2,n.target[a.cross]);let u=null,d=0,h=null,f=0,g=a.self;for(const m of n.geometry.intersectLineSegment(l,c,Ko.EXCLUDE_NON_STANDARD))Math.abs(m[a.self]-n.target[a.self])<1||(m[a.self]<n.target[a.self]?C.ManhattanDist(m,n.target)>d&&(d=C.ManhattanDist(m,n.target),u=m):C.ManhattanDist(m,n.target)>f&&(f=C.ManhattanDist(m,n.target),h=m));return u&&h?d>f?g=a.hiEdge:g=a.loEdge:u&&!h?g=a.hiEdge:!u&&h&&(g=a.loEdge),n.side=g,n}const Rae=8;function Lae(n){return n.props.kind!=="arc"?!1:Math.abs(n.props.bend)<Rae*n.props.scale}function wm(n,e,t){const r=n.getBindingsFromShape(e,"arrow").find(l=>l.props.terminal===t);if(!r)return;const s=n.getShape(r.toId);if(!s)return;const o=n.getShapePageTransform(s),i=t==="start"?e.props.arrowheadStart!=="none":e.props.arrowheadEnd!=="none",a=n.getShapeGeometry(s,i?void 0:{context:"@tldraw/arrow-without-arrowhead"});return{shape:s,transform:o,isClosed:a.isClosed,isExact:r.props.isExact,didIntersect:!1,geometry:a}}function Ck(n,e,t,r){const s=n.getShape(t.toId);if(s){const{point:o,size:i}=n.getShapeGeometry(s).bounds,a=C.Add(o,C.MulV(t.props.isPrecise||r?t.props.normalizedAnchor:{x:.5,y:.5},i)),l=Q.applyToPoint(n.getShapePageTransform(s),a);return Q.applyToPoint(Q.Inverse(e),l)}else return new C(0,0)}const jae=Rh("arrow bindings",(n,e)=>{const t=n.getBindingsFromShape(e.id,"arrow");return{start:t.find(r=>r.props.terminal==="start"),end:t.find(r=>r.props.terminal==="end")}},{areRecordsEqual:(n,e)=>n.id===e.id,areResultsEqual:(n,e)=>n.start===e.start&&n.end===e.end});function En(n,e){return jae.get(n,e.id)}const Nae=Rh("arrow info",(n,e)=>{const t=En(n,e);if(e.props.kind==="elbow"){const r=o5(n,e,t);if(!(r!=null&&r.route))return xm(n,e,t);const s=r.swapOrder?r.B:r.A,o=r.swapOrder?r.A:r.B;return{type:"elbow",bindings:t,start:{handle:s.target,point:r.route.points[0],arrowhead:e.props.arrowheadStart},end:{handle:o.target,point:r.route.points[r.route.points.length-1],arrowhead:e.props.arrowheadEnd},elbow:r,route:r.route,isValid:!0}}return Lae(e)?xm(n,e,t):gae(n,e,t)},{areRecordsEqual:(n,e)=>n.props===e.props,areResultsEqual:U4});function us(n,e){const t=typeof e=="string"?e:e.id;return Nae.get(n,t)}function pl(n,e,t){var a,l;const r=n.getShapePageTransform(e),s=KC(n,(a=t.start)==null?void 0:a.toId,(l=t.end)==null?void 0:l.toId),o=t.start?Ck(n,r,t.start,s==="double-bound"||s==="start-contains-end"):C.From(e.props.start),i=t.end?Ck(n,r,t.end,s==="double-bound"||s==="end-contains-start"):C.From(e.props.end);return{start:o,end:i}}function Wd(n,e,t,r){const s=typeof e=="string"?e:e.id,o=typeof t=="string"?t:t.id,i=n.getBindingsFromShape(s,"arrow").filter(l=>l.props.terminal===r.terminal);i.length>1&&n.deleteBindings(i.slice(1));const a=i[0];a?n.updateBinding({...a,toId:o,props:r}):n.createBinding({type:"arrow",fromId:s,toId:o,props:r})}function wu(n,e,t){const r=n.getBindingsFromShape(e,"arrow").filter(s=>s.props.terminal===t);n.deleteBindings(r)}const Dc=10,Ch=10,Fae=10,qr={s:2,m:3.5,l:5,xl:10};function KC(n,e,t){if(!e||!t)return"safe";if(e===t)return"double-bound";const r=n.getShapePageBounds(e),s=n.getShapePageBounds(t);if(r&&s){if(r.contains(s))return"start-contains-end";if(s.contains(r))return"end-contains-start"}return"safe"}function Bae(n){return n.getSelectedShapeIds().map(r=>n.getShape(r)).filter(r=>{if(!r)return!1;if(n.isShapeOfType(r,"arrow")){const s=En(n,r);if(s.start||s.end)return!1}return!0})}const i5=()=>{const n=K();return W("threeStackableItems",()=>Bae(n).length>2,[n])},qi=()=>{const n=K();return W("isInSelectState",()=>n.isIn("select"),[n])},a5=()=>{const n=K();return W("allow group",()=>{const e=n.getSelectedShapes();if(e.length<2)return!1;for(const t of e)if(n.isShapeOfType(t,"arrow")){const r=En(n,t);if(r.start&&!e.some(s=>s.id===r.start.toId)||r.end&&!e.some(s=>s.id===r.end.toId))return!1}return!0},[n])},l5=()=>{const n=K();return W("allowUngroup",()=>n.getSelectedShapeIds().some(e=>{var t;return((t=n.getShape(e))==null?void 0:t.type)==="group"}),[n])},zae=typeof window<"u"&&"navigator"in window&&!!navigator.clipboard&&!!navigator.clipboard.read;function $ae(n,e){const t=K();return W("selectedShapes",()=>t.getSelectedShapes().length>=n,[t,n,e])}function Br(n,e){const t=K();return W("selectedShapes",()=>{const r=t.getSelectedShapes().filter(s=>!t.isShapeOrAncestorLocked(s)).length;return n===void 0?r:r>=n},[t])}function Hae(){const n=K();return W("showAutoSizeToggle",()=>{const e=n.getSelectedShapes();return e.length===1&&n.isShapeOfType(e[0],"text")&&e[0].props.autoSize===!1},[n])}function c5(){const n=K();return W("hasLinkShapeSelected",()=>{const e=n.getOnlySelectedShape();return!!(e&&e.type!=="embed"&&"url"in e.props&&!e.isLocked)},[n])}function Uae(){const n=K();return W("onlyFlippableShape",()=>{const e=n.getOnlySelectedShape();return e&&(n.isShapeOfType(e,"group")||n.isShapeOfType(e,"image")||n.isShapeOfType(e,"arrow")||n.isShapeOfType(e,"line")||n.isShapeOfType(e,"draw"))},[n])}function d5(){const n=K();return W("useCanRedo",()=>n.getCanRedo(),[n])}function u5(){const n=K();return W("useCanUndo",()=>n.getCanUndo(),[n])}function AS(){const n=K();return W("canApplySelectionAction",()=>n.isIn("select")&&n.getSelectedShapeIds().length>0,[n])}function Kae(){return p.jsxs(p.Fragment,{children:[p.jsx(Wae,{}),p.jsx(Vae,{}),p.jsx(Gae,{}),p.jsx(Yae,{}),p.jsx(Xae,{}),p.jsx(Zae,{}),p.jsx(Jae,{}),p.jsx(Qae,{})]})}function Wae(){const n=Br(2),e=qi(),t=n&&e;return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"align-left",disabled:!t}),p.jsx(Z,{actionId:"align-center-horizontal",disabled:!t}),p.jsx(Z,{actionId:"align-right",disabled:!t}),p.jsx(Z,{actionId:"stretch-horizontal",disabled:!t}),p.jsx(Z,{actionId:"align-top",disabled:!t}),p.jsx(Z,{actionId:"align-center-vertical",disabled:!t}),p.jsx(Z,{actionId:"align-bottom",disabled:!t}),p.jsx(Z,{actionId:"stretch-vertical",disabled:!t})]})}function Vae(){const n=Br(3),e=qi(),t=n&&e;return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"distribute-horizontal",disabled:!t}),p.jsx(Z,{actionId:"distribute-vertical",disabled:!t})]})}function Gae(){const n=i5(),e=qi(),t=n&&e;return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"stack-horizontal",disabled:!t}),p.jsx(Z,{actionId:"stack-vertical",disabled:!t})]})}function Yae(){const n=Br(1),e=qi(),t=n&&e;return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"send-to-back",disabled:!t}),p.jsx(Z,{actionId:"send-backward",disabled:!t}),p.jsx(Z,{actionId:"bring-forward",disabled:!t}),p.jsx(Z,{actionId:"bring-to-front",disabled:!t})]})}function Xae(){return Gn()<Ot.TABLET_SM?p.jsx(JC,{}):p.jsx(qae,{})}function qae(){const n=Br(1),e=qi(),t=n&&e;return p.jsx(Z,{actionId:"rotate-ccw",disabled:!t})}function Zae(){const n=Br(1),e=qi(),t=n&&e;return p.jsx(Z,{actionId:"rotate-cw",disabled:!t})}function Jae(){const n=c5(),e=qi(),t=n&&e;return p.jsx(Z,{actionId:"edit-link",disabled:!t})}function Qae(){const n=a5(),e=l5();return n?p.jsx(Pk,{}):e?p.jsx(ele,{}):p.jsx(Pk,{})}function Pk(){const n=Br(2),e=qi(),t=n&&e;return p.jsx(Z,{actionId:"group",disabled:!t})}function ele(){return p.jsx(Z,{actionId:"ungroup"})}const tle=x.memo(function({children:e}){const t=Se(),r=Gn(),s=Ps(),{orientation:o}=pp(),i=x.useRef(null);Jo(i);const a=K(),l=W("should display quick actions when in readonly",()=>a.isInAny("hand","zoom"),[a]),c=e??p.jsx(Kae,{});if(!(s&&!l))return p.jsxs(Bl,{id:"actions-menu",children:[p.jsx(zl,{children:p.jsx(bt,{type:"icon","data-testid":"actions-menu.button",title:t("actions-menu.title"),children:p.jsx(Ae,{icon:o==="horizontal"?"dots-vertical":"dots-horizontal",small:!0})})}),p.jsx($l,{side:o==="horizontal"?r>=Ot.TABLET?"bottom":"top":"right",sideOffset:6,children:p.jsx(ur,{ref:i,label:t("actions-menu.title"),className:"tlui-actions-menu","data-testid":"actions-menu.content",orientation:"grid",children:p.jsx(Fr,{type:"icons",sourceId:"actions-menu",children:c})})})]})});function nle(){const n=K(),e=TS(),t=W("isSelectToolActive",()=>n.getCurrentToolId()==="select",[n]),r=W("isSinglePageMode",()=>n.options.maxPages<=1,[n]);return t?p.jsxs(p.Fragment,{children:[e&&p.jsx(Uue,{}),p.jsxs($e,{id:"modify",children:[p.jsx(Pue,{}),p.jsx(Tue,{}),p.jsx(kue,{}),!r&&p.jsx(_ue,{})]}),p.jsx(tz,{}),p.jsx(nz,{}),p.jsx($e,{id:"select-all",children:p.jsx(rz,{})})]}):null}const rle=x.memo(function({children:e,disabled:t=!1}){const r=K(),s=Se(),{Canvas:o}=xt(),i=x.useCallback(h=>{h.key==="Escape"&&(h.stopPropagation(),r.getContainer().focus())},[r]);x.useEffect(()=>()=>{document.body.removeEventListener("keydown",i,{capture:!0})},[i]);const a=x.useCallback(h=>{if(h){if(document.body.addEventListener("keydown",i,{capture:!0}),r.getInstanceState().isCoarsePointer){const f=r.getSelectedShapes(),g=r.inputs.getCurrentPagePoint(),m=r.getShapesAtPoint(g);if(!r.getSelectedShapes().length||!m.some(y=>f.includes(y))){const y=m.filter(S=>r.isShapeOrAncestorLocked(S));y.length&&r.select(...y.map(S=>S.id))}}}else{const f=r.getOnlySelectedShape();f&&r.isShapeOrAncestorLocked(f)&&r.setSelectedShapes([]),r.timers.requestAnimationFrame(()=>{document.body.removeEventListener("keydown",i,{capture:!0})})}},[r,i]),l=sn(),[c,u]=Yi("context menu",a),d=e??p.jsx(nle,{});return p.jsxs(vre,{dir:"ltr",onOpenChange:u,modal:!1,children:[p.jsx(Cre,{onContextMenu:void 0,dir:"ltr",disabled:t,children:o?p.jsx(o,{}):null}),c&&p.jsx(Pre,{container:l,children:p.jsx(Tre,{className:"tlui-menu tlui-scrollable","data-testid":"context-menu","aria-label":s("context-menu.title"),alignOffset:-4,collisionPadding:4,onContextMenu:je,children:p.jsx(Fr,{type:"context-menu",sourceId:"context-menu",children:d})})})]})}),sle=2e3,ole=5e3,ile=rn(function(){const e=K(),{isChatting:t,chatMessage:r}=e.getInstanceState(),s=x.useRef(-1),[o,i]=x.useState("");return x.useEffect(()=>{if(!t&&r||t){const l=t?ole:sle;s.current=e.timers.setTimeout(()=>{e.updateInstanceState({chatMessage:"",isChatting:!1}),i(""),e.focus()},l)}return()=>{clearTimeout(s.current)}},[e,r,t]),t?p.jsx(lle,{value:o,setValue:i,chatMessage:r}):r.trim()?p.jsx(ale,{chatMessage:r}):null});function h5(n){const e=K();x.useLayoutEffect(()=>{var i;if(!n.current)return;const{x:r,y:s}=e.inputs.getCurrentScreenPoint();(i=n.current)==null||i.style.setProperty("transform",`translate(${r}px, ${s}px)`);function o(a){var u;const{minX:l,minY:c}=e.getViewportScreenBounds();(u=n.current)==null||u.style.setProperty("transform",`translate(${a.clientX-l}px, ${a.clientY-c}px)`)}return window.addEventListener("pointermove",o),()=>{window.removeEventListener("pointermove",o)}},[n,e])}const ale=({chatMessage:n})=>{const e=K(),t=x.useRef(null);return h5(t),p.jsx("div",{ref:t,className:"tl-cursor-chat tl-cursor-chat__bubble",style:{backgroundColor:e.user.getColor()},children:n})},lle=rn(function({chatMessage:e,value:t,setValue:r}){const s=K(),o=Se(),i=x.useRef(null),a=e||o("cursor-chat.type-to-chat");h5(i),x.useLayoutEffect(()=>{const h=i.current;if(!h)return;const f=s.textMeasure.measureText(t||a,{fontFamily:"var(--font-body)",fontSize:12,fontWeight:"500",fontStyle:"normal",maxWidth:null,lineHeight:1,padding:"6px"});h.style.setProperty("width",f.w+"px")},[s,t,a]),x.useLayoutEffect(()=>{const h=s.timers.requestAnimationFrame(()=>{var f;(f=i.current)==null||f.focus()});return()=>{cancelAnimationFrame(h)}},[s]);const l=x.useCallback(()=>{s.updateInstanceState({isChatting:!1}),s.focus()},[s]),c=x.useCallback(h=>{const{value:f}=h.target;r(f.slice(0,64)),s.updateInstanceState({chatMessage:f})},[s,r]),u=x.useCallback(h=>{const f=i.current;if(!f)return;const{value:g}=f;switch(h.key){case"Enter":{if(je(h),h.stopPropagation(),!g){l();return}r("");break}case"Escape":{je(h),h.stopPropagation(),l();break}}},[l,r]),d=x.useCallback(h=>{h.stopPropagation()},[]);return p.jsx("input",{ref:i,className:"tl-cursor-chat",style:{backgroundColor:s.user.getColor()},onBlur:l,onChange:c,onKeyDown:u,onPaste:d,value:t,placeholder:a,spellCheck:!1})});function z0({checked:n}){const e=Se();return p.jsx(Co,{"data-checked":!!n,label:e(n?"ui.checked":"ui.unchecked"),icon:n?"check":"none",className:"tlui-button__icon",small:!0})}function mp({id:n,kbd:e,label:t,lang:r,readonlyOk:s,onSelect:o,toggle:i=!1,disabled:a=!1,checked:l=!1}){const{type:c,sourceId:u}=PS(),d=Ps(),h=Se();if(d&&!s)return null;const f=Ih(t,c),g=f?h(f):void 0;switch(c){case"menu":return p.jsxs(p3,{dir:"ltr",lang:r,className:"tlui-button tlui-button__menu tlui-button__checkbox",title:g,onSelect:m=>{o==null||o(u),je(m)},disabled:a,checked:l,children:[p.jsx(Co,{small:!0,label:h(l?"ui.checked":"ui.unchecked"),icon:i?l?"toggle-on":"toggle-off":l?"check":"none"}),g&&p.jsx("span",{className:"tlui-button__label",draggable:!1,children:g}),e&&p.jsx(Hu,{children:e})]});case"context-menu":return p.jsxs(Ere,{className:"tlui-button tlui-button__menu tlui-button__checkbox",dir:"ltr",lang:r,title:g,onSelect:m=>{o(u),je(m)},disabled:a,checked:l,children:[p.jsx(Co,{small:!0,label:h(l?"ui.checked":"ui.unchecked"),icon:i?l?"toggle-on":"toggle-off":l?"check":"none"}),g&&p.jsx("span",{className:"tlui-button__label",draggable:!1,children:g}),e&&p.jsx(Hu,{children:e})]},n);default:return null}}function mr({id:n,disabled:e=!1,label:t,size:r="small",children:s}){const{type:o,sourceId:i}=PS(),a=sn(),l=Se(),c=t?typeof t=="string"?t:t[o]??t.default:void 0,u=c?l(c):void 0;switch(o){case"menu":return p.jsxs(Pie,{id:`${i}-sub.${n}`,children:[p.jsx(Tie,{id:`${i}-sub.${n}-button`,disabled:e,label:u,title:u}),p.jsx(Iie,{id:`${i}-sub.${n}-content`,size:r,children:s})]});case"context-menu":return e?null:p.jsxs(cle,{id:`${i}-sub.${n}`,children:[p.jsx(QF,{dir:"ltr",disabled:e,asChild:!0,children:p.jsxs(Ye,{"data-testid":`${i}-sub.${n}-button`,type:"menu",className:"tlui-menu__submenu__trigger",children:[p.jsx(Qt,{children:u}),p.jsx(Ae,{icon:"chevron-right",small:!0})]})}),p.jsx(gC,{container:a,children:p.jsx(e3,{"data-testid":`${i}-sub.${n}-content`,className:"tlui-menu tlui-menu__submenu__content",alignOffset:-1,sideOffset:-4,collisionPadding:4,"data-size":r,children:s})})]});default:return s}}function cle({id:n,children:e}){const[t,r]=Yi(n);return p.jsx(JF,{open:t,onOpenChange:r,children:e})}function dle({customDebugFlags:n,customFeatureFlags:e}){const t=K(),{addToast:r}=Xi(),{addDialog:s}=gp(),[o,i]=_e.useState(!1);return p.jsxs(p.Fragment,{children:[p.jsxs($e,{id:"items",children:[p.jsx(Ze,{id:"hard-reset",onSelect:CA,label:"Hard reset"}),p.jsx(Ze,{id:"add-toast",onSelect:()=>{r({id:at(),title:"Something good happened",description:"Hey, attend to this thing over here. It might be important!",keepOpen:!0,severity:"success"}),r({id:at(),title:"Something happened",description:"Hey, attend to this thing over here. It might be important!",keepOpen:!0,severity:"info",actions:[{label:"Primary",type:"primary",onClick:()=>{}},{label:"Normal",type:"normal",onClick:()=>{}},{label:"Danger",type:"danger",onClick:()=>{}}]}),r({id:at(),title:"Something maybe bad happened",description:"Hey, attend to this thing over here. It might be important!",keepOpen:!0,severity:"warning",actions:[{label:"Primary",type:"primary",onClick:()=>{}},{label:"Normal",type:"normal",onClick:()=>{}},{label:"Danger",type:"danger",onClick:()=>{}}]}),r({id:at(),title:"Something bad happened",severity:"error",keepOpen:!0})},label:"Show toast"}),p.jsx(Ze,{id:"show-dialog",label:"Show dialog",onSelect:()=>{s({component:({onClose:a})=>p.jsx(ple,{displayDontShowAgain:!0,onCancel:()=>a(),onContinue:()=>a()}),onClose:()=>{}})}}),p.jsx(Ze,{id:"create-shapes",label:"Create 100 shapes",onSelect:()=>fle(t,100)}),p.jsx(Ze,{id:"count-nodes",label:"Count shapes / nodes",onSelect:()=>{var c;const a=t.getSelectedShapes(),l=a.length===0?t.getRenderingShapes():a;window.alert(`Shapes ${l.length}, DOM nodes:${(c=document.querySelector(".tl-shapes").querySelectorAll("*"))==null?void 0:c.length}`)}}),(()=>{if(o)throw Error("oh no!");return null})(),p.jsx(Ze,{id:"throw-error",onSelect:()=>i(!0),label:"Throw error"})]}),p.jsxs($e,{id:"flags",children:[p.jsx(ule,{customDebugFlags:n}),p.jsx(hle,{customFeatureFlags:e})]})]})}function ule(n){const e=Object.values(n.customDebugFlags??Dt);return e.length?p.jsx(mr,{id:"debug flags",label:"Debug flags",children:p.jsx($e,{id:"debug flags",children:e.map(t=>p.jsx(p5,{flag:t},t.name))})}):null}function hle(n){const e=Object.values(n.customFeatureFlags??HU);return e.length?p.jsx(mr,{id:"feature flags",label:"Feature flags",children:p.jsx($e,{id:"feature flags",children:e.map(t=>p.jsx(p5,{flag:t},t.name))})}):null}function ple({title:n="title",body:e="hello hello hello",cancel:t="Cancel",confirm:r="Continue",displayDontShowAgain:s=!1,maxWidth:o="350",onCancel:i,onContinue:a}){const[l,c]=_e.useState(!1);return p.jsxs(p.Fragment,{children:[p.jsxs(wS,{children:[p.jsx(vS,{children:n}),p.jsx(CS,{})]}),p.jsx(wh,{style:{maxWidth:o},children:e}),p.jsxs(jC,{className:"tlui-dialog__footer__actions",children:[s&&p.jsxs(Ye,{type:"normal",onClick:()=>c(!l),style:{marginRight:"auto"},children:[p.jsx(z0,{checked:l}),p.jsx(Qt,{children:"Don’t show again"})]}),p.jsx(Ye,{type:"normal",onClick:i,children:p.jsx(Qt,{children:t})}),p.jsx(Ye,{type:"primary",onClick:async()=>a(),children:p.jsx(Qt,{children:r})})]})]})}const p5=rn(function({flag:e,onChange:t}){const r=e.get();return p.jsx(mp,{id:e.name,title:e.name,label:e.name.replace(/([a-z0-9])([A-Z])/g,s=>`${s[0]} ${s[1].toLowerCase()}`).replace(/^[a-z]/,s=>s.toUpperCase()),checked:r,onSelect:()=>{e.set(!r),t==null||t(!r)}})});let Tk=0;function fle(n,e){const t=n.options.adjacentShapeMargin,r=Array(e),s=Math.floor(Math.sqrt(e));for(let o=0;o<e;o++)Tk++,r[o]={id:St("box"+Tk),type:"geo",x:o%s*(100+t),y:Math.floor(o/s)*(100+t)};n.run(()=>{n.createShapes(r).setSelectedShapes(r.map(o=>o.id))})}function gle({children:n}){const e=n??p.jsx(dle,{});return p.jsxs(IS,{id:"debug",children:[p.jsx(ES,{children:p.jsx(Ye,{type:"icon",title:"Debug menu",children:p.jsx(Ae,{icon:"dots-horizontal"})})}),p.jsx(kS,{side:"top",align:"end",alignOffset:0,children:p.jsx(Fr,{type:"menu",sourceId:"debug-panel",children:e})})]})}const mle=x.memo(function(){const{DebugMenu:e}=ti(),t=x.useRef(null);return Jo(t),p.jsxs("footer",{ref:t,className:"tlui-debug-panel",children:[p.jsx(yle,{}),p.jsx(Sle,{}),e&&p.jsx(e,{})]})}),yle=rn(function(){const t=K().getPath();return p.jsx("div",{className:"tlui-debug-panel__current-state",children:`${t}`})});function Sle(){const n=K(),e=W("show_fps",()=>Dt.showFps.get(),[Dt]),t=x.useRef(null);return x.useEffect(()=>{if(!e)return;const r=250;let s=0,o=-1,i=performance.now(),a=0,l=0,c=!1;function u(){if(l++,a=performance.now()-i,a>r){const d=Math.round(l*(r/a)*(1e3/r));d>s&&(s=d);const h=s*.75;(d<h&&!c||d>=h&&c)&&(c=!c),t.current.innerHTML=`FPS ${d.toString()} (max: ${s})`,t.current.className="tlui-debug-panel__fps"+(c?" tlui-debug-panel__fps__slow":""),a-=r,l=0,i=performance.now()}o=n.timers.requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(o)}},[e,n]),e?p.jsx("div",{ref:t}):null}function xle(){const n=K(),e=W("follow",()=>n.getInstanceState().followingUserId,[n]);return e?p.jsx(ble,{userId:e}):null}function ble({userId:n}){const e=Ey(n);return e?p.jsx("div",{className:"tlui-following-indicator",style:{borderColor:e.color}}):null}const wle=x.memo(function(){const e=Gn(),t=Se(),r=x.useRef(null);Jo(r);const{MainMenu:s,QuickActions:o,ActionsMenu:i,PageMenu:a}=ti(),l=K(),c=W("isSinglePageMode",()=>l.options.maxPages<=1,[l]),u=l.options.actionShortcutsLocation==="menu"?!0:l.options.actionShortcutsLocation==="toolbar"?!1:e>=Ot.TABLET;return!s&&!a&&!u?null:p.jsx("nav",{ref:r,className:"tlui-menu-zone",children:p.jsxs(Ql,{children:[s&&p.jsx(s,{}),a&&!c&&p.jsx(a,{}),u?p.jsxs(ur,{orientation:"horizontal",label:t("actions-menu.title"),children:[o&&p.jsx(o,{}),i&&p.jsx(i,{})]}):null]})})}),vle=({id:n,component:e,preventBackgroundClose:t})=>{const{removeDialog:r}=gp(),s=x.useRef(!1),o=sn(),i=x.useCallback(a=>{a||r(n)},[n,r]);return p.jsx(Yee,{onOpenChange:i,defaultOpen:!0,children:p.jsx(Xee,{container:o,children:p.jsx(qee,{dir:"ltr",className:"tlui-dialog__overlay",onClick:a=>{s.current||!t&&a.target===a.currentTarget&&i(!1)},children:p.jsx(Zee,{dir:"ltr",className:"tlui-dialog__content","aria-describedby":void 0,onMouseDown:()=>s.current=!0,onMouseUp:()=>s.current=!1,onInteractOutside:a=>{s.current=!1,t&&a.preventDefault()},children:p.jsx(e,{onClose:()=>{s.current=!1,i(!1)}})})})})})},Cle=x.memo(function(){const{dialogs:e}=gp();return W("dialogs",()=>e.get(),[e]).map(r=>p.jsx(vle,{...r},r.id))});function Ple(){const n=K(),e=ni(),[t,r]=x.useState(!1),s=x.useRef(!1);return Va("toggle showback to content",()=>{const o=s.current,i=n.getCurrentPageShapeIds();let a=!1;i.size&&(a=i.size===n.getNotVisibleShapes().size),o!==a&&(r(a),s.current=a)},[n]),t?p.jsx(Z,{actionId:"back-to-content",onSelect:()=>{e["back-to-content"].onSelect("helper-buttons"),r(!1)}}):null}function Tle(){const n=K();return W("is pen mode",()=>n.getInstanceState().isPenMode,[n])?p.jsx(Z,{actionId:"exit-pen-mode"}):null}function Ile(){const n=K(),e=ni();return W("is following user",()=>!!n.getInstanceState().followingUserId,[n])?p.jsx(Ze,{...e["stop-following"]}):null}function Ele(){return p.jsxs(p.Fragment,{children:[p.jsx(Tle,{}),p.jsx(Ple,{}),p.jsx(Ile,{})]})}function kle({children:n}){const e=n??p.jsx(Ele,{});return p.jsx("div",{className:"tlui-helper-buttons",children:p.jsx(Fr,{type:"helper-buttons",sourceId:"helper-buttons",children:e})})}const _le=[{colorScheme:"light",label:"theme.light"},{colorScheme:"dark",label:"theme.dark"},{colorScheme:"system",label:"theme.system"}];function Mle(){const n=K(),e=Rt(),t=W("colorScheme",()=>n.user.getUserPreferences().colorScheme??(n.user.getIsDarkMode()?"dark":"light"),[n]);return p.jsx(mr,{id:"help menu color-scheme",label:"menu.theme",children:p.jsx($e,{id:"theme",children:_le.map(({colorScheme:r,label:s})=>p.jsx(mp,{id:`color-scheme-${r}`,label:s,checked:r===t,readonlyOk:!0,onSelect:()=>{n.user.updateUserPreferences({colorScheme:r}),e("color-scheme",{source:"menu",value:r})}},r))})})}function f5(){const n=Xt(),e=Rt(),t=W("locale",()=>n==null?void 0:n.user.getLocale(),[n]);return n?p.jsx(mr,{id:"help menu language",label:"menu.language",children:p.jsx($e,{id:"languages",className:"tlui-language-menu",children:oh.map(({locale:r,label:s})=>p.jsx(mp,{id:`language-${r}`,lang:r,title:r,label:s,checked:r===t,readonlyOk:!0,onSelect:()=>{n.user.updateUserPreferences({locale:r}),e("change-language",{source:"menu",locale:r})}},r))})}):null}function Ale(){return p.jsxs(p.Fragment,{children:[p.jsx(f5,{}),p.jsx(g5,{})]})}function g5(){const{KeyboardShortcutsDialog:n}=ti(),{addDialog:e}=gp(),t=x.useCallback(()=>{n&&e({component:n})},[e,n]);return n?p.jsx(Ze,{id:"keyboard-shortcuts-button",label:"help-menu.keyboard-shortcuts",readonlyOk:!0,onSelect:t}):null}const Dle=["auto","trackpad","mouse"];function Ole(){const n=K(),e=Rt(),t=W("inputMode",()=>n.user.getUserPreferences().inputMode,[n]),r=W("wheelBehavior",()=>n.getCameraOptions().wheelBehavior,[n]),s=i=>i==="auto"?t===null:t===i,o=(i,a)=>i==="auto"?`action.toggle-auto-${a}`:i==="trackpad"?"action.toggle-trackpad":"action.toggle-mouse";return p.jsxs(mr,{id:"help menu input-mode",label:"menu.input-device",children:[p.jsx($e,{id:"peripheral-mode",children:Dle.map(i=>p.jsx(mp,{id:`peripheral-mode-${i}`,label:o(i,r),checked:s(i),readonlyOk:!0,onSelect:()=>{switch(e("input-mode",{source:"menu",value:i}),i){case"auto":n.user.updateUserPreferences({inputMode:null});break;case"trackpad":n.user.updateUserPreferences({inputMode:"trackpad"});break;case"mouse":n.user.updateUserPreferences({inputMode:"mouse"});break}}},i))}),p.jsx($e,{id:"invert-zoom-group",children:p.jsx(jue,{})})]})}function Rle(){return p.jsxs(p.Fragment,{children:[p.jsxs($e,{id:"basic",children:[p.jsx(jle,{}),p.jsx(zle,{}),p.jsx(Lle,{}),p.jsx($le,{})]}),p.jsx(Hle,{})]})}function Lle(){return p.jsxs(mr,{id:"export-all-as",label:"context-menu.export-all-as",size:"small",children:[p.jsxs($e,{id:"export-all-as-group",children:[p.jsx(Z,{actionId:"export-all-as-svg"}),p.jsx(Z,{actionId:"export-all-as-png"})]}),p.jsx($e,{id:"export-all-as-bg",children:p.jsx(ZC,{})})]})}function jle(){return p.jsxs(mr,{id:"edit",label:"menu.edit",children:[p.jsx(Ble,{}),p.jsx(tz,{}),p.jsx(nz,{}),p.jsx(Nle,{}),p.jsx(Fle,{}),p.jsx($e,{id:"select-all",children:p.jsx(rz,{})})]})}function Nle(){return p.jsxs($e,{id:"misc",children:[p.jsx(Y5,{}),p.jsx(X5,{}),p.jsx(V5,{}),p.jsx(W5,{}),p.jsx(q5,{}),p.jsx(Z5,{}),p.jsx(oz,{}),p.jsx(sz,{}),p.jsx(G5,{})]})}function Fle(){return p.jsxs($e,{id:"lock",children:[p.jsx(J5,{}),p.jsx(Sue,{})]})}function Ble(){const n=u5(),e=d5();return p.jsxs($e,{id:"undo-redo",children:[p.jsx(Z,{actionId:"undo",disabled:!n}),p.jsx(Z,{actionId:"redo",disabled:!e})]})}function zle(){return p.jsx(mr,{id:"view",label:"menu.view",children:p.jsxs($e,{id:"view-actions",children:[p.jsx(Z,{actionId:"zoom-in"}),p.jsx(Z,{actionId:"zoom-out"}),p.jsx(JC,{}),p.jsx(Q5,{}),p.jsx(ez,{})]})})}function $le(){return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"insert-embed"}),p.jsx(Z,{actionId:"insert-media"})]})}function Hle(){return p.jsxs($e,{id:"preferences",children:[p.jsxs(mr,{id:"preferences",label:"menu.preferences",children:[p.jsxs($e,{id:"preferences-actions",children:[p.jsx(Mue,{}),p.jsx(Aue,{}),p.jsx(Due,{}),p.jsx(Oue,{}),p.jsx(Rue,{}),p.jsx(Lue,{}),p.jsx($ue,{}),p.jsx(Hue,{}),p.jsx(zue,{})]}),p.jsxs($e,{id:"user-interface-submenus",children:[p.jsx(Mle,{}),p.jsx(Kue,{}),p.jsx(Ole,{})]})]}),p.jsx(f5,{}),p.jsx(g5,{})]})}const Ule=x.memo(function({children:e}){const t=sn(),[r,s]=Yi("main menu"),o=Se(),i=e??p.jsx(Rle,{});return p.jsxs(mC,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[p.jsx(yC,{asChild:!0,dir:"ltr",children:p.jsx(Ye,{type:"icon","data-testid":"main-menu.button",title:o("menu.title"),children:p.jsx(Ae,{icon:"menu",small:!0})})}),p.jsx(hS,{container:t,children:p.jsx(SC,{className:"tlui-menu",side:"bottom",align:"start",collisionPadding:4,alignOffset:0,sideOffset:6,children:p.jsx(Fr,{type:"menu",sourceId:"main-menu",children:i})})})]})}),kb={};function Vd(n){if(kb[n])return kb[n];const t=document.createElement("canvas").getContext("2d");t.fillStyle=n,t.fillRect(0,0,1,1);const[r,s,o,i]=t.getImageData(0,0,1,1).data,a=new Float32Array([r/255,s/255,o/255,i/255]);return kb[n]=a,a}const Zf=10,m5=24*Zf+12+48;function Tc(n,{center:e,radius:t,numArcSegments:r=20,startAngle:s=0,endAngle:o=vt,offset:i=0}){const a=(o-s)/r;let l=i;for(let c=s;c<o;c+=a)n[l++]=e.x,n[l++]=e.y,n[l++]=e.x+Math.cos(c)*t,n[l++]=e.y+Math.sin(c)*t,n[l++]=e.x+Math.cos(c+a)*t,n[l++]=e.y+Math.sin(c+a)*t;return n}function Ic(n,e,t,r,s,o){n[e++]=t,n[e++]=r,n[e++]=t,n[e++]=r+o,n[e++]=t+s,n[e++]=r,n[e++]=t+s,n[e++]=r,n[e++]=t,n[e++]=r+o,n[e++]=t+s,n[e++]=r+o}function Kle(n,e,t){const r=Zf;t=Math.min(t,Math.min(e.w,e.h)/2);const s=J.ExpandBy(e,-t);if(s.w<=0||s.h<=0)return Tc(n,{center:e.center,radius:t,numArcSegments:Zf*4}),Zf*4*6;let o=0;return Ic(n,o,s.minX,s.minY,s.w,s.h),o+=12,Ic(n,o,s.minX,e.minY,s.w,t),o+=12,Ic(n,o,s.maxX,s.minY,t,s.h),o+=12,Ic(n,o,s.minX,s.maxY,s.w,t),o+=12,Ic(n,o,e.minX,s.minY,t,s.h),o+=12,Tc(n,{numArcSegments:r,offset:o,center:s.point,radius:t,startAngle:ht,endAngle:ht*1.5}),o+=r*6,Tc(n,{numArcSegments:r,offset:o,center:C.Add(s.point,new C(s.w,0)),radius:t,startAngle:ht*1.5,endAngle:vt}),o+=r*6,Tc(n,{numArcSegments:r,offset:o,center:C.Add(s.point,s.size),radius:t,startAngle:0,endAngle:Bt}),o+=r*6,Tc(n,{numArcSegments:r,offset:o,center:C.Add(s.point,new C(0,s.h)),radius:t,startAngle:Bt,endAngle:ht}),m5}function Wle(n){if(!n)throw new Error("Canvas element not found");const e=n.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Failed to get webgl2 context");const t=`#version 300 es
427
+ precision mediump float;
428
+
429
+ in vec2 shapeVertexPosition;
430
+
431
+ uniform vec4 canvasPageBounds;
432
+
433
+ // taken (with thanks) from
434
+ // https://webglfundamentals.org/webgl/lessons/webgl-2d-matrices.html
435
+ void main() {
436
+ // convert the position from pixels to 0.0 to 1.0
437
+ vec2 zeroToOne = (shapeVertexPosition - canvasPageBounds.xy) / canvasPageBounds.zw;
438
+
439
+ // convert from 0->1 to 0->2
440
+ vec2 zeroToTwo = zeroToOne * 2.0;
441
+
442
+ // convert from 0->2 to -1->+1 (clipspace)
443
+ vec2 clipSpace = zeroToTwo - 1.0;
444
+
445
+ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
446
+ }`,r=e.createShader(e.VERTEX_SHADER);if(!r)throw new Error("Failed to create vertex shader");if(e.shaderSource(r,t),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw new Error("Failed to compile vertex shader");const s=`#version 300 es
447
+ precision mediump float;
448
+
449
+ uniform vec4 fillColor;
450
+ out vec4 outputColor;
451
+
452
+ void main() {
453
+ outputColor = fillColor;
454
+ }`,o=e.createShader(e.FRAGMENT_SHADER);if(!o)throw new Error("Failed to create fragment shader");if(e.shaderSource(o,s),e.compileShader(o),!e.getShaderParameter(o,e.COMPILE_STATUS))throw new Error("Failed to compile fragment shader");const i=e.createProgram();if(!i)throw new Error("Failed to create program");if(e.attachShader(i,r),e.attachShader(i,o),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS))throw new Error("Failed to link program");e.useProgram(i);const a=e.getAttribLocation(i,"shapeVertexPosition");if(a<0)throw new Error("Failed to get shapeVertexPosition attribute location");e.enableVertexAttribArray(a);const l=e.getUniformLocation(i,"canvasPageBounds"),c=e.getUniformLocation(i,"fillColor");if(!e.createBuffer())throw new Error("Failed to create buffer");if(!e.createBuffer())throw new Error("Failed to create buffer");return{context:e,selectedShapes:yf(e,1024),unselectedShapes:yf(e,4096),viewport:yf(e,m5),collaborators:yf(e,1024),prepareTriangles(h,f){e.bindBuffer(e.ARRAY_BUFFER,h.buffer),e.bufferData(e.ARRAY_BUFFER,h.vertices,e.STATIC_DRAW,0,f),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,2,e.FLOAT,!1,0,0)},drawTrianglesTransparently(h){e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,h/2),e.disable(e.BLEND)},drawTriangles(h){e.drawArrays(e.TRIANGLES,0,h/2)},setFillColor(h){e.uniform4fv(c,h)},setCanvasPageBounds(h){e.uniform4fv(l,h)}}}function yf(n,e){const t=n.createBuffer();if(!t)throw new Error("Failed to create buffer");return{buffer:t,vertices:new Float32Array(e)}}function Ik(n,e,t){let r=n.vertices.length;for(;r<e+t.length;)r*=2;if(r!=n.vertices.length){const s=new Float32Array(r);s.set(n.vertices),n.vertices=s}n.vertices.set(t,e)}var Vle=Object.create,y5=Object.defineProperty,Gle=Object.getOwnPropertyDescriptor,Yle=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),S5=n=>{throw TypeError(n)},x5=(n,e,t)=>e in n?y5(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Xle=n=>[,,,Vle(null)],b5=["class","method","getter","setter","accessor","field","value","get","set"],w5=n=>n!==void 0&&typeof n!="function"?S5("Function expected"):n,qle=(n,e,t,r,s)=>({kind:b5[n],name:e,metadata:r,addInitializer:o=>t._?S5("Already initialized"):s.push(w5(o||null))}),Zle=(n,e)=>x5(e,Yle("metadata"),n[3]),Jle=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},ei=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=b5[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,Gle(s,t)),S=r.length-1;S>=0;S--)l=qle(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,w5(i)&&(y[g]=i);return y&&y5(s,t,y),s},wi=(n,e,t)=>x5(n,typeof e!="symbol"?e+"":e,t),v5,C5,P5,T5,I5,E5,k5,_5,M5,A5,Ts;A5=[Xr],M5=[q],_5=[q],k5=[q],E5=[q],I5=[q],T5=[q],P5=[q],C5=[q],v5=[Xr];class qs{constructor(e,t,r){this.editor=e,this.elem=t,this.container=r,Jle(Ts,5,this),wi(this,"disposables",[]),wi(this,"gl"),wi(this,"shapeGeometryCache"),wi(this,"colors"),wi(this,"id",at()),wi(this,"canvasBoundingClientRect",We("canvasBoundingClientRect",new J)),wi(this,"originPagePoint",new C),wi(this,"originPageCenter",new C),wi(this,"isInViewport",!1),this.gl=Wle(t),this.shapeGeometryCache=e.store.createComputedCache("webgl-geometry",s=>{const o=e.getShapeMaskedPageBounds(s.id);if(!o)return null;const i=new Float32Array(12);return Ic(i,0,o.x,o.y,o.w,o.h),i}),this.colors=this._getColors(),this.disposables.push(this._listenForCanvasResize(),Mr("minimap render",this.render))}close(){return this.disposables.forEach(e=>e())}_getColors(){const e=getComputedStyle(this.editor.getContainer());return{shapeFill:Vd(e.getPropertyValue("--tl-color-text-3").trim()),selectFill:Vd(e.getPropertyValue("--tl-color-selected").trim()),viewportFill:Vd(e.getPropertyValue("--tl-color-muted-1").trim()),background:Vd(e.getPropertyValue("--tl-color-low").trim())}}updateColors(){this.colors=this._getColors()}getDpr(){return this.editor.getInstanceState().devicePixelRatio}getContentPageBounds(){const e=this.editor.getViewportPageBounds(),t=this.editor.getCurrentPageBounds();return t?J.Expand(t,e):e}getContentScreenBounds(){const e=this.getContentPageBounds(),t=this.editor.pageToScreen(e.point),r=this.editor.pageToScreen(new C(e.maxX,e.maxY));return new J(t.x,t.y,r.x-t.x,r.y-t.y)}_getCanvasBoundingRect(){const{x:e,y:t,width:r,height:s}=this.elem.getBoundingClientRect();return new J(e,t,r,s)}getCanvasScreenBounds(){return this.canvasBoundingClientRect.get()}_listenForCanvasResize(){const e=new ResizeObserver(()=>{const t=this._getCanvasBoundingRect();this.canvasBoundingClientRect.set(t)});return e.observe(this.elem),e.observe(this.container),()=>e.disconnect()}getCanvasSize(){const e=this.canvasBoundingClientRect.get(),t=this.getDpr();return new C(e.width*t,e.height*t)}getCanvasClientPosition(){return this.canvasBoundingClientRect.get().point}getCanvasPageBounds(){const e=this.getCanvasScreenBounds(),t=this.getContentPageBounds(),r=e.width/e.height;let s=t.width,o=s/r;o<t.height&&(o=t.height,s=o*r);const i=new J(0,0,s,o);return i.center=t.center,i}getZoom(){return this.getCanvasPageBounds().width/this.getCanvasScreenBounds().width}getCanvasPageBoundsArray(){const{x:e,y:t,w:r,h:s}=this.getCanvasPageBounds();return new Float32Array([e,t,r,s])}getMinimapPagePoint(e,t){const r=this.getCanvasPageBounds(),s=this.getCanvasScreenBounds();let o=e-s.x,i=t-s.y;return o*=r.width/s.width,i*=r.height/s.height,o+=r.minX,i+=r.minY,new C(o,i,1)}minimapScreenPointToPagePoint(e,t,r=!1,s=!1){const{editor:o}=this,i=o.getViewportPageBounds();let{x:a,y:l}=this.getMinimapPagePoint(e,t);if(s){const c=this.editor.getCurrentPageBounds()??new J,u=c.minX-i.width/2,d=c.maxX+i.width/2,h=c.minY-i.height/2,f=c.maxY+i.height/2,g=Math.max(0,u+i.width-a),m=Math.max(0,-(d-i.width-a)),y=Math.max(0,h+i.height-l),S=Math.max(0,-(f-i.height-l));a+=(g-m)/2,l+=(y-S)/2,a=Fe(a,u,d),l=Fe(l,h,f)}if(r){const{originPagePoint:c}=this,u=Math.abs(a-c.x),d=Math.abs(l-c.y);u>d?l=c.y:a=c.x}return new C(a,l)}render(){var l;const e=this.gl.context,t=this.getCanvasSize();this.gl.setCanvasPageBounds(this.getCanvasPageBoundsArray()),this.elem.width=t.x,this.elem.height=t.y,e.viewport(0,0,t.x,t.y),e.clearColor(this.colors.background[0],this.colors.background[1],this.colors.background[2],1),e.clear(e.COLOR_BUFFER_BIT);const r=new Set(this.editor.getSelectedShapeIds()),s=this.colors;let o=0,i=0;const a=this.editor.getCurrentPageShapeIdsSorted();for(let c=0,u=a.length;c<u;c++){const d=a[c],h=this.shapeGeometryCache.get(d);if(!h)continue;const f=h.length,g=this.editor.getShape(d);if(g){const m=this.editor.getShapeUtil(g.type);if((l=m.hideInMinimap)!=null&&l.call(m,g))continue}r.has(d)?(Ik(this.gl.selectedShapes,o,h),o+=f):(Ik(this.gl.unselectedShapes,i,h),i+=f)}this.drawShapes(this.gl.unselectedShapes,i,s.shapeFill),this.drawShapes(this.gl.selectedShapes,o,s.selectFill),this.drawViewport(),this.drawCollaborators()}drawShapes(e,t,r){this.gl.prepareTriangles(e,t),this.gl.setFillColor(r),this.gl.drawTriangles(t)}drawViewport(){const e=this.editor.getViewportPageBounds(),t=Kle(this.gl.viewport.vertices,e,4*this.getZoom());this.gl.prepareTriangles(this.gl.viewport,t),this.gl.setFillColor(this.colors.viewportFill),this.gl.drawTrianglesTransparently(t),dt.isSafari&&(this.gl.drawTrianglesTransparently(t),this.gl.drawTrianglesTransparently(t),this.gl.drawTrianglesTransparently(t))}drawCollaborators(){const e=this.editor.getCollaboratorsOnCurrentPage();if(!e.length)return;const t=20,r=t*6,s=r*e.length;this.gl.collaborators.vertices.length<s&&(this.gl.collaborators.vertices=new Float32Array(s));const o=this.gl.collaborators.vertices;let i=0;const a=this.getZoom();for(const{cursor:l}of e)l&&(Tc(o,{center:C.From(l),radius:3*a,offset:i,numArcSegments:t}),i+=r);this.gl.prepareTriangles(this.gl.collaborators,s),i=0;for(const{color:l}of e)this.gl.setFillColor(Vd(l)),this.gl.context.drawArrays(this.gl.context.TRIANGLES,i/2,r/2),i+=r}}Ts=Xle();ei(Ts,1,"close",A5,qs);ei(Ts,1,"getDpr",M5,qs);ei(Ts,1,"getContentPageBounds",_5,qs);ei(Ts,1,"getContentScreenBounds",k5,qs);ei(Ts,1,"getCanvasSize",E5,qs);ei(Ts,1,"getCanvasClientPosition",I5,qs);ei(Ts,1,"getCanvasPageBounds",T5,qs);ei(Ts,1,"getZoom",P5,qs);ei(Ts,1,"getCanvasPageBoundsArray",C5,qs);ei(Ts,1,"render",v5,qs);Zle(Ts,qs);function Qle(){const n=K(),e=sn(),t=Se(),r=x.useRef(null),s=x.useRef(!1),o=x.useRef(void 0);x.useEffect(()=>{try{const d=new qs(n,r.current,e);return o.current=d,o.current.close}catch(d){n.annotateError(d,{origin:"minimap",willCrashApp:!1}),n.timers.setTimeout(()=>{throw d})}},[n,e]);const i=x.useCallback(d=>{if(!n.getCurrentPageShapeIds().size||!o.current)return;const h=o.current.minimapScreenPointToPagePoint(d.clientX,d.clientY,!1,!1),f=o.current.minimapScreenPointToPagePoint(d.clientX,d.clientY,!1,!0);o.current.originPagePoint.setTo(f),o.current.originPageCenter.setTo(n.getViewportPageBounds().center),n.centerOnPoint(h,{animation:{duration:n.options.animationMediumMs}})},[n]),a=x.useCallback(d=>{if(!o.current)return;const h=d.currentTarget;if(Nh(h,d),!n.getCurrentPageShapeIds().size)return;s.current=!0,o.current.isInViewport=!1;const f=o.current.minimapScreenPointToPagePoint(d.clientX,d.clientY,!1,!1),g=n.getViewportPageBounds(),m=o.current.getContentPageBounds();if(new J(m.x-g.width/2,m.y-g.height/2,m.width+g.width,m.height+g.height).containsPoint(f)&&!g.containsPoint(f)){o.current.isInViewport=g.containsPoint(f);const b=C.Sub(g.center,g.point),w=C.Add(f,b);o.current.originPagePoint.setTo(w),o.current.originPageCenter.setTo(f),n.centerOnPoint(f,{animation:{duration:n.options.animationMediumMs}})}else{const b=o.current.minimapScreenPointToPagePoint(d.clientX,d.clientY,!1,!0);o.current.isInViewport=g.containsPoint(b),o.current.originPagePoint.setTo(b),o.current.originPageCenter.setTo(g.center)}function S(b){h&&Fh(h,b),s.current=!1,document.body.removeEventListener("pointerup",S)}document.body.addEventListener("pointerup",S)},[n]),l=x.useCallback(d=>{if(!o.current)return;const h=o.current.minimapScreenPointToPagePoint(d.clientX,d.clientY,d.shiftKey,!0);if(s.current){if(o.current.isInViewport){const y=o.current.originPagePoint.clone().sub(o.current.originPageCenter);n.centerOnPoint(C.Sub(h,y));return}n.centerOnPoint(h)}const f=o.current.getMinimapPagePoint(d.clientX,d.clientY),g=n.pageToScreen(f),m={type:"pointer",target:"canvas",name:"pointer_move",...$n(n,d),point:g,isPen:n.getInstanceState().isPenMode};n.dispatch(m)},[n]),c=x.useCallback(d=>{const h=_R(d);n.dispatch({type:"wheel",name:"wheel",delta:h,point:new C(d.clientX,d.clientY),shiftKey:d.shiftKey,altKey:d.altKey,ctrlKey:d.metaKey||d.ctrlKey,metaKey:d.metaKey,accelKey:Jt(d)})},[n]),u=Vh();return x.useEffect(()=>{n.timers.setTimeout(()=>{var d,h;(d=o.current)==null||d.updateColors(),(h=o.current)==null||h.render()})},[u,n]),p.jsx("div",{className:"tlui-minimap",children:p.jsx("canvas",{role:"img","aria-label":t("navigation-zone.minimap"),"data-testid":"minimap.canvas",ref:r,className:"tlui-minimap__canvas",onDoubleClick:i,onPointerMove:l,onPointerDown:a,onWheelCapture:c})})}function ece(n,e){const[t,r]=_e.useState(e);_e.useLayoutEffect(()=>{const o=gv(n);if(o)try{r(JSON.parse(o))}catch{console.error(`Could not restore value ${n} from local storage.`)}},[n]);const s=_e.useCallback(o=>{r(i=>{const a=typeof o=="function"?o(i):o;return mv(n,JSON.stringify(a)),a})},[n]);return[t,s]}const tce=x.memo(function(){const e=ni(),t=Se(),r=Gn(),s=x.useRef(null);Jo(s);const[o,i]=ece("minimap",!0),a=x.useCallback(()=>{i(u=>!u)},[i]),{ZoomMenu:l,Minimap:c}=ti();return r<Ot.MOBILE?null:p.jsxs("div",{ref:s,className:"tlui-navigation-panel",children:[p.jsx(ur,{orientation:"horizontal",label:t("navigation-zone.title"),children:l&&r<Ot.TABLET?p.jsx(l,{}):p.jsxs(p.Fragment,{children:[!o&&p.jsx(bt,{type:"icon","data-testid":"minimap.zoom-out",title:`${t(Ih(e["zoom-out"].label))} ${ym(e["zoom-out"].kbd)}`,onClick:()=>e["zoom-out"].onSelect("navigation-zone"),children:p.jsx(Ae,{small:!0,icon:"minus"})}),l&&p.jsx(l,{},"zoom-menu"),!o&&p.jsx(bt,{type:"icon","data-testid":"minimap.zoom-in",title:`${t(Ih(e["zoom-in"].label))} ${ym(e["zoom-in"].kbd)}`,onClick:()=>e["zoom-in"].onSelect("navigation-zone"),children:p.jsx(Ae,{small:!0,icon:"plus"})}),c&&p.jsx(bt,{type:"icon","data-testid":"minimap.toggle-button",title:t("navigation-zone.toggle-minimap"),onClick:a,children:p.jsx(Ae,{small:!0,icon:o?"chevron-right":"chevron-left"})})]})}),c&&r>=Ot.TABLET&&!o&&p.jsx(c,{})]})}),nce=function({name:e,id:t,isCurrentPage:r,onCancel:s,onComplete:o}){const i=K(),a=Rt(),l=x.useRef(null),c=x.useRef(null),u=x.useCallback(()=>{c.current=i.markHistoryStoppingPoint("rename page")},[i]),d=x.useCallback(f=>{i.renamePage(t,f||"New Page"),a("rename-page",{source:"page-menu"})},[i,t,a]),h=x.useCallback(()=>{c.current&&i.bailToMark(c.current),s()},[i,s]);return p.jsx(Id,{className:"tlui-page-menu__item__input",ref:f=>{l.current=f},defaultValue:e,onValueChange:d,onComplete:o,onCancel:h,onFocus:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:r,autoSelect:!0})},$0=(n,e,t,r,s)=>{let o;const i=n.getPages(),a=t>r?i[r-1]:i[r],l=t>r?i[r]:i[r+1];a&&!l?o=Ns(a.index):!a&&l?o=q4(i[0].index):o=Xc(a.index,l.index),o!==i[t].index&&(n.markHistoryStoppingPoint("moving page"),n.updatePage({id:e,index:o}),s("move-page",{source:"page-menu"}))},Ek=rn(function({index:e,listSize:t,item:r,onRename:s}){const o=K(),i=Se(),a=o.getPages(),l=Rt(),c=x.useCallback(()=>{o.markHistoryStoppingPoint("creating page");const f=Ar.createId();o.duplicatePage(r.id,f),l("duplicate-page",{source:"page-menu"})},[o,r,l]),u=x.useCallback(()=>{$0(o,r.id,e,e-1,l)},[o,r,e,l]),d=x.useCallback(()=>{$0(o,r.id,e,e+1,l)},[o,r,e,l]),h=x.useCallback(()=>{o.markHistoryStoppingPoint("deleting page"),o.deletePage(r.id),l("delete-page",{source:"page-menu"})},[o,r,l]);return p.jsxs(IS,{id:`page item submenu ${e}`,children:[p.jsx(ES,{children:p.jsx(Ye,{type:"icon",title:i("page-menu.submenu.title"),children:p.jsx(Ae,{icon:"dots-vertical",small:!0})})}),p.jsx(kS,{alignOffset:0,side:"right",sideOffset:-4,children:p.jsxs(Fr,{type:"menu",sourceId:"page-menu",children:[p.jsxs($e,{id:"modify",children:[s&&p.jsx(Ze,{id:"rename",label:"page-menu.submenu.rename",onSelect:s}),p.jsx(Ze,{id:"duplicate",label:"page-menu.submenu.duplicate-page",onSelect:c,disabled:a.length>=o.options.maxPages}),e>0&&p.jsx(Ze,{id:"move-up",onSelect:u,label:"page-menu.submenu.move-up"}),e<t-1&&p.jsx(Ze,{id:"move-down",label:"page-menu.submenu.move-down",onSelect:d})]}),t>1&&p.jsx($e,{id:"delete",children:p.jsx(Ze,{id:"delete",onSelect:h,label:"page-menu.submenu.delete"})})]})})]})}),rce=x.memo(function(){const e=K(),t=Rt(),r=Se(),s=Gn(),o=x.useCallback(()=>S(!1),[]),[i,a]=Yi("page-menu",o),l=36,c=x.useRef(null),u=W("pages",()=>e.getPages(),[e]),d=W("currentPage",()=>e.getCurrentPage(),[e]),h=W("currentPageId",()=>e.getCurrentPageId(),[e]),f=Ps(),g=W("maxPageCountReached",()=>e.getPages().length>=e.options.maxPages,[e]),m=W("isCoarsePointer",()=>e.getInstanceState().isCoarsePointer,[e]),[y,S]=x.useState(!1);x.useEffect(function(){function O(){y||document.activeElement===document.body&&e.menus.clearOpenMenus()}return document.addEventListener("keydown",O,{passive:!0}),()=>{document.removeEventListener("keydown",O)}},[e,y]);const b=x.useCallback(()=>{f||S(M=>!M)},[f]),w=x.useRef({isPointing:!1,status:"idle",pointing:null,startY:0,startIndex:0,dragIndex:0}),[v,P]=x.useState(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])));x.useLayoutEffect(()=>{P(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])))},[l,u]),x.useEffect(()=>{i&&e.timers.requestAnimationFrame(()=>{var O;const M=document.querySelector(`[data-pageid="${h}"]`);if(M){(O=M.querySelector("button"))==null||O.focus();const N=c.current;if(!N)return;const B=M.offsetTop,H=N.scrollTop;B<H&&N.scrollTo({top:B});const z=B+l,X=N.scrollTop+N.offsetHeight;z>X&&N.scrollTo({top:z-N.offsetHeight})}})},[l,h,i,e]);const T=x.useCallback(M=>{const{clientY:O,currentTarget:N}=M,{dataset:{id:B,index:H}}=N;if(!B||!H)return;const z=w.current;Nh(M.currentTarget,M),z.status="pointing",z.pointing={id:B,index:+H};const G=v[B].y;z.startY=O,z.startIndex=Math.max(0,Math.min(Math.round(G/l),u.length-1))},[l,u.length,v]),I=x.useCallback(M=>{const O=w.current;if(O.status==="pointing"){const{clientY:N}=M,B=N-O.startY;Math.abs(B)>5&&(O.status="dragging")}if(O.status==="dragging"){const{clientY:N}=M,B=N-O.startY,H=v[O.pointing.id],{startIndex:z,pointing:X}=O,G=H.y+B,ae=Math.max(0,Math.min(Math.round(G/l),u.length-1)),Ce={...v};if(Ce[X.id]={y:H.y,offsetY:B,isSelected:!0},ae!==O.dragIndex){O.dragIndex=ae;for(let fe=0;fe<u.length;fe++){const oe=u[fe];if(oe.id===O.pointing.id)continue;let{y:Te}=Ce[oe.id];ae===z?Te=fe*l:ae<z?ae<=fe&&fe<z?Te=(fe+1)*l:Te=fe*l:ae>z&&(ae>=fe&&fe>z?Te=(fe-1)*l:Te=fe*l),Te!==Ce[oe.id].y&&(Ce[oe.id]={y:Te,offsetY:0,isSelected:!0})}}P(Ce)}},[l,u,v]),k=x.useCallback(M=>{const O=w.current;if(O.status==="dragging"){const{id:N,index:B}=O.pointing;$0(e,N,B,O.dragIndex,t)}Fh(M.currentTarget,M),O.status="idle"},[e,t]),A=x.useCallback(M=>{const O=w.current;M.key==="Escape"&&(O.status==="dragging"&&P(Object.fromEntries(u.map((N,B)=>[N.id,{y:B*l,offsetY:0,isSelected:!1}]))),O.status="idle")},[l,u]),R=x.useCallback(()=>{f||(e.run(()=>{e.markHistoryStoppingPoint("creating page");const M=Ar.createId();e.createPage({name:r("page-menu.new-page-initial-name"),id:M}),e.setCurrentPage(M),S(!0),e.timers.requestAnimationFrame(()=>{var N;const O=document.querySelector(`[data-pageid="${M}"]`);O&&((N=O.querySelector("button"))==null||N.focus())})}),t("new-page",{source:"page-menu"}))},[e,r,f,t]),D=x.useCallback(M=>{e.setCurrentPage(M),t("change-page",{source:"page-menu"})},[e,t]),j=x.useCallback((M,O)=>{e.renamePage(M,O),t("rename-page",{source:"page-menu"})},[e,t]),_=s<Ot.TABLET_SM&&m;return p.jsxs(Bl,{id:"pages",onOpenChange:a,open:i,children:[p.jsx(zl,{"data-testid":"main.page-menu",children:p.jsxs(Ye,{type:"menu",title:d.name,"data-testid":"page-menu.button",className:"tlui-page-menu__trigger",children:[p.jsx("div",{className:"tlui-page-menu__name",children:d.name}),p.jsx(Ae,{icon:"chevron-down",small:!0})]})}),p.jsx($l,{side:"bottom",align:"start",sideOffset:0,disableEscapeKeyDown:y,children:p.jsxs("div",{className:"tlui-page-menu__wrapper",children:[p.jsxs("div",{className:"tlui-page-menu__header",children:[p.jsx("div",{className:"tlui-page-menu__header__title",children:r("page-menu.title")}),!f&&p.jsxs(Ql,{children:[p.jsx(Ye,{type:"icon","data-testid":"page-menu.edit",title:r(y?"page-menu.edit-done":"page-menu.edit-start"),onClick:b,children:p.jsx(Ae,{icon:y?"check":"edit"})}),p.jsx(Ye,{type:"icon","data-testid":"page-menu.create",title:r(g?"page-menu.max-page-count-reached":"page-menu.create-new-page"),disabled:g,onClick:R,children:p.jsx(Ae,{icon:"plus"})})]})]}),p.jsx("div",{"data-testid":"page-menu.list",className:"tlui-page-menu__list tlui-menu__group",style:{height:l*u.length+4},ref:c,children:u.map((M,O)=>{const N=v[M.id]??{offsetY:0};return y?p.jsxs("div",{"data-testid":"page-menu.item","data-pageid":M.id,className:"tlui-page_menu__item__sortable",style:{zIndex:M.id===d.id?888:O,transform:`translate(0px, ${N.y+N.offsetY}px)`},children:[p.jsx(Ye,{type:"icon",tabIndex:-1,className:"tlui-page_menu__item__sortable__handle",onPointerDown:T,onPointerUp:k,onPointerMove:I,onKeyDown:A,"data-id":M.id,"data-index":O,children:p.jsx(Ae,{icon:"drag-handle-dots"})}),_?p.jsxs(Ye,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>{const B=window.prompt(r("action.rename"),M.name);B&&B!==M.name&&j(M.id,B)},onDoubleClick:b,children:[p.jsx(z0,{checked:M.id===d.id}),p.jsx(Qt,{children:M.name})]}):p.jsx("div",{className:"tlui-page_menu__item__sortable__title",style:{height:l},children:p.jsx(nce,{id:M.id,name:M.name,isCurrentPage:M.id===d.id,onComplete:()=>{S(!1)},onCancel:()=>{S(!1)}})}),!f&&p.jsx("div",{className:"tlui-page_menu__item__submenu","data-isediting":y,children:p.jsx(Ek,{index:O,item:M,listSize:u.length})})]},M.id+"_editing"):p.jsxs("div",{"data-pageid":M.id,"data-testid":"page-menu.item",className:"tlui-page-menu__item",children:[p.jsxs(Ye,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>D(M.id),onDoubleClick:b,title:r("page-menu.go-to-page"),onKeyDown:B=>{B.key==="Enter"&&M.id===d.id&&(b(),e.markEventAsHandled(B))},children:[p.jsx(z0,{checked:M.id===d.id}),p.jsx(Qt,{children:M.name})]}),!f&&p.jsx("div",{className:"tlui-page_menu__item__submenu",children:p.jsx(Ek,{index:O,item:M,listSize:u.length,onRename:()=>{if(_){const B=window.prompt(r("action.rename"),M.name);B&&B!==M.name&&j(M.id,B)}else S(!0),h!==M.id&&D(M.id)}})})]},M.id)})})]})})]})});function sce(){const n=K(),e=Ps(),t=W("should display quick actions",()=>n.isInAny("select","hand","zoom"),[n]);if(!(e&&!t))return p.jsxs(p.Fragment,{children:[p.jsx(ice,{}),p.jsx(oce,{})]})}function oce(){const n=Br(1),e=qi(),t=n&&e;return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"delete",disabled:!t}),p.jsx(Z,{actionId:"duplicate",disabled:!t})]})}function ice(){const n=u5(),e=d5();return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"undo",disabled:!n}),p.jsx(Z,{actionId:"redo",disabled:!e})]})}const ace=x.memo(function({children:e}){const t=e??p.jsx(sce,{});return p.jsx(Fr,{type:"small-icons",sourceId:"quick-actions",children:t})});function lce(){const n=Se();return p.jsx(fp,{content:n("status.offline"),children:p.jsx("div",{className:"tlui-offline-indicator",children:p.jsx(Co,{icon:"status-offline",label:n("status.offline"),small:!0})})})}function cce({userId:n}){var t;const e=Ey(n);return e?p.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:e.color},children:((t=e.userName)==null?void 0:t[0])??""},n):null}const dce=rn(function({userId:e}){var c;const t=K(),r=Se(),s=Rt(),o=Ey(e),i=x.useCallback(()=>{t.getInstanceState().followingUserId===e?(t.stopFollowingUser(),s("stop-following",{source:"people-menu"})):(t.startFollowingUser(e),s("start-following",{source:"people-menu"}))},[t,e,s]),a=(o==null?void 0:o.followingUserId)===t.user.getId(),l=t.getInstanceState().followingUserId===e;return o?p.jsxs(Ql,{className:"tlui-people-menu__item","data-follow":l||a,children:[p.jsxs(Ye,{type:"menu",className:"tlui-people-menu__item__button",onClick:()=>t.zoomToUser(e),onDoubleClick:i,children:[p.jsx(Co,{label:r("people-menu.avatar-color"),icon:"color",color:o.color}),p.jsx("div",{className:"tlui-people-menu__name",children:((c=o.userName)==null?void 0:c.trim())||r("people-menu.anonymous-user")})]}),p.jsx(Ye,{type:"icon",className:"tlui-people-menu__item__follow",title:r(a?"people-menu.leading":l?"people-menu.following":"people-menu.follow"),onClick:i,disabled:a,children:p.jsx(Ae,{icon:a?"leading":l?"following":"follow"})})]}):null});function uce({count:n}){return p.jsx("div",{className:"tlui-people-menu__avatar tlui-people-menu__more",children:Math.abs(n)})}const hce=rn(function(){const e=K(),t=sn(),r=Se(),s=Rt(),o=x.useRef(!1),[i,a]=x.useState(!1),l=x.useCallback(m=>{a(m)},[]),c=e.user.getColor(),u=x.useCallback(m=>{e.user.updateUserPreferences({color:m}),s("set-color",{source:"people-menu"})},[e,s]),{handleButtonClick:d,handleButtonPointerDown:h,handleButtonPointerEnter:f,handleButtonPointerUp:g}=_e.useMemo(()=>{const m=()=>{o.current=!1,window.removeEventListener("pointerup",m)};return{handleButtonClick:v=>{const{id:P}=v.currentTarget.dataset;P&&c!==P&&u(P)},handleButtonPointerDown:v=>{const{id:P}=v.currentTarget.dataset;P&&(u(P),o.current=!0,window.addEventListener("pointerup",m))},handleButtonPointerEnter:v=>{if(!o.current)return;const{id:P}=v.currentTarget.dataset;P&&u(P)},handleButtonPointerUp:v=>{const{id:P}=v.currentTarget.dataset;P&&u(P)}}},[c,u]);return p.jsxs(bC,{onOpenChange:l,open:i,children:[p.jsx(wC,{dir:"ltr",asChild:!0,children:p.jsx(Ye,{type:"icon",className:"tlui-people-menu__user__color",style:{color:e.user.getColor()},title:r("people-menu.change-color"),children:p.jsx(Ae,{icon:"color"})})}),p.jsx(vC,{container:t,children:p.jsx(CC,{dir:"ltr",className:"tlui-menu tlui-people-menu__user__color-picker",align:"start",side:"left",sideOffset:8,children:p.jsx(MS,{children:Mw.map(m=>p.jsx(Ye,{type:"icon","data-id":m,"data-testid":m,"aria-label":m,isActive:c===m,title:m,style:{color:m},onPointerEnter:f,onPointerDown:h,onPointerUp:g,onClick:d,children:p.jsx(Ae,{icon:"color"})},m))})})})]})});function pce(){const n=K(),e=Rt(),t=W("userName",()=>n.user.getName(),[]),r=Se(),s=x.useRef(t),o=x.useRef(t),[i,a]=x.useState(!1),l=x.useCallback(()=>{a(h=>!h)},[]),c=x.useCallback(h=>{o.current=h,n.user.updateUserPreferences({name:h})},[n]),u=x.useCallback(()=>{s.current!==o.current&&(e("change-user-name",{source:"people-menu"}),s.current=o.current)},[e]),d=x.useCallback(()=>{a(!1),n.user.updateUserPreferences({name:s.current}),n.menus.clearOpenMenus()},[n]);return p.jsxs("div",{className:"tlui-people-menu__user",children:[p.jsx(hce,{}),i?p.jsx(Id,{className:"tlui-people-menu__user__input",defaultValue:t,onValueChange:c,onComplete:l,onCancel:d,onBlur:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:!0,autoSelect:!0}):p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"tlui-people-menu__user__name",onDoubleClick:()=>{i||a(!0)},children:t||r("people-menu.anonymous-user")}),t?null:p.jsx("div",{className:"tlui-people-menu__user__label",children:r("people-menu.user")})]}),p.jsx(Ye,{type:"icon",className:"tlui-people-menu__user__edit","data-testid":"people-menu.change-name",title:r("people-menu.change-name"),onClick:l,children:p.jsx(Ae,{icon:i?"check":"edit"})})]})}function fce({children:n}){const e=Se(),t=sn(),r=K(),s=OR(),o=W("user",()=>r.user.getColor(),[r]),i=W("user",()=>r.user.getName(),[r]),[a,l]=Yi("people menu"),u=Gn()<=Ot.MOBILE_XS?1:5;return wie()==="offline"?p.jsx(lce,{}):s.length?p.jsxs(bC,{onOpenChange:l,open:a,children:[p.jsx(wC,{dir:"ltr",asChild:!0,children:p.jsx("button",{className:"tlui-people-menu__avatars-button",title:e("people-menu.title"),children:p.jsxs("div",{className:"tlui-people-menu__avatars",children:[s.slice(-u).map(h=>p.jsx(cce,{userId:h},h)),s.length>0&&p.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:o},children:(i==null?void 0:i[0])??""}),s.length>u&&p.jsx(uce,{count:s.length-u})]})})}),p.jsx(vC,{container:t,children:p.jsx(CC,{dir:"ltr",className:"tlui-menu",side:"bottom",sideOffset:2,collisionPadding:4,children:p.jsxs("div",{className:"tlui-people-menu__wrapper",children:[p.jsx("div",{className:"tlui-people-menu__section",children:p.jsx(pce,{})}),s.length>0&&p.jsx("div",{className:"tlui-people-menu__section",children:s.map(h=>p.jsx(dce,{userId:h},h+"_presence"))}),n]})})})]}):null}function gce(){return p.jsx("div",{className:"tlui-share-zone",draggable:!1,children:p.jsx(fce,{})})}const mce=Object.freeze([Rr,Ml,Li,Vo]);function D5(n=mce){const e=K();return W("getRelevantStyles",()=>{var o;const t=new Lw(e.getSharedStyles()),r=!!((o=e.root.getCurrent())!=null&&o.shapeType),s=e.isIn("select")&&e.getSelectedShapeIds().length>0;if(t.size===0&&e.isIn("select")&&e.getSelectedShapeIds().length===0)for(const i of n)t.applyValue(i,e.getStyleForNextShape(i));return r||s||t.size>0?t:null},[e])}const ts={color:[{value:"black",icon:"color"},{value:"grey",icon:"color"},{value:"light-violet",icon:"color"},{value:"violet",icon:"color"},{value:"blue",icon:"color"},{value:"light-blue",icon:"color"},{value:"yellow",icon:"color"},{value:"orange",icon:"color"},{value:"green",icon:"color"},{value:"light-green",icon:"color"},{value:"light-red",icon:"color"},{value:"red",icon:"color"}],fill:[{value:"none",icon:"fill-none"},{value:"semi",icon:"fill-semi"},{value:"solid",icon:"fill-solid"}],fillExtra:[{value:"pattern",icon:"fill-pattern"},{value:"lined-fill",icon:"fill-lined-fill"},{value:"fill",icon:"fill-fill"}],dash:[{value:"draw",icon:"dash-draw"},{value:"dashed",icon:"dash-dashed"},{value:"dotted",icon:"dash-dotted"},{value:"solid",icon:"dash-solid"}],size:[{value:"s",icon:"size-small"},{value:"m",icon:"size-medium"},{value:"l",icon:"size-large"},{value:"xl",icon:"size-extra-large"}],font:[{value:"draw",icon:"font-draw"},{value:"sans",icon:"font-sans"},{value:"serif",icon:"font-serif"},{value:"mono",icon:"font-mono"}],textAlign:[{value:"start",icon:"text-align-left"},{value:"middle",icon:"text-align-center"},{value:"end",icon:"text-align-right"}],horizontalAlign:[{value:"start",icon:"horizontal-align-start"},{value:"middle",icon:"horizontal-align-middle"},{value:"end",icon:"horizontal-align-end"}],verticalAlign:[{value:"start",icon:"vertical-align-start"},{value:"middle",icon:"vertical-align-middle"},{value:"end",icon:"vertical-align-end"}],geo:[{value:"rectangle",icon:"geo-rectangle"},{value:"ellipse",icon:"geo-ellipse"},{value:"triangle",icon:"geo-triangle"},{value:"diamond",icon:"geo-diamond"},{value:"star",icon:"geo-star"},{value:"pentagon",icon:"geo-pentagon"},{value:"hexagon",icon:"geo-hexagon"},{value:"octagon",icon:"geo-octagon"},{value:"rhombus",icon:"geo-rhombus"},{value:"rhombus-2",icon:"geo-rhombus-2"},{value:"oval",icon:"geo-oval"},{value:"trapezoid",icon:"geo-trapezoid"},{value:"arrow-left",icon:"geo-arrow-left"},{value:"arrow-up",icon:"geo-arrow-up"},{value:"arrow-down",icon:"geo-arrow-down"},{value:"arrow-right",icon:"geo-arrow-right"},{value:"cloud",icon:"geo-cloud"},{value:"x-box",icon:"geo-x-box"},{value:"check-box",icon:"geo-check-box"},{value:"heart",icon:"geo-heart"}],arrowKind:[{value:"arc",icon:"arrow-arc"},{value:"elbow",icon:"arrow-elbow"}],arrowheadStart:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],arrowheadEnd:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],spline:[{value:"line",icon:"spline-line"},{value:"cubic",icon:"spline-cubic"}]},O5=_e.forwardRef(function({onHistoryMark:e,title:t,min:r,steps:s,value:o,label:i,onValueChange:a,["data-testid"]:l,ariaValueModifier:c=1},u){const d=Se(),[h,f]=x.useState(""),[g,m]=x.useState(-1);x.useEffect(()=>{m(0)},[]);const y=x.useCallback(w=>{a(w[0])},[a]),S=x.useCallback(()=>{zC(),e==null||e("click slider")},[e]);x.useEffect(()=>{const w=Ug.setTimeout("set title and label",()=>{f(t+" — "+d(i))},0);return()=>clearTimeout(w)},[i,d,t]);const b=x.useCallback(w=>{w.key==="Tab"&&w.stopPropagation()},[]);return p.jsx("div",{className:"tlui-slider__container",children:p.jsx(fp,{content:h,children:p.jsxs(ioe,{"data-testid":l,className:"tlui-slider",dir:"ltr",min:r??0,max:s,step:1,value:o!==null?[o]:void 0,onPointerDown:S,onValueChange:y,onKeyDownCapture:b,onKeyUpCapture:b,children:[p.jsx(aoe,{className:"tlui-slider__track",dir:"ltr",children:o!==null&&p.jsx(loe,{className:"tlui-slider__range",dir:"ltr"})}),o!==null&&p.jsx(coe,{"aria-valuemin":(r??0)*c,"aria-valuenow":o*c,"aria-valuemax":s*c,"aria-label":h,className:"tlui-slider__thumb",dir:"ltr",ref:u,tabIndex:g})]})})})});function Zs(){return Ga({isDarkMode:Vh()})}const R5=x.createContext(null);function yce({children:n,styles:e}){const t=K(),r=Rt(),s=x.useCallback(a=>t.markHistoryStoppingPoint(a),[t]),o=W("enhancedA11yMode",()=>t.user.getEnhancedA11yMode(),[t]),i=x.useCallback(function(a,l){t.run(()=>{t.isIn("select")&&t.setStyleForSelectedShapes(a,l),t.setStyleForNextShapes(a,l),t.updateInstanceState({isChangingStyle:!0})}),r("set-style",{source:"style-panel",id:a.id,value:l})},[t,r]);return p.jsx(R5.Provider,{value:{styles:e,enhancedA11yMode:o,onHistoryMark:s,onValueChange:i},children:n})}function yr(){const n=x.useContext(R5);if(!n)throw new Error("useStylePanelContext must be used within a StylePanelContextProvider");return n}function yp({children:n}){return p.jsx("h3",{className:"tlui-style-panel__subheading",children:n})}function Sce(n){const{enhancedA11yMode:e}=yr();return p.jsxs(p.Fragment,{children:[e&&p.jsx(yp,{children:n.title}),p.jsx(ur,{label:n.title,children:p.jsx(OS,{...n})})]})}function xce(n){const e=yr(),{uiType:t,items:r,title:s,style:o,value:i,onValueChange:a=e.onValueChange,onHistoryMark:l=e.onHistoryMark}=n,c=Zs(),u=K(),d=Se(),h=Gn(),f=x.useRef(!1),g=x.useRef(null),{handleButtonClick:m,handleButtonPointerDown:y,handleButtonPointerEnter:S,handleButtonPointerUp:b}=x.useMemo(()=>{const v=()=>{f.current=!1,window.removeEventListener("pointerup",v);const A=g.current;A&&(["TEXTAREA","INPUT"].includes(A.nodeName)||A.isContentEditable)?A.focus():h>=Ot.TABLET_SM&&u.getContainer().focus(),g.current=null};return{handleButtonClick:A=>{const{id:R}=A.currentTarget.dataset;i.type==="shared"&&i.value===R||(l==null||l("point picker item"),a(o,R))},handleButtonPointerDown:A=>{const{id:R}=A.currentTarget.dataset;l==null||l("point picker item"),a(o,R),f.current=!0,g.current=document.activeElement,window.addEventListener("pointerup",v)},handleButtonPointerEnter:A=>{if(!f.current)return;const{id:R}=A.currentTarget.dataset;a(o,R)},handleButtonPointerUp:A=>{const{id:R}=A.currentTarget.dataset;i.type==="shared"&&i.value===R||a(o,R)}}},[u,h,i,l,a,o]),w=r.length>4?MS:Ql;return p.jsx(Rie,{"data-testid":`style.${t}`,type:"single",value:i.type==="shared"?i.value:null,asChild:!0,children:p.jsx(w,{children:r.map(v=>{const P=i.type==="shared"&&i.value===v.value,T=s+" — "+d(`${t}-style.${v.value}`);return p.jsx(Lie,{type:"icon","data-id":v.value,"data-testid":`style.${t}.${v.value}`,"aria-label":T+(P?` (${d("style-panel.selected")})`:""),tooltip:p.jsxs(p.Fragment,{children:[p.jsx("div",{children:T}),P?p.jsxs("div",{children:["(",d("style-panel.selected"),")"]}):null]}),value:v.value,"data-state":i.type==="shared"&&i.value===v.value?"on":"off","data-isactive":P,title:T,style:o===Rr?{color:st(c,v.value,"solid")}:void 0,onPointerEnter:S,onPointerDown:y,onPointerUp:b,onClick:m,children:p.jsx(Ae,{icon:v.icon})},v.value)})})})}const DS=x.memo(Sce),OS=x.memo(xce);function bce(n){const e=Se();return p.jsxs("div",{className:"tlui-style-panel__double-select-picker",children:[p.jsx("div",{title:e(n.label),className:"tlui-style-panel__double-select-picker-label",children:e(n.label)}),p.jsx(ur,{orientation:"horizontal",label:e(n.label),children:p.jsx(Cce,{...n})})]})}function wce(n){const e=yr(),{uiTypeA:t,uiTypeB:r,labelA:s,labelB:o,itemsA:i,itemsB:a,styleA:l,styleB:c,valueA:u,valueB:d,onValueChange:h=e.onValueChange}=n,f=K(),g=Se(),[m,y]=x.useState(!1),[S,b]=x.useState(!1),w=x.useMemo(()=>{var I;return((I=i.find(k=>u.type==="shared"&&u.value===k.value))==null?void 0:I.icon)??"mixed"},[i,u]),v=x.useMemo(()=>{var I;return((I=a.find(k=>d.type==="shared"&&d.value===k.value))==null?void 0:I.icon)??"mixed"},[a,d]);if(u===void 0&&d===void 0)return null;const P=`style panel ${t} A`,T=`style panel ${r} B`;return p.jsxs(p.Fragment,{children:[p.jsxs(Bl,{id:P,open:m,onOpenChange:y,children:[p.jsx(zl,{children:p.jsx(bt,{type:"icon","data-testid":`style.${t}`,title:g(s)+" — "+(u===null||u.type==="mixed"?g("style-panel.mixed"):g(`${t}-style.${u.value}`)),children:p.jsx(Ae,{icon:w,small:!0,invertIcon:!0})})}),p.jsx($l,{side:"left",align:"center",sideOffset:80,alignOffset:0,children:p.jsx(ur,{orientation:"grid",label:g(s),children:p.jsx(Fr,{type:"icons",sourceId:"style-panel",children:i.map(I=>p.jsx(bt,{"data-testid":`style.${t}.${I.value}`,type:"icon",onClick:()=>{h(l,I.value),Tr.deleteOpenMenu(P,f.contextId),y(!1)},title:`${g(s)} — ${g(`${t}-style.${I.value}`)}`,children:p.jsx(Ae,{icon:I.icon,invertIcon:!0})},I.value))})})})]}),p.jsxs(Bl,{id:T,open:S,onOpenChange:b,children:[p.jsx(zl,{children:p.jsx(bt,{type:"icon","data-testid":`style.${r}`,title:g(o)+" — "+(d===null||d.type==="mixed"?g("style-panel.mixed"):g(`${r}-style.${d.value}`)),children:p.jsx(Ae,{icon:v,small:!0})})}),p.jsx($l,{side:"left",align:"center",sideOffset:116,alignOffset:0,children:p.jsx(ur,{orientation:"grid",label:g(o),children:p.jsx(Fr,{type:"icons",sourceId:"style-panel",children:a.map(I=>p.jsx(bt,{type:"icon",title:`${g(o)} — ${g(`${r}-style.${I.value}`)}`,"data-testid":`style.${r}.${I.value}`,onClick:()=>{h(c,I.value),Tr.deleteOpenMenu(T,f.contextId),b(!1)},children:p.jsx(Ae,{icon:I.icon})},I.value))})})})]})]})}const vce=x.memo(bce),Cce=x.memo(wce);function Pce(n){const e=Se(),t=n.label?e(n.label):e(`style-panel.${n.stylePanelType}`);return p.jsx(ur,{label:t,children:p.jsx(VC,{...n})})}function Tce(n){const e=yr(),{id:t,label:r,uiType:s,stylePanelType:o,style:i,items:a,type:l,value:c,onValueChange:u=e.onValueChange,testIdType:d=s}=n,h=Se(),f=K(),[g,m]=x.useState(!1),y=x.useMemo(()=>{var T,I;return c.type==="mixed"?"mixed":((T=a.find(k=>k.value===c.value))==null?void 0:T.icon)??((I=a[0])==null?void 0:I.icon)},[a,c]),S=h(`style-panel.${o}`),b=c.type==="mixed"?h("style-panel.mixed"):S+" — "+h(`${s}-style.${c.value}`),w=r?h(r):"",v=`style panel ${t}`;return p.jsxs(Bl,{id:v,open:g,onOpenChange:m,className:"tlui-style-panel__dropdown-picker",children:[p.jsx(zl,{children:p.jsxs(bt,{type:l,"data-testid":`style.${d}`,"data-direction":"left",title:b,children:[w&&p.jsx(Qt,{children:w}),p.jsx(Ae,{icon:y})]})}),p.jsx($l,{side:"left",align:"center",children:p.jsx(ur,{orientation:a.length>4?"grid":"horizontal",label:w,children:p.jsx(Fr,{type:"icons",sourceId:"style-panel",children:a.map(P=>p.jsx(bt,{type:"icon","data-testid":`style.${d}.${P.value}`,title:S+" — "+h(`${s}-style.${P.value}`),isActive:y===P.icon,onClick:()=>{e.onHistoryMark("select style dropdown item"),u(i,P.value),Tr.deleteOpenMenu(v,f.contextId),m(!1)},children:p.jsx(Ae,{icon:P.icon})},P.value))})})})]})}const WC=x.memo(Pce),VC=x.memo(Tce);function Ice(){return p.jsxs(p.Fragment,{children:[p.jsxs(Sf,{children:[p.jsx(Ece,{}),p.jsx(kce,{})]}),p.jsxs(Sf,{children:[p.jsx(_ce,{}),p.jsx(Mce,{}),p.jsx(Ace,{})]}),p.jsxs(Sf,{children:[p.jsx(Dce,{}),p.jsx(Oce,{}),p.jsx(Rce,{})]}),p.jsxs(Sf,{children:[p.jsx(Lce,{}),p.jsx(jce,{}),p.jsx(Nce,{}),p.jsx(Fce,{})]})]})}function Sf({children:n}){return p.jsx("div",{className:"tlui-style-panel__section",children:n})}function Ece(){const{styles:n}=yr(),e=Se(),t=n.get(Rr);return t===void 0?null:p.jsx(DS,{title:e("style-panel.color"),uiType:"color",style:Rr,items:ts.color,value:t})}const Gd=[.1,.25,.5,.75,1];function kce(){const n=K(),{onHistoryMark:e,enhancedA11yMode:t}=yr(),r=W("opacity",()=>n.getSharedOpacity(),[n]),s=Rt(),o=Se(),i=_e.useCallback(l=>{const c=Gd[l];n.run(()=>{n.isIn("select")&&n.setOpacityForSelectedShapes(c),n.setOpacityForNextShapes(c),n.updateInstanceState({isChangingStyle:!0})}),s("set-style",{source:"style-panel",id:"opacity",value:l})},[n,s]);if(r===void 0)return null;const a=r.type==="mixed"?-1:Gd.indexOf(F_(Gd,l=>Math.abs(l-r.value)));return p.jsxs(p.Fragment,{children:[t&&p.jsx(yp,{children:o("style-panel.opacity")}),p.jsx(O5,{"data-testid":"style.opacity",value:a>=0?a:Gd.length-1,label:r.type==="mixed"?"style-panel.mixed":`opacity-style.${r.value}`,onValueChange:i,steps:Gd.length-1,title:o("style-panel.opacity"),onHistoryMark:e,ariaValueModifier:25})]})}function _ce(){const{styles:n,enhancedA11yMode:e}=yr(),t=Se(),r=n.get(Li);if(r===void 0)return null;const s=t("style-panel.fill");return p.jsxs(p.Fragment,{children:[e&&p.jsx(yp,{children:s}),p.jsxs(ur,{orientation:"horizontal",label:s,children:[p.jsx(OS,{title:s,uiType:"fill",style:Li,items:ts.fill,value:r}),p.jsx(VC,{type:"icon",id:"fill-extra",uiType:"fill",testIdType:"fill-extra",stylePanelType:"fill",style:Li,items:ts.fillExtra,value:r})]})]})}function Mce(){const{styles:n}=yr(),e=Se(),t=n.get(Ml);return t===void 0?null:p.jsx(DS,{title:e("style-panel.dash"),uiType:"dash",style:Ml,items:ts.dash,value:t})}function Ace(){const n=K(),{styles:e,onValueChange:t}=yr(),r=Se(),s=e.get(Vo);return s===void 0?null:p.jsx(DS,{title:r("style-panel.size"),uiType:"size",style:Vo,items:ts.size,value:s,onValueChange:(o,i)=>{t(o,i);const a=n.getSelectedShapeIds();a.length>0&&mt(n,a)}})}function Dce(){const{styles:n}=yr(),e=Se(),t=n.get(Oa);return t===void 0?null:p.jsx(DS,{title:e("style-panel.font"),uiType:"font",style:Oa,items:ts.font,value:t})}function Oce(){const{styles:n,enhancedA11yMode:e}=yr(),t=Se(),r=n.get(Ew);if(r===void 0)return null;const s=t("style-panel.align");return p.jsxs(p.Fragment,{children:[e&&p.jsx(yp,{children:s}),p.jsxs(ur,{orientation:"horizontal",label:s,children:[p.jsx(OS,{title:s,uiType:"align",style:Ew,items:ts.textAlign,value:r}),p.jsx(bt,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:p.jsx(Ae,{icon:"vertical-align-middle"})})]})]})}function Rce(){const{styles:n,enhancedA11yMode:e}=yr(),t=Se(),r=n.get(jg),s=n.get(Ng);if(r===void 0)return null;const o=t("style-panel.label-align");return p.jsxs(p.Fragment,{children:[e&&p.jsx(yp,{children:o}),p.jsxs(ur,{orientation:"horizontal",label:o,children:[p.jsx(OS,{title:o,uiType:"align",style:jg,items:ts.horizontalAlign,value:r}),s===void 0?p.jsx(bt,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:p.jsx(Ae,{icon:"vertical-align-middle"})}):p.jsx(VC,{type:"icon",id:"geo-vertical-alignment",uiType:"verticalAlign",stylePanelType:"vertical-align",style:Ng,items:ts.verticalAlign,value:s})]})]})}function Lce(){const{styles:n}=yr(),e=n.get($o);return e===void 0?null:p.jsx(WC,{label:"style-panel.geo",type:"menu",id:"geo",uiType:"geo",stylePanelType:"geo",style:$o,items:ts.geo,value:e})}function jce(){const{styles:n}=yr(),e=n.get(Rg);return e===void 0?null:p.jsx(WC,{id:"arrow-kind",type:"menu",label:"style-panel.arrow-kind",uiType:"arrow-kind",stylePanelType:"arrow-kind",style:Rg,items:ts.arrowKind,value:e})}function Nce(){const{styles:n}=yr(),e=n.get(Pw),t=n.get(Cw);return e===void 0||t===void 0?null:p.jsx(vce,{label:"style-panel.arrowheads",uiTypeA:"arrowheadStart",styleA:Cw,itemsA:ts.arrowheadStart,valueA:t,uiTypeB:"arrowheadEnd",styleB:Pw,itemsB:ts.arrowheadEnd,valueB:e,labelA:"style-panel.arrowhead-start",labelB:"style-panel.arrowhead-end"})}function Fce(){const{styles:n}=yr(),e=n.get(Iw);return e===void 0?null:p.jsx(WC,{type:"menu",id:"spline",uiType:"spline",stylePanelType:"spline",label:"style-panel.spline",style:Iw,items:ts.spline,value:e})}const Bce=x.memo(function({isMobile:e,styles:t,children:r}){const s=K(),o=W("enhancedA11yMode",()=>s.user.getEnhancedA11yMode(),[s]),i=x.useRef(null);Jo(i);const a=x.useCallback(()=>{e||s.updateInstanceState({isChangingStyle:!1})},[s,e]),l=D5();return t===void 0&&(t=l),x.useEffect(()=>{function c(d){var h;d.key==="Escape"&&((h=i.current)!=null&&h.contains(document.activeElement))&&(d.stopPropagation(),s.getContainer().focus())}const u=i.current;return u==null||u.addEventListener("keydown",c,{capture:!0}),()=>{u==null||u.removeEventListener("keydown",c,{capture:!0})}},[s]),t&&p.jsx("div",{ref:i,"data-testid":"style.panel",className:xe("tlui-style-panel",{"tlui-style-panel__wrapper":!e}),"data-ismobile":e,"data-enhanced-a11y-mode":o,onPointerLeave:a,children:p.jsx(yce,{styles:t,children:r??p.jsx(Ice,{})})})}),zce=4e3,$ce={success:"check-circle",warning:"warning-triangle",error:"cross-circle",info:"info-circle"};function Hce({toast:n}){const{removeToast:e}=Xi(),t=Se(),r=a=>{a||e(n.id)},s=n.actions&&n.actions.length>0,o=n.icon||n.severity&&$ce[n.severity],i=n.iconLabel||(n.severity?t(`toast.${n.severity}`):"");return p.jsxs(koe,{onOpenChange:r,className:"tlui-toast__container",duration:n.keepOpen?1/0:zce,"data-severity":n.severity,children:[o&&p.jsx("div",{className:"tlui-toast__icon",children:p.jsx(Co,{label:i,icon:o})}),p.jsxs("div",{className:"tlui-toast__main","data-title":!!n.title,"data-description":!!n.description,"data-actions":!!n.actions,children:[p.jsxs("div",{className:"tlui-toast__content",children:[n.title&&p.jsx(_oe,{className:"tlui-toast__title",children:n.title}),n.description&&p.jsx(Moe,{className:"tlui-toast__description",children:n.description})]}),n.actions&&p.jsxs("div",{className:"tlui-toast__actions",children:[n.actions.map((a,l)=>p.jsx(Aoe,{altText:a.label,asChild:!0,onClick:a.onClick,children:p.jsx(Ye,{type:a.type,children:p.jsx(Qt,{children:a.label})})},l)),p.jsx(ek,{asChild:!0,children:p.jsx(Ye,{type:"normal",className:"tlui-toast__close",style:{marginLeft:"auto"},children:p.jsx(Qt,{children:n.closeLabel??t("toast.close")})})})]})]}),!s&&p.jsx(ek,{asChild:!0,children:p.jsx(Ye,{type:"normal",className:"tlui-toast__close",children:p.jsx(Qt,{children:n.closeLabel??t("toast.close")})})})]})}const Uce=x.memo(function(){const{toasts:e}=Xi(),t=W("toasts",()=>e.get(),[]);return p.jsxs(p.Fragment,{children:[t.map(r=>p.jsx(Hce,{toast:r},r.id)),p.jsx(rB,{className:"tlui-toast__viewport"})]})}),Kce=150,Wce=16,Vce=16,kk=16**2,Gce=8,sa=16,GC=({children:n,className:e,isMousingDown:t,getSelectionBounds:r,changeOnlyWhenYChanges:s=!1,label:o})=>{const i=K(),a=x.useRef(null);Jo(a),LG(a);const{isVisible:l,isInteractive:c,hide:u,show:d,position:h,move:f}=qce(s),g=x.useRef(!1),[m,y]=x.useState(!1),S=md("content size update counter",0);x.useEffect(()=>{be(a.current);const w=new ResizeObserver(()=>{S.update(v=>v+1)});return w.observe(a.current),()=>w.disconnect()},[S]),x.useEffect(()=>{let w=S.get();return Mr("toolbar position",function(){const P=a.current;if(!P)return;const T=S.get();i.getCamera(),S.get();const I=Yce(i,P,r);if(!I)g.current&&(g.current=!1,y(!1));else{if(i.getCameraState()==="moving"){const A=a.current;A&&A.style.setProperty("transform",`translate(${I.x}px, ${I.y}px)`)}else{const A=w!==T;f(I.x,I.y,A)}g.current||(g.current=!0,y(!0))}w=T})},[i,r,S,f]);const b=W("camera state",()=>i.getCameraState(),[i]);return x.useEffect(()=>{if(t||!m){u();return}d()},[m,b,t,d,u]),x.useLayoutEffect(()=>{const w=a.current;w&&(w.dataset.visible=`${l}`)},[l,h]),x.useLayoutEffect(()=>{const w=a.current;w&&w.style.setProperty("transform",`translate(${h.x}px, ${h.y}px)`)},[h]),x.useLayoutEffect(()=>{const w=a.current;w&&(w.dataset.interactive=`${c}`)},[c]),p.jsx("div",{ref:a,"data-interactive":!1,"data-visible":!1,"data-testid":"contextual-toolbar",className:xe("tlui-contextual-toolbar",e),onPointerDown:i.markEventAsHandled,children:p.jsx(ur,{orientation:"horizontal",className:"tlui-menu",label:o,tooltipSide:"top",children:n})})};function L5(n){return new J(n.x,n.y,n.width,n.height)}function Yce(n,e,t){var u;const r=(u=t())==null?void 0:u.clone();if(!r)return;const s=n.getViewportScreenBounds();if(r.x-=s.x,r.y-=s.y,r.midY<sa||r.midY>s.h-sa||r.midX<sa||r.midX>s.w-sa)return;const o=L5(e.getBoundingClientRect());if(!o.width||!o.height)return;const{scrollLeft:i,scrollTop:a}=n.getContainer();let l=r.midX-o.w/2,c=r.y-o.h-Gce;return l=Fe(l,sa,s.w-o.w-sa),c=Fe(c,sa,s.h-o.h-sa),l+=i,c+=a,l=Math.round(l),c=Math.round(c),{x:l,y:c}}function Xce(n,e,t){return t?C.Sub(e,n).y**2>=kk:C.Len2(C.Sub(e,n))>=kk}function qce(n){const e=K(),t=x.useRef({name:"hidden"}),[r,s]=x.useState(!1),[o,i]=x.useState(!1),[a,l]=x.useState({x:-1e3,y:-1e3}),c=x.useRef(new C(-1e3,-1e3)),u=x.useRef(new C(-1e3,-1e3)),d=x.useRef(-1),h=x.useRef(-1),f=x.useCallback((y,S,b=!1)=>{if(u.current.x=y,u.current.y=S,t.current.name==="hidden"||t.current.name==="showing")return;clearTimeout(h.current);const w=()=>{if(t.current.name==="shown"&&Xce(u.current,c.current,n)){const{x:v,y:P}=u.current;c.current=new C(v,P),b?Vi.flushSync(()=>l({x:v,y:P})):l({x:v,y:P})}};b?w():h.current=e.timers.setTimeout(w,Kce)},[e,n]),g=x.useCallback((y=!1)=>{switch(t.current.name){case"showing":{clearTimeout(d.current),t.current={name:"hidden"};break}case"shown":{t.current={name:"hiding"},s(!1),y?(t.current={name:"hidden"},i(!1)):d.current=e.timers.setTimeout(()=>{t.current={name:"hidden"},i(!1)},Wce);break}}},[e]),m=x.useCallback(()=>{switch(t.current.name){case"hidden":{t.current={name:"showing"},d.current=e.timers.setTimeout(()=>{const{x:y,y:S}=u.current;c.current=new C(y,S),l({x:y,y:S}),t.current={name:"shown"},i(!0),s(!0)},Vce);break}case"hiding":{clearTimeout(d.current),t.current={name:"shown"},s(!0),f(u.current.x,u.current.y);break}}},[e,f]);return{isVisible:o,isInteractive:r,show:m,hide:g,move:f,position:a}}function j5({shapeId:n,onClose:e,source:t}){const r=K(),[s,o]=x.useState(()=>{const g=r.getShape(n);if(!g)return"";if(!("altText"in g.props))throw Error("Shape does not have altText property");return g.props.altText||""}),i=Se(),a=x.useRef(null),l=Rt(),c=r.getIsReadonly(),u=g=>o(g),d=()=>{l("set-alt-text",{source:t});const g=r.getShape(n);g&&(r.updateShapes([{id:g.id,type:g.type,props:{altText:s}}]),e())},h=()=>d(),f=x.useCallback(()=>e(),[e]);return x.useEffect(()=>{var m;(m=a.current)==null||m.select();function g(y){y.key==="Escape"&&(y.stopPropagation(),f())}return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0})}},[f]),p.jsxs(p.Fragment,{children:[p.jsx(Id,{ref:a,className:"tlui-media__toolbar-alt-text-input","data-testid":"media-toolbar.alt-text-input",value:s,placeholder:i("tool.media-alt-text-desc"),"aria-label":i("tool.media-alt-text-desc"),onValueChange:u,onComplete:d,onCancel:f,disabled:c}),!c&&p.jsx(Ye,{title:i("tool.media-alt-text-confirm"),"data-testid":"tool.media-alt-text-confirm",type:"icon",onPointerDown:je,onClick:h,children:p.jsx(Ae,{small:!0,icon:"check"})})]})}const _k=8;function po(){return{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}}}const Zce=["original","square","circle","landscape","portrait","wide"],H0={original:0,square:1,circle:1,landscape:4/3,portrait:3/4,wide:16/9};function Po(n,e){if(!e)return{w:n.w,h:n.h};const t=n.w/(e.bottomRight.x-e.topLeft.x),r=n.h/(e.bottomRight.y-e.topLeft.y);return{w:t,h:r}}function RS(n){return{width:n.bottomRight.x-n.topLeft.x,height:n.bottomRight.y-n.topLeft.y}}function YC(n){const{width:e,height:t}=RS(n);return{x:n.topLeft.x+e/2,y:n.topLeft.y+t/2}}function XC(n,e,t,r,s){const o=Math.max(0,Math.min(1-t,n-t/2)),i=Math.max(0,Math.min(1-r,e-r/2));return{topLeft:{x:o,y:i},bottomRight:{x:o+t,y:i+r},isCircle:s}}function Jce(n,e,t={}){const{handle:r,change:s,crop:o,aspectRatioLocked:i}=e,{w:a,h:l}=e.uncroppedSize,{minWidth:c=_k,minHeight:u=_k}=t;if(a<c||l<u||s.x===0&&s.y===0)return;const d=new J(o.topLeft.x*a,o.topLeft.y*l,(o.bottomRight.x-o.topLeft.x)*a,(o.bottomRight.y-o.topLeft.y)*l),h=d.aspectRatio,f=d.clone();if(r==="top_left"||r==="bottom_left"||r==="left")f.x=Fe(f.x+s.x,0,d.maxX-c),f.w=d.maxX-f.x;else if(r==="top_right"||r==="bottom_right"||r==="right"){const y=Fe(f.maxX+s.x,d.x+c,a);f.w=y-f.x}if(r==="top_left"||r==="top_right"||r==="top")f.y=Fe(f.y+s.y,0,d.maxY-u),f.h=d.maxY-f.y;else if(r==="bottom_left"||r==="bottom_right"||r==="bottom"){const y=Fe(f.maxY+s.y,d.y+u,l);f.h=y-f.y}if(i)switch(f.aspectRatio>h?f.h=f.w/h:f.w=f.h*h,r){case"top_left":{f.x=d.maxX-f.w,f.y=d.maxY-f.h,f.x<=0&&(f.x=0,f.w=d.maxX-f.x,f.h=f.w/h,f.y=d.maxY-f.h),f.y<=0&&(f.y=0,f.h=d.maxY-f.y,f.w=f.h*h,f.x=d.maxX-f.w);break}case"top_right":{f.x=d.x,f.y=d.maxY-f.h,f.maxX>=a&&(f.w=a-d.x,f.h=f.w/h,f.y=d.maxY-f.h),f.y<=0&&(f.y=0,f.h=d.maxY-f.y,f.w=f.h*h);break}case"bottom_left":{f.x=d.maxX-f.w,f.y=d.y,f.x<=0&&(f.x=0,f.w=d.maxX-f.x,f.h=f.w/h),f.maxY>=l&&(f.h=l-d.y,f.w=f.h*h,f.x=d.maxX-f.w);break}case"bottom_right":{f.x=d.x,f.y=d.y,f.maxX>=a&&(f.w=a-d.x,f.h=f.w/h),f.maxY>=l&&(f.h=l-d.y,f.w=f.h*h);break}case"top":{if(f.h=d.maxY-f.y,f.w=f.h*h,f.x-=(f.w-d.w)/2,f.x<=0){const S=d.midX;f.w=S*2,f.h=f.w/h,f.x=0}if(f.maxX>=a){const S=a-d.midX;f.w=S*2,f.h=f.w/h,f.x=a-f.w}f.y=d.maxY-f.h;break}case"right":{if(f.w=f.maxX-d.x,f.h=f.w/h,f.y-=(f.h-d.h)/2,f.y<=0){const S=d.midY;f.h=S*2,f.w=f.h*h,f.y=0}if(f.maxY>=l){const S=l-d.midY;f.h=S*2,f.w=f.h*h,f.y=l-f.h}break}case"bottom":{if(f.h=f.maxY-d.y,f.w=f.h*h,f.x-=(f.w-d.w)/2,f.x<=0){const S=d.midX;f.w=S*2,f.h=f.w/h,f.x=0}if(f.maxX>=a){const S=a-d.midX;f.w=S*2,f.h=f.w/h,f.x=a-f.w}break}case"left":{if(f.w=d.maxX-f.x,f.h=f.w/h,f.y-=(f.h-d.h)/2,f.y<=0){const S=d.midY;f.h=S*2,f.w=f.h*h,f.y=0}if(f.maxY>=l){const S=l-d.midY;f.h=S*2,f.w=f.h*h,f.y=l-f.h}f.x=d.maxX-f.w;break}}const g={topLeft:{x:f.x/a,y:f.y/l},bottomRight:{x:f.maxX/a,y:f.maxY/l},isCircle:o.isCircle};if(g.topLeft.x===o.topLeft.x&&g.topLeft.y===o.topLeft.y&&g.bottomRight.x===o.bottomRight.x&&g.bottomRight.y===o.bottomRight.y)return;const m=new C(f.x-o.topLeft.x*a,f.y-o.topLeft.y*l).rot(n.rotation).add(n);return{id:n.id,type:n.type,x:m.x,y:m.y,props:{...n.props,w:f.w,h:f.h,crop:g}}}function Qce(n,e,t,r=!0,s=!1){const{w:o,h:i}=Po(n.props,n.props.crop??po()),a=n.props.crop||po(),l=n.x+n.props.w/2,c=n.y+n.props.h/2;let u,d;if(r){const{x:m,y}=YC(a);u=m,d=y}else u=.5,d=.5;const h=XC(u,d,e,t,s),f=e*o,g=t*i;return{crop:h,w:f,h:g,x:l-f/2,y:c-g/2}}const Kr=3;function ede(n,e,t){const r=e.props.crop||po(),{width:s,height:o}=RS(r),i=s/o,a=t?1/(1-t):Kr,l=1+n*(a-1);let c,u;i>1?(c=Math.min(1,1/l),u=c/i):(u=Math.min(1,1/l),c=u*i);const d=Qce(e,c,u,!0,r.isCircle),h=Math.min(Kr,s/c);d.w*=h,d.h*=h;const f=e.x+e.props.w/2,g=e.y+e.props.h/2;return d.x=f-d.w/2,d.y=g-d.h/2,d}function tde(n,e,t){const r=po(),s=n.props.crop||r,o=n.props.w,i=n.props.h,a=e/t;let l=r,c=o,u=i;if(So(n.props.crop,r))c=o,u=o*t/e;else{const{w:y,h:S}=Po(n.props,n.props.crop||po()),{width:b,height:w}=RS(s),v=b/w,P=y/S;let T,I;const k=YC(s);T=b;const A=a/P/v;I=T*A;const R=Kr/(Kr-1);if(A>R){const D=1/Kr;if(1/I<1/T){const j=I/D;I=I/j,T=T/j}else{const j=T/D;T=T/j,I=I/j}}T=Math.max(0,Math.min(1,T)),I=Math.max(0,Math.min(1,I)),l=XC(k.x,k.y,T,I,s.isCircle)}const h=n.x+o/2,f=n.y+i/2,g=h-c/2,m=f-u/2;return{crop:l,w:c,h:u,x:g,y:m}}function nde(n,e){if(n==="original"){const{w:D,h:j}=Po(e.props,e.props.crop??po()),_=e.x+e.props.w/2,M=e.y+e.props.h/2;return{crop:po(),w:D,h:j,x:_-D/2,y:M-j/2}}const t=H0[n],r=n==="circle",{w:s,h:o}=Po(e.props,e.props.crop||po()),i=s/o,a=e.props.crop||po(),{width:l,height:c}=RS(a),u=YC(a),d=Math.min(1/l,1/c);let h,f;if(i===0||!Number.isFinite(i)||t===0)h=1,f=1;else{const D=l*s,j=c*o,_=Math.max(D,j),M=D>=j;let O,N;M?(O=_,N=O/t):(N=_,O=N*t),h=O/s,f=N/o,h>1&&(h=1,f=i/t),f>1&&(f=1,h=t/i),h=Math.max(0,Math.min(1,h)),f=Math.max(0,Math.min(1,f))}const g=Math.min(1/h,1/f);h*=g/d,f*=g/d,h=Math.max(0,Math.min(1,h)),f=Math.max(0,Math.min(1,f));const m=XC(u.x,u.y,h,f,r),y=m.bottomRight.x-m.topLeft.x,S=m.bottomRight.y-m.topLeft.y,b=y*s,w=S*o;let v=1;l>0?v=e.props.w/(l*s):c>0&&(v=e.props.h/(c*o));const P=b*v,T=w*v,I=e.x+e.props.w/2,k=e.y+e.props.h/2,A=I-P/2,R=k-T/2;return{crop:m,w:P,h:T,x:A,y:R}}const rde=rn(function({imageShapeId:e,isManipulating:t,onEditAltTextStart:r,onManipulatingStart:s,onManipulatingEnd:o}){const i=K(),a=Rt(),l=Se(),c="image-toolbar",u=x.useRef(null),d=i.getIsReadonly(),h=W("crop",()=>i.getShape(e).props.crop,[i,e]),f=h?Math.min(1-(h.bottomRight.x-h.topLeft.x),1-(h.bottomRight.y-h.topLeft.y)):0,[g,m]=x.useState(h?Math.max(f,1-1/Kr):Kr),y=ni();x.useEffect(()=>{m(h?Math.max(f,1-1/Kr):Kr)},[h,f,g]);const S=x.useCallback(D=>i.markHistoryStoppingPoint(D),[i]),b=x.useCallback((D,j)=>{const _=Kr/(Kr-1);return Math.pow(D/j,_)*j},[]),w=h&&g?xo(b(f,g),[0,g],[0,100],!0):0,v=x.useCallback(D=>{i.setCurrentTool("select.crop.idle");const j=D/100,_=1-1/Kr,M=Math.min(_,g??_),O=Kr/(Kr-1),N=Math.pow(j,1/O)*M,B=N>=1?1:N/(2*(1-N)),H=i.getShape(e);if(!H)return;const z=ede(B,H,g);i.updateShape({id:H.id,type:H.type,x:z.x,y:z.y,props:{w:z.w,h:z.h,crop:z.crop}}),a("set-style",{source:"image-toolbar",id:"zoom",value:D})},[i,a,e,g]),P=x.useCallback(()=>y["image-replace"].onSelect("image-toolbar"),[y]),T=x.useCallback(()=>y["download-original"].onSelect("image-toolbar"),[y]),I=D=>{const j=i.getShape(e);j&&i.run(()=>{i.setCurrentTool("select.crop.idle");const _=nde(D,j);i.markHistoryStoppingPoint("aspect ratio"),i.updateShape({id:e,type:"image",x:_.x,y:_.y,props:{crop:_.crop,w:_.w,h:_.h}}),mt(i,[e])})},k=W("altText",()=>i.getShape(e).props.altText,[i,e]),A=W("shapeAspectRatio",()=>{const D=i.getShape(e);return D.props.w/D.props.h},[i,e]),R=!h||So(h,po());return x.useEffect(()=>{t&&i.timers.setTimeout(()=>{var D;return(D=u.current)==null?void 0:D.focus()},0)},[i,t]),x.useEffect(()=>{function D(_){t&&(_.key==="Escape"?(i.cancel(),o()):_.key==="Enter"&&(i.complete(),o()))}const j=u.current;return j&&j.addEventListener("keydown",D),()=>{j&&j.removeEventListener("keydown",D)}},[i,t,o]),t?p.jsxs(p.Fragment,{children:[p.jsx(O5,{ref:u,value:w,label:"tool.image-zoom",onValueChange:v,onHistoryMark:S,min:0,steps:100,"data-testid":"tool.image-zoom",title:l("tool.image-zoom")}),p.jsxs(IS,{id:"image-toolbar-aspect-ratio",children:[p.jsx(ES,{children:p.jsx(bt,{title:l("tool.aspect-ratio"),type:"icon","data-testid":"tool.image-aspect-ratio",children:p.jsx(Ae,{icon:"corners"})})}),p.jsx(kS,{side:"top",align:"center",children:Zce.map(D=>{let j=!1;return R?D==="original"&&(j=!0):D==="circle"?j=!!h.isCircle:D==="square"?j=!(h!=null&&h.isCircle)&&tn(A,H0[D],.1):D==="original"?j=!1:j=!R&&tn(A,H0[D],.01),p.jsx(_ie,{onSelect:()=>I(D),checked:j,title:l(`tool.aspect-ratio.${D}`),children:p.jsx(Qt,{children:l(`tool.aspect-ratio.${D}`)})},D)})})]}),p.jsx(bt,{type:"icon",onClick:o,"data-testid":"tool.image-crop-confirm",style:{borderLeft:"1px solid var(--tl-color-divider)",marginLeft:"2px"},title:l("tool.image-crop-confirm"),children:p.jsx(Ae,{small:!0,icon:"check"})})]}):p.jsxs(p.Fragment,{children:[!d&&p.jsx(bt,{type:"icon","data-testid":"tool.image-replace",onClick:P,title:l("tool.replace-media"),children:p.jsx(Ae,{small:!0,icon:"tool-media"})}),!d&&p.jsx(bt,{type:"icon",title:l("tool.image-crop"),onClick:s,"data-testid":"tool.image-crop",children:p.jsx(Ae,{small:!0,icon:"crop"})}),p.jsx(bt,{type:"icon",title:l("action.download-original"),onClick:T,"data-testid":"tool.image-download",children:p.jsx(Ae,{small:!0,icon:"download"})}),(k||!d)&&p.jsx(bt,{type:"icon",title:l("tool.media-alt-text"),"data-testid":"tool.image-alt-text",onClick:()=>{a("alt-text-start",{source:c}),r()},children:p.jsx(Ae,{small:!0,icon:"alt"})})]})});function sde({children:n}){const e=K(),t=W("imageShape",()=>{const o=e.getOnlySelectedShape();return!o||o.type!=="image"?null:o.id},[e]),r=W("showToolbar",()=>e.isInAny("select.idle","select.pointing_shape","select.crop"),[e]),s=W("locked",()=>{var o;return t?(o=e.getShape(t))==null?void 0:o.isLocked:!1},[e,t]);return!t||!r||s?null:p.jsx(ode,{imageShapeId:t,children:n},t)}function ode({children:n,imageShapeId:e}){const t=K(),r=Se(),s=W("editor path",()=>t.isInAny("select.crop.cropping","select.crop.pointing_crop_handle","select.crop.translating_crop"),[t]),o=W("camera",()=>t.getCamera(),[t]),i=W("editor path",()=>t.isIn("select.crop."),[t]),a=x.useRef(void 0),l=x.useCallback(()=>{t.setCroppingShape(null),t.setCurrentTool("select.idle")},[t]),[c,u]=x.useState(!1),d=x.useCallback(()=>u(!0),[]),h=x.useCallback(()=>t.setCurrentTool("select.crop.idle"),[t]),f=x.useCallback(()=>u(!1),[]);x.useEffect(()=>{a.current=void 0},[o]);const g=x.useCallback(()=>{if(i&&a.current)return a.current;const m=t.getSelectionScreenBounds();if(!m)return;const y=new J(m.x,m.y,m.width,0);return a.current=y,y},[t,i]);return s?(a.current=void 0,null):p.jsx(GC,{className:"tlui-image__toolbar",getSelectionBounds:g,label:r("tool.image-toolbar-title"),children:n||(c?p.jsx(j5,{shapeId:e,onClose:f,source:"image-toolbar"}):p.jsx(rde,{imageShapeId:e,isManipulating:i,onEditAltTextStart:d,onManipulatingStart:h,onManipulatingEnd:l}))})}function ide({textEditor:n,onEditLinkStart:e}){const t=Rt(),r=Se(),s="rich-text-menu",[o,i]=x.useState(0);return x.useEffect(function(){function c(){i(u=>u+1)}n.on("update",c),n.on("selectionUpdate",c)},[n]),x.useEffect(()=>{function l(c){e&&Jt(c)&&c.shiftKey&&c.key==="k"&&(c.preventDefault(),e())}return document.addEventListener("keydown",l),()=>{document.removeEventListener("keydown",l)}},[e]),x.useMemo(()=>{function l(c,u){n.view&&(t("rich-text",{operation:c,source:s}),n.chain().focus()[u]().run())}return[{name:"bold",onSelect(){l("bold","toggleBold")}},{name:"italic",onSelect(){l("bold","toggleItalic")}},{name:"code",onSelect(){l("bold","toggleCode")}},e?{name:"link",onSelect(){e()}}:void 0,{name:"bulletList",onSelect(){l("bulletList","toggleBulletList")}},{name:"highlight",onSelect(){l("bulletList","toggleHighlight")}}].filter(Boolean)},[n,t,e]).map(({name:l,attrs:c,onSelect:u})=>{const d=n.view?n.isActive(l,c):!1;return p.jsx(bt,{title:r(`tool.rich-text-${l}`),"data-testid":`rich-text.${l}`,type:"icon",isActive:d,onPointerDown:je,onClick:u,role:"option","aria-pressed":d,children:p.jsx(Ae,{small:!0,icon:l})},l)})}function ade({textEditor:n,value:e,onClose:t}){const r=K(),[s,o]=x.useState(e),i=Se(),a=x.useRef(null),l=Rt(),c="rich-text-menu",u=s.startsWith("http")?s:`https://${s}`,d=y=>o(y),h=y=>{l("rich-text",{operation:"link-edit",source:c}),!y.startsWith("http://")&&!y.startsWith("https://")&&(y=`https://${y}`),n.chain().setLink({href:y}).run(),r.getInstanceState().isCoarsePointer?n.commands.blur():n.commands.focus(),t()},f=()=>{l("rich-text",{operation:"link-visit",source:c}),$1(u,"_blank"),t()},g=()=>{l("rich-text",{operation:"link-remove",source:c}),n.chain().unsetLink().focus().run(),t()},m=()=>t();return x.useEffect(()=>{var y;(y=a.current)==null||y.focus()},[s]),x.useEffect(()=>{o(e)},[e]),p.jsxs(p.Fragment,{children:[p.jsx(Id,{ref:a,"data-testid":"rich-text.link-input",className:"tlui-rich-text__toolbar-link-input",value:s,onValueChange:d,onComplete:h,onCancel:m,placeholder:"example.com","aria-label":"example.com"}),p.jsx(Ye,{className:"tlui-rich-text__toolbar-link-visit",title:i("tool.rich-text-link-visit"),type:"icon",onPointerDown:je,onClick:f,disabled:!s,children:p.jsx(Ae,{small:!0,icon:"external-link"})}),p.jsx(Ye,{className:"tlui-rich-text__toolbar-link-remove",title:i("tool.rich-text-link-remove"),"data-testid":"rich-text.link-remove",type:"icon",onPointerDown:je,onClick:g,children:p.jsx(Ae,{small:!0,icon:"trash"})})]})}const lde=rn(function({children:e}){const t=K(),r=W("textEditor",()=>t.getRichTextEditor(),[t]);return t.getInstanceState().isCoarsePointer||!r?null:p.jsx(cde,{textEditor:r,children:e})});function cde({textEditor:n,children:e}){const{isEditingLink:t,onEditLinkStart:r,onEditLinkClose:s}=dde(n),[o,i]=x.useState(null),a=x.useRef(void 0),l=ude(n),c=Se(),u=x.useCallback(()=>{if(t)return a.current;const d=window.getSelection();if(!o||!d||d.rangeCount===0||d.isCollapsed)return;const h=[];for(let g=0;g<d.rangeCount;g++){const m=d.getRangeAt(g);h.push(L5(m.getBoundingClientRect()))}const f=J.Common(h);return a.current=f,f},[o,t]);return x.useEffect(()=>{const d=({editor:h})=>i(h.state.selection);return n.on("selectionUpdate",d),d({editor:n}),()=>{n.off("selectionUpdate",d)}},[n]),p.jsx(GC,{className:"tlui-rich-text__toolbar",getSelectionBounds:u,isMousingDown:l,changeOnlyWhenYChanges:!0,label:c("tool.rich-text-toolbar-title"),children:e||(t?p.jsx(ade,{textEditor:n,value:n.isActive("link")?n.getAttributes("link").href:"",onClose:s}):p.jsx(ide,{textEditor:n,onEditLinkStart:r}))})}function dde(n){const[e,t]=x.useState(!1);x.useEffect(()=>{if(!n){t(!1);return}const i=()=>{const a=n.isActive("link");t(a)};return n.view.dom.addEventListener("click",i),()=>{n.isInitialized&&n.view.dom.removeEventListener("click",i)}},[n,e]),x.useEffect(()=>{if(n&&n.isActive("link"))try{const{from:i,to:a}=By(n.state.doc.resolve(n.state.selection.from),n.schema.marks.link);n.state.selection.empty&&n.commands.setTextSelection({from:i,to:a})}catch{}},[n,e]);const r=x.useCallback(()=>{t(!0)},[]),s=x.useCallback(()=>{t(!1)},[]),o=x.useCallback(()=>{if(t(!1),!n)return;const i=n.state.selection.from;n.commands.setTextSelection({from:i,to:i})},[n]);return{isEditingLink:e,onEditLinkStart:r,onEditLinkClose:o,onEditLinkCancel:s}}function ude(n){const[e,t]=x.useState(!1);return x.useEffect(()=>{if(!n)return;const r=ry(({isPointing:l})=>{t(l)},16),s=()=>r({isPointing:!0}),o=()=>r({isPointing:!1}),i=["touchstart","pointerdown","mousedown"],a=["touchend","pointerup","mouseup"];return i.forEach(l=>{n.view.dom.addEventListener(l,s)}),a.forEach(l=>{document.body.addEventListener(l,o)}),()=>{i.forEach(l=>{n.isInitialized&&n.view.dom.removeEventListener(l,s)}),a.forEach(l=>{document.body.removeEventListener(l,o)})}},[n]),e}function hde(){const n=K(),e=Se(),{orientation:t}=pp(),r=D5(),s=r==null?void 0:r.get(Rr),o=Ga({isDarkMode:n.user.getIsDarkMode()}),i=(s==null?void 0:s.type)==="shared"?st(o,s.value,"solid"):st(o,"black","solid"),a=W("disable style panel",()=>n.isInAny("hand","zoom","eraser","laser"),[n]),l=x.useCallback(u=>{u||n.updateInstanceState({isChangingStyle:!1})},[n]),{StylePanel:c}=ti();return c?p.jsxs(Bl,{id:"mobile style menu",onOpenChange:l,children:[p.jsx(zl,{children:p.jsx(Ye,{type:"tool","data-testid":"mobile-styles.button",style:{color:a?"var(--tl-color-muted-1)":i},title:e("style-panel.title"),disabled:a,children:p.jsx(Ae,{icon:a?"blob":(s==null?void 0:s.type)==="mixed"?"mixed":"blob"})})}),p.jsx($l,{side:t==="horizontal"?"top":"right",align:"end",children:c&&p.jsx(c,{isMobile:!0})})]}):null}function pde(){return p.jsxs(p.Fragment,{children:[p.jsx(gde,{}),p.jsx(mde,{}),p.jsx(yde,{}),p.jsx(Sde,{}),p.jsx(xde,{}),p.jsx(bde,{}),p.jsx(wde,{}),p.jsx(vde,{}),p.jsx(Cde,{}),p.jsx(Pde,{}),p.jsx(Ide,{}),p.jsx(Tde,{}),p.jsx(_de,{}),p.jsx(Dde,{}),p.jsx(Ede,{}),p.jsx(Ade,{}),p.jsx(Mde,{}),p.jsx(kde,{}),p.jsx(Ode,{}),p.jsx(Rde,{}),p.jsx(Lde,{}),p.jsx(jde,{}),p.jsx(Nde,{}),p.jsx(Fde,{}),p.jsx(Bde,{}),p.jsx(zde,{}),p.jsx(Hde,{}),p.jsx($de,{})]})}function fde(n){var r;const e=K(),t=(r=n==null?void 0:n.meta)==null?void 0:r.geo;return W("is tool selected",()=>{if(!n)return!1;const s=e.getCurrentToolId();return s==="geo"?t===e.getSharedStyles().getAsKnownValue($o):s===n.id},[e,n==null?void 0:n.id,t])}function Ct({tool:n}){const e=UC(),t=fde(e[n]);return p.jsx(Ur,{toolId:n,isSelected:t})}function gde(){return p.jsx(Ct,{tool:"select"})}function mde(){return p.jsx(Ct,{tool:"hand"})}function yde(){return p.jsx(Ct,{tool:"draw"})}function Sde(){return p.jsx(Ct,{tool:"eraser"})}function xde(){return p.jsx(Ct,{tool:"arrow"})}function bde(){return p.jsx(Ct,{tool:"text"})}function wde(){return p.jsx(Ct,{tool:"note"})}function vde(){return p.jsx(Ur,{toolId:"asset"})}function Cde(){return p.jsx(Ct,{tool:"rectangle"})}function Pde(){return p.jsx(Ct,{tool:"ellipse"})}function Tde(){return p.jsx(Ct,{tool:"diamond"})}function Ide(){return p.jsx(Ct,{tool:"triangle"})}function Ede(){return p.jsx(Ct,{tool:"rhombus"})}function kde(){return p.jsx(Ct,{tool:"heart"})}function _de(){return p.jsx(Ct,{tool:"hexagon"})}function Mde(){return p.jsx(Ct,{tool:"cloud"})}function Ade(){return p.jsx(Ct,{tool:"star"})}function Dde(){return p.jsx(Ct,{tool:"oval"})}function Ode(){return p.jsx(Ct,{tool:"x-box"})}function Rde(){return p.jsx(Ct,{tool:"check-box"})}function Lde(){return p.jsx(Ct,{tool:"arrow-left"})}function jde(){return p.jsx(Ct,{tool:"arrow-up"})}function Nde(){return p.jsx(Ct,{tool:"arrow-down"})}function Fde(){return p.jsx(Ct,{tool:"arrow-right"})}function Bde(){return p.jsx(Ct,{tool:"line"})}function zde(){return p.jsx(Ct,{tool:"highlight"})}function $de(){return p.jsx(Ct,{tool:"frame"})}function Hde(){return p.jsx(Ct,{tool:"laser"})}const _b=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function Mb(n,e,t,r){n.addEventListener?n.addEventListener(e,t,r):n.attachEvent&&n.attachEvent("on".concat(e),t)}function Yd(n,e,t,r){n.removeEventListener?n.removeEventListener(e,t,r):n.detachEvent&&n.detachEvent("on".concat(e),t)}function N5(n,e){const t=e.slice(0,e.length-1);for(let r=0;r<t.length;r++)t[r]=n[t[r].toLowerCase()];return t}function F5(n){typeof n!="string"&&(n=""),n=n.replace(/\s/g,"");const e=n.split(",");let t=e.lastIndexOf("");for(;t>=0;)e[t-1]+=",",e.splice(t,1),t=e.lastIndexOf("");return e}function Ude(n,e){const t=n.length>=e.length?n:e,r=n.length>=e.length?e:n;let s=!0;for(let o=0;o<t.length;o++)r.indexOf(t[o])===-1&&(s=!1);return s}const Ph={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,arrowup:38,arrowdown:40,arrowleft:37,arrowright:39,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":_b?173:189,"=":_b?61:187,";":_b?59:186,"'":222,"{":219,"}":221,"[":219,"]":221,"\\":220},yo={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,meta:91,command:91},vu={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},Ln={16:!1,18:!1,17:!1,91:!1},$t={};for(let n=1;n<20;n++)Ph["f".concat(n)]=111+n;let At=[],Uu=null,B5="all";const _i=new Map,Ed=n=>Ph[n.toLowerCase()]||yo[n.toLowerCase()]||n.toUpperCase().charCodeAt(0),Kde=n=>Object.keys(Ph).find(e=>Ph[e]===n),Wde=n=>Object.keys(yo).find(e=>yo[e]===n);function z5(n){B5=n||"all"}function Th(){return B5||"all"}function Vde(){return At.slice(0)}function Gde(){return At.map(n=>Kde(n)||Wde(n)||String.fromCharCode(n))}function Yde(){const n=[];return Object.keys($t).forEach(e=>{$t[e].forEach(t=>{let{key:r,scope:s,mods:o,shortcut:i}=t;n.push({scope:s,shortcut:i,mods:o,keys:r.split("+").map(a=>Ed(a))})})}),n}function Xde(n){const e=n.target||n.srcElement,{tagName:t}=e;let r=!0;const s=t==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(s||t==="TEXTAREA"||t==="SELECT")&&!e.readOnly)&&(r=!1),r}function qde(n){return typeof n=="string"&&(n=Ed(n)),At.indexOf(n)!==-1}function Zde(n,e){let t,r;n||(n=Th());for(const s in $t)if(Object.prototype.hasOwnProperty.call($t,s))for(t=$t[s],r=0;r<t.length;)t[r].scope===n?t.splice(r,1).forEach(i=>{let{element:a}=i;return qC(a)}):r++;Th()===n&&z5(e||"all")}function Jde(n){let e=n.keyCode||n.which||n.charCode;n.key&&n.key.toLowerCase()==="capslock"&&(e=Ed(n.key));const t=At.indexOf(e);if(t>=0&&At.splice(t,1),n.key&&n.key.toLowerCase()==="meta"&&At.splice(0,At.length),(e===93||e===224)&&(e=91),e in Ln){Ln[e]=!1;for(const r in yo)yo[r]===e&&(Bs[r]=!1)}}function $5(n){if(typeof n>"u")Object.keys($t).forEach(s=>{Array.isArray($t[s])&&$t[s].forEach(o=>xf(o)),delete $t[s]}),qC(null);else if(Array.isArray(n))n.forEach(s=>{s.key&&xf(s)});else if(typeof n=="object")n.key&&xf(n);else if(typeof n=="string"){for(var e=arguments.length,t=new Array(e>1?e-1:0),r=1;r<e;r++)t[r-1]=arguments[r];let[s,o]=t;typeof s=="function"&&(o=s,s=""),xf({key:n,scope:s,method:o,splitKey:"+"})}}const xf=n=>{let{key:e,scope:t,method:r,splitKey:s="+"}=n;F5(e).forEach(i=>{const a=i.split(s),l=a.length,c=a[l-1],u=c==="*"?"*":Ed(c);if(!$t[u])return;t||(t=Th());const d=l>1?N5(yo,a):[],h=[];$t[u]=$t[u].filter(f=>{const m=(r?f.method===r:!0)&&f.scope===t&&Ude(f.mods,d);return m&&h.push(f.element),!m}),h.forEach(f=>qC(f))})};function Mk(n,e,t,r){if(e.element!==r)return;let s;if(e.scope===t||e.scope==="all"){s=e.mods.length>0;for(const o in Ln)Object.prototype.hasOwnProperty.call(Ln,o)&&(!Ln[o]&&e.mods.indexOf(+o)>-1||Ln[o]&&e.mods.indexOf(+o)===-1)&&(s=!1);(e.mods.length===0&&!Ln[16]&&!Ln[18]&&!Ln[17]&&!Ln[91]||s||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(At),e.method(n,e)===!1&&(n.preventDefault?n.preventDefault():n.returnValue=!1,n.stopPropagation&&n.stopPropagation(),n.cancelBubble&&(n.cancelBubble=!0)))}}function Ak(n,e){const t=$t["*"];let r=n.keyCode||n.which||n.charCode;if(n.key&&n.key.toLowerCase()==="capslock"||!Bs.filter.call(this,n))return;if((r===93||r===224)&&(r=91),At.indexOf(r)===-1&&r!==229&&At.push(r),["metaKey","ctrlKey","altKey","shiftKey"].forEach(a=>{const l=vu[a];n[a]&&At.indexOf(l)===-1?At.push(l):!n[a]&&At.indexOf(l)>-1?At.splice(At.indexOf(l),1):a==="metaKey"&&n[a]&&(At=At.filter(c=>c in vu||c===r))}),r in Ln){Ln[r]=!0;for(const a in yo)if(Object.prototype.hasOwnProperty.call(yo,a)){const l=vu[yo[a]];Bs[a]=n[l]}if(!t)return}for(const a in Ln)Object.prototype.hasOwnProperty.call(Ln,a)&&(Ln[a]=n[vu[a]]);n.getModifierState&&!(n.altKey&&!n.ctrlKey)&&n.getModifierState("AltGraph")&&(At.indexOf(17)===-1&&At.push(17),At.indexOf(18)===-1&&At.push(18),Ln[17]=!0,Ln[18]=!0);const s=Th();if(t)for(let a=0;a<t.length;a++)t[a].scope===s&&(n.type==="keydown"&&t[a].keydown||n.type==="keyup"&&t[a].keyup)&&Mk(n,t[a],s,e);if(!(r in $t))return;const o=$t[r],i=o.length;for(let a=0;a<i;a++)if((n.type==="keydown"&&o[a].keydown||n.type==="keyup"&&o[a].keyup)&&o[a].key){const l=o[a],{splitKey:c}=l,u=l.key.split(c),d=[];for(let h=0;h<u.length;h++)d.push(Ed(u[h]));d.sort().join("")===At.sort().join("")&&Mk(n,l,s,e)}}function Bs(n,e,t){At=[];const r=F5(n);let s=[],o="all",i=document,a=0,l=!1,c=!0,u="+",d=!1,h=!1;for(t===void 0&&typeof e=="function"&&(t=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(o=e.scope),e.element&&(i=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(c=e.keydown),e.capture!==void 0&&(d=e.capture),typeof e.splitKey=="string"&&(u=e.splitKey),e.single===!0&&(h=!0)),typeof e=="string"&&(o=e),h&&$5(n,o);a<r.length;a++)n=r[a].split(u),s=[],n.length>1&&(s=N5(yo,n)),n=n[n.length-1],n=n==="*"?"*":Ed(n),n in $t||($t[n]=[]),$t[n].push({keyup:l,keydown:c,scope:o,mods:s,shortcut:r[a],method:t,key:r[a],splitKey:u,element:i});if(typeof i<"u"&&window){if(!_i.has(i)){const f=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return Ak(m,i)},g=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;Ak(m,i),Jde(m)};_i.set(i,{keydownListener:f,keyupListenr:g,capture:d}),Mb(i,"keydown",f,d),Mb(i,"keyup",g,d)}if(!Uu){const f=()=>{At=[]};Uu={listener:f,capture:d},Mb(window,"focus",f,d)}}}function Qde(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys($t).forEach(t=>{$t[t].filter(s=>s.scope===e&&s.shortcut===n).forEach(s=>{s&&s.method&&s.method()})})}function qC(n){const e=Object.values($t).flat();if(e.findIndex(r=>{let{element:s}=r;return s===n})<0){const{keydownListener:r,keyupListenr:s,capture:o}=_i.get(n)||{};r&&s&&(Yd(n,"keyup",s,o),Yd(n,"keydown",r,o),_i.delete(n))}if((e.length<=0||_i.size<=0)&&(Object.keys(_i).forEach(s=>{const{keydownListener:o,keyupListenr:i,capture:a}=_i.get(s)||{};o&&i&&(Yd(s,"keyup",i,a),Yd(s,"keydown",o,a),_i.delete(s))}),_i.clear(),Object.keys($t).forEach(s=>delete $t[s]),Uu)){const{listener:s,capture:o}=Uu;Yd(window,"focus",s,o),Uu=null}}const Ab={getPressedKeyString:Gde,setScope:z5,getScope:Th,deleteScope:Zde,getPressedKeyCodes:Vde,getAllKeyCodes:Yde,isPressed:qde,filter:Xde,trigger:Qde,unbind:$5,keyMap:Ph,modifier:yo,modifierMap:vu};for(const n in Ab)Object.prototype.hasOwnProperty.call(Ab,n)&&(Bs[n]=Ab[n]);if(typeof window<"u"){const n=window.hotkeys;Bs.noConflict=e=>(e&&window.hotkeys===Bs&&(window.hotkeys=n),Bs),window.hotkeys=Bs}const Dk=["copy","cut","paste","asset"];function eue(){const n=K(),e=Ps(),t=ni(),r=UC(),s=W("is focused",()=>n.getInstanceState().isFocused,[n]);x.useEffect(()=>{if(!s)return;const o=new Array,i=n.getContainer(),a=(c,u)=>{Bs(c,{element:i.ownerDocument.body},u),o.push(()=>{Bs.unbind(c,u)})},l=(c,u)=>{Bs(c,{element:i.ownerDocument.body,keyup:!0,keydown:!1},u),o.push(()=>{Bs.unbind(c,u)})};for(const c of Object.values(t))c.kbd&&(e&&!c.readonlyOk||Dk.includes(c.id)||a(Ok(c.kbd),u=>{Cu(n)&&!c.isRequiredA11yAction||(je(u),c.onSelect("kbd"))}));for(const c of Object.values(r))!c.kbd||!c.readonlyOk&&n.getIsReadonly()||Dk.includes(c.id)||a(Ok(c.kbd),u=>{Cu(n)||(je(u),c.onSelect("kbd"))});return a(",",c=>{if(Cu(n)||n.inputs.keys.has("Comma"))return;je(c),n.focus(),n.inputs.keys.add("Comma");const{x:u,y:d,z:h}=n.inputs.getCurrentPagePoint(),f=n.pageToScreen({x:u,y:d}),g={type:"pointer",name:"pointer_down",point:{x:f.x,y:f.y,z:h},shiftKey:c.shiftKey,altKey:c.altKey,ctrlKey:c.metaKey||c.ctrlKey,metaKey:c.metaKey,accelKey:Jt(c),pointerId:0,button:0,isPen:n.getInstanceState().isPenMode,target:"canvas"};n.dispatch(g)}),l(",",c=>{if(Cu(n)||!n.inputs.keys.has("Comma"))return;n.inputs.keys.delete("Comma");const{x:u,y:d,z:h}=n.inputs.getCurrentScreenPoint(),f={type:"pointer",name:"pointer_up",point:{x:u,y:d,z:h},shiftKey:c.shiftKey,altKey:c.altKey,ctrlKey:c.metaKey||c.ctrlKey,metaKey:c.metaKey,accelKey:Jt(c),pointerId:0,button:0,isPen:n.getInstanceState().isPenMode,target:"canvas"};n.dispatch(f)}),()=>{o.forEach(c=>c())}},[t,r,e,n,s])}function Cu(n){return n.menus.hasAnyOpenMenus()||n.getEditingShapeId()!==null||n.getCrashingError()||!n.user.getAreKeyboardShortcutsEnabled()}function Ok(n){return tue(n).map(e=>{let t="";const r=e.includes("!"),s=e.includes("?"),o=e.includes("$"),i=e.replace(/[!?$]/g,"");return r&&s&&o?t=`cmd+shift+alt+${i},ctrl+shift+alt+${i}`:r&&o?t=`cmd+shift+${i},ctrl+shift+${i}`:s&&o?t=`cmd+alt+${i},ctrl+alt+${i}`:s&&r?t=`shift+alt+${i}`:r?t=`shift+${i}`:s?t=`alt+${i}`:o?t=`cmd+${i},ctrl+${i}`:t=i,t}).join(",")}function tue(n){typeof n!="string"&&(n=""),n=n.replace(/\s/g,"");const e=n.split(",");let t=e.lastIndexOf("");for(;t>=0;)e[t-1]+=",",e.splice(t,1),t=e.lastIndexOf("");return e}const nue=x.createContext(!1),rue={1:0,2:1,3:2,4:3,5:4,6:5,7:6,8:7,9:8,0:9};function sue({children:n,orientation:e,sizingParentClassName:t,minItems:r,minSizePx:s,maxItems:o,maxSizePx:i}){const a=K(),l=Yl(),c=Gn(),u=Se(),d=x.useRef([]),[h,f]=x.useState(!1),g=x.useRef(null),[m,y]=x.useState(null),[S,b]=x.useState(null),[w,v]=x.useState(!1),P=No(()=>{if(!g.current)return;const k=e==="horizontal"?"offsetWidth":"offsetHeight",A=D(g.current.children),R=m?D(m.children):null;function D(G){const ae=[];for(const Ce of G)Ce.classList.contains("tlui-main-toolbar__group")?ae.push({type:"group",items:D(Ce.children),element:Ce}):Ce.hasAttribute("data-radix-popper-content-wrapper")||ae.push({type:"item",element:Ce});return ae}const _=Rk(g.current,t)[k],M=Math.floor(xo(_,[s,i],[r,o],!0));let O=0,N=null,B=!1;const H=[];function z(G,ae){ae&&be(G.length===ae.length);let Ce=!1,fe=!1;for(let oe=0;oe<G.length;oe++){const Te=G[oe],te=ae==null?void 0:ae[oe];if(Te.type==="item"){const re=Te.element.getAttribute("data-value")===S;let ge;S?ge=O<M||re:ge=O<=M;const de=O>=M;Ce||(Ce=ge),fe||(fe=de),bf(Te.element,"data-toolbar-visible",ge?"true":"false"),te&&(be(te.type==="item"),bf(te.element,"data-toolbar-visible",de?"true":"false")),de&&Te.element.getAttribute("aria-pressed")==="true"&&(N=Te.element.getAttribute("data-value")),ge&&Te.element.tagName==="BUTTON"&&H.push(Te.element),!de&&re&&(B=!0),O++}else{let re,ge;te?(be(te.type==="group"),ge=te,re=z(Te.items,ge.items)):re=z(Te.items,null),Ce||(Ce=re.didShowAnyInMain),fe||(fe=re.didShowAnyInOverflow),bf(Te.element,"data-toolbar-visible",re.didShowAnyInMain?"true":"false"),ge&&bf(ge.element,"data-toolbar-visible",re.didShowAnyInOverflow?"true":"false")}}return{didShowAnyInMain:Ce,didShowAnyInOverflow:fe}}const{didShowAnyInOverflow:X}=z(A,R);v(X),N?b(N):B&&b(null),d.current=H});x.useLayoutEffect(()=>{P()}),x.useLayoutEffect(()=>{if(!g.current)return;const k=new MutationObserver(P);k.observe(g.current,{childList:!0,subtree:!0,attributes:!0,characterData:!0});const A=Rk(g.current,t),R=new ResizeObserver(P);return R.observe(A),()=>{k.disconnect(),R.disconnect()}},[P,t]),x.useEffect(()=>{if(!a.options.enableToolbarKeyboardShortcuts)return;function k(A){var D;if(Cu(a)||xA(!0)||A.ctrlKey||A.metaKey||A.altKey||A.shiftKey)return;const R=rue[A.key];typeof R=="number"&&(je(A),(D=d.current[R])==null||D.click())}return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[a]);const T="toolbar overflow",I=e==="horizontal"?Ql:BC;return p.jsx(p.Fragment,{children:p.jsxs(ur,{orientation:e,className:xe("tlui-main-toolbar__tools",{"tlui-main-toolbar__tools__mobile":c<Ot.TABLET_SM}),label:u("tool-panel.title"),children:[p.jsx(I,{id:`${l}_main`,ref:g,children:p.jsx(Fr,{type:"toolbar",sourceId:"toolbar",children:n})}),w&&p.jsx(nue.Provider,{value:!0,children:p.jsxs(Bl,{id:T,open:h,onOpenChange:f,children:[p.jsx(zl,{children:p.jsx(bt,{title:u("tool-panel.more"),type:"tool",className:"tlui-main-toolbar__overflow","data-testid":"tools.more-button",children:p.jsx(Ae,{icon:e==="horizontal"?"chevron-up":"chevron-right"})})}),p.jsx($l,{side:e==="horizontal"?"top":"right",align:e==="horizontal"?"center":"end",children:p.jsx(ur,{orientation:"grid",className:"tlui-main-toolbar__overflow-content",ref:y,"data-testid":"tools.more-content",label:u("tool-panel.more"),id:`${l}_more`,onClick:()=>{Tr.deleteOpenMenu(T,a.contextId),f(!1)},children:p.jsx(Fr,{type:"toolbar-overflow",sourceId:"toolbar",children:n})})})]})})]})})}function Rk(n,e){let t=n;for(;t;){if(t.classList.contains(e))return t;t=t.parentElement}throw new Error("Could not find parent with class name "+e)}function bf(n,e,t){n.getAttribute(e)!==t&&n.setAttribute(e,t)}function oue({activeToolId:n}){const e=K(),t=Gn(),r=Se(),s=ni(),o=W("is tool locked",()=>e.getInstanceState().isToolLocked,[e]),i=W("current tool",()=>e.getCurrentTool(),[e]);if(!n||!i.isLockable)return null;const a=s["toggle-tool-lock"],l=a!=null&&a.kbd?`${r("action.toggle-tool-lock")} ${ym(a.kbd)}`:r("action.toggle-tool-lock");return p.jsx(fp,{content:l,children:p.jsx(Ye,{type:"normal","data-testid":"tool-lock",className:xe("tlui-main-toolbar__lock-button",{"tlui-main-toolbar__lock-button__mobile":t<Ot.TABLET_SM}),onClick:()=>e.updateInstanceState({isToolLocked:!o}),children:p.jsx(Ae,{icon:o?"lock":"unlock",small:!0})})})}const iue=x.memo(function({children:e,orientation:t="horizontal",minItems:r=4,minSizePx:s=310,maxItems:o=8,maxSizePx:i=470}){const a=K(),l=Se(),c=Gn(),u=Ps(),d=W("current tool id",()=>a.getCurrentToolId(),[a]),h=x.useRef(null);Jo(h);const{ActionsMenu:f,QuickActions:g}=ti(),m=a.options.actionShortcutsLocation==="menu"?!1:a.options.actionShortcutsLocation==="toolbar"?!0:c<Ot.TABLET;return p.jsx(_S,{orientation:t,tooltipSide:t==="horizontal"?"top":"right",children:p.jsx("div",{ref:h,className:xe("tlui-main-toolbar",`tlui-main-toolbar--${t}`),children:p.jsxs("div",{className:"tlui-main-toolbar__inner",children:[p.jsxs("div",{className:"tlui-main-toolbar__left",children:[!u&&p.jsxs("div",{className:"tlui-main-toolbar__extras",children:[m&&p.jsxs(ur,{orientation:t,className:"tlui-main-toolbar__extras__controls",label:l("actions-menu.title"),children:[g&&p.jsx(g,{}),f&&p.jsx(f,{})]}),p.jsx(oue,{activeToolId:d})]}),p.jsx(sue,{orientation:t,sizingParentClassName:"tlui-main-toolbar",minItems:r,maxItems:o,minSizePx:s,maxSizePx:i,children:e??p.jsx(pde,{})})]}),c<Ot.TABLET_SM&&!u&&p.jsx("div",{className:"tlui-main-toolbar__tools tlui-main-toolbar__mobile-style-panel",children:p.jsx(hde,{})})]})})})}),aue=rn(function({videoShapeId:e,onEditAltTextStart:t}){const r=K(),s=Rt(),o=Se(),i="video-toolbar",a=r.getIsReadonly(),l=ni(),c=x.useCallback(()=>l["video-replace"].onSelect("video-toolbar"),[l]),u=x.useCallback(()=>l["download-original"].onSelect("video-toolbar"),[l]),d=W("altText",()=>r.getShape(e).props.altText,[r,e]);return p.jsxs(p.Fragment,{children:[!a&&p.jsx(Ye,{type:"icon",title:o("tool.replace-media"),onClick:c,"data-testid":"tool.video-replace",children:p.jsx(Ae,{small:!0,icon:"tool-media"})}),p.jsx(Ye,{type:"icon",title:o("action.download-original"),onClick:u,"data-testid":"tool.video-download",children:p.jsx(Ae,{small:!0,icon:"download"})}),(d||!a)&&p.jsx(bt,{type:"icon",isActive:!!d,title:o("tool.media-alt-text"),"data-testid":"tool.video-alt-text",onClick:()=>{s("alt-text-start",{source:i}),t()},children:p.jsx(Ae,{small:!0,icon:"alt"})})]})}),lue=rn(function({children:e}){const t=K(),r=W("videoShape",()=>{const i=t.getOnlySelectedShape();return!i||i.type!=="video"?null:i.id},[t]),s=t.isInAny("select.idle","select.pointing_shape"),o=W("locked",()=>{var i;return r?(i=t.getShape(r))==null?void 0:i.isLocked:!1},[t,r]);return!r||!s||o?null:p.jsx(cue,{videoShapeId:r,children:e},r)});function cue({children:n,videoShapeId:e}){const t=K(),r=Se(),[s,o]=x.useState(!1),i=x.useCallback(()=>o(!0),[]),a=x.useCallback(()=>o(!1),[]),l=x.useCallback(()=>{const c=t.getSelectionScreenBounds();if(c)return new J(c.x,c.y,c.width,0)},[t]);return p.jsx(GC,{className:"tlui-video__toolbar",getSelectionBounds:l,label:r("tool.video-toolbar-title"),children:n||(s?p.jsx(j5,{shapeId:e,onClose:a,source:"video-toolbar"}):p.jsx(aue,{videoShapeId:e,onEditAltTextStart:i}))})}function due(){return p.jsxs(p.Fragment,{children:[p.jsx(Z,{actionId:"zoom-in",noClose:!0}),p.jsx(Z,{actionId:"zoom-out",noClose:!0}),p.jsx(JC,{}),p.jsx(Q5,{}),p.jsx(ez,{})]})}const uue=x.memo(function({children:e}){const t=sn(),[r,s]=Yi("zoom menu"),o=e??p.jsx(due,{});return p.jsxs(mC,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[p.jsx(hue,{}),p.jsx(hS,{container:t,children:p.jsx(SC,{className:"tlui-menu",side:"top",align:"start",alignOffset:0,sideOffset:8,collisionPadding:4,children:p.jsx(Fr,{type:"menu",sourceId:"zoom-menu",children:o})})})]})}),hue=()=>{const n=K(),e=Gn(),t=W("zoom",()=>n.getZoomLevel(),[n]),r=Se(),s=x.useCallback(()=>{n.resetZoom(n.getViewportScreenCenter(),{animation:{duration:n.options.animationMediumMs}})},[n]),o=`${Math.floor(t*100)}%`;return p.jsx(bt,{asChild:!0,type:"icon","aria-label":`${r("navigation-zone.zoom")} — ${o}`,title:`${r("navigation-zone.zoom")} — ${o}`,"data-testid":"minimap.zoom-menu-button",className:"tlui-zoom-menu__button",onDoubleClick:s,children:p.jsx(yC,{dir:"ltr",children:e<Ot.MOBILE?null:p.jsx("span",{style:{flexGrow:0,textAlign:"center"},children:o})})})},H5=x.createContext(null);function pue({overrides:n={},children:e}){const t=yd(n),r=TS();return p.jsx(H5.Provider,{value:x.useMemo(()=>({ContextMenu:rle,ActionsMenu:tle,HelpMenu:null,ZoomMenu:uue,MainMenu:Ule,Minimap:Qle,StylePanel:Bce,PageMenu:rce,NavigationPanel:tce,Toolbar:iue,RichTextToolbar:lde,ImageToolbar:sde,VideoToolbar:lue,KeyboardShortcutsDialog:s5,QuickActions:ace,HelperButtons:kle,DebugPanel:mle,DebugMenu:gle,MenuPanel:wle,SharePanel:r?gce:null,CursorChatBubble:r?ile:null,TopPanel:null,Dialogs:Cle,Toasts:Uce,A11y:lQ,FollowingIndicator:xle,...t}),[t,r]),children:e})}function ti(){const n=x.useContext(H5);if(!n)throw new Error("useTldrawUiComponents must be used within a TldrawUiComponentsProvider");return n}const U5=x.createContext(null);function K5(n,e){return(e.isShapeOfType(n,"image")||e.isShapeOfType(n,"video"))&&!!n.props.assetId}function fue(n){return Object.fromEntries(n.map(e=>[e.id,e]))}function wf(n,e){if(n.getSelectedShapes().length===0)return n.getDocumentSettings().name||e}function gue({overrides:n,children:e}){const t=Xt(),r=TS(),s=HC(),o=ti(),i=Rt(),a=Yy(),l=Se(),c=s.msg("document.default-name"),u=x.useMemo(()=>{const d=t;if(!d)return{};function h(){return d.isIn("select")||(d.complete(),d.setCurrentTool("select")),!1}function f(){return d.isIn("select")&&d.getSelectedShapeIds().length>0}function g(S){if(!f()||h())return;d.markHistoryStoppingPoint("resize shapes");const b=d.getSelectedShapeIds();b.length!==0&&d.run(()=>{b.map(v=>d.getShape(v)).filter(Boolean).forEach(v=>{var P;d.resizeShape(v.id,new C(S,S),{scaleOrigin:(P=d.getSelectionPageBounds())==null?void 0:P.center})})})}const m=[{id:"edit-link",label:"action.edit-link",icon:"link",onSelect(S){f()&&(h()||(i("edit-link",{source:S}),d.markHistoryStoppingPoint("edit-link"),s.addDialog({component:hie})))}},{id:"insert-embed",label:"action.insert-embed",kbd:"cmd+i,ctrl+i",onSelect(S){i("insert-embed",{source:S}),s.addDialog({component:UB})}},{id:"open-kbd-shortcuts",label:"action.open-kbd-shortcuts",kbd:"cmd+alt+/,ctrl+alt+/",onSelect(S){i("open-kbd-shortcuts",{source:S}),s.addDialog({component:o.KeyboardShortcutsDialog??s5})}},{id:"insert-media",label:"action.insert-media",kbd:"cmd+u,ctrl+u",onSelect(S){i("insert-media",{source:S}),s.insertMedia()}},{id:"undo",label:"action.undo",icon:"undo",kbd:"cmd+z,ctrl+z",onSelect(S){i("undo",{source:S}),d.undo()}},{id:"redo",label:"action.redo",icon:"redo",kbd:"cmd+shift+z,ctrl+shift+z",onSelect(S){i("redo",{source:S}),d.redo()}},{id:"export-as-svg",label:{default:"action.export-as-svg",menu:"action.export-as-svg.short","context-menu":"action.export-as-svg.short"},readonlyOk:!0,onSelect(S){let b=d.getSelectedShapeIds();b.length===0&&(b=Array.from(d.getCurrentPageShapeIds().values())),b.length!==0&&(i("export-as",{format:"svg",source:S}),s.exportAs(b,{format:"svg",name:wf(d,c)}))}},{id:"export-as-png",label:{default:"action.export-as-png",menu:"action.export-as-png.short","context-menu":"action.export-as-png.short"},readonlyOk:!0,onSelect(S){let b=d.getSelectedShapeIds();b.length===0&&(b=Array.from(d.getCurrentPageShapeIds().values())),b.length!==0&&(i("export-as",{format:"png",source:S}),s.exportAs(b,{format:"png",name:wf(d,c)}))}},{id:"export-all-as-svg",label:{default:"action.export-all-as-svg",menu:"action.export-all-as-svg.short","context-menu":"action.export-all-as-svg.short"},readonlyOk:!0,onSelect(S){let b=d.getSelectedShapeIds();b.length===0&&(b=Array.from(d.getCurrentPageShapeIds().values())),b.length!==0&&(i("export-all-as",{format:"svg",source:S}),s.exportAs(Array.from(d.getCurrentPageShapeIds()),{format:"svg",name:wf(d,c)}))}},{id:"export-all-as-png",label:{default:"action.export-all-as-png",menu:"action.export-all-as-png.short","context-menu":"action.export-all-as-png.short"},readonlyOk:!0,onSelect(S){const b=Array.from(d.getCurrentPageShapeIds().values());b.length!==0&&(i("export-all-as",{format:"png",source:S}),s.exportAs(b,{format:"png",name:wf(d,c)}))}},{id:"copy-as-svg",label:{default:"action.copy-as-svg",menu:"action.copy-as-svg.short","context-menu":"action.copy-as-svg.short"},kbd:"cmd+shift+c,ctrl+shift+c",readonlyOk:!0,onSelect(S){let b=d.getSelectedShapeIds();b.length===0&&(b=Array.from(d.getCurrentPageShapeIds().values())),b.length!==0&&(i("copy-as",{format:"svg",source:S}),s.copyAs(b,"svg"))}},{id:"copy-as-png",label:{default:"action.copy-as-png",menu:"action.copy-as-png.short","context-menu":"action.copy-as-png.short"},readonlyOk:!0,onSelect(S){let b=d.getSelectedShapeIds();b.length===0&&(b=Array.from(d.getCurrentPageShapeIds().values())),b.length!==0&&(i("copy-as",{format:"png",source:S}),s.copyAs(b,"png"))}},{id:"toggle-auto-size",label:"action.toggle-auto-size",onSelect(S){f()&&(h()||(i("toggle-auto-size",{source:S}),d.markHistoryStoppingPoint("toggling auto size"),d.run(()=>{const b=d.getSelectedShapes().filter(w=>d.isShapeOfType(w,"text")&&w.props.autoSize===!1);d.updateShapes(b.map(w=>({id:w.id,type:w.type,props:{...w.props,w:8,autoSize:!0}}))),mt(d,b.map(w=>w.id))})))}},{id:"open-embed-link",label:"action.open-embed-link",readonlyOk:!0,onSelect(S){i("open-embed-link",{source:S});const b=d.getSelectedShapeIds(),w="No embed shapes selected";if(b.length!==1){console.error(w);return}const v=d.getShape(b[0]);if(!v||!d.isShapeOfType(v,"embed")){console.error(w);return}$1(v.props.url,"_blank")}},{id:"select-zoom-tool",label:"action.select-zoom-tool",readonlyOk:!0,kbd:"z, !z",onSelect(S){var w;if(d.inputs.getAccelKey())return;const b=d.getPath();b.endsWith(".idle")&&((w=d.root.getCurrent())==null?void 0:w.id)!=="zoom"&&(i("zoom-tool",{source:S}),d.setCurrentTool("zoom",{onInteractionEnd:b,maskAs:"zoom"}))}},{id:"convert-to-bookmark",label:"action.convert-to-bookmark",async onSelect(S){var P;if(!f()||h())return;i("convert-to-bookmark",{source:S});const b=d.getSelectedShapes(),w=d.markHistoryStoppingPoint("convert shapes to bookmark"),v=[];for(const T of b){if(!T||!d.isShapeOfType(T,"embed")||!T.props.url)continue;const I=(P=d.getShapePageBounds(T))==null?void 0:P.center;I&&(d.deleteShapes([T.id]),v.push(Jj(d,{url:T.props.url,center:I}).then(k=>{if(!k.ok)throw new Error(k.error);return k})))}await Promise.all(v).catch(T=>{d.bailToMark(w),console.error(T)})}},{id:"convert-to-embed",label:"action.convert-to-embed",onSelect(S){f()&&(h()||(i("convert-to-embed",{source:S}),d.run(()=>{const b=d.getSelectedShapeIds(),w=Le(b.map(T=>d.getShape(T))),v=[],P=[];for(const T of w){if(!d.isShapeOfType(T,"bookmark"))continue;const{url:I}=T.props,k=s.getEmbedDefinition(I);if(!k||!k.definition)continue;const{width:A,height:R}=k.definition,D=new C(T.x,T.y);D.rot(-T.rotation),D.add(new C(T.props.w/2-A/2,T.props.h/2-R/2)),D.rot(T.rotation);const j={id:St(),type:"embed",x:D.x,y:D.y,rotation:T.rotation,props:{url:I,w:A,h:R}};v.push(j),P.push(T.id)}d.markHistoryStoppingPoint("convert shapes to embed"),d.deleteShapes(P),d.createShapes(v)})))}},{id:"duplicate",kbd:"cmd+d,ctrl+d",label:"action.duplicate",icon:"duplicate",onSelect(S){if(!f()||h())return;i("duplicate-shapes",{source:S});const b=d.getInstanceState();let w,v;if(b.duplicateProps)w=b.duplicateProps.shapeIds,v=b.duplicateProps.offset;else{w=d.getSelectedShapeIds();const P=J.Common(Le(w.map(T=>d.getShapePageBounds(T))));v=d.getCameraOptions().isLocked?{x:d.options.adjacentShapeMargin,y:d.options.adjacentShapeMargin}:{x:P.width+d.options.adjacentShapeMargin,y:0}}d.markHistoryStoppingPoint("duplicate shapes"),d.duplicateShapes(w,v),b.duplicateProps&&d.updateInstanceState({duplicateProps:{...b.duplicateProps,shapeIds:d.getSelectedShapeIds()}})}},{id:"ungroup",label:"action.ungroup",kbd:"cmd+shift+g,ctrl+shift+g",icon:"ungroup",onSelect(S){f()&&(h()||(i("ungroup-shapes",{source:S}),d.markHistoryStoppingPoint("ungroup"),d.ungroupShapes(d.getSelectedShapeIds())))}},{id:"group",label:"action.group",kbd:"cmd+g,ctrl+g",icon:"group",onSelect(S){if(!f()||h())return;i("group-shapes",{source:S});const b=d.getOnlySelectedShape();b&&d.isShapeOfType(b,"group")?(d.markHistoryStoppingPoint("ungroup"),d.ungroupShapes(d.getSelectedShapeIds())):(d.markHistoryStoppingPoint("group"),d.groupShapes(d.getSelectedShapeIds()))}},{id:"remove-frame",label:"action.remove-frame",kbd:"cmd+shift+f,ctrl+shift+f",onSelect(S){if(!f())return;i("remove-frame",{source:S});const b=d.getSelectedShapes();b.length>0&&b.every(w=>d.isShapeOfType(w,"frame"))&&(d.markHistoryStoppingPoint("remove-frame"),gQ(d,b.map(w=>w.id)))}},{id:"fit-frame-to-content",label:"action.fit-frame-to-content",onSelect(S){if(!f())return;i("fit-frame-to-content",{source:S});const b=d.getOnlySelectedShape();b&&d.isShapeOfType(b,"frame")&&(d.markHistoryStoppingPoint("fit-frame-to-content"),eN(d,b.id))}},{id:"align-left",label:"action.align-left",kbd:"alt+A",icon:"align-left",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"left",source:S}),d.markHistoryStoppingPoint("align left"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"left"),mt(d,b)})))}},{id:"align-center-horizontal",label:{default:"action.align-center-horizontal","context-menu":"action.align-center-horizontal.short"},kbd:"alt+H",icon:"align-center-horizontal",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"center-horizontal",source:S}),d.markHistoryStoppingPoint("align center horizontal"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"center-horizontal"),mt(d,b)})))}},{id:"align-right",label:"action.align-right",kbd:"alt+D",icon:"align-right",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"right",source:S}),d.markHistoryStoppingPoint("align right"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"right"),mt(d,b)})))}},{id:"align-center-vertical",label:{default:"action.align-center-vertical","context-menu":"action.align-center-vertical.short"},kbd:"alt+V",icon:"align-center-vertical",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"center-vertical",source:S}),d.markHistoryStoppingPoint("align center vertical"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"center-vertical"),mt(d,b)})))}},{id:"align-top",label:"action.align-top",icon:"align-top",kbd:"alt+W",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"top",source:S}),d.markHistoryStoppingPoint("align top"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"top"),mt(d,b)})))}},{id:"align-bottom",label:"action.align-bottom",icon:"align-bottom",kbd:"alt+S",onSelect(S){f()&&(h()||(i("align-shapes",{operation:"bottom",source:S}),d.markHistoryStoppingPoint("align bottom"),d.run(()=>{const b=d.getSelectedShapeIds();d.alignShapes(b,"bottom"),mt(d,b)})))}},{id:"distribute-horizontal",label:{default:"action.distribute-horizontal","context-menu":"action.distribute-horizontal.short"},icon:"distribute-horizontal",kbd:"alt+shift+h",onSelect(S){f()&&(h()||(i("distribute-shapes",{operation:"horizontal",source:S}),d.markHistoryStoppingPoint("distribute horizontal"),d.run(()=>{const b=d.getSelectedShapeIds();d.distributeShapes(b,"horizontal"),mt(d,b)})))}},{id:"distribute-vertical",label:{default:"action.distribute-vertical","context-menu":"action.distribute-vertical.short"},icon:"distribute-vertical",kbd:"alt+shift+V",onSelect(S){f()&&(h()||(i("distribute-shapes",{operation:"vertical",source:S}),d.markHistoryStoppingPoint("distribute vertical"),d.run(()=>{const b=d.getSelectedShapeIds();d.distributeShapes(b,"vertical"),mt(d,b)})))}},{id:"stretch-horizontal",label:{default:"action.stretch-horizontal","context-menu":"action.stretch-horizontal.short"},icon:"stretch-horizontal",onSelect(S){f()&&(h()||(i("stretch-shapes",{operation:"horizontal",source:S}),d.markHistoryStoppingPoint("stretch horizontal"),d.run(()=>{const b=d.getSelectedShapeIds();d.stretchShapes(b,"horizontal"),mt(d,b)})))}},{id:"stretch-vertical",label:{default:"action.stretch-vertical","context-menu":"action.stretch-vertical.short"},icon:"stretch-vertical",onSelect(S){f()&&(h()||(i("stretch-shapes",{operation:"vertical",source:S}),d.markHistoryStoppingPoint("stretch vertical"),d.run(()=>{const b=d.getSelectedShapeIds();d.stretchShapes(b,"vertical"),mt(d,b)})))}},{id:"flip-horizontal",label:{default:"action.flip-horizontal","context-menu":"action.flip-horizontal.short"},kbd:"shift+h",onSelect(S){f()&&(h()||(i("flip-shapes",{operation:"horizontal",source:S}),d.markHistoryStoppingPoint("flip horizontal"),d.run(()=>{const b=d.getSelectedShapeIds();d.flipShapes(b,"horizontal"),mt(d,b)})))}},{id:"flip-vertical",label:{default:"action.flip-vertical","context-menu":"action.flip-vertical.short"},kbd:"shift+v",onSelect(S){f()&&(h()||(i("flip-shapes",{operation:"vertical",source:S}),d.markHistoryStoppingPoint("flip vertical"),d.run(()=>{const b=d.getSelectedShapeIds();d.flipShapes(b,"vertical"),mt(d,b)})))}},{id:"pack",label:"action.pack",icon:"pack",onSelect(S){f()&&(h()||(i("pack-shapes",{source:S}),d.markHistoryStoppingPoint("pack"),d.run(()=>{const b=d.getSelectedShapeIds();d.packShapes(b,d.options.adjacentShapeMargin),mt(d,b)})))}},{id:"stack-vertical",label:{default:"action.stack-vertical","context-menu":"action.stack-vertical.short"},icon:"stack-vertical",onSelect(S){f()&&(h()||(i("stack-shapes",{operation:"vertical",source:S}),d.markHistoryStoppingPoint("stack-vertical"),d.run(()=>{const b=d.getSelectedShapeIds();d.stackShapes(b,"vertical",d.options.adjacentShapeMargin),mt(d,b)})))}},{id:"stack-horizontal",label:{default:"action.stack-horizontal","context-menu":"action.stack-horizontal.short"},icon:"stack-horizontal",onSelect(S){f()&&(h()||(i("stack-shapes",{operation:"horizontal",source:S}),d.markHistoryStoppingPoint("stack-horizontal"),d.run(()=>{const b=d.getSelectedShapeIds();d.stackShapes(b,"horizontal",d.options.adjacentShapeMargin),mt(d,b)})))}},{id:"bring-to-front",label:"action.bring-to-front",kbd:"]",icon:"bring-to-front",onSelect(S){f()&&(h()||(i("reorder-shapes",{operation:"toFront",source:S}),d.markHistoryStoppingPoint("bring to front"),d.bringToFront(d.getSelectedShapeIds())))}},{id:"bring-forward",label:"action.bring-forward",icon:"bring-forward",kbd:"alt+]",onSelect(S){f()&&(h()||(i("reorder-shapes",{operation:"forward",source:S}),d.markHistoryStoppingPoint("bring forward"),d.bringForward(d.getSelectedShapeIds())))}},{id:"send-backward",label:"action.send-backward",icon:"send-backward",kbd:"alt+[",onSelect(S){f()&&(h()||(i("reorder-shapes",{operation:"backward",source:S}),d.markHistoryStoppingPoint("send backward"),d.sendBackward(d.getSelectedShapeIds())))}},{id:"send-to-back",label:"action.send-to-back",icon:"send-to-back",kbd:"[",onSelect(S){f()&&(h()||(i("reorder-shapes",{operation:"toBack",source:S}),d.markHistoryStoppingPoint("send to back"),d.sendToBack(d.getSelectedShapeIds())))}},{id:"cut",label:"action.cut",kbd:"cmd+x,ctrl+x",onSelect(S){f()&&(h()||(d.markHistoryStoppingPoint("cut"),s.cut(S)))}},{id:"copy",label:"action.copy",kbd:"cmd+c,ctrl+c",readonlyOk:!0,onSelect(S){f()&&(h()||s.copy(S))}},{id:"paste",label:"action.paste",kbd:"cmd+v,ctrl+v",onSelect(S){var b;(b=navigator.clipboard)==null||b.read().then(w=>{s.paste(w,S,S==="context-menu"?d.inputs.getCurrentPagePoint():void 0)}).catch(()=>{s.addToast({title:s.msg("action.paste-error-title"),description:s.msg("action.paste-error-description"),severity:"error"})})}},{id:"select-all",label:"action.select-all",kbd:"cmd+a,ctrl+a",readonlyOk:!0,onSelect(S){d.run(()=>{h()||(i("select-all-shapes",{source:S}),d.markHistoryStoppingPoint("select all kbd"),d.selectAll())})}},{id:"select-none",label:"action.select-none",readonlyOk:!0,onSelect(S){f()&&(h()||(i("select-none-shapes",{source:S}),d.markHistoryStoppingPoint("select none"),d.selectNone()))}},{id:"delete",label:"action.delete",kbd:"⌫,del",icon:"trash",onSelect(S){f()&&(h()||(i("delete-shapes",{source:S}),d.markHistoryStoppingPoint("delete"),d.deleteShapes(d.getSelectedShapeIds())))}},{id:"rotate-cw",label:"action.rotate-cw",icon:"rotate-cw",kbd:"shift+.,shift+alt+.",onSelect(S){if(!f()||h())return;const b=d.inputs.getAltKey();i("rotate-cw",{source:S,fine:b}),d.markHistoryStoppingPoint("rotate-cw"),d.run(()=>{const w=Bt/(b?96:6),v=d.getSelectionRotation()%w,P=tn(v,0)||tn(v,w),T=d.getSelectedShapeIds();d.rotateShapesBy(T,w-(P?0:v)),mt(d,T)})}},{id:"rotate-ccw",label:"action.rotate-ccw",icon:"rotate-ccw",kbd:"shift+,,shift+alt+,",onSelect(S){if(!f()||h())return;const b=d.inputs.getAltKey();i("rotate-ccw",{source:S,fine:b}),d.markHistoryStoppingPoint("rotate-ccw"),d.run(()=>{const w=Bt/(b?96:6),v=d.getSelectionRotation()%w,P=tn(v,0),T=d.getSelectedShapeIds();d.rotateShapesBy(T,P?-w:-v),mt(d,T)})}},{id:"zoom-in",label:"action.zoom-in",kbd:"cmd+=,ctrl+=,=",readonlyOk:!0,onSelect(S){i("zoom-in",{source:S,towardsCursor:!1}),d.zoomIn(void 0,{animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-in-on-cursor",label:"action.zoom-in",kbd:"shift+cmd+=,shift+ctrl+=,shift+=",readonlyOk:!0,onSelect(S){i("zoom-in",{source:S,towardsCursor:!0}),d.zoomIn(d.inputs.getCurrentScreenPoint(),{animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-out",label:"action.zoom-out",kbd:"cmd+-,ctrl+-,-",readonlyOk:!0,onSelect(S){i("zoom-out",{source:S,towardsCursor:!1}),d.zoomOut(void 0,{animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-out-on-cursor",label:"action.zoom-out",kbd:"shift+cmd+-,shift+ctrl+-,shift+-",readonlyOk:!0,onSelect(S){i("zoom-out",{source:S,towardsCursor:!0}),d.zoomOut(d.inputs.getCurrentScreenPoint(),{animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-to-100",label:"action.zoom-to-100",icon:"reset-zoom",kbd:"shift+0",readonlyOk:!0,onSelect(S){i("reset-zoom",{source:S}),d.resetZoom(void 0,{animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-to-fit",label:"action.zoom-to-fit",kbd:"shift+1",readonlyOk:!0,onSelect(S){i("zoom-to-fit",{source:S}),d.zoomToFit({animation:{duration:d.options.animationMediumMs}})}},{id:"zoom-to-selection",label:"action.zoom-to-selection",kbd:"shift+2",readonlyOk:!0,onSelect(S){f()&&(h()||(i("zoom-to-selection",{source:S}),d.zoomToSelection({animation:{duration:d.options.animationMediumMs}})))}},{id:"toggle-snap-mode",label:{default:"action.toggle-snap-mode",menu:"action.toggle-snap-mode.menu"},onSelect(S){i("toggle-snap-mode",{source:S}),d.user.updateUserPreferences({isSnapMode:!d.user.getIsSnapMode()})},checkbox:!0},{id:"toggle-dark-mode",label:{default:"action.toggle-dark-mode",menu:"action.toggle-dark-mode.menu"},kbd:"cmd+/,ctrl+/",readonlyOk:!0,onSelect(S){const b=d.user.getIsDarkMode()?"light":"dark";i("color-scheme",{source:S,value:b}),d.user.updateUserPreferences({colorScheme:b})},checkbox:!0},{id:"toggle-wrap-mode",label:{default:"action.toggle-wrap-mode",menu:"action.toggle-wrap-mode.menu"},readonlyOk:!0,onSelect(S){i("toggle-wrap-mode",{source:S}),d.user.updateUserPreferences({isWrapMode:!d.user.getIsWrapMode()})},checkbox:!0},{id:"toggle-dynamic-size-mode",label:{default:"action.toggle-dynamic-size-mode",menu:"action.toggle-dynamic-size-mode.menu"},readonlyOk:!1,onSelect(S){i("toggle-dynamic-size-mode",{source:S}),d.user.updateUserPreferences({isDynamicSizeMode:!d.user.getIsDynamicResizeMode()})},checkbox:!0},{id:"toggle-paste-at-cursor",label:{default:"action.toggle-paste-at-cursor",menu:"action.toggle-paste-at-cursor.menu"},readonlyOk:!1,onSelect(S){i("toggle-paste-at-cursor",{source:S}),d.user.updateUserPreferences({isPasteAtCursorMode:!d.user.getIsPasteAtCursorMode()})},checkbox:!0},{id:"toggle-reduce-motion",label:{default:"action.toggle-reduce-motion",menu:"action.toggle-reduce-motion.menu"},readonlyOk:!0,onSelect(S){i("toggle-reduce-motion",{source:S}),d.user.updateUserPreferences({animationSpeed:d.user.getAnimationSpeed()===0?1:0})},checkbox:!0},{id:"toggle-keyboard-shortcuts",label:{default:"action.toggle-keyboard-shortcuts",menu:"action.toggle-keyboard-shortcuts.menu"},readonlyOk:!0,onSelect(S){i("toggle-keyboard-shortcuts",{source:S}),d.user.updateUserPreferences({areKeyboardShortcutsEnabled:!d.user.getAreKeyboardShortcutsEnabled()})},checkbox:!0},{id:"enhanced-a11y-mode",label:{default:"action.enhanced-a11y-mode",menu:"action.enhanced-a11y-mode.menu"},readonlyOk:!0,onSelect(S){i("enhanced-a11y-mode",{source:S}),d.user.updateUserPreferences({enhancedA11yMode:!d.user.getEnhancedA11yMode()})},checkbox:!0},{id:"toggle-edge-scrolling",label:{default:"action.toggle-edge-scrolling",menu:"action.toggle-edge-scrolling.menu"},readonlyOk:!0,onSelect(S){i("toggle-edge-scrolling",{source:S}),d.user.updateUserPreferences({edgeScrollSpeed:d.user.getEdgeScrollSpeed()===0?1:0})},checkbox:!0},{id:"toggle-invert-zoom",label:{default:"action.toggle-invert-zoom",menu:"action.toggle-invert-zoom.menu"},readonlyOk:!0,onSelect(S){i("toggle-invert-zoom",{source:S}),d.user.updateUserPreferences({isZoomDirectionInverted:!d.user.getIsZoomDirectionInverted()})},checkbox:!0},{id:"toggle-transparent",label:{default:"action.toggle-transparent",menu:"action.toggle-transparent.menu","context-menu":"action.toggle-transparent.context-menu"},readonlyOk:!0,onSelect(S){i("toggle-transparent",{source:S}),d.updateInstanceState({exportBackground:!d.getInstanceState().exportBackground})},checkbox:!0},{id:"toggle-tool-lock",label:{default:"action.toggle-tool-lock",menu:"action.toggle-tool-lock.menu"},kbd:"q",onSelect(S){i("toggle-tool-lock",{source:S}),d.updateInstanceState({isToolLocked:!d.getInstanceState().isToolLocked})},checkbox:!0},{id:"unlock-all",label:"action.unlock-all",onSelect(S){i("unlock-all",{source:S});const b=[];for(const w of d.getCurrentPageShapes())w.isLocked&&b.push({id:w.id,type:w.type,isLocked:!1});b.length>0&&d.updateShapes(b)}},{id:"toggle-focus-mode",label:{default:"action.toggle-focus-mode",menu:"action.toggle-focus-mode.menu"},readonlyOk:!0,kbd:"cmd+.,ctrl+.",checkbox:!0,onSelect(S){d.timers.requestAnimationFrame(()=>{d.run(()=>{i("toggle-focus-mode",{source:S}),s.clearDialogs(),s.clearToasts(),d.updateInstanceState({isFocusMode:!d.getInstanceState().isFocusMode})})})}},{id:"toggle-grid",label:{default:"action.toggle-grid",menu:"action.toggle-grid.menu"},readonlyOk:!0,kbd:"cmd+',ctrl+'",onSelect(S){i("toggle-grid-mode",{source:S}),d.updateInstanceState({isGridMode:!d.getInstanceState().isGridMode})},checkbox:!0},{id:"toggle-debug-mode",label:{default:"action.toggle-debug-mode",menu:"action.toggle-debug-mode.menu"},readonlyOk:!0,onSelect(S){i("toggle-debug-mode",{source:S}),d.updateInstanceState({isDebugMode:!d.getInstanceState().isDebugMode})},checkbox:!0},{id:"print",label:"action.print",kbd:"cmd+p,ctrl+p",readonlyOk:!0,onSelect(S){i("print",{source:S}),s.printSelectionOrPages()}},{id:"exit-pen-mode",label:"action.exit-pen-mode",icon:"cross-2",readonlyOk:!0,onSelect(S){i("exit-pen-mode",{source:S}),d.updateInstanceState({isPenMode:!1})}},{id:"stop-following",label:"action.stop-following",icon:"cross-2",readonlyOk:!0,onSelect(S){i("stop-following",{source:S}),d.stopFollowingUser()}},{id:"back-to-content",label:"action.back-to-content",icon:"arrow-left",readonlyOk:!0,onSelect(S){i("zoom-to-content",{source:S});const b=d.getSelectionPageBounds()??d.getCurrentPageBounds();b&&d.zoomToBounds(b,{targetZoom:Math.min(1,d.getZoomLevel()),animation:{duration:220}})}},{id:"toggle-lock",label:"action.toggle-lock",kbd:"shift+l",onSelect(S){f()&&(d.markHistoryStoppingPoint("locking"),i("toggle-lock",{source:S}),d.toggleLock(d.getSelectedShapeIds()))}},{id:"move-to-new-page",label:"context.pages.new-page",onSelect(S){const b=Ar.createId(),w=d.getSelectedShapeIds();d.run(()=>{d.markHistoryStoppingPoint("move_shapes_to_page"),d.createPage({name:s.msg("page-menu.new-page-initial-name"),id:b}),d.moveShapesToPage(w,b)}),i("move-to-new-page",{source:S})}},{id:"select-white-color",label:"color-style.white",kbd:"alt+t",onSelect(S){const b=Rr;d.run(()=>{d.markHistoryStoppingPoint("change-color"),d.isIn("select")&&d.setStyleForSelectedShapes(b,"white"),d.setStyleForNextShapes(b,"white")}),i("set-style",{source:S,id:b.id,value:"white"})}},{id:"select-fill-fill",label:"fill-style.fill",kbd:"alt+f",onSelect(S){const b=Li;d.run(()=>{d.markHistoryStoppingPoint("change-fill"),d.isIn("select")&&d.setStyleForSelectedShapes(b,"fill"),d.setStyleForNextShapes(b,"fill")}),i("set-style",{source:S,id:b.id,value:"fill"})}},{id:"select-fill-lined-fill",label:"fill-style.lined-fill",kbd:"alt+shift+f",onSelect(S){const b=Li;d.run(()=>{d.markHistoryStoppingPoint("change-fill"),d.isIn("select")&&d.setStyleForSelectedShapes(b,"lined-fill"),d.setStyleForNextShapes(b,"lined-fill")}),i("set-style",{source:S,id:b.id,value:"lined-fill"})}},{id:"flatten-to-image",label:"action.flatten-to-image",kbd:"shift+f",onSelect:async S=>{const b=d.getSelectedShapeIds();if(b.length===0)return;d.markHistoryStoppingPoint("flattening to image"),i("flatten-to-image",{source:S});const w=await fae(d,b,d.options.flattenImageBoundsExpand);w!=null&&w.length&&d.setSelectedShapes(w)}},{id:"select-geo-tool",kbd:"g",onSelect:async S=>{i("select-tool",{source:S,id:"geo-previous"}),d.setCurrentTool("geo")}},{id:"change-page-prev",kbd:"alt+left,alt+up",readonlyOk:!0,onSelect:async S=>{const b=d.getPages(),w=b.findIndex(v=>v.id===d.getCurrentPageId());w<1||(i("change-page",{source:S,direction:"prev"}),d.setCurrentPage(b[w-1].id))}},{id:"change-page-next",kbd:"alt+right,alt+down",readonlyOk:!0,onSelect:async S=>{const b=d.getPages(),w=b.findIndex(v=>v.id===d.getCurrentPageId());if(w===-1||w>=b.length-1){if(d.getCurrentPageShapes().length<=0||d.getIsReadonly())return;i("new-page",{source:S}),d.run(()=>{d.markHistoryStoppingPoint("creating page");const v=Ar.createId();d.createPage({name:s.msg("page-menu.new-page-initial-name"),id:v}),d.setCurrentPage(v)});return}d.setCurrentPage(b[w+1].id),i("change-page",{source:S,direction:"next"})}},{id:"adjust-shape-styles",label:"a11y.adjust-shape-styles",kbd:"cmd+Enter,ctrl+Enter",isRequiredA11yAction:!0,onSelect:async S=>{if(!f())return;const b=d.getOnlySelectedShape();if(b&&(d.isShapeOfType(b,"image")||d.isShapeOfType(b,"video"))){const v=d.getContainer().querySelector(".tlui-contextual-toolbar button:first-child");v==null||v.focus();return}const w=d.getContainer().querySelector(".tlui-style-panel button");w==null||w.focus(),i("adjust-shape-styles",{source:S})}},{id:"a11y-open-context-menu",kbd:"cmd+shift+Enter,ctrl+shift+Enter",isRequiredA11yAction:!0,readonlyOk:!0,onSelect:async S=>{var T;if(!f())return;const b=d.getSelectionPageBounds();if(!b)return;const w=b.x+b.width/2,v=b.y+b.height/2,P=d.pageToScreen(new C(w,v));(T=d.getContainer().querySelector(".tl-canvas"))==null||T.dispatchEvent(new PointerEvent("contextmenu",{clientX:P.x,clientY:P.y,bubbles:!0})),i("open-context-menu",{source:S})}},{id:"enlarge-shapes",label:"a11y.enlarge-shape",kbd:"cmd+alt+shift+=,ctrl+alt+shift+=",onSelect:async S=>{f()&&(g(1.1),i("enlarge-shapes",{source:S}))}},{id:"shrink-shapes",label:"a11y.shrink-shape",kbd:"cmd+alt+shift+-,ctrl+alt+shift+-",onSelect:async S=>{f()&&(g(1/1.1),i("shrink-shapes",{source:S}))}},{id:"a11y-repeat-shape-announce",kbd:"alt+r",label:"a11y.repeat-shape",isRequiredA11yAction:!0,readonlyOk:!0,onSelect:async S=>{const b=d.getSelectedShapeIds();if(!b.length)return;const w=qj({editor:d,selectedShapeIds:b,msg:l});w&&(a.announce({msg:""}),d.timers.requestAnimationFrame(()=>{a.announce({msg:w})}),i("a11y-repeat-shape-announce",{source:S}))}},{id:"image-replace",label:"tool.replace-media",icon:"arrow-cycle",readonlyOk:!1,onSelect:async S=>{i("image-replace",{source:S}),s.replaceImage()}},{id:"video-replace",label:"tool.replace-media",icon:"arrow-cycle",readonlyOk:!1,onSelect:async S=>{i("video-replace",{source:S}),s.replaceVideo()}},{id:"download-original",label:"action.download-original",readonlyOk:!0,onSelect:async S=>{const b=d.getSelectedShapes();if(b.length===0)return;const w=b.filter(v=>K5(v,d));if(w.length!==0){for(const v of w){const P=d.getAsset(v.props.assetId);if(!P||!P.props.src)continue;const T=await d.resolveAssetUrl(P.id,{shouldResolveToOriginal:!0});if(!T)return;const I=document.createElement("a");I.href=T,(P.type==="video"||P.type==="image")&&!P.props.src.startsWith("asset:")?I.download=P.props.name:I.download="download",document.body.appendChild(I),I.click(),document.body.removeChild(I)}i("download-original",{source:S})}}}];r&&m.push({id:"open-cursor-chat",label:"action.open-cursor-chat",readonlyOk:!0,kbd:"/",onSelect(S){i("open-cursor-chat",{source:S}),!d.getInstanceState().isCoarsePointer&&d.timers.requestAnimationFrame(()=>{d.updateInstanceState({isChatting:!0})})}});const y=fue(m);return n?n(d,y,s):y},[s,t,i,n,c,r,l,a,o]);return p.jsx(U5.Provider,{value:u,children:e})}function ni(){const n=x.useContext(U5);if(!n)throw new Error("useTools must be used within a ToolProvider");return n}function Ih(n,e){return n?typeof n=="string"?n:e?n[e]??n.default:void 0:void 0}function ss({actionId:n="",...e}){const r=ni()[n];return r?p.jsx(mp,{...r,...e}):null}function W5(){return Hae()?p.jsx(Z,{actionId:"toggle-auto-size"}):null}function V5(){return c5()?p.jsx(Z,{actionId:"edit-link"}):null}function mue(){return Br(1)?p.jsx(Z,{actionId:"duplicate"}):null}function G5(){const n=K();return W("should display flatten option",()=>{if(n.getSelectedShapeIds().length===0)return!1;const r=n.getOnlySelectedShape();return!(r&&n.isShapeOfType(r,"image"))},[n])?p.jsx(Z,{actionId:"flatten-to-image"}):null}function yue(){const n=K();return W("should display download original option",()=>{const t=n.getSelectedShapes();return t.length===0?!1:t.some(r=>K5(r,n))},[n])?p.jsx(Z,{actionId:"download-original"}):null}function Y5(){return a5()?p.jsx(Z,{actionId:"group"}):null}function X5(){return l5()?p.jsx(Z,{actionId:"ungroup"}):null}function q5(){const n=K();return W("allow unframe",()=>{const t=n.getSelectedShapes();return t.length===0?!1:t.every(r=>n.isShapeOfType(r,"frame"))},[n])?p.jsx(Z,{actionId:"remove-frame"}):null}function Z5(){const n=K();return W("allow fit frame to content",()=>{const t=n.getOnlySelectedShape();return t?n.isShapeOfType(t,"frame")&&n.getSortedChildIdsForParent(t).length>0:!1},[n])?p.jsx(Z,{actionId:"fit-frame-to-content"}):null}function J5(){const n=K();return W("selected shapes",()=>n.getSelectedShapes().length>0,[n])?p.jsx(Z,{actionId:"toggle-lock"}):null}function ZC(){const n=K(),e=W("isTransparentBg",()=>!n.getInstanceState().exportBackground,[n]);return p.jsx(ss,{actionId:"toggle-transparent",checked:e,toggle:!0})}function Sue(){const n=K(),e=W("any shapes",()=>n.getCurrentPageShapeIds().size>0,[n]);return p.jsx(Z,{actionId:"unlock-all",disabled:!e})}function JC(){const n=K(),e=W("zoomed to 100",()=>n.getEfficientZoomLevel()===1,[n]);return p.jsx(Z,{actionId:"zoom-to-100",noClose:!0,disabled:e})}function Q5(){const n=K(),e=W("has shapes",()=>n.getCurrentPageShapeIds().size>0,[n]);return p.jsx(Z,{actionId:"zoom-to-fit",disabled:!e,"data-testid":"minimap.zoom-menu.zoom-to-fit",noClose:!0})}function ez(){const n=AS();return p.jsx(Z,{actionId:"zoom-to-selection",disabled:!n,"data-testid":"minimap.zoom-menu.zoom-to-selection",noClose:!0})}function tz(){return p.jsxs($e,{id:"clipboard",children:[p.jsx(bue,{}),p.jsx(wue,{}),p.jsx(vue,{}),p.jsx(mue,{}),p.jsx(Cue,{})]})}function xue(){var t;const n=K(),e=W("atLeastOneShapeOnPage",()=>n.getCurrentPageShapeIds().size>0,[n]);return p.jsxs(mr,{id:"copy-as",label:"context-menu.copy-as",size:"small",disabled:!e,children:[p.jsxs($e,{id:"copy-as-group",children:[p.jsx(Z,{actionId:"copy-as-svg"}),!!((t=window.navigator.clipboard)!=null&&t.write)&&p.jsx(Z,{actionId:"copy-as-png"})]}),p.jsx($e,{id:"copy-as-bg",children:p.jsx(ZC,{})})]})}function bue(){const n=AS(),e=Br(1);return p.jsx(Z,{actionId:"cut",disabled:!n||!e})}function wue(){const n=AS();return p.jsx(Z,{actionId:"copy",disabled:!n})}function vue(){const n=zae;return p.jsx(Z,{actionId:"paste",disabled:!n})}function nz(){const n=K();return W("atLeastOneShapeOnPage",()=>n.getCurrentPageShapeIds().size>0,[n])?p.jsxs($e,{id:"conversions",children:[p.jsx(xue,{}),p.jsxs(mr,{id:"export-as",label:"context-menu.export-as",size:"small",children:[p.jsxs($e,{id:"export-as-group",children:[p.jsx(Z,{actionId:"export-as-svg"}),p.jsx(Z,{actionId:"export-as-png"})]}),p.jsx($e,{id:"export-as-bg",children:p.jsx(ZC,{})})]}),p.jsx(yue,{})]}):null}function rz(){const n=K(),e=W("atLeastOneShapeOnPage",()=>n.getCurrentPageShapeIds().size>0,[n]);return p.jsx(Z,{actionId:"select-all",disabled:!e})}function Cue(){const n=AS(),e=Br(1);return p.jsx(Z,{actionId:"delete",disabled:!n||!e})}function Pue(){const n=Ps();return!$ae(1)||n?null:p.jsxs(mr,{id:"edit",label:"context-menu.edit",size:"small",children:[p.jsx(Y5,{}),p.jsx(X5,{}),p.jsx(G5,{}),p.jsx(V5,{}),p.jsx(Z5,{}),p.jsx(q5,{}),p.jsx(oz,{}),p.jsx(sz,{}),p.jsx(W5,{}),p.jsx(J5,{})]})}function Tue(){const n=Br(2),e=Uae();return Ps()||!(n||e)?null:p.jsxs(mr,{id:"arrange",label:"context-menu.arrange",size:"small",children:[n&&p.jsxs($e,{id:"align",children:[p.jsx(Z,{actionId:"align-left"}),p.jsx(Z,{actionId:"align-center-horizontal"}),p.jsx(Z,{actionId:"align-right"}),p.jsx(Z,{actionId:"align-top"}),p.jsx(Z,{actionId:"align-center-vertical"}),p.jsx(Z,{actionId:"align-bottom"})]}),p.jsx(Iue,{}),n&&p.jsxs($e,{id:"stretch",children:[p.jsx(Z,{actionId:"stretch-horizontal"}),p.jsx(Z,{actionId:"stretch-vertical"})]}),(n||e)&&p.jsxs($e,{id:"flip",children:[p.jsx(Z,{actionId:"flip-horizontal"}),p.jsx(Z,{actionId:"flip-vertical"})]}),p.jsx(Eue,{})]})}function Iue(){return Br(3)?p.jsxs($e,{id:"distribute",children:[p.jsx(Z,{actionId:"distribute-horizontal"}),p.jsx(Z,{actionId:"distribute-vertical"})]}):null}function Eue(){const n=Br(2),e=i5();return n?p.jsxs($e,{id:"order",children:[p.jsx(Z,{actionId:"pack"}),e&&p.jsx(Z,{actionId:"stack-horizontal"}),e&&p.jsx(Z,{actionId:"stack-vertical"})]}):null}function kue(){const n=Ps(),e=Br(1);return n||!e?null:p.jsx(mr,{id:"reorder",label:"context-menu.reorder",size:"small",children:p.jsxs($e,{id:"reorder",children:[p.jsx(Z,{actionId:"bring-to-front"}),p.jsx(Z,{actionId:"bring-forward"}),p.jsx(Z,{actionId:"send-backward"}),p.jsx(Z,{actionId:"send-to-back"})]})})}function _ue(){const n=K(),e=W("pages",()=>n.getPages(),[n]),t=W("current page id",()=>n.getCurrentPageId(),[n]),{addToast:r}=Xi(),s=Rt(),o=Ps();return!Br(1)||o?null:p.jsxs(mr,{id:"move-to-page",label:"context-menu.move-to-page",size:"small",children:[p.jsx($e,{id:"pages",children:e.map(a=>p.jsx(Ze,{id:a.id,disabled:t===a.id,label:a.name.length>30?`${a.name.slice(0,30)}…`:a.name,onSelect:()=>{n.markHistoryStoppingPoint("move_shapes_to_page"),n.moveShapesToPage(n.getSelectedShapeIds(),a.id);const l=n.getPage(a.id);l&&r({title:"Changed page",description:`Moved to ${l.name}.`,actions:[{label:"Go back",type:"primary",onClick:()=>{n.markHistoryStoppingPoint("change-page"),n.setCurrentPage(t)}}]}),s("move-to-page",{source:"context-menu"})}},a.id))}),p.jsx($e,{id:"new-page",children:p.jsx(Z,{actionId:"move-to-new-page"})})]})}function sz(){const n=K();return W("oneEmbedSelected",()=>{const t=n.getOnlySelectedShape();return t?!!(n.isShapeOfType(t,"embed")&&t.props.url&&!n.isShapeOrAncestorLocked(t)):!1},[n])?p.jsx(Z,{actionId:"convert-to-bookmark"}):null}function oz(){const n=K(),e=FC();return W("oneEmbeddableBookmarkSelected",()=>{const r=n.getOnlySelectedShape();return r?!!(n.isShapeOfType(r,"bookmark")&&r.props.url&&e(r.props.url)&&!n.isShapeOrAncestorLocked(r)):!1},[n])?p.jsx(Z,{actionId:"convert-to-embed"}):null}function Mue(){const n=K(),e=W("isSnapMode",()=>n.user.getIsSnapMode(),[n]);return p.jsx(ss,{actionId:"toggle-snap-mode",checked:e})}function Aue(){const n=K(),e=W("isToolLock",()=>n.getInstanceState().isToolLocked,[n]);return p.jsx(ss,{actionId:"toggle-tool-lock",checked:e})}function Due(){const n=K(),e=W("isGridMode",()=>n.getInstanceState().isGridMode,[n]);return p.jsx(ss,{actionId:"toggle-grid",checked:e})}function Oue(){const n=K(),e=W("isWrapMode",()=>n.user.getIsWrapMode(),[n]);return p.jsx(ss,{actionId:"toggle-wrap-mode",checked:e})}function Rue(){const n=K(),e=W("isFocusMode",()=>n.getInstanceState().isFocusMode,[n]);return p.jsx(ss,{actionId:"toggle-focus-mode",checked:e})}function Lue(){const n=K(),e=W("edgeScrollSpeed",()=>n.user.getEdgeScrollSpeed(),[n]);return p.jsx(ss,{actionId:"toggle-edge-scrolling",checked:e===1})}function jue(){const n=K(),e=W("inputMode",()=>n.user.getUserPreferences().inputMode==="mouse",[n]),t=W("isZoomDirectionInverted",()=>n.user.getIsZoomDirectionInverted(),[n]);return p.jsx(ss,{actionId:"toggle-invert-zoom",checked:t,disabled:!e})}function Nue(){const n=K(),e=W("animationSpeed",()=>n.user.getAnimationSpeed(),[n]);return p.jsx(ss,{actionId:"toggle-reduce-motion",checked:e===0})}function Fue(){const n=K(),e=W("keyboardShortcuts",()=>n.user.getAreKeyboardShortcutsEnabled(),[n]);return p.jsx(ss,{actionId:"toggle-keyboard-shortcuts",checked:e})}function Bue(){const n=K(),e=W("enhancedA11yMode",()=>n.user.getEnhancedA11yMode(),[n]);return p.jsx(ss,{actionId:"enhanced-a11y-mode",checked:e})}function zue(){const n=K(),e=W("isDebugMode",()=>n.getInstanceState().isDebugMode,[n]);return p.jsx(ss,{actionId:"toggle-debug-mode",checked:e})}function $ue(){const n=K(),e=W("dynamic resize",()=>n.user.getIsDynamicResizeMode(),[n]);return p.jsx(ss,{actionId:"toggle-dynamic-size-mode",checked:e})}function Hue(){const n=K(),e=W("paste at cursor",()=>n.user.getIsPasteAtCursorMode(),[n]);return p.jsx(ss,{actionId:"toggle-paste-at-cursor",checked:e})}function Uue(){const n=K();return W("show cursor chat",()=>n.getCurrentToolId()==="select"&&!n.getInstanceState().isCoarsePointer,[n])?p.jsx(Z,{actionId:"open-cursor-chat"}):null}function Kue(){return p.jsx(mr,{id:"help menu accessibility",label:"menu.accessibility",children:p.jsxs($e,{id:"accessibility",children:[p.jsx(Nue,{}),p.jsx(Fue,{}),p.jsx(Bue,{})]})})}class Jf extends $f{getDefaultProps(){return{isPrecise:!1,isExact:!1,normalizedAnchor:{x:.5,y:.5},snap:"none"}}onAfterCreate({binding:e}){const t=this.editor.getShape(e.fromId);t&&Db(this.editor,t)}onAfterChange({bindingAfter:e}){const t=this.editor.getShape(e.fromId);t&&Db(this.editor,t)}onAfterChangeFromShape({shapeBefore:e,shapeAfter:t,reason:r}){r!=="ancestry"&&e.parentId===t.parentId&&e.index===t.index||Db(this.editor,t)}onAfterChangeToShape({binding:e,shapeBefore:t,shapeAfter:r,reason:s}){s!=="ancestry"&&t.parentId===r.parentId&&t.index===r.index||iz(this.editor,e.fromId)}onBeforeIsolateFromShape({binding:e}){const t=this.editor.getShape(e.fromId);t&&vm({editor:this.editor,arrow:t,terminal:e.props.terminal})}}E(Jf,"type","arrow"),E(Jf,"props",jM),E(Jf,"migrations",NM);function iz(n,e){var y;const t=n.getShape(e);if(!t)return;const r=En(n,t),{start:s,end:o}=r,i=s?n.getShape(s.toId):void 0,a=o?n.getShape(o.toId):void 0,l=n.getAncestorPageId(t);if(!l)return;let c;if(i&&a)c=n.findCommonAncestor([i,a])??l;else if(i||a){const S=(y=i||a)==null?void 0:y.parentId;S&&S===t.parentId?c=t.parentId:c=l}else return;c&&c!==t.parentId&&n.reparentShapes([e],c);const u=n.getShape(e);if(!u)throw Error("no reparented arrow");const d=n.getShapeNearestSibling(u,i),h=n.getShapeNearestSibling(u,a);let f;if(d&&h)f=d.index>h.index?d:h;else if(d&&!h)f=d;else if(h&&!d)f=h;else return;let g;const m=n.getSortedChildIdsForParent(f.parentId).map(S=>n.getShape(S)).filter(S=>S.index>f.index);if(m.length){const S=m.find(b=>b.type!=="arrow");if(u.index>f.index&&(!S||u.index<S.index))return;g=Xc(f.index,m[0].index)}else g=Ns(f.index);g!==u.index&&n.updateShapes([{id:e,type:"arrow",index:g}])}function Db(n,e){const t=En(n,e);for(const r of["start","end"]){const s=t[r];if(!s)continue;const o=n.getShape(s.toId),i=n.getAncestorPageId(e)===n.getAncestorPageId(o);(!o||!i)&&vm({editor:n,arrow:e,terminal:r,unbind:!0})}iz(n,e.id)}function vm({editor:n,arrow:e,terminal:t,unbind:r=!1,useHandle:s=!1}){const o=us(n,e);if(!o)throw new Error("expected arrow info");const i=s?o.start.handle:o.start.point,a=s?o.end.handle:o.end.point,l=t==="start"?i:a,c={id:e.id,type:"arrow",props:{[t]:{x:l.x,y:l.y},bend:e.props.bend}};if(o.type==="arc"){const u=t==="start"?i:o.start.handle,d=t==="end"?a:o.end.handle,h=C.Med(u,d),f=C.Sub(u,d).per().uni().mul(o.handleArc.radius*2*Math.sign(e.props.bend)),g=zh(o.handleArc.center,C.Add(h,f),o.handleArc.center,o.handleArc.radius);be((g==null?void 0:g.length)===1);const m=C.Dist(h,g[0])*Math.sign(e.props.bend);tn(m,c.props.bend)||(c.props.bend=m)}n.updateShape(c),r&&wu(n,e,t)}function Wue({size:n,width:e,height:t,hideAlternateHandles:r}){const s=$(n/3),o=s/2,i=Se();return p.jsxs("svg",{className:"tl-overlays__item","aria-hidden":"true",children:[p.jsx("polyline",{className:"tl-corner-crop-handle",points:`
455
+ ${$(0-o)},${$(n)}
456
+ ${$(0-o)},${$(0-o)}
457
+ ${$(n)},${$(0-o)}`,strokeWidth:s,"data-testid":"selection.crop.top_left",role:"button","aria-label":i("handle.crop.top-left")}),p.jsx("line",{className:xe("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:$(e/2-n),y1:$(0-o),x2:$(e/2+n),y2:$(0-o),strokeWidth:s,"data-testid":"selection.crop.top",role:"button","aria-label":i("handle.crop.top")}),p.jsx("polyline",{className:xe("tl-corner-crop-handle",{"tl-hidden":r}),points:`
458
+ ${$(e-n)},${$(0-o)}
459
+ ${$(e+o)},${$(0-o)}
460
+ ${$(e+o)},${$(n)}`,strokeWidth:s,"data-testid":"selection.crop.top_right",role:"button","aria-label":i("handle.crop.top-right")}),p.jsx("line",{className:xe("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:$(e+o),y1:$(t/2-n),x2:$(e+o),y2:$(t/2+n),strokeWidth:s,"data-testid":"selection.crop.right",role:"button","aria-label":i("handle.crop.right")}),p.jsx("polyline",{className:"tl-corner-crop-handle",points:`
461
+ ${$(e+o)},${$(t-n)}
462
+ ${$(e+o)},${$(t+o)}
463
+ ${$(e-n)},${$(t+o)}`,strokeWidth:s,"data-testid":"selection.crop.bottom_right",role:"button","aria-label":i("handle.crop.bottom-right")}),p.jsx("line",{className:xe("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:$(e/2-n),y1:$(t+o),x2:$(e/2+n),y2:$(t+o),strokeWidth:s,"data-testid":"selection.crop.bottom",role:"button","aria-label":i("handle.crop.bottom")}),p.jsx("polyline",{className:xe("tl-corner-crop-handle",{"tl-hidden":r}),points:`
464
+ ${$(0+n)},${$(t+o)}
465
+ ${$(0-o)},${$(t+o)}
466
+ ${$(0-o)},${$(t-n)}`,strokeWidth:s,"data-testid":"selection.crop.bottom_left",role:"button","aria-label":i("handle.crop.bottom-left")}),p.jsx("line",{className:xe("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:$(0-o),y1:$(t/2-n),x2:$(0-o),y2:$(t/2+n),strokeWidth:s,"data-testid":"selection.crop.left",role:"button","aria-label":i("handle.crop.left")})]})}function Vue({children:n}){const e=K();return W("shouldDisplayHandles",()=>{if(e.isInAny("select.idle","select.pointing_handle","select.pointing_shape"))return!0;if(e.isInAny("select.editing_shape")){const r=e.getOnlySelectedShape();return r&&e.isShapeOfType(r,"note")}return!1},[e])?p.jsx("svg",{className:"tl-user-handles tl-overlays__item","aria-hidden":"true",children:n}):null}const Gue=new Vn;function Ku(n){return Gue.get(n,()=>We("arrowTarget",null))}function Yue(n){return Ku(n).get()}function QC(n){Ku(n).set(null)}function LS({editor:n,pointInPageSpace:e,arrow:t,isPrecise:r,currentBinding:s,oppositeBinding:o}){const i=n.getShapeUtil("arrow");if(i.options.shouldIgnoreTargets(n))return Ku(n).set(null),null;const a=t?t.props.kind:n.getStyleForNextShape(Rg),l=n.getShapeAtPoint(e,{hitInside:!0,hitFrameInside:!0,margin:a==="elbow"?8:[8,0],filter:O=>!O.isLocked&&n.canBindShapes({fromShape:t??Xue,toShape:O,binding:"arrow"})});if(!l)return Ku(n).set(null),null;const c=n.getShapeGeometry(l),u=J.ZeroFix(c.bounds),d=c.center,h=n.getShapePageTransform(l),f=n.getPointInShapeSpace(l,e),g=Math.max(c.bounds.width,c.bounds.height),m=Ka(yae,(O,N)=>{const B=vh[Sae[O]],H=C.Mul(N,g).add(d);let z=!1,X=B.v(u[O],u[B.crossMid]),G=0;const ae=c.intersectLineSegment(d,H,Ko.EXCLUDE_NON_STANDARD);for(const fe of ae){const oe=C.Dist2(fe,d);oe>G&&(G=oe,X=fe,z=c.isClosed)}return{point:h.applyToPoint(X),isEnabled:z,far:h.applyToPoint(H)}}),y=n.getZoomLevel(),S=i.options.minElbowHandleDistance/y,b=h.applyToPoint(d);for(const O of Au(m)){const N=m[O];C.DistMin(N.point,b,S)&&(N.isEnabled=!1)}let w=r;w||(!s||s&&l.id!==s.toId)&&(w=n.inputs.getPointerVelocity().len()<.5),r||(c.isClosed||(w=!0),o&&l.id===o.toId&&o.props.isPrecise&&(w=!0));const v=i.options.shouldBeExact(n,w);v&&(w=!0);const P=!v&&w&&c.isClosed,T=!v&&(w&&a==="elbow"||!c.isClosed),I=!v&&w&&a==="elbow"&&c.isClosed,k=w&&(c.isClosed||v),A=!v&&w&&a==="elbow"&&c.isClosed;let R="none",D=e;if(k||(R="center",D=b),T){const O=k?vf(n,u,i.options.elbowArrowEdgeSnapDistance):1/0,N=c.nearestPoint(f,{includeLabels:!1,includeInternal:!1}),B=h.applyToPoint(N);C.Dist(B,e)<O&&(R="edge",D=B)}if(A){const O=vf(n,u,i.options.elbowArrowAxisSnapDistance),N=C.DistanceToLineSegment(m.left.far,m.right.far,e),B=C.DistanceToLineSegment(m.top.far,m.bottom.far,e),H=N<B&&N<O?"x":B<O?"y":null;if(H){const z=vh[H],X=C.Dist2(m[z.loEdge].far,e),G=C.Dist2(m[z.hiEdge].far,e),ae=X<G?z.loEdge:z.hiEdge;m[ae].isEnabled&&(R="edge-point",D=m[ae].point)}}if(I){const O=vf(n,u,i.options.elbowArrowPointSnapDistance);let N=null,B=1/0;for(const[H,z]of $s(m)){if(!z.isEnabled)continue;const X=C.Dist(z.point,e);X<O&&X<B&&(B=X,N=H)}N&&(R="edge-point",D=m[N].point)}if(P){const O=vf(n,u,a==="elbow"?i.options.elbowArrowCenterSnapDistance:i.options.arcArrowCenterSnapDistance);C.Dist(f,u.center)<O&&(R="center",D=b)}const j=n.getPointInShapeSpace(l,D),_={x:nh(u.minX,u.maxX,j.x),y:nh(u.minY,u.maxY,j.y)},M={target:l,arrowKind:a,handlesInPageSpace:m,centerInPageSpace:b,anchorInPageSpace:D,isExact:v,isPrecise:w,snap:R,normalizedAnchor:_};return Ku(n).set(M),M}const Xue={type:"arrow"};function vf(n,e,t){return Fe(Math.min(e.width,e.height)*.15,4,t)/n.getZoomLevel()}function que(){const n=K();return W("should show arrow hints",()=>{if(n.isInAny("arrow.idle","arrow.pointing"))return!0;if(n.isIn("select.pointing_handle")){const t=n.getStateDescendant("select.pointing_handle");if(t.info.shape.type==="arrow"&&(t.info.handle.id==="start"||t.info.handle.id==="end"))return!0}if(n.isIn("select.dragging_handle")){const t=n.getStateDescendant("select.dragging_handle");if(t.info.shape.type==="arrow"&&(t.info.handle.id==="start"||t.info.handle.id==="end"))return!0}return!1},[n])?p.jsx(Zue,{}):null}function Zue(){const n=K(),{ShapeIndicator:e}=xt(),t=W("arrow target info",()=>Yue(n),[n]);if(!t)return null;const{handlesInPageSpace:r,snap:s,anchorInPageSpace:o,arrowKind:i,isExact:a,isPrecise:l}=t,c=!a&&i==="elbow";return p.jsxs(p.Fragment,{children:[e&&p.jsx(e,{shapeId:t.target.id}),c&&p.jsxs("svg",{className:"tl-overlays__item","aria-hidden":"true",children:[p.jsx("circle",{cx:o.x,cy:o.y,className:`tl-arrow-hint-snap tl-arrow-hint-snap__${l?s??"none":"none"}`}),Object.entries(r).map(([u,d])=>d.isEnabled?p.jsx("circle",{cx:d.point.x,cy:d.point.y,className:"tl-arrow-hint-handle"},u):null)]})]})}const{PI:Jue}=Math,Yc=Jue+1e-4;function az(n,e={}){const{size:t=16,smoothing:r=.5}=e;if(n.length===0||t<=0)return{left:[],right:[]};const s=n[0],o=n[n.length-1],i=o.runningLength,a=Math.pow(t*r,2),l=[],c=[];let u=n[0].vector,d=n[0].point,h=d,f=d,g=h,m=!1,y;for(let S=0;S<n.length;S++){y=n[S];const{point:b,vector:w}=n[S],v=y.vector.dpr(u),P=(S<n.length-1?n[S+1]:n[S]).vector,T=S<n.length-1?P.dpr(y.vector):1,I=v<0&&!m,k=T!==null&&T<.2;if(I||k){if(T>-.62&&i-y.runningLength>y.radius){const R=u.clone().mul(y.radius);u.clone().cpr(P)<0?(f=C.Add(b,R),g=C.Sub(b,R)):(f=C.Sub(b,R),g=C.Add(b,R)),l.push(f),c.push(g)}else{const R=u.clone().mul(y.radius).per(),D=C.Sub(y.input,R);for(let j=1/13,_=0;_<1;_+=j)f=C.RotWith(D,y.input,Yc*_),l.push(f),g=C.RotWith(D,y.input,Yc+Yc*-_),c.push(g)}d=f,h=g,k&&(m=!0);continue}if(m=!1,y===s||y===o){const R=C.Per(w).mul(y.radius);l.push(C.Sub(b,R)),c.push(C.Add(b,R));continue}const A=C.Lrp(P,w,T).per().mul(y.radius);f=C.Sub(b,A),(S<=1||C.Dist2(d,f)>a)&&(l.push(f),d=f),g=C.Add(b,A),(S<=1||C.Dist2(h,g)>a)&&(c.push(g),h=g),u=w}return{left:l,right:c}}function lz(n,e={}){const{size:t=16,start:r={},end:s={},last:o=!1}=e,{cap:i=!0}=r,{cap:a=!0}=s;if(n.length===0||t<=0)return[];const l=n[0],c=n[n.length-1],u=c.runningLength,d=r.taper===!1?0:r.taper===!0?Math.max(t,u):r.taper,h=s.taper===!1?0:s.taper===!0?Math.max(t,u):s.taper,{left:f,right:g}=az(n,e),m=l.point,y=n.length>1?n[n.length-1].point:C.AddXY(l.point,1,1);if(n.length===1&&(!(d||h)||o)){const v=C.Add(m,C.Sub(m,y).uni().per().mul(-l.radius)),P=[];for(let T=1/13,I=T;I<=1;I+=T)P.push(C.RotWith(v,m,Yc*2*I));return P}const S=[];if(!(d||h&&n.length===1))if(i)for(let v=1/8,P=v;P<=1;P+=v){const T=C.RotWith(g[0],m,Yc*P);S.push(T)}else{const v=C.Sub(f[0],g[0]),P=C.Mul(v,.5),T=C.Mul(v,.51);S.push(C.Sub(m,P),C.Sub(m,T),C.Add(m,T),C.Add(m,P))}const b=[],w=c.vector.clone().per().neg();if(h||d&&n.length===1)b.push(y);else if(a){const v=C.Add(y,C.Mul(w,c.radius));for(let P=1/29,T=P;T<1;T+=P)b.push(C.RotWith(v,y,Yc*3*T))}else b.push(C.Add(y,C.Mul(w,c.radius)),C.Add(y,C.Mul(w,c.radius*.99)),C.Sub(y,C.Mul(w,c.radius*.99)),C.Sub(y,C.Mul(w,c.radius)));return f.concat(b,g.reverse(),S)}const Que=.025,ehe=.01;function zi(n,e={}){var y;const{streamline:t=.5,size:r=16,simulatePressure:s=!1}=e;if(n.length===0)return[];const o=.15+(1-t)*.85;let i=n.map(C.From),a=0;if(!s){let S=i[0];for(;S&&!(S.z>=Que);)i.shift(),S=i[0]}if(!s){let S=i[i.length-1];for(;S&&!(S.z>=ehe);)i.pop(),S=i[i.length-1]}if(i.length===0)return[{point:C.From(n[0]),input:C.From(n[0]),pressure:s?.5:.15,vector:new C(1,1),distance:0,runningLength:0,radius:1}];let l=i[1];for(;l&&!(C.Dist2(l,i[0])>(r/3)**2);)i[0].z=Math.max(i[0].z,l.z),i.splice(1,1),l=i[1];const c=i.pop();for(l=i[i.length-1];l&&!(C.Dist2(l,c)>(r/3)**2);)i.pop(),l=i[i.length-1],a++;i.push(c);const u=e.last||!e.simulatePressure||i.length>1&&C.Dist2(i[i.length-1],i[i.length-2])<r**2||a>0;if(i.length===2&&e.simulatePressure){const S=i[1];i=i.slice(0,-1);for(let b=1;b<5;b++){const w=C.Lrp(i[0],S,b/4);w.z=(i[0].z+(S.z-i[0].z))*b/4,i.push(w)}}const d=[{point:i[0],input:i[0],pressure:s?.5:i[0].z,vector:new C(1,1),distance:0,runningLength:0,radius:1}];let h=0,f=d[0],g,m;u&&t>0&&i.push(i[i.length-1].clone());for(let S=1,b=i.length;S<b;S++)g=!o||e.last&&S===b-1?i[S].clone():i[S].clone().lrp(f.point,1-o),!f.point.equals(g)&&(m=C.Dist(g,f.point),h+=m,!(S<4&&h<r)&&(f={input:i[S],point:g,pressure:s?.5:i[S].z,vector:C.Sub(f.point,g).uni(),distance:m,runningLength:h,radius:1},d.push(f)));if((y=d[1])!=null&&y.vector&&(d[0].vector=d[1].vector.clone()),h<1){const S=Math.max(.5,...d.map(b=>b.pressure));d.forEach(b=>b.pressure=S)}return d}const{min:oa}=Math,Ob=.275;function eP(n,e){const{size:t=16,thinning:r=.5,simulatePressure:s=!0,easing:o=y=>y,start:i={},end:a={}}=e,{easing:l=ar.easeOutQuad}=i,{easing:c=ar.easeOutCubic}=a,u=n[n.length-1].runningLength;let d,h=n[0].pressure,f;if(!s&&u<t){const y=n.reduce((S,b)=>Math.max(S,b.pressure),.5);return n.forEach(S=>{S.pressure=y,S.radius=t*o(.5-r*(.5-S.pressure))}),n}else{let y;for(let S=0,b=n.length;S<b&&(f=n[S],!(f.runningLength>t*5));S++){const w=oa(1,f.distance/t);if(s){const v=oa(1,1-w);y=oa(1,h+(v-h)*(w*Ob))}else y=oa(1,h+(f.pressure-h)*.5);h=h+(y-h)*.5}for(let S=0;S<n.length;S++){if(f=n[S],r){let{pressure:b}=f;const w=oa(1,f.distance/t);if(s){const v=oa(1,1-w);b=oa(1,h+(v-h)*(w*Ob))}else b=oa(1,h+(b-h)*(w*Ob));f.radius=t*o(.5-r*(.5-b)),h=b}else f.radius=t/2;d===void 0&&(d=f.radius)}}const g=i.taper===!1?0:i.taper===!0?Math.max(t,u):i.taper,m=a.taper===!1?0:a.taper===!0?Math.max(t,u):a.taper;if(g||m)for(let y=0;y<n.length;y++){f=n[y];const{runningLength:S}=f,b=S<g?l(S/g):1,w=u-S<m?c((u-S)/m):1;f.radius=Math.max(.01,f.radius*Math.min(b,w))}return n}function the(n,e={}){return lz(eP(zi(n,e),e),e)}function Lk({scribble:n,zoom:e,color:t,opacity:r,className:s}){if(!n.points.length)return null;const o=the(n.points,{size:n.size/e,start:{taper:n.taper,easing:ar.linear},last:n.state==="complete"||n.state==="stopping",simulatePressure:!1,streamline:.32});let i;if(o.length<4){const a=n.size/e/2,{x:l,y:c}=n.points[n.points.length-1];i=`M ${l-a},${c} a ${a},${a} 0 1,0 ${a*2},0 a ${a},${a} 0 1,0 ${-a*2},0`}else i=yR(o);return p.jsx("svg",{className:s&&xe("tl-overlays__item",s),children:p.jsx("path",{className:"tl-scribble",d:i,fill:t??`var(--tl-color-${n.color})`,opacity:r??n.opacity})})}const nhe=rn(function({bounds:e,rotation:t}){const r=K(),s=Se(),o=x.useRef(null),i=Ps(),a=Oo("top"),l=Oo("right"),c=Oo("bottom"),u=Oo("left"),d=Oo("top_left"),h=Oo("top_right"),f=Oo("bottom_right"),g=Oo("bottom_left"),m=r.getInstanceState().cursor.type==="default",y=r.getInstanceState().isCoarsePointer,S=r.getOnlySelectedShape(),b=S&&r.isShapeOrAncestorLocked(S),w=S?r.getShapeUtil(S).expandSelectionOutlinePx(S):0,v=w instanceof J?e.clone().expand(w).zeroFix():e.clone().expandBy(w).zeroFix(),P=r.getSelectionRotation(),T=P/Bt>1.6&&P/Bt<2.4;if(jh(o,e==null?void 0:e.x,e==null?void 0:e.y,1,P,{x:v.x-e.x,y:v.y-e.y}),S&&r.isShapeHidden(S))return null;const I=r.getEfficientZoomLevel(),k=r.getInstanceState().isChangingStyle,A=v.width,R=v.height,D=8/I,j=A<D*2,_=R<D*2,M=A<D*4,O=R<D*4,N=A<D*5,B=R<D*5,H=y?1.75:1,z=6/I*H,X=(M?z/2:z)*(H*.75),G=(O?z/2:z)*(H*.75),ae=(S?!r.getShapeUtil(S).hideSelectionBoundsFg(S):!0)&&!k;let Ce=ae&&r.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_canvas","select.pointing_selection","select.pointing_shape","select.crop.idle","select.crop.pointing_crop","select.crop.pointing_crop_handle","select.pointing_resize_handle")||ae&&r.isIn("select.resizing")&&S&&r.isShapeOfType(S,"text");S&&Ce&&dt.isFirefox&&r.isShapeOfType(S,"embed")&&(Ce=!1);const fe=r.isInAny("select.crop.idle","select.crop.pointing_crop","select.crop.pointing_crop_handle")&&!k&&!i,oe=r.isInAny("select.idle","select.pointing_selection","select.pointing_shape","select.crop.idle")&&!k&&!i,Te=!y&&!(j||_)&&(oe||fe)&&(S?!r.getShapeUtil(S).hideRotateHandle(S):!0)&&!b,te=y&&(!M||!O)&&(oe||fe)&&(S?!r.getShapeUtil(S).hideRotateHandle(S):!0)&&!b,re=oe&&(S?r.getShapeUtil(S).canResize(S)&&!r.getShapeUtil(S).hideResizeHandles(S):!0)&&!fe&&!b,ge=j||_,de=j&&_,Ne=N||B,De=re||fe,rt=!Te,lt=!oe||!te,pt=!oe||!De,fn=!oe||!De||ge,Yn=!oe||!De||ge,Is=!oe||!De||de&&!fe;let xn=!0,Sr=!0;if(fe)xn=Ne,Sr=Ne;else if(re){xn=ge||de||y;const Ji=y&&S&&S.type==="text";Sr=xn&&!Ji}const Xn=Math.min(24/I,R-G*3),ri=oe&&y&&S&&r.isShapeOfType(S,"text")&&Xn*I>=4,Zi=S&&(r.isShapeOfType(S,"image")||r.isShapeOfType(S,"video"));return p.jsx("svg",{className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground","aria-hidden":"true",children:p.jsxs("g",{ref:o,children:[Ce&&p.jsx("rect",{className:"tl-selection__fg__outline",width:$(A),height:$(R)}),p.jsx(Cf,{"data-testid":"selection.rotate.top-left",cx:0,cy:0,targetSize:z,corner:"top_left_rotate",cursor:m?ds("nwse-rotate",t):void 0,isHidden:rt}),p.jsx(Cf,{"data-testid":"selection.rotate.top-right",cx:A+z*3,cy:0,targetSize:z,corner:"top_right_rotate",cursor:m?ds("nesw-rotate",t):void 0,isHidden:rt}),p.jsx(Cf,{"data-testid":"selection.rotate.bottom-left",cx:0,cy:R+z*3,targetSize:z,corner:"bottom_left_rotate",cursor:m?ds("swne-rotate",t):void 0,isHidden:rt}),p.jsx(Cf,{"data-testid":"selection.rotate.bottom-right",cx:A+z*3,cy:R+z*3,targetSize:z,corner:"bottom_right_rotate",cursor:m?ds("senw-rotate",t):void 0,isHidden:rt}),p.jsx(she,{"data-testid":"selection.rotate.mobile",cx:M?-z*1.5:A/2,cy:M?R/2:Zi&&!T?R+z*1.5:-z*1.5,size:D,isHidden:lt}),p.jsx(ia,{hide:xn,dataTestId:"selection.resize.top",ariaLabel:s("handle.resize-top"),x:0,y:$(0-(O?G*2:G)),width:$(A),height:$(Math.max(1,G*2)),cursor:m?ds("ns-resize",t):void 0,events:a}),p.jsx(ia,{hide:Sr,dataTestId:"selection.resize.right",ariaLabel:s("handle.resize-right"),x:$(A-(M?0:X)),y:0,height:$(R),width:$(Math.max(1,X*2)),cursor:m?ds("ew-resize",t):void 0,events:l}),p.jsx(ia,{hide:xn,dataTestId:"selection.resize.bottom",ariaLabel:s("handle.resize-bottom"),x:0,y:$(R-(O?0:G)),width:$(A),height:$(Math.max(1,G*2)),cursor:m?ds("ns-resize",t):void 0,events:c}),p.jsx(ia,{hide:Sr,dataTestId:"selection.resize.left",ariaLabel:s("handle.resize-left"),x:$(0-(M?X*2:X)),y:0,height:$(R),width:$(Math.max(1,X*2)),cursor:m?ds("ew-resize",t):void 0,events:u}),p.jsx(ia,{hide:pt,dataTestId:"selection.target.top-left",ariaLabel:s("handle.resize-top-left"),x:$(0-(M?X*2:X*1.5)),y:$(0-(O?G*2:G*1.5)),width:$(X*3),height:$(G*3),cursor:m?ds("nwse-resize",t):void 0,events:d}),p.jsx(ia,{hide:fn,dataTestId:"selection.target.top-right",ariaLabel:s("handle.resize-top-right"),x:$(A-(M?0:X*1.5)),y:$(0-(O?G*2:G*1.5)),width:$(X*3),height:$(G*3),cursor:m?ds("nesw-resize",t):void 0,events:h}),p.jsx(ia,{hide:Is,dataTestId:"selection.target.bottom-right",ariaLabel:s("handle.resize-bottom-right"),x:$(A-(M?X:X*1.5)),y:$(R-(O?G:G*1.5)),width:$(X*3),height:$(G*3),cursor:m?ds("nwse-resize",t):void 0,events:f}),p.jsx(ia,{hide:Yn,dataTestId:"selection.target.bottom-left",ariaLabel:s("handle.resize-bottom-left"),x:$(0-(M?X*3:X*1.5)),y:$(R-(O?0:G*1.5)),width:$(X*3),height:$(G*3),cursor:m?ds("nesw-resize",t):void 0,events:g}),re&&p.jsxs(p.Fragment,{children:[p.jsx("rect",{"data-testid":"selection.resize.top-left",className:xe("tl-corner-handle",{"tl-hidden":pt}),x:$(0-D/2),y:$(0-D/2),width:$(D),height:$(D)}),p.jsx("rect",{"data-testid":"selection.resize.top-right",className:xe("tl-corner-handle",{"tl-hidden":fn}),x:$(A-D/2),y:$(0-D/2),width:$(D),height:$(D)}),p.jsx("rect",{"data-testid":"selection.resize.bottom-right",className:xe("tl-corner-handle",{"tl-hidden":Is}),x:$(A-D/2),y:$(R-D/2),width:$(D),height:$(D)}),p.jsx("rect",{"data-testid":"selection.resize.bottom-left",className:xe("tl-corner-handle",{"tl-hidden":Yn}),x:$(0-D/2),y:$(R-D/2),width:$(D),height:$(D)})]}),ri&&p.jsxs(p.Fragment,{children:[p.jsx("rect",{"data-testid":"selection.text-resize.left.handle",className:"tl-text-handle",x:$(0-D/4),y:$(R/2-Xn/2),rx:D/4,width:$(D/2),height:$(Xn)}),p.jsx("rect",{"data-testid":"selection.text-resize.right.handle",className:"tl-text-handle",rx:D/4,x:$(A-D/4),y:$(R/2-Xn/2),width:$(D/2),height:$(Xn)})]}),fe&&p.jsx(Wue,{size:D,width:A,height:R,hideAlternateHandles:Ne})]})})}),ia=function({hide:e,dataTestId:t,ariaLabel:r,x:s,y:o,width:i,height:a,cursor:l,events:c}){return p.jsx("rect",{className:xe("tl-resize-handle","tl-transparent",{"tl-hidden":e}),"data-testid":t,role:"button","aria-label":r,pointerEvents:"all",x:s,y:o,width:i,height:a,cursor:l,...c})},Cf=function({cx:e,cy:t,targetSize:r,corner:s,cursor:o,isHidden:i,"data-testid":a}){const l=Oo(s),u=Se()(`handle.rotate.${s}`);return p.jsx("rect",{className:xe("tl-transparent","tl-rotate-corner",{"tl-hidden":i}),"data-testid":a,role:"button","aria-label":u,pointerEvents:"all",x:$(e-r*3),y:$(t-r*3),width:$(Math.max(1,r*3)),height:$(Math.max(1,r*3)),cursor:o,...l})},rhe=Math.sqrt(Math.PI),she=function({cx:e,cy:t,size:r,isHidden:s,"data-testid":o}){const i=Oo("mobile_rotate"),a=K(),l=W("zoom level",()=>a.getEfficientZoomLevel(),[a]),c=Math.max(14*(1/l),20/Math.max(1,l)),u=Se();return p.jsxs("g",{role:"button","aria-label":u("handle.rotate.mobile_rotate"),children:[p.jsx("circle",{"data-testid":o,pointerEvents:"all",className:xe("tl-transparent","tl-mobile-rotate__bg",{"tl-hidden":s}),cx:e,cy:t,r:c,...i}),p.jsx("circle",{className:xe("tl-mobile-rotate__fg",{"tl-hidden":s}),cx:e,cy:t,r:r/rhe})]})};function ohe(){const n=K(),e=W("is in a valid select state",()=>n.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle"),[n]);return p.jsx(SR,{hideAll:!e})}const cz=[Jf],Dr={lineHeight:1.35,fontWeight:"normal",fontVariant:"normal",fontStyle:"normal",padding:"0px"},Gt={s:2,m:3.5,l:5,xl:10},dd={s:18,m:24,l:36,xl:44},$a={s:18,m:22,l:26,xl:32},ihe={s:18,m:20,l:24,xl:28},Ha={draw:"var(--tl-font-draw)",sans:"var(--tl-font-sans)",serif:"var(--tl-font-serif)",mono:"var(--tl-font-mono)"},ahe=20,U0=4.25,Ir=16;function lhe(n,e){const t=n.w/e.w,r=n.h/e.h;return t<=1&&r<=1?n:t>r?{w:n.w/t,h:n.h/t}:{w:n.w/r,h:n.h/r}}async function che(n,e,t){var S,b,w;const{elements:r,files:s}=e,o={shapes:[],bindings:[],rootShapeIds:[],assets:[],schema:n.store.schema.serialize()},i=new Map,a=new Map,l=n.getCurrentPageId(),c=new Map,u=[],d=new Set;r.forEach(v=>{if(c.set(v.id,St()),v.boundElements!==null)for(const P of v.boundElements)P.type==="text"&&d.add(P.id)});let h=fv;for(const v of r){if(d.has(v.id))continue;const P=c.get(v.id),T={id:P,typeName:"shape",parentId:l,index:h,x:v.x,y:v.y,rotation:0,isLocked:v.locked,opacity:dhe(v.opacity),meta:{}};switch(v.angle!==0&&a.set(P,v.angle),v.groupIds&&v.groupIds.length>0?i.has(v.groupIds[0])?(S=i.get(v.groupIds[0]))==null||S.push(P):i.set(v.groupIds[0],[P]):u.push(P),v.type){case"rectangle":case"ellipse":case"diamond":{let I="",k="middle";if(v.boundElements!==null){for(const R of v.boundElements)if(R.type==="text"){const D=r.find(j=>j.id===R.id);D&&(I=D.text,k=yhe[D.textAlign])}}const A=v.backgroundColor==="transparent"?v.strokeColor:v.backgroundColor;o.shapes.push({...T,type:"geo",props:{...n.getShapeUtil("geo").getDefaultProps(),geo:v.type,url:v.link??"",w:v.width,h:v.height,size:Pf[v.strokeWidth]??"draw",color:Xd[A]??"black",richText:Kn(I),align:k,dash:Tf(v),fill:bhe(v)}});break}case"freedraw":{const I=v.points.map(([A,R,D=.5])=>({x:A,y:R,z:D})),k=ot.encodePoints(I);o.shapes.push({...T,type:"draw",props:{...n.getShapeUtil("draw").getDefaultProps(),dash:Tf(v),size:Pf[v.strokeWidth],color:Xd[v.strokeColor]??"black",segments:[{type:"free",path:k}]}});break}case"line":{if(v.points.slice().length<2)break;const k=rh(v.points.length);o.shapes.push({...T,type:"line",props:{...n.getShapeUtil("line").getDefaultProps(),dash:Tf(v),size:Pf[v.strokeWidth],color:Xd[v.strokeColor]??"black",spline:v.roundness?"cubic":"line",points:{...Object.fromEntries(v.points.map(([A,R],D)=>{const j=k[D];return[j,{id:j,index:j,x:A,y:R}]}))}}});break}case"arrow":{let I="";if(v.boundElements!==null){for(const j of v.boundElements)if(j.type==="text"){const _=r.find(M=>M.id===j.id);_&&(I=_.text)}}const k=v.points[0],A=v.points[v.points.length-1],R=c.get((b=v.startBinding)==null?void 0:b.elementId),D=c.get((w=v.endBinding)==null?void 0:w.elementId);o.shapes.push({...T,type:"arrow",props:{...n.getShapeUtil("arrow").getDefaultProps(),richText:Kn(I),kind:v.elbowed?"elbow":"arc",bend:xhe(v,k,A),dash:Tf(v),size:Pf[v.strokeWidth]??"m",color:Xd[v.strokeColor]??"black",start:{x:k[0],y:k[1]},end:{x:A[0],y:A[1]},arrowheadEnd:jk[v.endArrowhead]??"none",arrowheadStart:jk[v.startArrowhead]??"none"}}),R&&o.bindings.push({id:wl(),typeName:"binding",type:"arrow",fromId:P,toId:R,props:{terminal:"start",snap:"none",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}}),D&&o.bindings.push({id:wl(),typeName:"binding",type:"arrow",fromId:P,toId:D,props:{terminal:"end",snap:"none",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}});break}case"text":{const{size:I,scale:k}=hhe(v.fontSize);o.shapes.push({...T,type:"text",props:{...n.getShapeUtil("text").getDefaultProps(),size:I,scale:k,font:phe[v.fontFamily]??"draw",color:Xd[v.strokeColor]??"black",richText:Kn(v.text),textAlign:She[v.textAlign]}});break}case"image":{const I=s[v.fileId];if(!I)break;const k=Gl.createId();o.assets.push({id:k,typeName:"asset",type:"image",props:{w:v.width,h:v.height,fileSize:I.size,name:v.id??"Untitled",isAnimated:!1,mimeType:I.mimeType,src:I.dataURL},meta:{}}),o.shapes.push({...T,type:"image",props:{...n.getShapeUtil("image").getDefaultProps(),w:v.width,h:v.height,assetId:k}})}}h=Ns(h)}const f=t??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():void 0);n.putContentOntoCurrentPage(o,{point:f,select:!1,preserveIds:!0});for(const v of i.values())if(v.length>1){n.groupShapes(v);const P=n.getShape(v[0]);P!=null&&P.parentId&&Pr(P.parentId)&&u.push(P.parentId)}for(const[v,P]of a)n.select(v),n.rotateShapesBy([v],P);const g=Le(u.map(v=>n.getShape(v))),m=J.Common(g.map(v=>n.getShapePageBounds(v))),y=n.getViewportPageBounds().center;n.updateShapes(g.map(v=>{const P={x:(v.x??0)-(m.x+m.w/2),y:(v.y??0)-(m.y+m.h/2)};return{id:v.id,type:v.type,x:y.x+P.x,y:y.y+P.y}})),n.setSelectedShapes(u)}const dhe=n=>{const e=n/100;return e<.2?.1:e<.4?.25:e<.6?.5:e<.8?.75:1},Pf={1:"s",2:"m",3:"l",4:"xl"},uhe={16:"s",20:"m",28:"l",36:"xl"};function hhe(n){const e=uhe[n];return e?{size:e,scale:1}:n<16?{size:"s",scale:n/16}:n>36?{size:"xl",scale:n/36}:{size:"m",scale:1}}const phe={1:"draw",2:"sans",3:"mono"},fhe={gray:["#f8f9fa","#e9ecef","#ced4da","#868e96","#343a40"],red:["#fff5f5","#ffc9c9","#ff8787","#fa5252","#e03131"],pink:["#fff0f6","#fcc2d7","#f783ac","#e64980","#c2255c"],grape:["#f8f0fc","#eebefa","#da77f2","#be4bdb","#9c36b5"],violet:["#f3f0ff","#d0bfff","#9775fa","#7950f2","#6741d9"],indigo:["#edf2ff","#bac8ff","#748ffc","#4c6ef5","#3b5bdb"],blue:["#e7f5ff","#a5d8ff","#4dabf7","#228be6","#1971c2"],cyan:["#e3fafc","#99e9f2","#3bc9db","#15aabf","#0c8599"],teal:["#e6fcf5","#96f2d7","#38d9a9","#12b886","#099268"],green:["#ebfbee","#b2f2bb","#69db7c","#40c057","#2f9e44"],lime:["#f4fce3","#d8f5a2","#a9e34b","#82c91e","#66a80f"],yellow:["#fff9db","#ffec99","#ffd43b","#fab005","#f08c00"],orange:["#fff4e6","#ffd8a8","#ffa94d","#fd7e14","#e8590c"]};function Ao(n,e,t){const r=[0,1,2,3,4].map(s=>fhe[n][s]);return Object.fromEntries(r.map((s,o)=>[s,o<3?e:t]))}const Xd={...Ao("gray","grey","black"),...Ao("red","light-red","red"),...Ao("pink","light-red","red"),...Ao("grape","light-violet","violet"),...Ao("blue","light-blue","blue"),...Ao("cyan","light-blue","blue"),...Ao("teal","light-green","green"),...Ao("green","light-green","green"),...Ao("yellow","yellow","orange"),...Ao("orange","yellow","orange"),"#ffffff":"white","#000000":"black"},ghe={solid:"draw",dashed:"dashed",dotted:"dotted"},mhe={"cross-hatch":"pattern",hachure:"pattern",solid:"solid"},yhe={left:"start",center:"middle",right:"end"},She={left:"start",center:"middle",right:"end"},jk={arrow:"arrow",dot:"dot",triangle:"triangle",bar:"pipe"};function xhe(n,e,t){let r=0;if(n.points.length>2){const s=new C(e[0],e[1]),o=new C(t[0],t[1]),i=new C(n.points[1][0],n.points[1][1]),a=C.Sub(o,s),l=C.Per(a),c=C.Med(o,s),u=C.Sub(c,l),d=C.Add(c,l),h=C.NearestPointOnLineSegment(u,d,i,!1);r=C.Dist(h,c),C.Clockwise(h,o,c)&&(r*=-1)}return r}const Tf=n=>{let e=ghe[n.strokeStyle]??"draw";return e==="draw"&&n.roughness===0&&(e="solid"),e},bhe=n=>n.backgroundColor==="transparent"?"none":mhe[n.fillStyle]??"solid";var whe=/(^|[^`])`([^`]+)`(?!`)$/,vhe=/(^|[^`])`([^`]+)`(?!`)/g,dz=Za.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",nn(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e)=>n.content?`\`${e.renderChildren(n.content)}\``:"",addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Ll({find:whe,type:this.type})]},addPasteRules(){return[Na({find:vhe,type:this.type})]}}),Che=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,Phe=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,uz=Za.create({name:"highlight",addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:n=>n.getAttribute("data-color")||n.style.backgroundColor,renderHTML:n=>n.color?{"data-color":n.color,style:`background-color: ${n.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:"mark"}]},renderHTML({HTMLAttributes:n}){return["mark",nn(this.options.HTMLAttributes,n),0]},renderMarkdown:(n,e)=>`==${e.renderChildren(n)}==`,parseMarkdown:(n,e)=>e.applyMark("highlight",e.parseInline(n.tokens||[])),markdownTokenizer:{name:"highlight",level:"inline",start:n=>n.indexOf("=="),tokenize(n,e,t){const s=/^(==)([^=]+)(==)/.exec(n);if(s){const o=s[2].trim(),i=t.inlineTokens(o);return{type:"highlight",raw:s[0],text:o,tokens:i}}}},addCommands(){return{setHighlight:n=>({commands:e})=>e.setMark(this.name,n),toggleHighlight:n=>({commands:e})=>e.toggleMark(this.name,n),unsetHighlight:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[Ll({find:Che,type:this.type})]},addPasteRules(){return[Na({find:Phe,type:this.type})]}}),Cm=(n,e)=>{if(n==="slot")return 0;if(n instanceof Function)return n(e);const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");return[n,r,t]},The=/^\s*>\s$/,Ihe=Cs.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:n}){return Cm("blockquote",{...nn(this.options.HTMLAttributes,n),children:Cm("slot",{})})},parseMarkdown:(n,e)=>e.createNode("blockquote",void 0,e.parseChildren(n.tokens||[])),renderMarkdown:(n,e)=>{if(!n.content)return"";const t=">",r=[];return n.content.forEach(s=>{const a=e.renderChildren([s]).split(`
467
+ `).map(l=>l.trim()===""?t:`${t} ${l}`);r.push(a.join(`
468
+ `))}),r.join(`
469
+ ${t}
470
+ `)},addCommands(){return{setBlockquote:()=>({commands:n})=>n.wrapIn(this.name),toggleBlockquote:()=>({commands:n})=>n.toggleWrap(this.name),unsetBlockquote:()=>({commands:n})=>n.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[id({find:The,type:this.type})]}}),Ehe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,khe=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,_he=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,Mhe=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,Ahe=Za.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Cm("strong",{...nn(this.options.HTMLAttributes,n),children:Cm("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Ll({find:Ehe,type:this.type}),Ll({find:_he,type:this.type})]},addPasteRules(){return[Na({find:khe,type:this.type}),Na({find:Mhe,type:this.type})]}}),Rb=4,Dhe=/^```([a-z]+)?[\s\n]$/,Ohe=/^~~~([a-z]+)?[\s\n]$/,Rhe=Cs.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:Rb,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:n=>{var e;const{languageClassPrefix:t}=this.options;if(!t)return null;const o=[...((e=n.firstElementChild)==null?void 0:e.classList)||[]].filter(i=>i.startsWith(t)).map(i=>i.replace(t,""))[0];return o||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:n,HTMLAttributes:e}){return["pre",nn(this.options.HTMLAttributes,e),["code",{class:n.attrs.language?this.options.languageClassPrefix+n.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(n,e)=>{var t;return((t=n.raw)==null?void 0:t.startsWith("```"))===!1&&n.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:n.lang||null},n.text?[e.createTextNode(n.text)]:[])},renderMarkdown:(n,e)=>{var t;let r="";const s=((t=n.attrs)==null?void 0:t.language)||"";return n.content?r=[`\`\`\`${s}`,e.renderChildren(n.content),"```"].join(`
471
+ `):r=`\`\`\`${s}
472
+
473
+ \`\`\``,r},addCommands(){return{setCodeBlock:n=>({commands:e})=>e.setNode(this.name,n),toggleCodeBlock:n=>({commands:e})=>e.toggleNode(this.name,"paragraph",n)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:n,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!n||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!=null?e:Rb,{state:r}=n,{selection:s}=r,{$from:o,empty:i}=s;if(o.parent.type!==this.type)return!1;const a=" ".repeat(t);return i?n.commands.insertContent(a):n.commands.command(({tr:l})=>{const{from:c,to:u}=s,f=r.doc.textBetween(c,u,`
474
+ `,`
475
+ `).split(`
476
+ `).map(g=>a+g).join(`
477
+ `);return l.replaceWith(c,u,r.schema.text(f)),!0})},"Shift-Tab":({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!=null?e:Rb,{state:r}=n,{selection:s}=r,{$from:o,empty:i}=s;return o.parent.type!==this.type?!1:i?n.commands.command(({tr:a})=>{var l;const{pos:c}=o,u=o.start(),d=o.end(),f=r.doc.textBetween(u,d,`
478
+ `,`
479
+ `).split(`
480
+ `);let g=0,m=0;const y=c-u;for(let T=0;T<f.length;T+=1){if(m+f[T].length>=y){g=T;break}m+=f[T].length+1}const b=((l=f[g].match(/^ */))==null?void 0:l[0])||"",w=Math.min(b.length,t);if(w===0)return!0;let v=u;for(let T=0;T<g;T+=1)v+=f[T].length+1;return a.delete(v,v+w),c-v<=w&&a.setSelection(He.create(a.doc,v)),!0}):n.commands.command(({tr:a})=>{const{from:l,to:c}=s,h=r.doc.textBetween(l,c,`
481
+ `,`
482
+ `).split(`
483
+ `).map(f=>{var g;const m=((g=f.match(/^ */))==null?void 0:g[0])||"",y=Math.min(m.length,t);return f.slice(y)}).join(`
484
+ `);return a.replaceWith(l,c,r.schema.text(h)),!0})},Enter:({editor:n})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=n,{selection:t}=e,{$from:r,empty:s}=t;if(!s||r.parent.type!==this.type)return!1;const o=r.parentOffset===r.parent.nodeSize-2,i=r.parent.textContent.endsWith(`
485
+
486
+ `);return!o||!i?!1:n.chain().command(({tr:a})=>(a.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:n})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=n,{selection:t,doc:r}=e,{$from:s,empty:o}=t;if(!o||s.parent.type!==this.type||!(s.parentOffset===s.parent.nodeSize-2))return!1;const a=s.after();return a===void 0?!1:r.nodeAt(a)?n.commands.command(({tr:c})=>(c.setSelection(Je.near(r.resolve(a))),!0)):n.commands.exitCode()}}},addInputRules(){return[d0({find:Dhe,type:this.type,getAttributes:n=>({language:n[1]})}),d0({find:Ohe,type:this.type,getAttributes:n=>({language:n[1]})})]},addProseMirrorPlugins(){return[new Ht({key:new Sn("codeBlockVSCodeHandler"),props:{handlePaste:(n,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const t=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,o=s==null?void 0:s.mode;if(!t||!o)return!1;const{tr:i,schema:a}=n.state,l=a.text(t.replace(/\r\n?/g,`
487
+ `));return i.replaceSelectionWith(this.type.create({language:o},l)),i.selection.$from.parent.type!==this.type&&i.setSelection(He.near(i.doc.resolve(Math.max(0,i.selection.from-2)))),i.setMeta("paste",!0),n.dispatch(i),!0}}})]}}),Lhe=Cs.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
488
+
489
+ `):""}),jhe=Cs.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",nn(this.options.HTMLAttributes,n)]},renderText(){return`
490
+ `},renderMarkdown:()=>`
491
+ `,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:n,chain:e,state:t,editor:r})=>n.first([()=>n.exitCode(),()=>n.command(()=>{const{selection:s,storedMarks:o}=t;if(s.$from.parent.type.spec.isolating)return!1;const{keepMarks:i}=this.options,{splittableMarks:a}=r.extensionManager,l=o||s.$to.parentOffset&&s.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&l&&i){const d=l.filter(h=>a.includes(h.type.name));c.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Nhe=Cs.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(n=>({tag:`h${n}`,attrs:{level:n}}))},renderHTML({node:n,HTMLAttributes:e}){return[`h${this.options.levels.includes(n.attrs.level)?n.attrs.level:this.options.levels[0]}`,nn(this.options.HTMLAttributes,e),0]},parseMarkdown:(n,e)=>e.createNode("heading",{level:n.depth||1},e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>{var t;const r=(t=n.attrs)!=null&&t.level?parseInt(n.attrs.level,10):1,s="#".repeat(r);return n.content?`${s} ${e.renderChildren(n.content)}`:""},addCommands(){return{setHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.setNode(this.name,n):!1,toggleHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.toggleNode(this.name,"paragraph",n):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((n,e)=>({...n,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(n=>d0({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${n}})\\s$`),type:this.type,getAttributes:{level:n}}))}}),Fhe=Cs.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",nn(this.options.HTMLAttributes,n)]},markdownTokenName:"hr",parseMarkdown:(n,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:n,state:e})=>{if(!BJ(e,e.schema.nodes[this.name]))return!1;const{selection:t}=e,{$to:r}=t,s=n();return Ij(t)?s.insertContentAt(r.pos,{type:this.name}):s.insertContent({type:this.name}),s.command(({state:o,tr:i,dispatch:a})=>{if(a){const{$to:l}=i.selection,c=l.end();if(l.nodeAfter)l.nodeAfter.isTextblock?i.setSelection(He.create(i.doc,l.pos+1)):l.nodeAfter.isBlock?i.setSelection(Me.create(i.doc,l.pos)):i.setSelection(He.create(i.doc,l.pos));else{const u=o.schema.nodes[this.options.nextNodeType]||l.parent.type.contentMatch.defaultType,d=u==null?void 0:u.create();d&&(i.insert(c,d),i.setSelection(He.create(i.doc,c+1)))}i.scrollIntoView()}return!0}).run()}}},addInputRules(){return[FJ({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Bhe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,zhe=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,$he=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Hhe=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Uhe=Za.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",nn(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Ll({find:Bhe,type:this.type}),Ll({find:$he,type:this.type})]},addPasteRules(){return[Na({find:zhe,type:this.type}),Na({find:Hhe,type:this.type})]}});const Khe="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Whe="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",K0="numeric",W0="ascii",V0="alpha",Wu="asciinumeric",Pu="alphanumeric",G0="domain",hz="emoji",Vhe="scheme",Ghe="slashscheme",Lb="whitespace";function Yhe(n,e){return n in e||(e[n]=[]),e[n]}function xl(n,e,t){e[K0]&&(e[Wu]=!0,e[Pu]=!0),e[W0]&&(e[Wu]=!0,e[V0]=!0),e[Wu]&&(e[Pu]=!0),e[V0]&&(e[Pu]=!0),e[Pu]&&(e[G0]=!0),e[hz]&&(e[G0]=!0);for(const r in e){const s=Yhe(r,t);s.indexOf(n)<0&&s.push(n)}}function Xhe(n,e){const t={};for(const r in e)e[r].indexOf(n)>=0&&(t[r]=!0);return t}function Yr(n=null){this.j={},this.jr=[],this.jd=null,this.t=n}Yr.groups={};Yr.prototype={accepts(){return!!this.t},go(n){const e=this,t=e.j[n];if(t)return t;for(let r=0;r<e.jr.length;r++){const s=e.jr[r][0],o=e.jr[r][1];if(o&&s.test(n))return o}return e.jd},has(n,e=!1){return e?n in this.j:!!this.go(n)},ta(n,e,t,r){for(let s=0;s<n.length;s++)this.tt(n[s],e,t,r)},tr(n,e,t,r){r=r||Yr.groups;let s;return e&&e.j?s=e:(s=new Yr(e),t&&r&&xl(e,t,r)),this.jr.push([n,s]),s},ts(n,e,t,r){let s=this;const o=n.length;if(!o)return s;for(let i=0;i<o-1;i++)s=s.tt(n[i]);return s.tt(n[o-1],e,t,r)},tt(n,e,t,r){r=r||Yr.groups;const s=this;if(e&&e.j)return s.j[n]=e,e;const o=e;let i,a=s.go(n);if(a?(i=new Yr,Object.assign(i.j,a.j),i.jr.push.apply(i.jr,a.jr),i.jd=a.jd,i.t=a.t):i=new Yr,o){if(r)if(i.t&&typeof i.t=="string"){const l=Object.assign(Xhe(i.t,r),t);xl(o,l,r)}else t&&xl(o,t,r);i.t=o}return s.j[n]=i,i}};const qe=(n,e,t,r,s)=>n.ta(e,t,r,s),Kt=(n,e,t,r,s)=>n.tr(e,t,r,s),Nk=(n,e,t,r,s)=>n.ts(e,t,r,s),se=(n,e,t,r,s)=>n.tt(e,t,r,s),Ei="WORD",Y0="UWORD",pz="ASCIINUMERICAL",fz="ALPHANUMERICAL",Eh="LOCALHOST",X0="TLD",q0="UTLD",Qf="SCHEME",Ec="SLASH_SCHEME",tP="NUM",Z0="WS",nP="NL",Vu="OPENBRACE",Gu="CLOSEBRACE",Pm="OPENBRACKET",Tm="CLOSEBRACKET",Im="OPENPAREN",Em="CLOSEPAREN",km="OPENANGLEBRACKET",_m="CLOSEANGLEBRACKET",Mm="FULLWIDTHLEFTPAREN",Am="FULLWIDTHRIGHTPAREN",Dm="LEFTCORNERBRACKET",Om="RIGHTCORNERBRACKET",Rm="LEFTWHITECORNERBRACKET",Lm="RIGHTWHITECORNERBRACKET",jm="FULLWIDTHLESSTHAN",Nm="FULLWIDTHGREATERTHAN",Fm="AMPERSAND",Bm="APOSTROPHE",zm="ASTERISK",ma="AT",$m="BACKSLASH",Hm="BACKTICK",Um="CARET",ba="COLON",rP="COMMA",Km="DOLLAR",Ro="DOT",Wm="EQUALS",sP="EXCLAMATION",Os="HYPHEN",Yu="PERCENT",Vm="PIPE",Gm="PLUS",Ym="POUND",Xu="QUERY",oP="QUOTE",gz="FULLWIDTHMIDDLEDOT",iP="SEMI",Lo="SLASH",qu="TILDE",Xm="UNDERSCORE",mz="EMOJI",qm="SYM";var yz=Object.freeze({__proto__:null,ALPHANUMERICAL:fz,AMPERSAND:Fm,APOSTROPHE:Bm,ASCIINUMERICAL:pz,ASTERISK:zm,AT:ma,BACKSLASH:$m,BACKTICK:Hm,CARET:Um,CLOSEANGLEBRACKET:_m,CLOSEBRACE:Gu,CLOSEBRACKET:Tm,CLOSEPAREN:Em,COLON:ba,COMMA:rP,DOLLAR:Km,DOT:Ro,EMOJI:mz,EQUALS:Wm,EXCLAMATION:sP,FULLWIDTHGREATERTHAN:Nm,FULLWIDTHLEFTPAREN:Mm,FULLWIDTHLESSTHAN:jm,FULLWIDTHMIDDLEDOT:gz,FULLWIDTHRIGHTPAREN:Am,HYPHEN:Os,LEFTCORNERBRACKET:Dm,LEFTWHITECORNERBRACKET:Rm,LOCALHOST:Eh,NL:nP,NUM:tP,OPENANGLEBRACKET:km,OPENBRACE:Vu,OPENBRACKET:Pm,OPENPAREN:Im,PERCENT:Yu,PIPE:Vm,PLUS:Gm,POUND:Ym,QUERY:Xu,QUOTE:oP,RIGHTCORNERBRACKET:Om,RIGHTWHITECORNERBRACKET:Lm,SCHEME:Qf,SEMI:iP,SLASH:Lo,SLASH_SCHEME:Ec,SYM:qm,TILDE:qu,TLD:X0,UNDERSCORE:Xm,UTLD:q0,UWORD:Y0,WORD:Ei,WS:Z0});const vi=/[a-z]/,qd=new RegExp("\\p{L}","u"),jb=new RegExp("\\p{Emoji}","u"),Ci=/\d/,Nb=/\s/,Fk="\r",Fb=`
492
+ `,qhe="️",Zhe="‍",Bb="";let If=null,Ef=null;function Jhe(n=[]){const e={};Yr.groups=e;const t=new Yr;If==null&&(If=Bk(Khe)),Ef==null&&(Ef=Bk(Whe)),se(t,"'",Bm),se(t,"{",Vu),se(t,"}",Gu),se(t,"[",Pm),se(t,"]",Tm),se(t,"(",Im),se(t,")",Em),se(t,"<",km),se(t,">",_m),se(t,"(",Mm),se(t,")",Am),se(t,"「",Dm),se(t,"」",Om),se(t,"『",Rm),se(t,"』",Lm),se(t,"<",jm),se(t,">",Nm),se(t,"&",Fm),se(t,"*",zm),se(t,"@",ma),se(t,"`",Hm),se(t,"^",Um),se(t,":",ba),se(t,",",rP),se(t,"$",Km),se(t,".",Ro),se(t,"=",Wm),se(t,"!",sP),se(t,"-",Os),se(t,"%",Yu),se(t,"|",Vm),se(t,"+",Gm),se(t,"#",Ym),se(t,"?",Xu),se(t,'"',oP),se(t,"/",Lo),se(t,";",iP),se(t,"~",qu),se(t,"_",Xm),se(t,"\\",$m),se(t,"・",gz);const r=Kt(t,Ci,tP,{[K0]:!0});Kt(r,Ci,r);const s=Kt(r,vi,pz,{[Wu]:!0}),o=Kt(r,qd,fz,{[Pu]:!0}),i=Kt(t,vi,Ei,{[W0]:!0});Kt(i,Ci,s),Kt(i,vi,i),Kt(s,Ci,s),Kt(s,vi,s);const a=Kt(t,qd,Y0,{[V0]:!0});Kt(a,vi),Kt(a,Ci,o),Kt(a,qd,a),Kt(o,Ci,o),Kt(o,vi),Kt(o,qd,o);const l=se(t,Fb,nP,{[Lb]:!0}),c=se(t,Fk,Z0,{[Lb]:!0}),u=Kt(t,Nb,Z0,{[Lb]:!0});se(t,Bb,u),se(c,Fb,l),se(c,Bb,u),Kt(c,Nb,u),se(u,Fk),se(u,Fb),Kt(u,Nb,u),se(u,Bb,u);const d=Kt(t,jb,mz,{[hz]:!0});se(d,"#"),Kt(d,jb,d),se(d,qhe,d);const h=se(d,Zhe);se(h,"#"),Kt(h,jb,d);const f=[[vi,i],[Ci,s]],g=[[vi,null],[qd,a],[Ci,o]];for(let m=0;m<If.length;m++)aa(t,If[m],X0,Ei,f);for(let m=0;m<Ef.length;m++)aa(t,Ef[m],q0,Y0,g);xl(X0,{tld:!0,ascii:!0},e),xl(q0,{utld:!0,alpha:!0},e),aa(t,"file",Qf,Ei,f),aa(t,"mailto",Qf,Ei,f),aa(t,"http",Ec,Ei,f),aa(t,"https",Ec,Ei,f),aa(t,"ftp",Ec,Ei,f),aa(t,"ftps",Ec,Ei,f),xl(Qf,{scheme:!0,ascii:!0},e),xl(Ec,{slashscheme:!0,ascii:!0},e),n=n.sort((m,y)=>m[0]>y[0]?1:-1);for(let m=0;m<n.length;m++){const y=n[m][0],b=n[m][1]?{[Vhe]:!0}:{[Ghe]:!0};y.indexOf("-")>=0?b[G0]=!0:vi.test(y)?Ci.test(y)?b[Wu]=!0:b[W0]=!0:b[K0]=!0,Nk(t,y,y,b)}return Nk(t,"localhost",Eh,{ascii:!0}),t.jd=new Yr(qm),{start:t,tokens:Object.assign({groups:e},yz)}}function Sz(n,e){const t=Qhe(e.replace(/[A-Z]/g,a=>a.toLowerCase())),r=t.length,s=[];let o=0,i=0;for(;i<r;){let a=n,l=null,c=0,u=null,d=-1,h=-1;for(;i<r&&(l=a.go(t[i]));)a=l,a.accepts()?(d=0,h=0,u=a):d>=0&&(d+=t[i].length,h++),c+=t[i].length,o+=t[i].length,i++;o-=d,i-=h,c-=d,s.push({t:u.t,v:e.slice(o-c,o),s:o-c,e:o})}return s}function Qhe(n){const e=[],t=n.length;let r=0;for(;r<t;){let s=n.charCodeAt(r),o,i=s<55296||s>56319||r+1===t||(o=n.charCodeAt(r+1))<56320||o>57343?n[r]:n.slice(r,r+2);e.push(i),r+=i.length}return e}function aa(n,e,t,r,s){let o;const i=e.length;for(let a=0;a<i-1;a++){const l=e[a];n.j[l]?o=n.j[l]:(o=new Yr(r),o.jr=s.slice(),n.j[l]=o),n=o}return o=new Yr(t),o.jr=s.slice(),n.j[e[i-1]]=o,o}function Bk(n){const e=[],t=[];let r=0,s="0123456789";for(;r<n.length;){let o=0;for(;s.indexOf(n[r+o])>=0;)o++;if(o>0){e.push(t.join(""));for(let i=parseInt(n.substring(r,r+o),10);i>0;i--)t.pop();r+=o}else t.push(n[r]),r++}return e}const kh={defaultProtocol:"http",events:null,format:zk,formatHref:zk,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function aP(n,e=null){let t=Object.assign({},kh);n&&(t=Object.assign(t,n instanceof aP?n.o:n));const r=t.ignoreTags,s=[];for(let o=0;o<r.length;o++)s.push(r[o].toUpperCase());this.o=t,e&&(this.defaultRender=e),this.ignoreTags=s}aP.prototype={o:kh,ignoreTags:[],defaultRender(n){return n},check(n){return this.get("validate",n.toString(),n)},get(n,e,t){const r=e!=null;let s=this.o[n];return s&&(typeof s=="object"?(s=t.t in s?s[t.t]:kh[n],typeof s=="function"&&r&&(s=s(e,t))):typeof s=="function"&&r&&(s=s(e,t.t,t)),s)},getObj(n,e,t){let r=this.o[n];return typeof r=="function"&&e!=null&&(r=r(e,t.t,t)),r},render(n){const e=n.render(this);return(this.get("render",null,n)||this.defaultRender)(e,n.t,n)}};function zk(n){return n}function xz(n,e){this.t="token",this.v=n,this.tk=e}xz.prototype={isLink:!1,toString(){return this.v},toHref(n){return this.toString()},toFormattedString(n){const e=this.toString(),t=n.get("truncate",e,this),r=n.get("format",e,this);return t&&r.length>t?r.substring(0,t)+"…":r},toFormattedHref(n){return n.get("formatHref",this.toHref(n.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(n=kh.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(n),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(n){return{type:this.t,value:this.toFormattedString(n),isLink:this.isLink,href:this.toFormattedHref(n),start:this.startIndex(),end:this.endIndex()}},validate(n){return n.get("validate",this.toString(),this)},render(n){const e=this,t=this.toHref(n.get("defaultProtocol")),r=n.get("formatHref",t,this),s=n.get("tagName",t,e),o=this.toFormattedString(n),i={},a=n.get("className",t,e),l=n.get("target",t,e),c=n.get("rel",t,e),u=n.getObj("attributes",t,e),d=n.getObj("events",t,e);return i.href=r,a&&(i.class=a),l&&(i.target=l),c&&(i.rel=c),u&&Object.assign(i,u),{tagName:s,attributes:i,content:o,eventListeners:d}}};function jS(n,e){class t extends xz{constructor(s,o){super(s,o),this.t=n}}for(const r in e)t.prototype[r]=e[r];return t.t=n,t}const $k=jS("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Hk=jS("text"),epe=jS("nl"),kf=jS("url",{isLink:!0,toHref(n=kh.defaultProtocol){return this.hasProtocol()?this.v:`${n}://${this.v}`},hasProtocol(){const n=this.tk;return n.length>=2&&n[0].t!==Eh&&n[1].t===ba}}),Ds=n=>new Yr(n);function tpe({groups:n}){const e=n.domain.concat([Fm,zm,ma,$m,Hm,Um,Km,Wm,Os,tP,Yu,Vm,Gm,Ym,Lo,qm,qu,Xm]),t=[Bm,ba,rP,Ro,sP,Yu,Xu,oP,iP,km,_m,Vu,Gu,Tm,Pm,Im,Em,Mm,Am,Dm,Om,Rm,Lm,jm,Nm],r=[Fm,Bm,zm,$m,Hm,Um,Km,Wm,Os,Vu,Gu,Yu,Vm,Gm,Ym,Xu,Lo,qm,qu,Xm],s=Ds(),o=se(s,qu);qe(o,r,o),qe(o,n.domain,o);const i=Ds(),a=Ds(),l=Ds();qe(s,n.domain,i),qe(s,n.scheme,a),qe(s,n.slashscheme,l),qe(i,r,o),qe(i,n.domain,i);const c=se(i,ma);se(o,ma,c),se(a,ma,c),se(l,ma,c);const u=se(o,Ro);qe(u,r,o),qe(u,n.domain,o);const d=Ds();qe(c,n.domain,d),qe(d,n.domain,d);const h=se(d,Ro);qe(h,n.domain,d);const f=Ds($k);qe(h,n.tld,f),qe(h,n.utld,f),se(c,Eh,f);const g=se(d,Os);se(g,Os,g),qe(g,n.domain,d),qe(f,n.domain,d),se(f,Ro,h),se(f,Os,g);const m=se(f,ba);qe(m,n.numeric,$k);const y=se(i,Os),S=se(i,Ro);se(y,Os,y),qe(y,n.domain,i),qe(S,r,o),qe(S,n.domain,i);const b=Ds(kf);qe(S,n.tld,b),qe(S,n.utld,b),qe(b,n.domain,i),qe(b,r,o),se(b,Ro,S),se(b,Os,y),se(b,ma,c);const w=se(b,ba),v=Ds(kf);qe(w,n.numeric,v);const P=Ds(kf),T=Ds();qe(P,e,P),qe(P,t,T),qe(T,e,P),qe(T,t,T),se(b,Lo,P),se(v,Lo,P);const I=se(a,ba),k=se(l,ba),A=se(k,Lo),R=se(A,Lo);qe(a,n.domain,i),se(a,Ro,S),se(a,Os,y),qe(l,n.domain,i),se(l,Ro,S),se(l,Os,y),qe(I,n.domain,P),se(I,Lo,P),se(I,Xu,P),qe(R,n.domain,P),qe(R,e,P),se(R,Lo,P);const D=[[Vu,Gu],[Pm,Tm],[Im,Em],[km,_m],[Mm,Am],[Dm,Om],[Rm,Lm],[jm,Nm]];for(let j=0;j<D.length;j++){const[_,M]=D[j],O=se(P,_);se(T,_,O),se(O,M,P);const N=Ds(kf);qe(O,e,N);const B=Ds();qe(O,t),qe(N,e,N),qe(N,t,B),qe(B,e,N),qe(B,t,B),se(N,M,P),se(B,M,P)}return se(s,Eh,b),se(s,nP,epe),{start:s,tokens:yz}}function npe(n,e,t){let r=t.length,s=0,o=[],i=[];for(;s<r;){let a=n,l=null,c=null,u=0,d=null,h=-1;for(;s<r&&!(l=a.go(t[s].t));)i.push(t[s++]);for(;s<r&&(c=l||a.go(t[s].t));)l=null,a=c,a.accepts()?(h=0,d=a):h>=0&&h++,s++,u++;if(h<0)s-=u,s<r&&(i.push(t[s]),s++);else{i.length>0&&(o.push(zb(Hk,e,i)),i=[]),s-=h,u-=h;const f=d.t,g=t.slice(s-u,s);o.push(zb(f,e,g))}}return i.length>0&&o.push(zb(Hk,e,i)),o}function zb(n,e,t){const r=t[0].s,s=t[t.length-1].e,o=e.slice(r,s);return new n(o,t)}const rpe=typeof console<"u"&&console&&console.warn||(()=>{}),spe="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",It={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function ope(){return Yr.groups={},It.scanner=null,It.parser=null,It.tokenQueue=[],It.pluginQueue=[],It.customSchemes=[],It.initialized=!1,It}function Uk(n,e=!1){if(It.initialized&&rpe(`linkifyjs: already initialized - will not register custom scheme "${n}" ${spe}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))throw new Error(`linkifyjs: incorrect scheme format.
493
+ 1. Must only contain digits, lowercase ASCII letters or "-"
494
+ 2. Cannot start or end with "-"
495
+ 3. "-" cannot repeat`);It.customSchemes.push([n,e])}function ipe(){It.scanner=Jhe(It.customSchemes);for(let n=0;n<It.tokenQueue.length;n++)It.tokenQueue[n][1]({scanner:It.scanner});It.parser=tpe(It.scanner.tokens);for(let n=0;n<It.pluginQueue.length;n++)It.pluginQueue[n][1]({scanner:It.scanner,parser:It.parser});return It.initialized=!0,It}function lP(n){return It.initialized||ipe(),npe(It.parser.start,n,Sz(It.scanner.start,n))}lP.scan=Sz;function bz(n,e=null,t=null){if(e&&typeof e=="object"){if(t)throw Error(`linkifyjs: Invalid link type ${e}; must be a string`);t=e,e=null}const r=new aP(t),s=lP(n),o=[];for(let i=0;i<s.length;i++){const a=s[i];a.isLink&&(!e||a.t===e)&&r.check(a)&&o.push(a.toFormattedObject(r))}return o}var cP="[\0-   ᠎ -\u2029  ]",ape=new RegExp(cP),lpe=new RegExp(`${cP}$`),cpe=new RegExp(cP,"g");function dpe(n){return n.length===1?n[0].isLink:n.length===3&&n[1].isLink?["()","[]"].includes(n[0].value+n[2].value):!1}function upe(n){return new Ht({key:new Sn("autolink"),appendTransaction:(e,t,r)=>{const s=e.some(c=>c.docChanged)&&!t.doc.eq(r.doc),o=e.some(c=>c.getMeta("preventAutolink"));if(!s||o)return;const{tr:i}=r,a=Sj(t.doc,[...e]);if(Tj(a).forEach(({newRange:c})=>{const u=BZ(r.doc,c,f=>f.isTextblock);let d,h;if(u.length>1)d=u[0],h=r.doc.textBetween(d.pos,d.pos+d.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(c.from,c.to," "," ");if(!lpe.test(f))return;d=u[0],h=r.doc.textBetween(d.pos,c.to,void 0," ")}if(d&&h){const f=h.split(ape).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],m=d.pos+h.lastIndexOf(g);if(!g)return!1;const y=lP(g).map(S=>S.toObject(n.defaultProtocol));if(!dpe(y))return!1;y.filter(S=>S.isLink).map(S=>({...S,from:m+S.start+1,to:m+S.end+1})).filter(S=>r.schema.marks.code?!r.doc.rangeHasMark(S.from,S.to,r.schema.marks.code):!0).filter(S=>n.validate(S.value)).filter(S=>n.shouldAutoLink(S.value)).forEach(S=>{j1(S.from,S.to,r.doc).some(b=>b.mark.type===n.type)||i.addMark(S.from,S.to,n.type.create({href:S.href}))})}}),!!i.steps.length)return i}})}function hpe(n){return new Ht({key:new Sn("handleClickLink"),props:{handleClick:(e,t,r)=>{var s,o;if(r.button!==0||!e.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{const l=r.target;if(!l)return!1;const c=n.editor.view.dom;i=l.closest("a"),i&&!c.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(n.enableClickSelection&&(a=n.editor.commands.extendMarkRange(n.type.name)),n.openOnClick){const l=Pj(e.state,n.type.name),c=(s=i.href)!=null?s:l.href,u=(o=i.target)!=null?o:l.target;c&&(window.open(c,u),a=!0)}return a}}})}function ppe(n){return new Ht({key:new Sn("handlePasteLink"),props:{handlePaste:(e,t,r)=>{const{shouldAutoLink:s}=n,{state:o}=e,{selection:i}=o,{empty:a}=i;if(a)return!1;let l="";r.content.forEach(u=>{l+=u.textContent});const c=bz(l,{defaultProtocol:n.defaultProtocol}).find(u=>u.isLink&&u.value===l);return!l||!c||s!==void 0&&!s(c.value)?!1:n.editor.commands.setMark(n.type,{href:c.href})}}})}function dl(n,e){const t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const s=typeof r=="string"?r:r.scheme;s&&t.push(s)}),!n||n.replace(cpe,"").match(new RegExp(`^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var fpe=Za.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(n=>{if(typeof n=="string"){Uk(n);return}Uk(n.scheme,n.optionalSlashes)})},onDestroy(){ope()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(n,e)=>!!dl(n,e.protocols),validate:n=>!!n,shouldAutoLink:n=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(n),t=/^[a-z][a-z0-9+.-]*:/i.test(n);if(e||t&&!n.includes("@"))return!0;const s=(n.includes("@")?n.split("@").pop():n).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||!/\./.test(s))}}},addAttributes(){return{href:{default:null,parseHTML(n){return n.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:n=>{const e=n.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!dl(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:n}){return this.options.isAllowedUri(n.href,{defaultValidate:e=>!!dl(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",nn(this.options.HTMLAttributes,n),0]:["a",nn(this.options.HTMLAttributes,{...n,href:""}),0]},markdownTokenName:"link",parseMarkdown:(n,e)=>e.applyMark("link",e.parseInline(n.tokens||[]),{href:n.href,title:n.title||null}),renderMarkdown:(n,e)=>{var t,r,s,o;const i=(r=(t=n.attrs)==null?void 0:t.href)!=null?r:"",a=(o=(s=n.attrs)==null?void 0:s.title)!=null?o:"",l=e.renderChildren(n);return a?`[${l}](${i} "${a}")`:`[${l}](${i})`},addCommands(){return{setLink:n=>({chain:e})=>{const{href:t}=n;return this.options.isAllowedUri(t,{defaultValidate:r=>!!dl(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,n).setMeta("preventAutolink",!0).run():!1},toggleLink:n=>({chain:e})=>{const{href:t}=n||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:r=>!!dl(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,n,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:n})=>n().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[Na({find:n=>{const e=[];if(n){const{protocols:t,defaultProtocol:r}=this.options,s=bz(n).filter(o=>o.isLink&&this.options.isAllowedUri(o.value,{defaultValidate:i=>!!dl(i,t),protocols:t,defaultProtocol:r}));s.length&&s.forEach(o=>{this.options.shouldAutoLink(o.value)&&e.push({text:o.value,data:{href:o.href},index:o.start})})}return e},type:this.type,getAttributes:n=>{var e;return{href:(e=n.data)==null?void 0:e.href}}})]},addProseMirrorPlugins(){const n=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&n.push(upe({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:s=>!!dl(s,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),n.push(hpe({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&n.push(ppe({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),n}}),gpe=Object.defineProperty,mpe=(n,e)=>{for(var t in e)gpe(n,t,{get:e[t],enumerable:!0})},ype="listItem",Kk="textStyle",Wk=/^\s*([-+*])\s$/,wz=Cs.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:n}){return["ul",nn(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>n.type!=="list"||n.ordered?[]:{type:"bulletList",content:n.items?e.parseChildren(n.items):[]},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
496
+ `):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(ype,this.editor.getAttributes(Kk)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let n=id({find:Wk,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(n=id({find:Wk,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(Kk),editor:this.editor})),[n]}}),vz=Cs.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:n}){return["li",nn(this.options.HTMLAttributes,n),0]},markdownTokenName:"list_item",parseMarkdown:(n,e)=>{if(n.type!=="list_item")return[];let t=[];if(n.tokens&&n.tokens.length>0)if(n.tokens.some(s=>s.type==="paragraph"))t=e.parseChildren(n.tokens);else{const s=n.tokens[0];if(s&&s.type==="text"&&s.tokens&&s.tokens.length>0){if(t=[{type:"paragraph",content:e.parseInline(s.tokens)}],n.tokens.length>1){const i=n.tokens.slice(1),a=e.parseChildren(i);t.push(...a)}}else t=e.parseChildren(n.tokens)}return t.length===0&&(t=[{type:"paragraph",content:[]}]),{type:"listItem",content:t}},renderMarkdown:(n,e,t)=>z1(n,e,r=>{var s,o;return r.parentType==="bulletList"?"- ":r.parentType==="orderedList"?`${(((o=(s=r.meta)==null?void 0:s.parentAttrs)==null?void 0:o.start)||1)+r.index}. `:"- "},t),addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),Spe={};mpe(Spe,{findListItemPos:()=>Sp,getNextListDepth:()=>dP,handleBackspace:()=>J0,handleDelete:()=>Q0,hasListBefore:()=>Cz,hasListItemAfter:()=>xpe,hasListItemBefore:()=>Pz,listItemHasSubList:()=>Tz,nextListIsDeeper:()=>Iz,nextListIsHigher:()=>Ez});var Sp=(n,e)=>{const{$from:t}=e.selection,r=pn(n,e.schema);let s=null,o=t.depth,i=t.pos,a=null;for(;o>0&&a===null;)s=t.node(o),s.type===r?a=o:(o-=1,i-=1);return a===null?null:{$pos:e.doc.resolve(i),depth:a}},dP=(n,e)=>{const t=Sp(n,e);if(!t)return!1;const[,r]=qZ(e,n,t.$pos.pos+4);return r},Cz=(n,e,t)=>{const{$anchor:r}=n.selection,s=Math.max(0,r.pos-2),o=n.doc.resolve(s).node();return!(!o||!t.includes(o.type.name))},Pz=(n,e)=>{var t;const{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-2);return!(s.index()===0||((t=s.nodeBefore)==null?void 0:t.type.name)!==n)},Tz=(n,e,t)=>{if(!t)return!1;const r=pn(n,e.schema);let s=!1;return t.descendants(o=>{o.type===r&&(s=!0)}),s},J0=(n,e,t)=>{if(n.commands.undoInputRule())return!0;if(n.state.selection.from!==n.state.selection.to)return!1;if(!ja(n.state,e)&&Cz(n.state,e,t)){const{$anchor:a}=n.state.selection,l=n.state.doc.resolve(a.before()-1),c=[];l.node().descendants((h,f)=>{h.type.name===e&&c.push({node:h,pos:f})});const u=c.at(-1);if(!u)return!1;const d=n.state.doc.resolve(l.start()+u.pos+1);return n.chain().cut({from:a.start()-1,to:a.end()+1},d.end()).joinForward().run()}if(!ja(n.state,e)||!eJ(n.state))return!1;const r=Sp(e,n.state);if(!r)return!1;const o=n.state.doc.resolve(r.$pos.pos-2).node(r.depth),i=Tz(e,n.state,o);return Pz(e,n.state)&&!i?n.commands.joinItemBackward():n.chain().liftListItem(e).run()},Iz=(n,e)=>{const t=dP(n,e),r=Sp(n,e);return!r||!t?!1:t>r.depth},Ez=(n,e)=>{const t=dP(n,e),r=Sp(n,e);return!r||!t?!1:t<r.depth},Q0=(n,e)=>{if(!ja(n.state,e)||!QZ(n.state,e))return!1;const{selection:t}=n.state,{$from:r,$to:s}=t;return!t.empty&&r.sameParent(s)?!1:Iz(e,n.state)?n.chain().focus(n.state.selection.from+4).lift(e).joinBackward().run():Ez(e,n.state)?n.chain().joinForward().joinBackward().run():n.commands.joinItemForward()},xpe=(n,e)=>{var t;const{$anchor:r}=e.selection,s=e.doc.resolve(r.pos-r.parentOffset-2);return!(s.index()===s.parent.childCount-1||((t=s.nodeAfter)==null?void 0:t.type.name)!==n)},kz=qt.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Q0(n,t)&&(e=!0)}),e},"Mod-Delete":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&Q0(n,t)&&(e=!0)}),e},Backspace:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&J0(n,t,r)&&(e=!0)}),e},"Mod-Backspace":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&J0(n,t,r)&&(e=!0)}),e}}}}),Vk=/^(\s*)(\d+)\.\s+(.*)$/,bpe=/^\s/;function wpe(n){const e=[];let t=0,r=0;for(;t<n.length;){const s=n[t],o=s.match(Vk);if(!o)break;const[,i,a,l]=o,c=i.length;let u=l,d=t+1;const h=[s];for(;d<n.length;){const f=n[d];if(f.match(Vk))break;if(f.trim()==="")h.push(f),u+=`
497
+ `,d+=1;else if(f.match(bpe))h.push(f),u+=`
498
+ ${f.slice(c+2)}`,d+=1;else break}e.push({indent:c,number:parseInt(a,10),content:u.trim(),raw:h.join(`
499
+ `)}),r=d,t=d}return[e,r]}function _z(n,e,t){var r;const s=[];let o=0;for(;o<n.length;){const i=n[o];if(i.indent===e){const a=i.content.split(`
500
+ `),l=((r=a[0])==null?void 0:r.trim())||"",c=[];l&&c.push({type:"paragraph",raw:l,tokens:t.inlineTokens(l)});const u=a.slice(1).join(`
501
+ `).trim();if(u){const f=t.blockTokens(u);c.push(...f)}let d=o+1;const h=[];for(;d<n.length&&n[d].indent>e;)h.push(n[d]),d+=1;if(h.length>0){const f=Math.min(...h.map(m=>m.indent)),g=_z(h,f,t);c.push({type:"list",ordered:!0,start:h[0].number,items:g,raw:h.map(m=>m.raw).join(`
502
+ `)})}s.push({type:"list_item",raw:i.raw,tokens:c}),o=d}else o+=1}return s}function vpe(n,e){return n.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];const r=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(s=>{if(s.type==="paragraph"||s.type==="list"||s.type==="blockquote"||s.type==="code")r.push(...e.parseChildren([s]));else if(s.type==="text"&&s.tokens){const o=e.parseChildren([s]);r.push({type:"paragraph",content:o})}else{const o=e.parseChildren([s]);o.length>0&&r.push(...o)}}),{type:"listItem",content:r}})}var Cpe="listItem",Gk="textStyle",Yk=/^(\d+)\.\s$/,Mz=Cs.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:n=>n.hasAttribute("start")?parseInt(n.getAttribute("start")||"",10):1},type:{default:null,parseHTML:n=>n.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:n}){const{start:e,...t}=n;return e===1?["ol",nn(this.options.HTMLAttributes,t),0]:["ol",nn(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>{if(n.type!=="list"||!n.ordered)return[];const t=n.start||1,r=n.items?vpe(n.items,e):[];return t!==1?{type:"orderedList",attrs:{start:t},content:r}:{type:"orderedList",content:r}},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
503
+ `):"",markdownTokenizer:{name:"orderedList",level:"block",start:n=>{const e=n.match(/^(\s*)(\d+)\.\s+/),t=e==null?void 0:e.index;return t!==void 0?t:-1},tokenize:(n,e,t)=>{var r;const s=n.split(`
504
+ `),[o,i]=wpe(s);if(o.length===0)return;const a=_z(o,0,t);return a.length===0?void 0:{type:"list",ordered:!0,start:((r=o[0])==null?void 0:r.number)||1,items:a,raw:s.slice(0,i).join(`
505
+ `)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(Cpe,this.editor.getAttributes(Gk)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let n=id({find:Yk,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(n=id({find:Yk,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(Gk)}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1],editor:this.editor})),[n]}}),Ppe=/^\s*(\[([( |x])?\])\s$/,Tpe=Cs.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:n=>{const e=n.getAttribute("data-checked");return e===""||e==="true"},renderHTML:n=>({"data-checked":n.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51}]},renderHTML({node:n,HTMLAttributes:e}){return["li",nn(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:n.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(n,e)=>{const t=[];if(n.tokens&&n.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(n.tokens))):n.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:n.text})])):t.push(e.createNode("paragraph",{},[])),n.nestedTokens&&n.nestedTokens.length>0){const r=e.parseChildren(n.nestedTokens);t.push(...r)}return e.createNode("taskItem",{checked:n.checked||!1},t)},renderMarkdown:(n,e)=>{var t;const s=`- [${(t=n.attrs)!=null&&t.checked?"x":" "}] `;return z1(n,e,s)},addKeyboardShortcuts(){const n={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...n,Tab:()=>this.editor.commands.sinkListItem(this.name)}:n},addNodeView(){return({node:n,HTMLAttributes:e,getPos:t,editor:r})=>{const s=document.createElement("li"),o=document.createElement("label"),i=document.createElement("span"),a=document.createElement("input"),l=document.createElement("div"),c=d=>{var h,f;a.ariaLabel=((f=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:f.call(h,d,a.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};c(n),o.contentEditable="false",a.type="checkbox",a.addEventListener("mousedown",d=>d.preventDefault()),a.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){a.checked=!a.checked;return}const{checked:h}=d.target;r.isEditable&&typeof t=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:f})=>{const g=t();if(typeof g!="number")return!1;const m=f.doc.nodeAt(g);return f.setNodeMarkup(g,void 0,{...m==null?void 0:m.attrs,checked:h}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(n,h)||(a.checked=!a.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{s.setAttribute(d,h)}),s.dataset.checked=n.attrs.checked,a.checked=n.attrs.checked,o.append(a,i),s.append(o,l),Object.entries(e).forEach(([d,h])=>{s.setAttribute(d,h)});let u=new Set(Object.keys(e));return{dom:s,contentDOM:l,update:d=>{if(d.type!==this.type)return!1;s.dataset.checked=d.attrs.checked,a.checked=d.attrs.checked,c(d);const h=r.extensionManager.attributes,f=mh(d,h),g=new Set(Object.keys(f)),m=this.options.HTMLAttributes;return u.forEach(y=>{g.has(y)||(y in m?s.setAttribute(y,m[y]):s.removeAttribute(y))}),Object.entries(f).forEach(([y,S])=>{S==null?y in m?s.setAttribute(y,m[y]):s.removeAttribute(y):s.setAttribute(y,S)}),u=g,!0}}}},addInputRules(){return[id({find:Ppe,type:this.type,getAttributes:n=>({checked:n[n.length-1]==="x"})})]}}),Ipe=Cs.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:n}){return["ul",nn(this.options.HTMLAttributes,n,{"data-type":this.name}),0]},parseMarkdown:(n,e)=>e.createNode("taskList",{},e.parseChildren(n.items||[])),renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,`
506
+ `):"",markdownTokenizer:{name:"taskList",level:"block",start(n){var e;const t=(e=n.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))==null?void 0:e.index;return t!==void 0?t:-1},tokenize(n,e,t){const r=o=>{const i=u0(o,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:a=>({indentLevel:a[1].length,mainContent:a[4],checked:a[3].toLowerCase()==="x"}),createToken:(a,l)=>({type:"taskItem",raw:"",mainContent:a.mainContent,indentLevel:a.indentLevel,checked:a.checked,text:a.mainContent,tokens:t.inlineTokens(a.mainContent),nestedTokens:l}),customNestedParser:r},t);return i?[{type:"taskList",raw:i.raw,items:i.items}]:t.blockTokens(o)},s=u0(n,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:o=>({indentLevel:o[1].length,mainContent:o[4],checked:o[3].toLowerCase()==="x"}),createToken:(o,i)=>({type:"taskItem",raw:"",mainContent:o.mainContent,indentLevel:o.indentLevel,checked:o.checked,text:o.mainContent,tokens:t.inlineTokens(o.mainContent),nestedTokens:i}),customNestedParser:r},t);if(s)return{type:"taskList",raw:s.raw,items:s.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:n})=>n.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});qt.create({name:"listKit",addExtensions(){const n=[];return this.options.bulletList!==!1&&n.push(wz.configure(this.options.bulletList)),this.options.listItem!==!1&&n.push(vz.configure(this.options.listItem)),this.options.listKeymap!==!1&&n.push(kz.configure(this.options.listKeymap)),this.options.orderedList!==!1&&n.push(Mz.configure(this.options.orderedList)),this.options.taskItem!==!1&&n.push(Tpe.configure(this.options.taskItem)),this.options.taskList!==!1&&n.push(Ipe.configure(this.options.taskList)),n}});var Xk="&nbsp;",Epe=" ",kpe=Cs.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:n}){return["p",nn(this.options.HTMLAttributes,n),0]},parseMarkdown:(n,e)=>{const t=n.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);const r=e.parseInline(t);return r.length===1&&r[0].type==="text"&&(r[0].text===Xk||r[0].text===Epe)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(n,e)=>{if(!n)return"";const t=Array.isArray(n.content)?n.content:[];return t.length===0?Xk:e.renderChildren(t)},addCommands(){return{setParagraph:()=>({commands:n})=>n.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),_pe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Mpe=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Ape=Za.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["s",nn(this.options.HTMLAttributes,n),0]},markdownTokenName:"del",parseMarkdown:(n,e)=>e.applyMark("strike",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`~~${e.renderChildren(n)}~~`,addCommands(){return{setStrike:()=>({commands:n})=>n.setMark(this.name),toggleStrike:()=>({commands:n})=>n.toggleMark(this.name),unsetStrike:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Ll({find:_pe,type:this.type})]},addPasteRules(){return[Na({find:Mpe,type:this.type})]}}),Dpe=Cs.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""}),Ope=Za.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["u",nn(this.options.HTMLAttributes,n),0]},parseMarkdown(n,e){return e.applyMark(this.name||"underline",e.parseInline(n.tokens||[]))},renderMarkdown(n,e){return`++${e.renderChildren(n)}++`},markdownTokenizer:{name:"underline",level:"inline",start(n){return n.indexOf("++")},tokenize(n,e,t){const s=/^(\+\+)([\s\S]+?)(\+\+)/.exec(n);if(!s)return;const o=s[2].trim();return{type:"underline",raw:s[0],text:o,tokens:t.inlineTokens(o)}}},addCommands(){return{setUnderline:()=>({commands:n})=>n.setMark(this.name),toggleUnderline:()=>({commands:n})=>n.toggleMark(this.name),unsetUnderline:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function Rpe(n={}){return new Ht({view(e){return new Lpe(e,n)}})}class Lpe{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(s=>{let o=i=>{this[s](i)};return e.dom.addEventListener(s,o),{name:s,handler:o}})}destroy(){this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){this.cursorPos!=null&&t.doc!=e.state.doc&&(this.cursorPos>e.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,s=this.editorView.dom,o=s.getBoundingClientRect(),i=o.width/s.offsetWidth,a=o.height/s.offsetHeight;if(t){let d=e.nodeBefore,h=e.nodeAfter;if(d||h){let f=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(f){let g=f.getBoundingClientRect(),m=d?g.bottom:g.top;d&&h&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*a;r={left:g.left,right:g.right,top:m-y,bottom:m+y}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*i;r={left:d.left-h,right:d.left+h,top:d.top,bottom:d.bottom}}let l=this.editorView.dom.offsetParent;this.element||(this.element=l.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,u;if(!l||l==document.body&&getComputedStyle(l).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=l.getBoundingClientRect(),h=d.width/l.offsetWidth,f=d.height/l.offsetHeight;c=d.left-l.scrollLeft*h,u=d.top-l.scrollTop*f}this.element.style.left=(r.left-c)/i+"px",this.element.style.top=(r.top-u)/a+"px",this.element.style.width=(r.right-r.left)/i+"px",this.element.style.height=(r.bottom-r.top)/a+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}dragover(e){if(!this.editorView.editable)return;let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),s=r&&r.type.spec.disableDropCursor,o=typeof s=="function"?s(this.editorView,t,e):s;if(t&&!o){let i=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let a=cL(this.editorView.state.doc,i,this.editorView.dragging.slice);a!=null&&(i=a)}this.setCursor(i),this.scheduleRemoval(5e3)}}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class Vt extends Je{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return Vt.valid(r)?new Vt(r):Je.near(r)}content(){return ye.empty}eq(e){return e instanceof Vt&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new Vt(e.resolve(t.pos))}getBookmark(){return new uP(this.anchor)}static valid(e){let t=e.parent;if(t.isTextblock||!jpe(e)||!Npe(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let s=t.contentMatchAt(e.index()).defaultType;return s&&s.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&Vt.valid(e))return e;let s=e.pos,o=null;for(let i=e.depth;;i--){let a=e.node(i);if(t>0?e.indexAfter(i)<a.childCount:e.index(i)>0){o=a.child(t>0?e.indexAfter(i):e.index(i)-1);break}else if(i==0)return null;s+=t;let l=e.doc.resolve(s);if(Vt.valid(l))return l}for(;;){let i=t>0?o.firstChild:o.lastChild;if(!i){if(o.isAtom&&!o.isText&&!Me.isSelectable(o)){e=e.doc.resolve(s+o.nodeSize*t),r=!1;continue e}break}o=i,s+=t;let a=e.doc.resolve(s);if(Vt.valid(a))return a}return null}}}Vt.prototype.visible=!1;Vt.findFrom=Vt.findGapCursorFrom;Je.jsonID("gapcursor",Vt);class uP{constructor(e){this.pos=e}map(e){return new uP(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return Vt.valid(t)?new Vt(t):Je.near(t)}}function Az(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function jpe(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t-1);;s=s.lastChild){if(s.childCount==0&&!s.inlineContent||Az(s.type))return!0;if(s.inlineContent)return!1}}return!0}function Npe(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let s=r.child(t);;s=s.firstChild){if(s.childCount==0&&!s.inlineContent||Az(s.type))return!0;if(s.inlineContent)return!1}}return!0}function Fpe(){return new Ht({props:{decorations:Hpe,createSelectionBetween(n,e,t){return e.pos==t.pos&&Vt.valid(t)?new Vt(t):null},handleClick:zpe,handleKeyDown:Bpe,handleDOMEvents:{beforeinput:$pe}}})}const Bpe=dj({ArrowLeft:_f("horiz",-1),ArrowRight:_f("horiz",1),ArrowUp:_f("vert",-1),ArrowDown:_f("vert",1)});function _f(n,e){const t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,s,o){let i=r.selection,a=e>0?i.$to:i.$from,l=i.empty;if(i instanceof He){if(!o.endOfTextblock(t)||a.depth==0)return!1;l=!1,a=r.doc.resolve(e>0?a.after():a.before())}let c=Vt.findGapCursorFrom(a,e,l);return c?(s&&s(r.tr.setSelection(new Vt(c))),!0):!1}}function zpe(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!Vt.valid(r))return!1;let s=n.posAtCoords({left:t.clientX,top:t.clientY});return s&&s.inside>-1&&Me.isSelectable(n.state.doc.nodeAt(s.inside))?!1:(n.dispatch(n.state.tr.setSelection(new Vt(r))),!0)}function $pe(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof Vt))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let s=ne.empty;for(let i=r.length-1;i>=0;i--)s=ne.from(r[i].createAndFill(null,s));let o=n.state.tr.replace(t.pos,t.pos,new ye(s,0,0));return o.setSelection(He.near(o.doc.resolve(t.pos+1))),n.dispatch(o),!1}function Hpe(n){if(!(n.selection instanceof Vt))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",Nt.create(n.doc,[_r.widget(n.selection.head,e,{key:"gapcursor"})])}var Zm=200,_n=function(){};_n.prototype.append=function(e){return e.length?(e=_n.from(e),!this.length&&e||e.length<Zm&&this.leafAppend(e)||this.length<Zm&&e.leafPrepend(this)||this.appendInner(e)):this};_n.prototype.prepend=function(e){return e.length?_n.from(e).append(this):this};_n.prototype.appendInner=function(e){return new Upe(this,e)};_n.prototype.slice=function(e,t){return e===void 0&&(e=0),t===void 0&&(t=this.length),e>=t?_n.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};_n.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};_n.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};_n.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var s=[];return this.forEach(function(o,i){return s.push(e(o,i))},t,r),s};_n.from=function(e){return e instanceof _n?e:e&&e.length?new Dz(e):_n.empty};var Dz=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(s,o){return s==0&&o==this.length?this:new e(this.values.slice(s,o))},e.prototype.getInner=function(s){return this.values[s]},e.prototype.forEachInner=function(s,o,i,a){for(var l=o;l<i;l++)if(s(this.values[l],a+l)===!1)return!1},e.prototype.forEachInvertedInner=function(s,o,i,a){for(var l=o-1;l>=i;l--)if(s(this.values[l],a+l)===!1)return!1},e.prototype.leafAppend=function(s){if(this.length+s.length<=Zm)return new e(this.values.concat(s.flatten()))},e.prototype.leafPrepend=function(s){if(this.length+s.length<=Zm)return new e(s.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(_n);_n.empty=new Dz([]);var Upe=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return r<this.left.length?this.left.get(r):this.right.get(r-this.left.length)},e.prototype.forEachInner=function(r,s,o,i){var a=this.left.length;if(s<a&&this.left.forEachInner(r,s,Math.min(o,a),i)===!1||o>a&&this.right.forEachInner(r,Math.max(s-a,0),Math.min(this.length,o)-a,i+a)===!1)return!1},e.prototype.forEachInvertedInner=function(r,s,o,i){var a=this.left.length;if(s>a&&this.right.forEachInvertedInner(r,s-a,Math.max(o,a)-a,i+a)===!1||o<a&&this.left.forEachInvertedInner(r,Math.min(s,a),o,i)===!1)return!1},e.prototype.sliceInner=function(r,s){if(r==0&&s==this.length)return this;var o=this.left.length;return s<=o?this.left.slice(r,s):r>=o?this.right.slice(r-o,s-o):this.left.slice(r,o).append(this.right.slice(0,s-o))},e.prototype.leafAppend=function(r){var s=this.right.leafAppend(r);if(s)return new e(this.left,s)},e.prototype.leafPrepend=function(r){var s=this.left.leafPrepend(r);if(s)return new e(s,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(_n);const Kpe=500;class lo{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let s,o;t&&(s=this.remapping(r,this.items.length),o=s.maps.length);let i=e.tr,a,l,c=[],u=[];return this.items.forEach((d,h)=>{if(!d.step){s||(s=this.remapping(r,h+1),o=s.maps.length),o--,u.push(d);return}if(s){u.push(new jo(d.map));let f=d.step.map(s.slice(o)),g;f&&i.maybeStep(f).doc&&(g=i.mapping.maps[i.mapping.maps.length-1],c.push(new jo(g,void 0,void 0,c.length+u.length))),o--,g&&s.appendMap(g,o)}else i.maybeStep(d.step);if(d.selection)return a=s?d.selection.map(s.slice(o)):d.selection,l=new lo(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:l,transform:i,selection:a}}addTransform(e,t,r,s){let o=[],i=this.eventCount,a=this.items,l=!s&&a.length?a.get(a.length-1):null;for(let u=0;u<e.steps.length;u++){let d=e.steps[u].invert(e.docs[u]),h=new jo(e.mapping.maps[u],d,t),f;(f=l&&l.merge(h))&&(h=f,u?o.pop():a=a.slice(0,a.length-1)),o.push(h),t&&(i++,t=void 0),s||(l=h)}let c=i-r.depth;return c>Vpe&&(a=Wpe(a,c),i-=c),new lo(a.append(o),i)}remapping(e,t){let r=new dh;return this.items.forEach((s,o)=>{let i=s.mirrorOffset!=null&&o-s.mirrorOffset>=e?r.maps.length-s.mirrorOffset:void 0;r.appendMap(s.map,i)},e,t),r}addMaps(e){return this.eventCount==0?this:new lo(this.items.append(e.map(t=>new jo(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;let r=[],s=Math.max(0,this.items.length-t),o=e.mapping,i=e.steps.length,a=this.eventCount;this.items.forEach(h=>{h.selection&&a--},s);let l=t;this.items.forEach(h=>{let f=o.getMirror(--l);if(f==null)return;i=Math.min(i,f);let g=o.maps[f];if(h.step){let m=e.steps[f].invert(e.docs[f]),y=h.selection&&h.selection.map(o.slice(l+1,f));y&&a++,r.push(new jo(g,m,y))}else r.push(new jo(g))},s);let c=[];for(let h=t;h<i;h++)c.push(new jo(o.maps[h]));let u=this.items.slice(0,s).append(c).append(r),d=new lo(u,a);return d.emptyItemCount()>Kpe&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,s=[],o=0;return this.items.forEach((i,a)=>{if(a>=e)s.push(i),i.selection&&o++;else if(i.step){let l=i.step.map(t.slice(r)),c=l&&l.getMap();if(r--,c&&t.appendMap(c,r),l){let u=i.selection&&i.selection.map(t.slice(r));u&&o++;let d=new jo(c.invert(),l,u),h,f=s.length-1;(h=s.length&&s[f].merge(d))?s[f]=h:s.push(d)}}else i.map&&r--},this.items.length,0),new lo(_n.from(s.reverse()),o)}}lo.empty=new lo(_n.empty,0);function Wpe(n,e){let t;return n.forEach((r,s)=>{if(r.selection&&e--==0)return t=s,!1}),n.slice(t)}class jo{constructor(e,t,r,s){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=s}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new jo(t.getMap().invert(),t,this.selection)}}}class ya{constructor(e,t,r,s,o){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=s,this.prevComposition=o}}const Vpe=20;function Gpe(n,e,t,r){let s=t.getMeta(Il),o;if(s)return s.historyState;t.getMeta(qpe)&&(n=new ya(n.done,n.undone,null,0,-1));let i=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(i&&i.getMeta(Il))return i.getMeta(Il).redo?new ya(n.done.addTransform(t,void 0,r,eg(e)),n.undone,qk(t.mapping.maps),n.prevTime,n.prevComposition):new ya(n.done,n.undone.addTransform(t,void 0,r,eg(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(i&&i.getMeta("addToHistory")===!1)){let a=t.getMeta("composition"),l=n.prevTime==0||!i&&n.prevComposition!=a&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Ype(t,n.prevRanges)),c=i?$b(n.prevRanges,t.mapping):qk(t.mapping.maps);return new ya(n.done.addTransform(t,l?e.selection.getBookmark():void 0,r,eg(e)),lo.empty,c,t.time,a??n.prevComposition)}else return(o=t.getMeta("rebased"))?new ya(n.done.rebased(t,o),n.undone.rebased(t,o),$b(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new ya(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),$b(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Ype(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,s)=>{for(let o=0;o<e.length;o+=2)r<=e[o+1]&&s>=e[o]&&(t=!0)}),t}function qk(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,s,o,i)=>e.push(o,i));return e}function $b(n,e){if(!n)return null;let t=[];for(let r=0;r<n.length;r+=2){let s=e.map(n[r],1),o=e.map(n[r+1],-1);s<=o&&t.push(s,o)}return t}function Xpe(n,e,t){let r=eg(e),s=Il.get(e).spec.config,o=(t?n.undone:n.done).popEvent(e,r);if(!o)return null;let i=o.selection.resolve(o.transform.doc),a=(t?n.done:n.undone).addTransform(o.transform,e.selection.getBookmark(),s,r),l=new ya(t?a:o.remaining,t?o.remaining:a,null,0,-1);return o.transform.setSelection(i).setMeta(Il,{redo:t,historyState:l})}let Hb=!1,Zk=null;function eg(n){let e=n.plugins;if(Zk!=e){Hb=!1,Zk=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){Hb=!0;break}}return Hb}const Il=new Sn("history"),qpe=new Sn("closeHistory");function Zpe(n={}){return n={depth:n.depth||100,newGroupDelay:n.newGroupDelay||500},new Ht({key:Il,state:{init(){return new ya(lo.empty,lo.empty,null,0,-1)},apply(e,t,r){return Gpe(t,r,e,n)}},config:n,props:{handleDOMEvents:{beforeinput(e,t){let r=t.inputType,s=r=="historyUndo"?Rz:r=="historyRedo"?Lz:null;return!s||!e.editable?!1:(t.preventDefault(),s(e.state,e.dispatch))}}}})}function Oz(n,e){return(t,r)=>{let s=Il.getState(t);if(!s||(n?s.undone:s.done).eventCount==0)return!1;if(r){let o=Xpe(s,t,n);o&&r(e?o.scrollIntoView():o)}return!0}}const Rz=Oz(!1,!0),Lz=Oz(!0,!0);qt.create({name:"characterCount",addOptions(){return{limit:null,mode:"textSize",textCounter:n=>n.length,wordCounter:n=>n.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=n=>{const e=(n==null?void 0:n.node)||this.editor.state.doc;if(((n==null?void 0:n.mode)||this.options.mode)==="textSize"){const r=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(r)}return e.nodeSize},this.storage.words=n=>{const e=(n==null?void 0:n.node)||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let n=!1;return[new Ht({key:new Sn("characterCount"),appendTransaction:(e,t,r)=>{if(n)return;const s=this.options.limit;if(s==null||s===0){n=!0;return}const o=this.storage.characters({node:r.doc});if(o>s){const i=o-s,a=0,l=i;console.warn(`[CharacterCount] Initial content exceeded limit of ${s} characters. Content was automatically trimmed.`);const c=r.tr.deleteRange(a,l);return n=!0,c}n=!0},filterTransaction:(e,t)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const s=this.storage.characters({node:t.doc}),o=this.storage.characters({node:e.doc});if(o<=r||s>r&&o>r&&o<=s)return!0;if(s>r&&o>r&&o>s||!e.getMeta("paste"))return!1;const a=e.selection.$head.pos,l=o-r,c=a-l,u=a;return e.deleteRange(c,u),!(this.storage.characters({node:e.doc})>r)}})]}});var Jpe=qt.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Rpe(this.options)]}});qt.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Ht({key:new Sn("focus"),props:{decorations:({doc:n,selection:e})=>{const{isEditable:t,isFocused:r}=this.editor,{anchor:s}=e,o=[];if(!t||!r)return Nt.create(n,[]);let i=0;this.options.mode==="deepest"&&n.descendants((l,c)=>{if(l.isText)return;if(!(s>=c&&s<=c+l.nodeSize-1))return!1;i+=1});let a=0;return n.descendants((l,c)=>{if(l.isText||!(s>=c&&s<=c+l.nodeSize-1))return!1;if(a+=1,this.options.mode==="deepest"&&i-a>0||this.options.mode==="shallowest"&&a>1)return this.options.mode==="deepest";o.push(_r.node(c,c+l.nodeSize,{class:this.options.className}))}),Nt.create(n,o)}}})]}});var Qpe=qt.create({name:"gapCursor",addProseMirrorPlugins(){return[Fpe()]},extendNodeSchema(n){var e;const t={name:n.name,options:n.options,storage:n.storage};return{allowGapCursor:(e=gt(Ee(n,"allowGapCursor",t)))!=null?e:null}}}),Jk="placeholder";function efe(n){return n.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}qt.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:Jk,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){const n=this.options.dataAttribute?`data-${efe(this.options.dataAttribute)}`:`data-${Jk}`;return[new Ht({key:new Sn("placeholder"),props:{decorations:({doc:e,selection:t})=>{const r=this.editor.isEditable||!this.options.showOnlyWhenEditable,{anchor:s}=t,o=[];if(!r)return null;const i=this.editor.isEmpty;return e.descendants((a,l)=>{const c=s>=l&&s<=l+a.nodeSize,u=!a.isLeaf&&Ky(a);if((c||!this.options.showOnlyCurrent)&&u){const d=[this.options.emptyNodeClass];i&&d.push(this.options.emptyEditorClass);const h=_r.node(l,l+a.nodeSize,{class:d.join(" "),[n]:typeof this.options.placeholder=="function"?this.options.placeholder({editor:this.editor,node:a,pos:l,hasAnchor:c}):this.options.placeholder});o.push(h)}return this.options.includeChildren}),Nt.create(e,o)}}})]}});qt.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:n,options:e}=this;return[new Ht({key:new Sn("selection"),props:{decorations(t){return t.selection.empty||n.isFocused||!n.isEditable||Ij(t.selection)||n.view.dragging?null:Nt.create(t.doc,[_r.inline(t.selection.from,t.selection.to,{class:e.className})])}}})]}});function Qk({types:n,node:e}){return e&&Array.isArray(n)&&n.includes(e.type)||(e==null?void 0:e.type)===n}var tfe=qt.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var n;const e=new Sn(this.name),t=this.options.node||((n=this.editor.schema.topNodeType.contentMatch.defaultType)==null?void 0:n.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,s])=>s).filter(s=>(this.options.notAfter||[]).concat(t).includes(s.name));return[new Ht({key:e,appendTransaction:(s,o,i)=>{const{doc:a,tr:l,schema:c}=i,u=e.getState(i),d=a.content.size,h=c.nodes[t];if(u)return l.insert(d,h.create())},state:{init:(s,o)=>{const i=o.tr.doc.lastChild;return!Qk({node:i,types:r})},apply:(s,o)=>{if(!s.docChanged||s.getMeta("__uniqueIDTransaction"))return o;const i=s.doc.lastChild;return!Qk({node:i,types:r})}}})]}}),nfe=qt.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:n,dispatch:e})=>Rz(n,e),redo:()=>({state:n,dispatch:e})=>Lz(n,e)}},addProseMirrorPlugins(){return[Zpe(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),rfe=qt.create({name:"starterKit",addExtensions(){var n,e,t,r;const s=[];return this.options.bold!==!1&&s.push(Ahe.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(Ihe.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(wz.configure(this.options.bulletList)),this.options.code!==!1&&s.push(dz.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(Rhe.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(Lhe.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(Jpe.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(Qpe.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(jhe.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(Nhe.configure(this.options.heading)),this.options.undoRedo!==!1&&s.push(nfe.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&s.push(Fhe.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(Uhe.configure(this.options.italic)),this.options.listItem!==!1&&s.push(vz.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(kz.configure((n=this.options)==null?void 0:n.listKeymap)),this.options.link!==!1&&s.push(fpe.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&s.push(Mz.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(kpe.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Ape.configure(this.options.strike)),this.options.text!==!1&&s.push(Dpe.configure(this.options.text)),this.options.underline!==!1&&s.push(Ope.configure((t=this.options)==null?void 0:t.underline)),this.options.trailingNode!==!1&&s.push(tfe.configure((r=this.options)==null?void 0:r.trailingNode)),s}});const jz={tldraw_draw:{normal:{normal:{family:"tldraw_draw",src:{url:"tldraw_draw",format:"woff2"},weight:"normal"},bold:{family:"tldraw_draw",src:{url:"tldraw_draw_bold",format:"woff2"},weight:"bold"}},italic:{normal:{family:"tldraw_draw",src:{url:"tldraw_draw_italic",format:"woff2"},weight:"normal",style:"italic"},bold:{family:"tldraw_draw",src:{url:"tldraw_draw_italic_bold",format:"woff2"},weight:"bold",style:"italic"}}},tldraw_sans:{normal:{normal:{family:"tldraw_sans",src:{url:"tldraw_sans",format:"woff2"},weight:"normal",style:"normal"},bold:{family:"tldraw_sans",src:{url:"tldraw_sans_bold",format:"woff2"},weight:"bold",style:"normal"}},italic:{normal:{family:"tldraw_sans",src:{url:"tldraw_sans_italic",format:"woff2"},weight:"normal",style:"italic"},bold:{family:"tldraw_sans",src:{url:"tldraw_sans_italic_bold",format:"woff2"},weight:"bold",style:"italic"}}},tldraw_serif:{normal:{normal:{family:"tldraw_serif",src:{url:"tldraw_serif",format:"woff2"},weight:"normal",style:"normal"},bold:{family:"tldraw_serif",src:{url:"tldraw_serif_bold",format:"woff2"},weight:"bold",style:"normal"}},italic:{normal:{family:"tldraw_serif",src:{url:"tldraw_serif_italic",format:"woff2"},weight:"normal",style:"italic"},bold:{family:"tldraw_serif",src:{url:"tldraw_serif_italic_bold",format:"woff2"},weight:"bold",style:"italic"}}},tldraw_mono:{normal:{normal:{family:"tldraw_mono",src:{url:"tldraw_mono",format:"woff2"},weight:"normal",style:"normal"},bold:{family:"tldraw_mono",src:{url:"tldraw_mono_bold",format:"woff2"},weight:"bold",style:"normal"}},italic:{normal:{family:"tldraw_mono",src:{url:"tldraw_mono_italic",format:"woff2"},weight:"normal",style:"italic"},bold:{family:"tldraw_mono",src:{url:"tldraw_mono_italic_bold",format:"woff2"},weight:"bold",style:"italic"}}}},sfe=Et(jz).flatMap(n=>Et(n).flatMap(e=>Object.values(e))),ofe=qt.create({name:"keyboardShiftEnterHandler",addKeyboardShortcuts(){return{"Shift-Enter":({editor:n})=>n.commands.enter()}}});dz.config.excludes=void 0;uz.config.priority=1100;const xp=[rfe.configure({blockquote:!1,codeBlock:!1,horizontalRule:!1,link:{openOnClick:!1,autolink:!0},trailingNode:{notAfter:["paragraph","bulletList","orderedList","listItem"]}}),uz,ofe,Aj.TextDirection.configure({direction:"auto"})],ife=new Vn;function hP(n,e){return ife.get(e,()=>{var s;const t=((s=n.getTextOptions().tipTapConfig)==null?void 0:s.extensions)??xp;return KZ(e,t).replaceAll('<p dir="auto"></p>',"<p><br /></p>")??""})}function _h(n,e){return`<div class="tl-rich-text">${hP(n,e)}</div>`}const afe=new Vn;function Wt(n){return n.content.length===1&&!n.content[0].content}function Hl(n,e){return Wt(e)?"":afe.get(e,()=>{var r;const t=((r=n.getTextOptions().tipTapConfig)==null?void 0:r.extensions)??xp;return VZ(e,t,{blockSeparator:`
507
+ `})})}function lfe(n,e){var r;const t=((r=n.getTextOptions().tipTapConfig)==null?void 0:r.extensions)??xp;return WZ(e,t)}function Nz(n,e,t){for(const i of n.marks)i.type.name==="bold"&&e.weight!=="bold"&&(e={...e,weight:"bold"}),i.type.name==="italic"&&e.style!=="italic"&&(e={...e,style:"italic"}),i.type.name==="code"&&e.family!=="tldraw_mono"&&(e={...e,family:"tldraw_mono"});const r=un(jz,e.family);if(!r)return e;const s=un(r,e.style);if(!s)return e;const o=un(s,e.weight);return o&&t(o),e}const cfe=" ",Qu=class Qu{static normalizeText(e){return e.replace(Qu.fixNewLines,`
508
+ `)}static normalizeTextForDom(e){return e.replace(Qu.fixNewLines,`
509
+ `).split(`
510
+ `).map(t=>t||" ").join(`
511
+ `)}};E(Qu,"fixNewLines",/\r?\n|\r/g);let Jm=Qu;const dfe=/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;function Fz(n){return dfe.test(n)}function ufe(n){return n.replace(/\t/g,cfe)}function hfe(n){const e=n.split(`
512
+ `);for(;e[0]&&e[0].trim().length===0;)e.shift();let t=1/0;for(const r of e)if(r.trim().length>0){const s=r.length-r.trimStart().length;t=Math.min(t,s)}return e.map(r=>r.slice(t)).join(`
513
+ `)}const Bz={"&amp;":"&","&quot;":'"',"&apos;":"'","&#27;":"'","&#34;":'"',"&#38;":"&","&#39;":"'","&#8211;":"–","&#8212;":"—","&#8216;":"‘","&#8217;":"’","&#8220;":"“","&#8221;":"”","&#8230;":"…"},pfe=new RegExp(Object.keys(Bz).join("|"),"g");function zz(n){return n.replace(pfe,e=>Bz[e])}function ffe(n){return n.replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function gfe(n){return ffe(hfe(ufe(n)))}const mfe=5e3,yfe=10*1024*1024;function Sfe(n,e){n.registerExternalAssetHandler("file",async t=>xfe(n,t,e)),n.registerExternalAssetHandler("url",async t=>wfe(n,t,e)),n.registerExternalContentHandler("svg-text",async t=>vfe(n,t)),n.registerExternalContentHandler("embed",t=>Cfe(n,t)),n.registerExternalContentHandler("files",async t=>Pfe(n,t,e)),n.registerExternalContentHandler("file-replace",async t=>bfe(n,t,e)),n.registerExternalContentHandler("text",async t=>Tfe(n,t)),n.registerExternalContentHandler("url",async t=>Ife(n,t,e)),n.registerExternalContentHandler("tldraw",async t=>Efe(n,t)),n.registerExternalContentHandler("excalidraw",async t=>kfe(n,t))}async function xfe(n,{file:e,assetId:t},r){pP(e,r)||be(!1,"File checks failed");const o=await Uz(e,r,t),i=await n.uploadAsset(o,e);return o.props.src=i.src,i.meta&&(o.meta={...o.meta,...i.meta}),Gl.create(o)}async function bfe(n,{file:e,shapeId:t,isImage:r},s){pP(e,s)||be(!1,"File checks failed");const i=n.getShape(t);i||be(!1,"Shape not found");const a=$_(await e.arrayBuffer()),l=Gl.createId(a);n.createTemporaryAssetPreview(l,e);const c=await $z(e,l,r,!r);if(n.createAssets([c]),i.type==="image"){const d=i,h=d.props.crop;let f=c.props.w,g=c.props.h,m=d.x,y=d.y,S=h;if(h){const b=tde(d,c.props.w,c.props.h);S=b.crop,f=b.w,g=b.h,m=b.x,y=b.y}n.updateShapes([{id:d.id,type:d.type,props:{assetId:l,crop:S,w:f,h:g},x:m,y}])}else i.type==="video"&&n.updateShapes([{id:i.id,type:i.type,props:{assetId:l,w:c.props.w,h:c.props.h}}]);const u=await n.getAssetForExternalContent({type:"file",file:e,assetId:l});return n.updateAssets([{...u,id:l}]),u}async function wfe(n,{url:e},{toasts:t,msg:r}){var o,i,a,l,c;let s;try{const d=await(await $i(e,{method:"GET",mode:"no-cors"})).text(),h=new DOMParser().parseFromString(d,"text/html");s={image:((o=h.head.querySelector('meta[property="og:image"]'))==null?void 0:o.getAttribute("content"))??"",favicon:((i=h.head.querySelector('link[rel="apple-touch-icon"]'))==null?void 0:i.getAttribute("href"))??((a=h.head.querySelector('link[rel="icon"]'))==null?void 0:a.getAttribute("href"))??"",title:((l=h.head.querySelector('meta[property="og:title"]'))==null?void 0:l.getAttribute("content"))??e,description:((c=h.head.querySelector('meta[property="og:description"]'))==null?void 0:c.getAttribute("content"))??""},s.image.startsWith("http")||(s.image=new URL(s.image,e).href),s.favicon.startsWith("http")||(s.favicon=new URL(s.favicon,e).href)}catch(u){console.error(u),t.addToast({title:r("assets.url.failed"),severity:"error"}),s={image:"",favicon:"",title:"",description:""}}return{id:Gl.createId(z_(e)),typeName:"asset",type:"bookmark",props:{src:e,description:s.description,image:s.image,favicon:s.favicon,title:s.title},meta:{}}}async function vfe(n,{point:e,text:t}){const r=e??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():n.getViewportPageBounds().center),s=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("svg");if(!s)throw new Error("No <svg/> element present");let o=parseFloat(s.getAttribute("width")||"0"),i=parseFloat(s.getAttribute("height")||"0");if(!(o&&i)){document.body.appendChild(s);const l=s.getBoundingClientRect();document.body.removeChild(s),o=l.width,i=l.height}const a=await n.getAssetForExternalContent({type:"file",file:new File([t],"asset.svg",{type:"image/svg+xml"})});if(!a)throw Error("Could not create an asset");Hz(n,[a],r)}function Cfe(n,{point:e,url:t,embed:r}){const s=e??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():n.getViewportPageBounds().center),{width:o,height:i}=r,a=St(),l=ws(new C(s.x-(o||450)/2,s.y-(i||450)/2),n),c={id:a,type:"embed",x:l.x,y:l.y,props:{w:o,h:i,url:t}};n.canCreateShape(c)&&n.createShape(c).select(a)}async function Pfe(n,{point:e,files:t},r){const{acceptedImageMimeTypes:s=fd,toasts:o,msg:i}=r;if(t.length>n.options.maxFilesAtOnce){o.addToast({title:i("assets.files.amount-too-many"),severity:"error"});return}const a=e??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():n.getViewportPageBounds().center),l=new C(a.x,a.y),c=[],u=[];for(const d of t){if(!pP(d,r))continue;const f=await Uz(d,r);s.includes(d.type)&&n.createTemporaryAssetPreview(f.id,d),c.push(f),u.push({asset:f,file:d})}Promise.allSettled(u.map(async d=>{try{const h=await n.getAssetForExternalContent({type:"file",file:d.file});if(!h)throw Error("Could not create an asset");n.updateAssets([{...h,id:d.asset.id}])}catch(h){o.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error(h),n.deleteAssets([d.asset.id]);return}})),Hz(n,c,l)}async function Tfe(n,{point:e,text:t,html:r}){const s=e??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():n.getViewportPageBounds().center),o=n.getShapeUtil("text").getDefaultProps(),i=gfe(t),a=r?lfe(n,r):Kn(i);let l,c,u,d="middle";const h=r??i.replace(/\n/g,"<br>"),f=r?a.content.length>1:i.split(`
514
+ `).length>1,g=Fz(i);f&&(d=f?g?"end":"start":"middle");const m=n.textMeasure.measureHtml(h,{...Dr,fontFamily:Ha[o.font],fontSize:dd[o.size],maxWidth:null}),y=Math.min(f?n.getViewportPageBounds().width*.9:920,Math.max(200,n.getViewportPageBounds().width*.9));if(m.w>y){const w=n.textMeasure.measureHtml(h,{...Dr,fontFamily:Ha[o.font],fontSize:dd[o.size],maxWidth:y});l=w.w,c=w.h,u=!1,d=g?"end":"start"}else l=Math.max(m.w,10),c=Math.max(m.h,10),u=!0;s.y-c/2<n.getViewportPageBounds().minY+40&&(s.y=n.getViewportPageBounds().minY+40+c/2);const S=ws(new C(s.x-l/2,s.y-c/2),n),b=St();n.createShapes([{id:b,type:"text",x:S.x,y:S.y,props:{richText:a,textAlign:d,autoSize:u,w:l}}])}async function Ife(n,{point:e,url:t},{toasts:r,msg:s}){const o=n.getShapeUtil("embed"),i=o==null?void 0:o.getEmbedDefinition(t);if(i&&i.definition.embedOnPaste!==!1)return n.putExternalContent({type:"embed",url:i.url,point:e,embed:i.definition});const a=e??(n.inputs.getShiftKey()?n.inputs.getCurrentPagePoint():n.getViewportPageBounds().center);if(!(await Jj(n,{url:t,center:a})).ok){r.addToast({title:s("assets.url.failed"),severity:"error"});return}}async function Efe(n,{point:e,content:t}){n.run(()=>{const r=n.getSelectionPageBounds();n.markHistoryStoppingPoint("paste");for(const o of t.shapes)t.rootShapeIds.includes(o.id)&&(o.isLocked=!1);n.putContentOntoCurrentPage(t,{point:e,select:!0});const s=n.getSelectionPageBounds();r&&s&&(r!=null&&r.collides(s))&&(n.updateInstanceState({isChangingStyle:!0}),n.timers.setTimeout(()=>{n.updateInstanceState({isChangingStyle:!1})},150))})}async function kfe(n,{point:e,content:t}){n.run(()=>{che(n,t,e)})}async function $z(n,e,t,r,s){let o=n.type;n.type==="video/quicktime"&&(o="video/mp4");const i=t?await fs.getImageSize(n):await fs.getVideoSize(n),a=await fs.isAnimated(n)||r,l={id:e,type:t?"image":"video",typeName:"asset",props:{name:n.name,src:"",w:i.w,h:i.h,fileSize:n.size,mimeType:o,isAnimated:a},meta:{}};if(s&&isFinite(s)){const c={w:l.props.w,h:l.props.h},u=lhe(c,{w:s,h:s});c!==u&&fs.isStaticImageType(n.type)&&(l.props.w=u.w,l.props.h=u.h)}return l}async function Hz(n,e,t){if(!e.length)return[];const r=C.From(t),s=[];for(let o=0;o<e.length;o++){const i=e[o];switch(i.type){case"image":{s.push({id:St(),type:"image",x:r.x,y:r.y,opacity:1,props:{assetId:i.id,w:i.props.w,h:i.props.h}}),r.x+=i.props.w;break}case"video":s.push({id:St(),type:"video",x:r.x,y:r.y,opacity:1,props:{assetId:i.id,w:i.props.w,h:i.props.h}}),r.x+=i.props.w}}return n.run(()=>{const o=e.filter(i=>!n.getAsset(i.id));n.store.atomic(()=>{n.canCreateShapes(s)&&(o.length&&n.createAssets(o),n.createShapes(s).select(...s.map(i=>i.id)),_fe(n,t))})}),s.map(o=>o.id)}function _fe(n,e){const t=n.getViewportPageBounds();let r=n.getSelectionPageBounds();if(r){const s=r.center.sub(e);n.updateShapes(n.getSelectedShapes().map(o=>{const i=n.getShapeParentTransform(o).decompose().rotation,a=C.Rot(s,-i);return{id:o.id,type:o.type,x:o.x-a.x,y:o.y-a.y}}))}if(r=n.getSelectionPageBounds(),r&&n.getInstanceState().isGridMode){const s=n.getDocumentSettings().gridSize,o=new C(r.minX,r.minY),i=o.clone().snapToGrid(s),a=C.Sub(o,i);n.updateShapes(n.getSelectedShapes().map(l=>{const c={x:l.x-a.x,y:l.y-a.y};return{id:l.id,type:l.type,x:c.x,y:c.y}}))}r=n.getSelectionPageBounds(),r&&!t.contains(r)&&n.zoomToSelection({animation:{duration:n.options.animationMediumMs}})}function pP(n,e){const{acceptedImageMimeTypes:t=fd,acceptedVideoMimeTypes:r=sy,maxAssetSize:s=yfe,toasts:o,msg:i}=e,a=t.includes(n.type),l=r.includes(n.type);if(!a&&!l)return o.addToast({title:i("assets.files.type-not-allowed"),severity:"error"}),!1;if(n.size>s){const c=u=>{if(u===0)return"0 bytes";const d=["bytes","KB","MB","GB","TB","PB"],h=1024,f=Math.floor(Math.log(u)/Math.log(h)),g=u/Math.pow(h,f);return`${g%1===0?g.toString():g.toFixed(1)} ${d[f]}`};return o.addToast({title:i("assets.files.size-too-big"),description:i("assets.files.maximum-size").replace("{size}",c(s)),severity:"error"}),!1}return n.type?!0:(o.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error("No mime type"),!1)}async function Uz(n,e,t){const{acceptedImageMimeTypes:r=fd,acceptedVideoMimeTypes:s=sy,maxImageDimension:o=mfe}=e,i=r.includes(n.type),a=s.includes(n.type),l=$_(await n.arrayBuffer());return t??(t=Gl.createId(l)),await $z(n,t,i,a,o)}var Jb;let Mfe=(Jb=class extends ve{constructor(){super(...arguments);E(this,"isPrecise",!1);E(this,"isPreciseTimerId",null);E(this,"preciseTargetId",null)}onPointerMove(){this.update()}onPointerDown(t){this.parent.transition("pointing",{...t,isPrecise:this.isPrecise})}onEnter(){this.editor.setCursor({type:"cross",rotation:0}),this.update()}onCancel(){this.editor.setCurrentTool("select")}onExit(){QC(this.editor),this.isPreciseTimerId!==null&&clearTimeout(this.isPreciseTimerId)}onKeyDown(){this.update()}onKeyUp(t){if(this.update(),t.key==="Enter"){const r=this.editor.getOnlySelectedShape();this.editor.canEditShape(r)&&Nr(this.editor,r,{selectAll:!0})}}update(){const t=this.editor.getShapeUtil("arrow"),r=LS({editor:this.editor,pointInPageSpace:this.editor.inputs.getCurrentPagePoint(),arrow:void 0,isPrecise:this.isPrecise,currentBinding:void 0,oppositeBinding:void 0});r&&r.target.id!==this.preciseTargetId?(this.isPreciseTimerId!==null&&clearTimeout(this.isPreciseTimerId),this.preciseTargetId=r.target.id,this.isPreciseTimerId=this.editor.timers.setTimeout(()=>{this.isPrecise=!0,this.update()},t.options.hoverPreciseTimeout)):!r&&this.preciseTargetId&&(this.isPrecise=!1,this.preciseTargetId=null,this.isPreciseTimerId!==null&&clearTimeout(this.isPreciseTimerId))}},E(Jb,"id","idle"),Jb);var Qb;let Afe=(Qb=class extends ve{constructor(){super(...arguments);E(this,"shape");E(this,"isPrecise",!1);E(this,"isPreciseTimerId",null);E(this,"markId","")}onEnter(t){if(this.markId="",this.isPrecise=!!t.isPrecise,!LS({editor:this.editor,pointInPageSpace:this.editor.inputs.getCurrentPagePoint(),arrow:void 0,isPrecise:this.isPrecise,currentBinding:void 0,oppositeBinding:void 0})&&(this.createArrowShape(),!this.shape)){this.cancel();return}this.startPreciseTimeout()}onExit(){this.shape=void 0,QC(this.editor),this.clearPreciseTimeout()}onPointerMove(){if(this.editor.inputs.getIsDragging()){if(this.shape||this.createArrowShape(),!this.shape){this.cancel();return}this.updateArrowShapeEndHandle(),this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,handle:{id:"end",type:"vertex",index:"a3",x:0,y:0},isCreating:!0,creatingMarkId:this.markId||void 0,onInteractionEnd:"arrow"})}}onPointerUp(){this.cancel()}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}cancel(){this.shape&&this.editor.bailToMark(this.markId),this.parent.transition("idle")}createArrowShape(){var d;const t=this.editor.inputs.getOriginPagePoint(),r=St();this.markId=this.editor.markHistoryStoppingPoint(`creating_arrow:${r}`);const s=ws(t,this.editor);this.editor.createShape({id:r,type:"arrow",x:s.x,y:s.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const o=this.editor.getShape(r);if(!o)return;const i=this.editor.getShapeHandles(o);if(!i)throw Error("expected handles for arrow");const a=this.editor.getShapeUtil("arrow"),l=this.shape,c=i.find(h=>h.id==="start"),u=(d=a.onHandleDrag)==null?void 0:d.call(a,o,{handle:{...c,x:0,y:0},isPrecise:!0,isCreatingShape:!0,initial:l});u&&this.editor.updateShapes([u]),this.shape=this.editor.getShape(r),this.editor.select(r)}updateArrowShapeEndHandle(){var s,o;const t=this.shape;if(!t)throw Error("expected shape");const r=this.editor.getShapeHandles(t);if(!r)throw Error("expected handles for arrow");{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=r.find(u=>u.id==="start"),c=(s=i.onHandleDrag)==null?void 0:s.call(i,t,{handle:{...l,x:0,y:0},isPrecise:this.isPrecise,isCreatingShape:!0,initial:a});c&&this.editor.updateShapes([c])}{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=this.editor.getPointInShapeSpace(t,this.editor.inputs.getCurrentPagePoint()),c=r.find(d=>d.id==="end"),u=(o=i.onHandleDrag)==null?void 0:o.call(i,this.editor.getShape(t),{handle:{...c,x:l.x,y:l.y},isPrecise:this.isPrecise,isCreatingShape:!0,initial:a});u&&this.editor.updateShapes([u])}this.shape=this.editor.getShape(t.id)}startPreciseTimeout(){const t=this.editor.getShapeUtil("arrow");this.isPreciseTimerId=this.editor.timers.setTimeout(()=>{this.getIsActive()&&(this.isPrecise=!0)},t.options.pointingPreciseTimeout)}clearPreciseTimeout(){this.isPreciseTimerId!==null&&clearTimeout(this.isPreciseTimerId)}},E(Qb,"id","pointing"),Qb);class ev extends ve{constructor(){super(...arguments);E(this,"shapeType","arrow")}static children(){return[Mfe,Afe]}}E(ev,"id","arrow"),E(ev,"initial","idle");class fP extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"initialShape");E(this,"shapeType",this.parent.id==="highlight"?"highlight":"draw");E(this,"util",this.editor.getShapeUtil(this.shapeType));E(this,"isPen",!1);E(this,"isPenOrStylus",!1);E(this,"segmentMode","free");E(this,"didJustShiftClickToExtendPreviousShapeLine",!1);E(this,"pagePointWhereCurrentSegmentChanged",{});E(this,"pagePointWhereNextSegmentChanged",null);E(this,"lastRecordedPoint",{});E(this,"mergeNextPoint",!1);E(this,"currentLineLength",0);E(this,"currentSegmentPoints",[]);E(this,"markId",null)}onEnter(t){this.markId=null,this.info=t,this.lastRecordedPoint=this.editor.inputs.getCurrentPagePoint().clone(),this.startShape()}onPointerMove(){const{inputs:t}=this.editor,r=t.getIsPen();if(this.isPen&&!r&&this.markId){this.editor.bailToMark(this.markId),this.startShape();return}if(this.isPenOrStylus){const s=t.getCurrentPagePoint();C.Dist(s,this.lastRecordedPoint)>=1/this.editor.getZoomLevel()?(this.lastRecordedPoint=s.clone(),this.mergeNextPoint=!1):this.mergeNextPoint=!0}else this.mergeNextPoint=!1;this.updateDrawingShape()}onKeyDown(t){if(t.key==="Shift")switch(this.segmentMode){case"free":{this.segmentMode="starting_straight",this.pagePointWhereNextSegmentChanged=this.editor.inputs.getCurrentPagePoint().clone();break}case"starting_free":this.segmentMode="starting_straight"}this.updateDrawingShape()}onKeyUp(t){if(t.key==="Shift")switch(this.editor.snaps.clearIndicators(),this.segmentMode){case"straight":{this.segmentMode="starting_free",this.pagePointWhereNextSegmentChanged=this.editor.inputs.getCurrentPagePoint().clone();break}case"starting_straight":{this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";break}}this.updateDrawingShape()}onExit(){this.editor.snaps.clearIndicators(),this.pagePointWhereCurrentSegmentChanged=this.editor.inputs.getCurrentPagePoint().clone()}canClose(){return this.shapeType!=="highlight"}getIsClosed(t,r,s){if(!this.canClose())return!1;const o=Gt[r],i=ot.decodeFirstPoint(t[0].path),a=t[t.length-1],l=ot.decodeLastPoint(a.path);return i!==null&&l!==null&&i!==l&&this.currentLineLength>o*4*s&&C.DistMin(i,l,o*2*s)}startShape(){const t=this.editor.inputs,r=t.getOriginPagePoint(),s=t.getIsPen();this.markId=this.editor.markHistoryStoppingPoint("draw start");const{z:o=.5}=this.info.point;this.isPen=s,this.isPenOrStylus=s||o>0&&o<.5||o>.5&&o<1;const i=this.isPenOrStylus?o*1.25:.5;if(this.segmentMode=this.editor.inputs.getShiftKey()?"straight":"free",this.didJustShiftClickToExtendPreviousShapeLine=!1,this.lastRecordedPoint=r.clone(),this.initialShape){const u=this.editor.getShape(this.initialShape.id);if(u&&this.segmentMode==="straight"){this.didJustShiftClickToExtendPreviousShapeLine=!0;const d=gs(u.props.segments);if(!d)throw Error("Expected a previous segment!");const h=ot.decodeLastPoint(d.path);if(!h)throw Error("Expected a previous point!");const{x:f,y:g}=this.editor.getPointInShapeSpace(u,r).toFixed(),m={type:this.segmentMode,path:ot.encodePoints([{x:h.x,y:h.y,z:+i.toFixed(2)},{x:f,y:g,z:+i.toFixed(2)}])},y=Q.applyToPoint(this.editor.getShapePageTransform(u.id),h);this.pagePointWhereCurrentSegmentChanged=y,this.pagePointWhereNextSegmentChanged=null;const S=[...u.props.segments,m];this.currentLineLength<Gt[u.props.size]*4&&(this.currentLineLength=this.getLineLength(S));const b={id:u.id,type:this.shapeType,props:{segments:S}};this.canClose()&&(b.props.isClosed=this.getIsClosed(S,u.props.size,u.props.scale)),this.editor.updateShapes([b]);return}}this.pagePointWhereCurrentSegmentChanged=r.clone();const a=St(),l=new C(0,0,+i.toFixed(2));if(this.currentSegmentPoints=[l],this.editor.createShape({id:a,type:this.shapeType,x:r.x,y:r.y,props:{isPen:this.isPenOrStylus,scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1,segments:[{type:this.segmentMode,path:ot.encodePoints([l])}]}}),!this.editor.getShape(a)){this.cancel();return}this.currentLineLength=0,this.initialShape=this.editor.getShape(a)}updateDrawingShape(){const{initialShape:t}=this,{inputs:r}=this.editor;if(!t)return;const{id:s,props:{size:o,scale:i}}=t,a=this.editor.getShape(s);if(!a)return;const{segments:l}=a.props,c=r.getCurrentPagePoint(),{x:u,y:d,z:h}=this.editor.getPointInShapeSpace(a,c).toFixed(),f=this.isPenOrStylus?+(c.z*1.25).toFixed(2):.5,g={x:u,y:d,z:f};switch(this.segmentMode){case"starting_straight":{const{pagePointWhereNextSegmentChanged:m}=this;if(m===null)throw Error("We should have a point where the segment changed");if(C.Dist2(m,r.getCurrentPagePoint())>this.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="straight";const S=gs(l);if(!S)throw Error("Expected a previous segment!");const b=ot.decodeLastPoint(S.path);if(!b)throw Error("Expected a previous last point!");let w;const v=this.editor.getPointInShapeSpace(a,this.pagePointWhereCurrentSegmentChanged).toFixed().toJson();if(S.type==="straight"){this.currentLineLength+=C.Dist(b,v),w={type:"straight",path:ot.encodePoints([b,v])};const T=this.editor.getShapePageTransform(a);this.pagePointWhereCurrentSegmentChanged=Q.applyToPoint(T,b)}else w={type:"straight",path:ot.encodePoints([v,g])};const P={id:s,type:this.shapeType,props:{segments:[...l,w]}};this.canClose()&&(P.props.isClosed=this.getIsClosed(l,o,i)),this.editor.updateShapes([P])}break}case"starting_free":{const{pagePointWhereNextSegmentChanged:m}=this;if(m===null)throw Error("We should have a point where the segment changed");if(C.Dist2(m,r.getCurrentPagePoint())>this.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";const S=l.slice(),b=S[S.length-1],w=ot.decodeLastPoint(b.path);if(!w)throw Error("No previous point!");const v=C.PointsBetween(w,g,6).map(k=>new C(Ai(k.x),Ai(k.y),Ai(k.z)));this.currentSegmentPoints=v;const P={type:"free",path:ot.encodePoints(v)},T=[...S,P];this.currentLineLength<Gt[a.props.size]*4&&(this.currentLineLength=this.getLineLength(T));const I={id:s,type:this.shapeType,props:{segments:T}};this.canClose()&&(I.props.isClosed=this.getIsClosed(T,o,i)),this.editor.updateShapes([I])}break}case"straight":{const m=l.slice(),y=m[m.length-1],{pagePointWhereCurrentSegmentChanged:S}=this,b=this.editor.inputs,w=b.getCtrlKey(),v=b.getCurrentPagePoint();if(!S)throw Error("We should have a point where the segment changed");let P,T=!1;this.didJustShiftClickToExtendPreviousShapeLine?this.editor.inputs.getIsDragging()&&(T=!w,this.didJustShiftClickToExtendPreviousShapeLine=!1):T=!w;let I=this.editor.getPointInShapeSpace(a,v).toFixed().toJson(),k=!1,A;if((this.editor.user.getIsSnapMode()?!w:w)&&m.length>2){let j,_=8/this.editor.getZoomLevel();for(let M=0,O=l.length-2;M<O;M++){const N=l[M];if(!N)break;if(N.type==="free")continue;const B=ot.decodeFirstPoint(N.path),H=ot.decodeLastPoint(N.path);if(!(B&&H))continue;const z=C.NearestPointOnLineSegment(B,H,I);if(C.DistMin(z,I,_)){j=z.toFixed().toJson(),_=C.Dist(z,I),A=N;break}}j&&(k=!0,I=j)}if(k&&A){const j=this.editor.getShapePageTransform(a),_=ot.decodeFirstPoint(A.path),M=ot.decodeLastPoint(A.path);if(!_||!M)throw Error("Expected a last point!");const O=Q.applyToPoint(j,_),N=Q.applyToPoint(j,M),B=Q.applyToPoint(j,I);this.editor.snaps.setIndicators([{id:at(),type:"points",points:[O,B,N]}])}else{if(this.editor.snaps.clearIndicators(),T){const j=C.Angle(S,v),M=Bg(j,24)-j;P=C.RotWith(v,S,M)}else P=v.clone();I=this.editor.getPointInShapeSpace(a,P).toFixed().toJson()}this.currentLineLength+=m.length&&ot.decodeFirstPoint(y.path)?C.Dist(ot.decodeFirstPoint(y.path),C.From(I)):0,m[m.length-1]={...y,type:"straight",path:ot.encodePoints([ot.decodeFirstPoint(y.path),C.From(I)])};const D={id:s,type:this.shapeType,props:{segments:m}};this.canClose()&&(D.props.isClosed=this.getIsClosed(l,o,i)),this.editor.updateShapes([D]);break}case"free":{const m=this.currentSegmentPoints;if(m.length&&this.mergeNextPoint){const w=m[m.length-1];w.x=g.x,w.y=g.y,w.z=w.z?Math.max(w.z,g.z):g.z}else this.currentLineLength+=m.length?C.Dist(m[m.length-1],g):0,m.push(new C(g.x,g.y,g.z));const y=l.slice(),S=y[y.length-1];y[y.length-1]={...S,path:ot.encodePoints(m)},this.currentLineLength<Gt[a.props.size]*4&&(this.currentLineLength=this.getLineLength(y));const b={id:s,type:this.shapeType,props:{segments:y}};if(this.canClose()&&(b.props.isClosed=this.getIsClosed(y,o,i)),this.editor.updateShapes([b]),m.length>this.util.options.maxPointsPerShape){this.editor.updateShapes([{id:s,type:this.shapeType,props:{isComplete:!0}}]);const w=St(),v=this.editor.getShape(s).props;if(!this.editor.canCreateShapes([w]))return this.cancel();const P=r.getCurrentPagePoint(),T=new C(0,0,this.isPenOrStylus?+(h*1.25).toFixed():.5);this.currentSegmentPoints=[T],this.editor.createShape({id:w,type:this.shapeType,x:Ai(P.x),y:Ai(P.y),props:{isPen:this.isPenOrStylus,scale:v.scale,segments:[{type:"free",path:ot.encodePoints([T])}]}});const I=this.editor.getShape(w);if(!I)return this.cancel();this.initialShape=Ft(I),this.mergeNextPoint=!1,this.lastRecordedPoint=P.clone(),this.currentLineLength=0}break}}}getLineLength(t){let r=0;for(let s=0;s<t.length;s++){const o=ot.decodePoints(t[s].path);for(let i=0;i<o.length-1;i++)r+=C.Dist2(o[i],o[i+1])}return Math.sqrt(r)}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.editor.inputs.getIsDragging()||(this.markId&&this.editor.bailToMark(this.markId),this.cancel())}complete(){const{initialShape:t}=this;t&&(this.editor.updateShapes([{id:t.id,type:t.type,props:{isComplete:!0}}]),this.parent.transition("idle"))}cancel(){this.parent.transition("idle",this.info)}}E(fP,"id","drawing");var ew;let Kz=(ew=class extends ve{onPointerDown(e){this.parent.transition("drawing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onCancel(){this.editor.setCurrentTool("select")}},E(ew,"id","idle"),ew);class Tu extends ve{constructor(){super(...arguments);E(this,"shapeType","draw")}static children(){return[Kz,fP]}onExit(){const t=this.children.drawing;t.initialShape=void 0}}E(Tu,"id","draw"),E(Tu,"initial","idle"),E(Tu,"isLockable",!1),E(Tu,"useCoalescedEvents",!0);class tv extends Kw{constructor(){super(...arguments);E(this,"shapeType","frame")}onCreate(t){if(!t)return;const r=this.editor.getShapePageBounds(t),s=[],o=this.editor.getShapeAncestors(t).map(i=>i.id);this.editor.getSortedChildIdsForParent(t.parentId).map(i=>{const a=this.editor.getShape(i);if(!a||a.id===t.id||a.isLocked)return;const l=this.editor.getShapePageBounds(a);l&&r.contains(l)&&Dfe(a,o,t)&&s.push(a.id)}),this.editor.reparentShapes(s,t.id),this.editor.getInstanceState().isToolLocked?this.editor.setCurrentTool("frame"):this.editor.setCurrentTool("select.idle")}}E(tv,"id","frame"),E(tv,"initial","idle");function Dfe(n,e,t){return e.includes(n.id)?!1:n.parentId===t.parentId}var tw;let Ofe=(tw=class extends ve{onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onKeyUp(e){const{editor:t}=this;if(e.key==="Enter"){const r=t.getOnlySelectedShape();t.canEditShape(r)&&Nr(t,r,{selectAll:!0})}}onCancel(){this.editor.setCurrentTool("select")}},E(tw,"id","idle"),tw);var nw;let Rfe=(nw=class extends ve{onPointerUp(){this.complete()}onPointerMove(e){if(this.editor.inputs.getIsDragging()){const t=this.editor.inputs.getOriginPagePoint(),r=St(),s=this.editor.markHistoryStoppingPoint(`creating_geo:${r}`),o=ws(t,this.editor);if(this.editor.createShapes([{id:r,type:"geo",x:o.x,y:o.y,props:{w:1,h:1,geo:this.editor.getStyleForNextShape($o),scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]).select(r),!this.editor.getShape(r)){this.cancel();return}this.editor.setCurrentTool("select.resizing",{...e,target:"selection",handle:"bottom_right",isCreating:!0,creatingMarkId:s,creationCursorOffset:{x:1,y:1},onInteractionEnd:"geo"})}}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.cancel()}complete(){const e=this.editor.inputs.getOriginPagePoint(),t=St();this.editor.markHistoryStoppingPoint(`creating_geo:${t}`);const r=this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1,s=this.editor.getStyleForNextShape($o),o=s==="star"?{w:200,h:190}:s==="cloud"?{w:300,h:180}:{w:200,h:200};this.editor.createShapes([{id:t,type:"geo",x:e.x,y:e.y,props:{geo:this.editor.getStyleForNextShape($o),scale:r,...o}}]);const i=this.editor.getShape(t);if(!i){this.cancel();return}const{w:a,h:l}=i.props,c=new C(a/2,l/2).mul(r),u=this.editor.getShapeParentTransform(i);u&&c.rot(-u.rotation());const d=ws(new C(i.x-c.x,i.y-c.y),this.editor);this.editor.select(t),this.editor.updateShape({id:i.id,type:"geo",x:d.x,y:d.y,props:{geo:this.editor.getStyleForNextShape($o),w:a*r,h:l*r}}),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select",{})}cancel(){this.parent.transition("idle")}},E(nw,"id","pointing"),nw);class nv extends ve{constructor(){super(...arguments);E(this,"shapeType","geo")}static children(){return[Ofe,Rfe]}}E(nv,"id","geo"),E(nv,"initial","idle");class Iu extends ve{constructor(){super(...arguments);E(this,"shapeType","highlight")}static children(){return[Kz,fP]}onExit(){const t=this.children.drawing;t.initialShape=void 0}}E(Iu,"id","highlight"),E(Iu,"initial","idle"),E(Iu,"useCoalescedEvents",!0),E(Iu,"isLockable",!1);var rw;let Lfe=(rw=class extends ve{constructor(){super(...arguments);E(this,"shapeId","")}onEnter(t){this.shapeId=t.shapeId,this.editor.setCursor({type:"cross",rotation:0})}onPointerDown(){this.parent.transition("pointing",{shapeId:this.shapeId})}onCancel(){this.editor.setCurrentTool("select")}},E(rw,"id","idle"),rw);const e_=2;var sw;let jfe=(sw=class extends ve{constructor(){super(...arguments);E(this,"shape",{});E(this,"markId")}onEnter(t){const{inputs:r}=this.editor,s=r.getCurrentPagePoint();this.markId=void 0;const o=t.shapeId&&this.editor.getShape(t.shapeId);if(o&&r.getShiftKey()){this.markId=this.editor.markHistoryStoppingPoint(`creating_line:${o.id}`),this.shape=o;const i=this.editor.getShapeHandles(this.shape);if(!i)return;const a=i.filter(g=>g.type==="vertex").sort(Tn),l=a[a.length-1],c=a[a.length-2],u=Q.applyToPoint(this.editor.getShapeParentTransform(this.shape),new C(this.shape.x,this.shape.y)),d=C.Sub(s,u).addXY(.1,.1),h=ws(d,this.editor),f=Ft(this.shape.props.points);if(C.DistMin(l,c,e_)||C.DistMin(h,l,e_))f[l.id]={id:l.id,index:l.index,x:h.x,y:h.y};else{const g=Ns(l.index);f[g]={id:g,index:g,x:h.x,y:h.y}}this.editor.updateShapes([{id:this.shape.id,type:this.shape.type,props:{points:f}}])}else{const i=St();this.markId=this.editor.markHistoryStoppingPoint(`creating_line:${i}`);const a=ws(s,this.editor);if(this.editor.createShapes([{id:i,type:"line",x:a.x,y:a.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]),!this.editor.getShape(i)){this.cancel();return}this.editor.select(i),this.shape=this.editor.getShape(i)}}onPointerMove(){if(this.shape&&this.editor.inputs.getIsDragging()){const t=this.editor.getShapeHandles(this.shape);if(!t)throw this.markId&&this.editor.bailToMark(this.markId),Error("No handles found");const r=gs(t);this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,isCreating:!0,creatingMarkId:this.markId,handle:{...r,x:r.x-.1,y:r.y-.1},onInteractionEnd:"line"})}}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.parent.transition("idle"),this.markId&&this.editor.bailToMark(this.markId),this.editor.snaps.clearIndicators()}complete(){this.parent.transition("idle",{shapeId:this.shape.id}),this.editor.snaps.clearIndicators()}cancel(){this.markId&&this.editor.bailToMark(this.markId),this.parent.transition("idle",{shapeId:this.shape.id}),this.editor.snaps.clearIndicators()}},E(sw,"id","pointing"),sw);class rv extends ve{constructor(){super(...arguments);E(this,"shapeType","line")}static children(){return[Lfe,jfe]}}E(rv,"id","line"),E(rv,"initial","idle");var ow;let Nfe=(ow=class extends ve{onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onCancel(){this.editor.setCurrentTool("select")}},E(ow,"id","idle"),ow);const Ffe=0,yt=200,NS=new C(yt/2,yt/2),Wz=10,Bfe=n=>[[["a1"],new C(yt*.5,yt*-.5-n.options.adjacentShapeMargin)],[["a2"],new C(yt*1.5+n.options.adjacentShapeMargin,yt*.5)],[["a3"],new C(yt*.5,yt*1.5+n.options.adjacentShapeMargin)],[["a4"],new C(yt*-.5-n.options.adjacentShapeMargin,yt*.5)]];function zfe(n,e){if(e===1)return Bfe(n);const t=yt*e,r=n.options.adjacentShapeMargin*e;return[[["a1"],new C(t*.5,t*-.5-r)],[["a2"],new C(t*1.5+r,t*.5)],[["a3"],new C(t*.5,t*1.5+r)],[["a4"],new C(t*-.5-r,t*.5)]]}function Vz(n,e,t,r,s,o){return Object.fromEntries(zfe(n,o).map(([i,a],l)=>{const c=a.clone();return l===0&&s?c.y-=s:l===2&&r&&(c.y+=r),[i,c.rot(t).add(e)]}))}function Gz(n,e,t,r){const s=new Set(n.getSelectedShapeIds()),o=(yt+n.options.adjacentShapeMargin+r)**2,i=new Map,a=[];for(const u of n.getCurrentPageShapes()){if(!n.isShapeOfType(u,"note")||t!==u.props.scale||s.has(u.id))continue;const d=n.getShapePageTransform(u.id);e===d.rotation()&&(i.set(u,n.getShapePageBounds(u).center),a.push(...Object.values(Vz(n,d.point(),e,u.props.growY,r,t))))}const l=a.length;let c;for(const[u,d]of i)for(let h=0;h<l;h++)c=a[h],c&&(C.Dist2(d,c)>o||n.isPointInShape(u,c)&&(a[h]=void 0));return Le(a)}function Yz(n,e,t,r,s=!1){let o;const i=n.getCurrentPageShapesSorted(),a=(yt+n.options.adjacentShapeMargin**2)**e.props.scale;for(let l=i.length-1;l>=0;l--){const c=i[l];if(c.type==="note"&&c.id!==e.id){const u=n.getShapePageBounds(c);if(u&&C.Dist2(u.center,t)<a&&n.isPointInShape(c,t)){o=c;break}}}if(n.complete(),!o||s){n.markHistoryStoppingPoint("creating note shape");const l=St();n.createShape({id:l,type:"note",x:t.x,y:t.y,rotation:r,opacity:e.opacity,props:{...e.props,richText:Kn(""),growY:0,fontSizeAdjustment:0,url:""}});const c=n.getShape(l);if(!c)return;const u=n.getPointInParentSpace(c,C.Sub(t,C.Rot(NS.clone().mul(c.props.scale),r)));n.updateShape({id:l,type:"note",x:u.x,y:u.y}),o=n.getShape(l)}return n.zoomToSelectionIfOffscreen(16,{animation:{duration:n.options.animationMediumMs},inset:0}),o}var iw;let $fe=(iw=class extends ve{constructor(){super(...arguments);E(this,"dragged",!1);E(this,"info",{});E(this,"markId","");E(this,"shape",{})}onEnter(){const{editor:t}=this,r=St();this.markId=t.markHistoryStoppingPoint(`creating_note:${r}`);const s=this.editor.inputs.getOriginPagePoint().clone(),o=Hfe(this.editor,s,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);o&&s.sub(o);const i=Ufe(this.editor,r,s);i?this.shape=i:this.cancel()}onPointerMove(t){this.editor.inputs.getIsDragging()&&this.editor.setCurrentTool("select.translating",{...t,target:"shape",shape:this.shape,onInteractionEnd:"note",isCreating:!0,creatingMarkId:this.markId,onCreate:()=>{Nr(this.editor,this.shape.id)}})}onPointerUp(){this.complete()}onInterrupt(){this.cancel()}onComplete(){this.complete()}onCancel(){this.cancel()}complete(){this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):Nr(this.editor,this.shape.id,{info:this.info})}cancel(){this.editor.bailToMark(this.markId),this.parent.transition("idle",this.info)}},E(iw,"id","pointing"),iw);function Hfe(n,e,t){let r=Wz/n.getZoomLevel(),s;for(const o of Gz(n,0,t,0)){const i=C.Sub(e,o),a=i.len();a<r&&(r=a,s=i)}return s}function Ufe(n,e,t){n.createShape({id:e,type:"note",x:t.x,y:t.y,props:{scale:n.user.getIsDynamicResizeMode()?1/n.getZoomLevel():1}});const r=n.getShape(e);if(!r)return;n.select(e);const s=n.getShapeGeometry(r).bounds,o=ws(new C(r.x-s.width/2,r.y-s.height/2),n);return n.updateShapes([{id:e,type:"note",x:o.x,y:o.y}]),n.getShape(e)}class sv extends ve{constructor(){super(...arguments);E(this,"shapeType","note")}static children(){return[Nfe,$fe]}}E(sv,"id","note"),E(sv,"initial","idle");const Mf=new WeakMap;function t_(n){const e=n.getShapeAtPoint(n.inputs.getCurrentPagePoint(),{hitInside:!1,hitLabels:!1,margin:n.options.hitTestMargin/n.getZoomLevel(),renderingOnly:!0});if(!e)return null;let t;const r=n.getOutermostSelectableShape(e);return r===e||r.id===n.getFocusedGroupId()||n.getSelectedShapeIds().includes(r.id)?t=e:t=r,t.id}function Kfe(n){if(!(n.getCameraState()==="moving")){Mf.set(n,!1);const s=t_(n);return n.setHoveredShape(s)}if(Mf.get(n))return;const t=n.getHoveredShapeId();if(!t){Mf.set(n,!0);return}t_(n)!==t&&(n.setHoveredShape(null),Mf.set(n,!0))}const Uo=N_(Kfe,32);var aw;let Wfe=(aw=class extends ve{onPointerMove(e){switch(e.target){case"shape":case"canvas":Uo(this.editor)}}onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onExit(){Uo.cancel()}onKeyDown(e){if(e.key==="Enter"){const t=this.editor.getOnlySelectedShape();if(!this.editor.canEditShape(t))return;this.editor.setCurrentTool("select"),Nr(this.editor,t.id,{info:e})}}onCancel(){this.editor.setCurrentTool("select")}},E(aw,"id","idle"),aw);var lw;let Vfe=(lw=class extends ve{constructor(){super(...arguments);E(this,"shape");E(this,"markId","");E(this,"enterTime",0)}onEnter(){this.enterTime=Date.now()}onExit(){this.editor.setHintingShapes([])}onPointerMove(t){if(Date.now()-this.enterTime<150)return;const{editor:r}=this;if(!r.inputs.getIsPointing())return;const o=r.inputs.getOriginPagePoint(),i=r.inputs.getCurrentPagePoint(),a=Math.abs(o.x-i.x),c=Math.sqrt(r.getInstanceState().isCoarsePointer?r.options.coarseDragDistanceSquared:r.options.dragDistanceSquared)*6/r.getZoomLevel();if(a>c){const u=St();this.markId=r.markHistoryStoppingPoint(`creating_text:${u}`);const d=this.createTextShape(u,o,!1,a);if(!d){this.cancel();return}this.shape=r.getShape(d),r.select(u);const h=this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1;r.setCurrentTool("select.resizing",{...t,target:"selection",handle:"right",isCreating:!0,creatingMarkId:this.markId,creationCursorOffset:{x:a*h,y:1},onInteractionEnd:"text",onCreate:()=>{Nr(r,d.id)}})}}onPointerUp(){this.complete()}onComplete(){this.cancel()}onCancel(){this.cancel()}onInterrupt(){this.cancel()}complete(){this.editor.markHistoryStoppingPoint("creating text shape");const t=St(),r=this.editor.inputs.getOriginPagePoint();this.createTextShape(t,r,!0,20)&&(this.editor.select(t),Nr(this.editor,t))}cancel(){this.parent.transition("idle"),this.editor.bailToMark(this.markId)}createTextShape(t,r,s,o){this.editor.createShape({id:t,type:"text",x:r.x,y:r.y,props:{richText:Kn(""),autoSize:s,w:o,scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const i=this.editor.getShape(t);if(!i){this.cancel();return}const a=this.editor.getShapePageBounds(i),l=new C;if(s)switch(i.props.textAlign){case"start":{l.x=0;break}case"middle":{l.x=-a.width/2;break}case"end":{l.x=-a.width;break}}else l.x=0;if(l.y=-a.height/2,Pr(i.parentId)){const d=this.editor.getShapeParentTransform(i);l.rot(-d.rotation())}const c=i.x+l.x,u=i.y+l.y;if(this.editor.getInstanceState().isGridMode){const d=new C(c,u),h=ws(d,this.editor),f=C.Sub(d,h);this.editor.updateShape({...i,x:c-f.x,y:u-f.y})}else this.editor.updateShape({...i,x:c,y:u});return i}},E(lw,"id","pointing"),lw);class ov extends ve{constructor(){super(...arguments);E(this,"shapeType","text")}static children(){return[Wfe,Vfe]}}E(ov,"id","text"),E(ov,"initial","idle");const Gfe=[ov,Tu,nv,sv,rv,tv,ev,Iu],Yfe=_e.forwardRef(function({shapeId:e,isEditing:t,richText:r,handleFocus:s,handleChange:o,handleBlur:i,handleKeyDown:a,handleDoubleClick:l,hasCustomTabBehavior:c,handlePaste:u},d){const h=K(),f=Yl("tip-tap-editor"),g=h.getTextOptions().tipTapConfig,m=x.useRef(r),y=x.useRef(null),S=x.useRef(null);x.useLayoutEffect(()=>{y.current?So(m.current,r)||y.current.commands.setContent(r):m.current=r},[r]);const b=x.useRef({selectAll:!1,caretPosition:null});x.useLayoutEffect(()=>{function A(D){D.shapeId===h.getEditingShapeId()&&(b.current.selectAll=!0)}function R(D){D.shapeId===h.getEditingShapeId()&&(b.current.caretPosition=D.point)}return h.on("select-all-text",A),h.on("place-caret",R),()=>{h.off("select-all-text",A),h.off("place-caret",R)}},[h,t]);const w=No(o),v=No(a),P=No(s),T=No(i),I=No(l),k=No(u);return x.useLayoutEffect(()=>{if(!t||!g||!S.current)return;const{editorProps:A,...R}=g,D=new NJ({element:S.current,autofocus:!0,editable:t,onUpdate:_=>{const M=_.editor.state.doc.toJSON();m.current=M,w({richText:M})},onFocus:P,onBlur:T,onCreate:_=>{var B;if(h.getEditingShapeId()!==e)return;const M=_.editor;h.setRichTextEditor(M);const{selectAll:O,caretPosition:N}=b.current;if(O)M.chain().focus().selectAll().run();else if(N){const H=(B=M.view.posAtCoords({left:N.x,top:N.y}))==null?void 0:B.pos;H?M.chain().focus().setTextSelection(H).run():M.chain().focus().selectAll().run()}},editorProps:{handleKeyDown:(_,M)=>{!c&&M.key==="Tab"&&Xfe(h,_,M),v(M)},handlePaste:(_,M)=>{if(k(M),M.defaultPrevented)return!0},handleDoubleClick:(_,M,O)=>I(O),...A},coreExtensionOptions:{clipboardTextSerializer:{blockSeparator:`
515
+ `}},enableCoreExtensions:{textDirection:!1},textDirection:"auto",...R,content:m.current}),j=h.timers.setTimeout(()=>{b.current.caretPosition||b.current.selectAll?D.commands.focus():D.commands.focus("end"),b.current.selectAll=!1,b.current.caretPosition=null},100);return y.current=D,()=>{y.current=null,clearTimeout(j),D.destroy()}},[t,g,P,T,I,w,k,v,h,e,c]),!t||!g?null:p.jsx("div",{id:f,ref:d,tabIndex:-1,"data-testid":"rich-text-area",className:"tl-rich-text tl-text tl-text-input",onContextMenu:t?A=>A.stopPropagation():void 0,onPointerDownCapture:A=>A.stopPropagation(),onTouchEnd:A=>A.stopPropagation(),onDragStart:je,children:p.jsx("div",{className:"tl-rich-text",ref:S})})});function Xfe(n,e,t){t.preventDefault();const r=n.getRichTextEditor();if(r!=null&&r.isActive("bulletList")||r!=null&&r.isActive("orderedList"))return;const{state:s,dispatch:o}=e,{$from:i,$to:a}=s.selection,l=t.shiftKey;let c=s.tr,u=a.end();for(;u>=i.start();){const h=s.doc.resolve(u).blockRange();if(!h)break;const f=h.start,g=h.end,m=s.doc.textBetween(f,g,`
516
+ `);let y=!1;s.doc.nodesBetween(f,g,S=>{if(S.type.name==="bulletList"||S.type.name==="orderedList")return y=!0,!1}),y||(l?m.startsWith(" ")&&(c=c.delete(f+1,f+2)):c=c.insertText(" ",f+1)),u=f-1}const d=s.selection.map(c.doc,c.mapping);c.setSelection(d),c.docChanged&&o(c)}function Xz(n){return n==="start-legacy"||n==="middle-legacy"||n==="end-legacy"}function qfe(n,e,t){const r=qz(n),s=r.isEditing,o=K(),i=x.useRef(null),a=(t||"").trim().length===0;x.useEffect(()=>{function u(d){var h,f;d.shapeId===n&&((f=(h=i.current)==null?void 0:h.select)==null||f.call(h))}return o.on("select-all-text",u),()=>{o.off("select-all-text",u)}},[o,n,s]),x.useEffect(()=>{var u,d,h,f;s&&(document.activeElement!==i.current&&((u=i.current)==null||u.focus()),o.getInstanceState().isCoarsePointer&&((d=i.current)==null||d.select()),dt.isSafari&&((h=i.current)==null||h.blur(),(f=i.current)==null||f.focus()))},[o,s]);const l=x.useCallback(u=>{if(o.getEditingShapeId()===n)switch(u.key){case"Enter":{(u.ctrlKey||u.metaKey)&&o.complete();break}}},[o,n]),c=x.useCallback(({plaintext:u})=>{if(o.getEditingShapeId()!==n)return;const d=Jm.normalizeText(u||"");o.updateShape({id:n,type:e,props:{text:d}})},[o,n,e]);return{rInput:i,handleKeyDown:l,handleChange:c,isEmpty:a,...r}}function gP(n,e){return W("isReadyForEditing",()=>{const t=n.getEditingShapeId();return t!==null&&(t===e||n.getHoveredShapeId()===e)},[n,e])}function qz(n){const e=K(),t=W("isEditing",()=>e.getEditingShapeId()===n,[e]),r=gP(e,n),s=x.useCallback(i=>{e.dispatch({...$n(e,i),type:"pointer",name:"pointer_down",target:"shape",shape:e.getShape(n)}),i.stopPropagation()},[e,n]),o=x.useCallback(i=>{if(e.getEditingShapeId()===n&&i.clipboardData){const a=i.clipboardData.getData("text/html");a&&a.includes("<div data-tldraw")&&je(i)}},[e,n]);return{handleFocus:eh,handleBlur:eh,handleInputPointerDown:s,handleDoubleClick:e.markEventAsHandled,handlePaste:o,isEditing:t,isReadyForEditing:r}}function Zfe(n,e,t){const r=qz(n),s=r.isEditing,o=K(),i=x.useRef(null),a=t&&Wt(t);x.useEffect(()=>{var d;if(!s)return;const u=(d=i.current)==null?void 0:d.querySelector("[contenteditable]");u&&document.activeElement!==i.current&&u.focus()},[o,s]);const l=x.useCallback(u=>{o.getEditingShapeId()===n&&u.key==="Enter"&&Jt(u)&&o.complete()},[o,n]),c=x.useCallback(({richText:u})=>{o.getEditingShapeId()===n&&o.updateShape({id:n,type:e,props:{richText:u}})},[o,n,e]);return{rInput:i,handleKeyDown:l,handleChange:c,isEmpty:a,...r}}const FS=_e.memo(function({shapeId:e,type:t,richText:r,labelColor:s,font:o,fontSize:i,lineHeight:a,align:l,verticalAlign:c,wrap:u,isSelected:d,padding:h=0,onKeyDown:f,classNamePrefix:g,style:m,textWidth:y,textHeight:S,hasCustomTabBehavior:b,showTextOutline:w=!0}){const v=K(),P=_e.useRef(!1),{rInput:T,isEmpty:I,isEditing:k,isReadyForEditing:A,...R}=Zfe(e,t,r),D=x.useMemo(()=>{if(r)return hP(v,r)},[v,r]),j=W("isSelectToolActive",()=>v.getCurrentToolId()==="select",[v]);iy("isDragging",()=>{v.getInstanceState(),P.current=v.inputs.getIsDragging()},[v]);const _=Xz(l),M=N=>{var B;if(N.target instanceof HTMLElement&&(N.target.tagName==="A"||N.target.closest("a"))){if(je(N),!j)return;const H=((B=N.target.closest("a"))==null?void 0:B.getAttribute("href"))??"",z=X=>{X.name!=="pointer_up"||!H||(P.current||$1(H,"_blank",!1),v.off("event",z))};v.on("event",z)}};if(!k&&I)return null;const O=g||"tl-text";return p.jsx("div",{className:xe(`${O}-label tl-text-wrapper tl-rich-text-wrapper`,w?"tl-text__outline":"tl-text__no-outline"),"aria-hidden":!k,"data-font":o,"data-align":l,"data-hastext":!I,"data-isediting":k,"data-textwrap":!!u,"data-isselected":d,style:{justifyContent:l==="middle"||_?"center":l,alignItems:c==="middle"?"center":c,padding:h,...m},children:p.jsxs("div",{className:`${O}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:a.toString(),minHeight:Math.floor(i*a)+"px",minWidth:Math.ceil(y||0),color:s,width:y?Math.ceil(y):void 0,height:S?Math.ceil(S):void 0},children:[p.jsx("div",{className:`${O} tl-text tl-text-content`,dir:"auto",children:r&&p.jsx("div",{className:"tl-rich-text","data-is-select-tool-active":j,dangerouslySetInnerHTML:{__html:D||""},onPointerDown:M,"data-is-ready-for-editing":A})}),(A||d)&&p.jsx(Yfe,{ref:T,richText:r,isEditing:k,shapeId:e,...R,hasCustomTabBehavior:b,handleKeyDown:f??R.handleKeyDown})]})})});function BS({bounds:n,richText:e,fontSize:t,font:r,align:s,verticalAlign:o,wrap:i,labelColor:a,padding:l,showTextOutline:c=!0}){const u=K(),d=hP(u,e),h=s==="middle"?"center":s==="start"?"start":"end",f=s==="middle"?"center":s==="start"?"flex-start":"flex-end",g=o==="middle"?"center":o==="start"?"flex-start":"flex-end",m={display:"flex",fontFamily:vH[r],height:"100%",justifyContent:f,alignItems:g,padding:`${l}px`},y={fontSize:`${t}px`,wrap:i?"wrap":"nowrap",color:a,lineHeight:Dr.lineHeight,textAlign:h,width:"100%",wordWrap:"break-word",overflowWrap:"break-word",whiteSpace:"pre-wrap",textShadow:c?"var(--tl-text-outline)":"none",tabSize:"var(--tl-tab-size, 2)"};return p.jsx("foreignObject",{x:n.minX,y:n.minY,width:n.w,height:n.h,className:xe("tl-export-embed-styles tl-rich-text tl-rich-text-svg",c?"tl-text__outline":"tl-text__no-outline"),children:p.jsx("div",{style:m,children:p.jsx("div",{dangerouslySetInnerHTML:{__html:d},style:y})})})}function mP(n){return{key:`${Oa.id}:${n}`,async getElement(){return n!=="pattern"?null:p.jsx(Jfe,{})}}}function Jfe(){const n=SP(),e=Yl(),t=Zs(),r=8/12;return p.jsxs(p.Fragment,{children:[p.jsxs("mask",{id:e,children:[p.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:"white"}),p.jsxs("g",{strokeLinecap:"round",stroke:"black",children:[p.jsx("line",{x1:r*1,y1:r*3,x2:r*3,y2:r*1}),p.jsx("line",{x1:r*5,y1:r*7,x2:r*7,y2:r*5}),p.jsx("line",{x1:r*9,y1:r*11,x2:r*11,y2:r*9})]})]}),p.jsx("pattern",{id:n(1,t.id),width:"8",height:"8",patternUnits:"userSpaceOnUse",children:p.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:t.solid,mask:`url(#${e})`})})]})}function yP(){return{key:`${Oa.id}:pattern`,component:nge}}const Eu=8,n_=(n,e,t)=>new Promise((r,s)=>{const o=Eu*e*n,i=document.createElement("canvas");i.width=o,i.height=o;const a=i.getContext("2d");if(!a)return;a.fillStyle=t?Og.darkMode.solid:Og.lightMode.solid,a.fillRect(0,0,o,o),a.globalCompositeOperation="destination-out",a.lineCap="round",a.lineWidth=1.25*e*n;const l=8/12,c=u=>u*e*n;a.beginPath(),a.moveTo(c(l*1),c(l*3)),a.lineTo(c(l*3),c(l*1)),a.moveTo(c(l*5),c(l*7)),a.lineTo(c(l*7),c(l*5)),a.moveTo(c(l*9),c(l*11)),a.lineTo(c(l*11),c(l*9)),a.stroke(),i.toBlob(u=>{!u||Dt.throwToBlob.get()?s():r(u)})}),r_=(n,e)=>{const t=document.createElement("canvas");t.width=n[0],t.height=n[1];const r=t.getContext("2d");return r?(e(r),t.toDataURL()):""};let Ub=null;function Qfe(){return Ub||(Ub={white:r_([1,1],n=>{n.fillStyle="#f8f9fa",n.fillRect(0,0,1,1)}),black:r_([1,1],n=>{n.fillStyle="#212529",n.fillRect(0,0,1,1)})}),Ub}function Zz(n){return Math.ceil(Math.log2(Math.max(1,n)))}function SP(){const n=fo("hash_pattern");return x.useCallback((e,t)=>{const r=Zz(e);return Wv(n,`${t}_${r}`)},[n])}function Jz(n){const e=[],r=Zz(n);for(let s=0;s<=r;s++)e.push(Math.pow(2,s));return e}function ege(n){const e=Qfe();return Jz(n).flatMap(t=>[{zoom:t,url:e.white,theme:"light"},{zoom:t,url:e.black,theme:"dark"}])}function tge(){const n=K(),e=W("devicePixelRatio",()=>n.getInstanceState().devicePixelRatio,[n]),t=W("maxZoom",()=>Math.ceil(gs(n.getCameraOptions().zoomSteps)),[n]),[r,s]=x.useState(!1),[o,i]=x.useState(()=>ege(t)),a=SP();return x.useEffect(()=>{const c=Promise.all(Jz(t).flatMap(d=>[n_(e,d,!1).then(h=>({zoom:d,theme:"light",url:URL.createObjectURL(h)})),n_(e,d,!0).then(h=>({zoom:d,theme:"dark",url:URL.createObjectURL(h)}))]));let u=!1;return c.then(d=>{u||(i(d),s(!0))}),()=>{u=!0,s(!1),c.then(d=>{for(const{url:h}of d)URL.revokeObjectURL(h)})}},[e,t]),{defs:p.jsx(p.Fragment,{children:o.map(c=>{const u=a(c.zoom,c.theme);return p.jsx("pattern",{id:u,width:Eu,height:Eu,patternUnits:"userSpaceOnUse",children:p.jsx("image",{href:c.url,width:Eu,height:Eu})},u)})}),isReady:r}}function nge(){const n=K(),e=x.useRef(null),{defs:t,isReady:r}=tge();return x.useEffect(()=>{if(r&&dt.isSafari){const s=Qz(e.current);s&&n.timers.requestAnimationFrame(()=>{s.style.display="none",n.timers.requestAnimationFrame(()=>{s.style.display=""})})}},[n,r]),p.jsx("g",{ref:e,"data-testid":r?"ready-pattern-fill-defs":void 0,children:t})}function Qz(n){return n.classList.contains("tl-html-layer")?n:n.parentElement?Qz(n.parentElement):null}const Mh=_e.memo(function({theme:e,d:t,color:r,fill:s,scale:o}){switch(s){case"none":return null;case"solid":return p.jsx("path",{fill:st(e,r,"semi"),d:t});case"semi":return p.jsx("path",{fill:e.solid,d:t});case"fill":return p.jsx("path",{fill:st(e,r,"fill"),d:t});case"pattern":return p.jsx(rge,{theme:e,color:r,fill:s,d:t,scale:o});case"lined-fill":return p.jsx("path",{fill:st(e,r,"linedFill"),d:t})}});function rge({d:n,color:e,theme:t}){const r=K(),s=Hh(),o=W("zoomLevel",()=>r.getEfficientZoomLevel(),[r]),i=SP(),a=o<=.18;return p.jsxs(p.Fragment,{children:[p.jsx("path",{fill:st(t,e,"pattern"),d:n}),p.jsx("path",{fill:s?`url(#${i(1,t.id)})`:a?st(t,e,"semi"):`url(#${i(o,t.id)})`,d:n})]})}function Ah(n=.25){const e=K();return W("efficient zoom threshold",()=>e.getEfficientZoomLevel()<n,[e,n])}function e$(n){switch(n.type){case"straight":return new ct().moveTo(n.start.point.x,n.start.point.y,{offset:0,roundness:0}).lineTo(n.end.point.x,n.end.point.y,{offset:0,roundness:0});case"arc":return new ct().moveTo(n.start.point.x,n.start.point.y,{offset:0,roundness:0}).circularArcTo(n.bodyArc.radius,!!n.bodyArc.largeArcFlag,!!n.bodyArc.sweepFlag,n.end.point.x,n.end.point.y,{offset:0,roundness:0});case"elbow":{const e=new ct;e.moveTo(n.start.point.x,n.start.point.y,{offset:0});for(let t=1;t<n.route.points.length;t++){const r=n.route.points[t];n.route.skipPointsWhenDrawing.has(r)||e.lineTo(r.x,r.y,{offset:t===n.route.points.length-1?0:void 0})}return e}default:it(n,"type")}}function t$(n,e,t){return e$(e).toSvg(t)}function sge(n,e){switch(n.type){case"straight":return new ct().moveTo(n.start.handle.x,n.start.handle.y).lineTo(n.end.handle.x,n.end.handle.y).toSvg(e);case"arc":return new ct().moveTo(n.start.handle.x,n.start.handle.y).circularArcTo(n.handleArc.radius,!!n.handleArc.largeArcFlag,!!n.handleArc.sweepFlag,n.end.handle.x,n.end.handle.y).toSvg(e);case"elbow":{const t=_ae(n.elbow,n.route);return ct.lineThroughPoints(t.points).toSvg(e)}default:it(n,"type")}}function ud(n,e){const t=us(n,e);switch(t.type){case"straight":return new Qc({start:C.From(t.start.point),end:C.From(t.end.point)});case"arc":return new jR({center:C.Cast(t.handleArc.center),start:C.Cast(t.start.point),end:C.Cast(t.end.point),sweepFlag:t.bodyArc.sweepFlag,largeArcFlag:t.bodyArc.largeArcFlag});case"elbow":return new $h({points:t.route.points});default:it(t,"type")}}const oge=Rh("arrow label size",(n,e)=>{n.fonts.trackFontsForShape(e);let t=0,r=0;const s=ud(n,e),o=Wt(e.props.richText),i=_h(n,o?Kn("i"):e.props.richText),a=s.bounds,l=iv(e),{w:c,h:u}=n.textMeasure.measureHtml(i,{...Dr,fontFamily:Ha[e.props.font],fontSize:l,maxWidth:null});t=c,r=u;let d=!1;const h=us(n,e),f=r$(e),g=h.type==="elbow"?Math.max(h.elbow.A.arrowheadOffset+f,32)+Math.max(h.elbow.B.arrowheadOffset+f,32):64;if(a.width>a.height?(t=Math.max(Math.min(c,g),Math.min(a.width-g,c)),d=!0):t>16*l&&(t=16*l,d=!0),d){const{w:m,h:y}=n.textMeasure.measureHtml(i,{...Dr,fontFamily:Ha[e.props.font],fontSize:l,maxWidth:t});t=m,r=y}return new C(t,r).addScalar(U0*2*e.props.scale)},{areRecordsEqual:(n,e)=>{if(n.props===e.props)return!0;const t=H4(n.props,e.props);return t.length===1&&t[0]==="labelPosition"}});function n$(n,e){return oge.get(n,e.id)??new C(0,0)}function r$(n){const e=Gt[n.props.size];return(ahe+(e-Gt.s)*2+(e===Gt.xl?20:0))*n.props.scale}function ige(n,e,t){const r=ud(n,e),s=[],o=[new es({children:[r],debugColor:"lime"})],i=n$(n,e),a=r$(e),l=a/r.length;let c,u;if(t.type==="elbow")s.push(t.start.point,t.end.point),c=J.FromCenter(t.start.point,i).expandBy(a),u=J.FromCenter(t.end.point,i).expandBy(a);else{const S=r.interpolateAlongEdge(l),b=r.interpolateAlongEdge(1-l);s.push(S,b),c=J.FromCenter(S,i),u=J.FromCenter(b,i)}const d=r.intersectPolygon(c.corners),h=r.intersectPolygon(u.corners),f=s_(t.start.point,d),g=s_(t.end.point,h);let m=f?r.uninterpolateAlongEdge(f):.5,y=g?r.uninterpolateAlongEdge(g):.5;m>y&&(m=.5,y=.5);for(const S of[...d,...h,...s])o.push(new Gg({x:S.x-3,y:S.y-3,radius:3,isFilled:!1,debugColor:"magenta",ignore:!0}));return o.push(new ah({points:c.corners,debugColor:"lime",isFilled:!1,ignore:!0}),new ah({points:u.corners,debugColor:"lime",isFilled:!1,ignore:!0})),{start:m,end:y,dbg:o}}function tg(n,e){if(!(n.getEditingShapeId()===e.id)&&Wt(e.props.richText)){const h=ud(n,e).interpolateAlongEdge(.5);return{box:J.FromCenter(h,new C(0,0)),debugGeom:[]}}const r=[],s=us(n,e),o={hasStartBinding:!!s.bindings.start,hasEndBinding:!!s.bindings.end,hasStartArrowhead:s.start.arrowhead!=="none",hasEndArrowhead:s.end.arrowhead!=="none"},i=ige(n,e,s);i.dbg&&r.push(...i.dbg);const a=age(e,i,o),c=ud(n,e).interpolateAlongEdge(a),u=n$(n,e);return{box:J.FromCenter(c,u),debugGeom:r}}function age(n,e,t){const{hasEndArrowhead:r,hasEndBinding:s,hasStartBinding:o,hasStartArrowhead:i}=t;return Fe(n.props.labelPosition,i||o?e.start:0,r||s?e.end:1)}function s_(n,e){let t=null,r=-1/0;for(const s of e){const o=C.Dist2(n,s);o>r&&(t=s,r=o)}return t}function iv(n){return ihe[n.props.size]*n.props.scale}function s$(n,e){const t=us(n,e);switch(t.type){case"straight":case"arc":return .5;case"elbow":{const r=t.route.midpointHandle,s=ud(n,e);return r&&s?s.uninterpolateAlongEdge(r.point):.5}default:it(t,"type")}}function o$(n,e){if(!n.isShapeOfType(e,"arrow"))return!1;const t=n.getPointInShapeSpace(e,n.inputs.getCurrentPagePoint()),r=n.getShapeGeometry(e).children[1];return r&&kr(t,r.vertices)}function lge(n,e,t){const r=e==="end"?n.end.point:n.start.point;let s;switch(n.type){case"straight":{const o=e==="end"?n.start.point:n.end.point,i=C.Dist(o,r),a=Fe(i/5,t,t*3);s=C.Nudge(r,o,a);break}case"arc":{const o=Math.abs(n.bodyArc.length),i=Fe(o/5,t,t*3),a=v8(r,i,n.handleArc.center,n.handleArc.radius);s=e==="end"?n.handleArc.sweepFlag?a[0]:a[1]:n.handleArc.sweepFlag?a[1]:a[0];break}case"elbow":{const o=e==="end"?n.route.points[n.route.points.length-2]:n.route.points[1],i=C.ManhattanDist(o,r),a=Fe(i/2,t,t*3);s=o?C.Nudge(r,o,a):r;break}default:it(n,"type")}return C.IsNaN(s)&&(s=r),{point:r,int:s}}function cge({point:n,int:e}){const t=C.RotWith(e,n,ht/6),r=C.RotWith(e,n,-ht/6);return`M ${t.x} ${t.y} L ${n.x} ${n.y} L ${r.x} ${r.y}`}function dge({point:n,int:e}){const t=C.RotWith(e,n,ht/6),r=C.RotWith(e,n,-ht/6);return`M ${t.x} ${t.y} L ${r.x} ${r.y} L ${n.x} ${n.y} Z`}function uge({point:n,int:e}){const t=C.Sub(e,n).div(2),r=C.Add(n,C.Rot(t,Bt)),s=C.Sub(n,C.Rot(t,Bt));return`M ${r.x} ${r.y} L ${e.x} ${e.y} L ${s.x} ${s.y} Z`}function hge({point:n,int:e}){const t=C.Lrp(n,e,.45),r=C.Dist(t,n);return`M ${t.x-r},${t.y}
517
+ a ${r},${r} 0 1,0 ${r*2},0
518
+ a ${r},${r} 0 1,0 -${r*2},0 `}function pge({point:n,int:e}){const t=C.Lrp(n,e,.75),r=C.RotWith(t,n,ht/4),s=C.RotWith(t,n,-ht/4),o=C.Lrp(r,s,.5);return o.add(C.Sub(o,n)),`M ${o.x} ${o.y} L ${s.x} ${s.y} ${n.x} ${n.y} L ${r.x} ${r.y} Z`}function fge({int:n,point:e}){const t=C.Lrp(e,n,.85),r=C.Sub(t,e).div(2),s=C.Add(e,C.Rot(r,Bt)),o=C.Sub(e,C.Rot(r,Bt)),i=C.Add(t,C.Rot(r,Bt)),a=C.Sub(t,C.Rot(r,Bt));return`M ${s.x} ${s.y} L ${i.x} ${i.y} L ${a.x} ${a.y} L ${o.x} ${o.y} Z`}function gge({int:n,point:e}){const t=C.Sub(n,e).div(2),r=C.Add(e,C.Rot(t,Bt)),s=C.Sub(e,C.Rot(t,Bt));return`M ${r.x} ${r.y} L ${s.x} ${s.y}`}function Oc(n,e,t){const r=e==="end"?n.end.arrowhead:n.start.arrowhead;if(r==="none")return;const s=lge(n,e,t);if(s){switch(r){case"bar":return gge(s);case"square":return fge(s);case"diamond":return pge(s);case"dot":return hge(s);case"inverted":return uge(s);case"arrow":return cge(s);case"triangle":return dge(s)}return""}}function mge({arrow:n}){var i,a;const e=K(),t=W("elbow arrow grid",()=>{try{return o5(e,e.getShape(n.id),En(e,n))}catch(l){console.error(l);return}},[e,n.id]);if(!t)return null;const r=J.Common([t.A.original,t.B.original]).expandBy(50),s=((i=t.route)==null?void 0:i.name)??"",o=(a=t.route)==null?void 0:a.midpointHandle;return p.jsxs(p.Fragment,{children:[t.midX!==null&&p.jsx(bl,{a:{x:t.midX,y:r.minY},b:{x:t.midX,y:r.maxY},stroke:"red"}),t.midY!==null&&p.jsx(bl,{a:{x:r.minX,y:t.midY},b:{x:r.maxX,y:t.midY},stroke:"blue"}),(o==null?void 0:o.axis)==="x"&&t.midXRange&&p.jsx(bl,{a:{x:t.midXRange.lo,y:o.point.y},b:{x:t.midXRange.hi,y:o.point.y},stroke:"red",strokeDasharray:"0 2"}),(o==null?void 0:o.axis)==="y"&&t.midYRange&&p.jsx(bl,{a:{x:o.point.x,y:t.midYRange.lo},b:{x:o.point.x,y:t.midYRange.hi},stroke:"blue",strokeDasharray:"0 2"}),p.jsx(wc,{box:t.A.original,stroke:"orange"}),p.jsx(wc,{box:t.A.expanded,stroke:"orange",strokeWidth:.5}),p.jsx(wc,{box:t.A.original.clone().expandBy(t.options.minElbowLegLength),stroke:"orange",strokeWidth:.5}),p.jsx(wc,{box:t.B.original,stroke:"lightskyblue"}),p.jsx(wc,{box:t.B.expanded,stroke:"lightskyblue",strokeWidth:.5}),p.jsx(wc,{box:t.B.original.clone().expandBy(t.options.minElbowLegLength),stroke:"lightskyblue",strokeWidth:.5}),p.jsx(la,{edge:t.A.edges.top,axis:"x",stroke:"orange"}),p.jsx(la,{edge:t.B.edges.top,axis:"x",stroke:"lightskyblue"}),p.jsx(la,{edge:t.A.edges.right,axis:"y",stroke:"orange"}),p.jsx(la,{edge:t.B.edges.right,axis:"y",stroke:"lightskyblue"}),p.jsx(la,{edge:t.A.edges.bottom,axis:"x",stroke:"orange"}),p.jsx(la,{edge:t.B.edges.bottom,axis:"x",stroke:"lightskyblue"}),p.jsx(la,{edge:t.A.edges.left,axis:"y",stroke:"orange"}),p.jsx(la,{edge:t.B.edges.left,axis:"y",stroke:"lightskyblue"}),t.route&&p.jsx(yge,{route:t.route.points,strokeWidth:10}),p.jsx("text",{x:r.minX+5,y:r.minY-3,fontSize:10,fill:"black",stroke:"var(--tl-color-background)",strokeWidth:2,paintOrder:"stroke",children:s}),p.jsxs("text",{x:t.A.expanded.x,y:t.A.expanded.y,fontSize:10,fill:"black",stroke:"var(--tl-color-background)",strokeWidth:2,paintOrder:"stroke",children:["A",t.route&&`, ${t.route.aEdgePicking}`,t.A.isPoint&&", point"]}),p.jsxs("text",{x:t.B.expanded.x,y:t.B.expanded.y,fontSize:10,fill:"black",stroke:"var(--tl-color-background)",strokeWidth:2,paintOrder:"stroke",children:["B",t.route&&`, ${t.route.bEdgePicking}`,t.B.isPoint&&", point"]})]})}function bl({a:n,b:e,...t}){return p.jsx("line",{fill:"none",strokeWidth:1,strokeDasharray:"4,4",stroke:"green",x1:n.x,y1:n.y,x2:e.x,y2:e.y,...t})}function yge({route:n,...e}){return p.jsx("polyline",{fill:"none",stroke:"darkorchid",strokeWidth:3,opacity:.5,points:n.map(t=>`${t.x},${t.y}`).join(" "),...e})}function la({edge:n,axis:e,...t}){if(!n||n.expanded===null)return null;const r=s=>e==="x"?{x:s.y,y:s.x}:s;return p.jsxs("g",{children:[p.jsx(bl,{a:r({x:n.expanded,y:n.cross.min}),b:r({x:n.expanded,y:n.cross.max}),strokeDasharray:"0",strokeWidth:1.5,...t}),p.jsx(bl,{a:r({x:n.expanded-4,y:n.cross.min}),b:r({x:n.expanded+4,y:n.cross.min}),strokeDasharray:"0",strokeWidth:1.5,...t}),p.jsx(bl,{a:r({x:n.expanded-4,y:n.cross.max}),b:r({x:n.expanded+4,y:n.cross.max}),strokeDasharray:"0",strokeWidth:1.5,...t})]})}function wc({box:n,...e}){return p.jsx("rect",{x:n.minX,y:n.minY,width:n.width,height:n.height,strokeDasharray:"4,4",strokeWidth:1,fill:"none",...e})}const Sge=new Vn;function xge(n){return Sge.get(n,e=>{const t=q("current selected arrow shape",()=>{const s=e.getOnlySelectedShape();return!s||!e.isShapeOfType(s,"arrow")?null:s.id}),r=e.store.query.ids("shape",()=>{const s=t.get();return s?{type:{eq:"arrow"},id:{neq:s}}:{type:{eq:"arrow"}}});return q("elbow arrow snap lines",()=>{var a,l;const s=new Map,o=e.getCurrentPageShapeIds(),i=e.getViewportPageBounds();for(const c of r.get()){if(!o.has(c))continue;const u=e.getShape(c);if((u==null?void 0:u.type)!=="arrow")continue;const d=e.getShapePageBounds(c);if(!d||!i.includes(d))continue;const h=En(e,u),f=e.getShapePageTransform(c);if(!f)continue;const g=e.getShapeGeometry(c),m=f.applyToPoints(g.vertices);for(let y=1;y<m.length;y++){const S=m[y-1],b=m[y];let w=C.Angle(S,b);w<0&&(w+=Math.PI);let v=s.get(w);v||(v=new Set,s.set(w,v));const P=ku(S,w);v.add({perpDistance:P,startBoundShapeId:(a=h.start)==null?void 0:a.toId,endBoundShapeId:(l=h.end)==null?void 0:l.toId})}}return s})}).get()}function ku(n,e){const t=C.FromAngle(e).per();return C.Dpr(n,t)}class ng extends go{constructor(){super(...arguments);E(this,"options",{expandElbowLegLength:{s:28,m:36,l:44,xl:66},minElbowLegLength:{s:Gt.s*3,m:Gt.m*3,l:Gt.l*3,xl:Gt.xl*3},minElbowHandleDistance:16,arcArrowCenterSnapDistance:16,elbowArrowCenterSnapDistance:24,elbowArrowEdgeSnapDistance:20,elbowArrowPointSnapDistance:24,elbowArrowAxisSnapDistance:16,labelCenterSnapDistance:10,elbowMidpointSnapDistance:10,elbowMinSegmentLengthToShowMidpointHandle:20,hoverPreciseTimeout:600,pointingPreciseTimeout:320,shouldBeExact(t){return t.inputs.getAltKey()},shouldIgnoreTargets(t){return t.inputs.getCtrlKey()},showTextOutline:!0});E(this,"_resizeInitialBindings",new Vn)}canEdit(){return!0}canBind({toShape:t}){return t.type!=="arrow"}canSnap(){return!1}hideResizeHandles(){return!0}hideRotateHandle(){return!0}hideSelectionBoundsBg(){return!0}hideSelectionBoundsFg(){return!0}hideInMinimap(){return!0}canBeLaidOut(t,r){if(r.type==="flip"){const s=En(this.editor,t),{start:o,end:i}=s,{shapes:a=[]}=r;if(o&&!a.find(l=>l.id===o.toId)||i&&!a.find(l=>l.id===i.toId))return!1}return!0}getFontFaces(t){return Wt(t.props.richText)?Yt:Gy(this.editor,t.props.richText,{family:`tldraw_${t.props.font}`,weight:"normal",style:"normal"})}getDefaultProps(){return{kind:"arc",elbowMidPoint:.5,dash:"draw",size:"m",fill:"none",color:"black",labelColor:"black",bend:0,start:{x:0,y:0},end:{x:2,y:0},arrowheadStart:"none",arrowheadEnd:"arrow",richText:Kn(""),labelPosition:.5,font:"draw",scale:1}}getGeometry(t){const r=this.editor.getEditingShapeId()===t.id,s=us(this.editor,t),o=[],i=s.type==="straight"?new Qc({start:C.From(s.start.point),end:C.From(s.end.point)}):s.type==="arc"?new jR({center:C.Cast(s.handleArc.center),start:C.Cast(s.start.point),end:C.Cast(s.end.point),sweepFlag:s.bodyArc.sweepFlag,largeArcFlag:s.bodyArc.largeArcFlag}):new $h({points:s.route.points});let a;if(r||!Wt(t.props.richText)){const l=tg(this.editor,t);Dt.debugGeometry.get()&&o.push(...l.debugGeom),a=new bo({x:l.box.x,y:l.box.y,width:l.box.w,height:l.box.h,isFilled:!0,isLabel:!0})}return new es({children:[...a?[i,a]:[i],...o]})}getHandles(t){const r=us(this.editor,t),s=[{id:"start",type:"vertex",index:"a1",x:r.start.handle.x,y:r.start.handle.y},{id:"end",type:"vertex",index:"a3",x:r.end.handle.x,y:r.end.handle.y}];if(t.props.kind==="arc"&&(r.type==="straight"||r.type==="arc")&&s.push({id:"middle",type:"virtual",index:"a2",x:r.middle.x,y:r.middle.y}),t.props.kind==="elbow"&&r.type==="elbow"&&r.route.midpointHandle){const o=this.editor.getShapePageTransform(t.id),i=o.applyToPoint(r.route.midpointHandle.segmentStart),a=o.applyToPoint(r.route.midpointHandle.segmentEnd);C.Dist(i,a)*this.editor.getEfficientZoomLevel()>this.options.elbowMinSegmentLengthToShowMidpointHandle&&s.push({id:"middle",type:"vertex",index:"a2",x:r.route.midpointHandle.point.x,y:r.route.midpointHandle.point.y})}return s}getText(t){return Hl(this.editor,t.props.richText)}onHandleDrag(t,r){const s=r.handle.id;switch(s){case"middle":switch(t.props.kind){case"arc":return this.onArcMidpointHandleDrag(t,r);case"elbow":return this.onElbowMidpointHandleDrag(t,r);default:it(t.props.kind)}case"start":case"end":return this.onTerminalHandleDrag(t,r,s);default:it(s)}}onArcMidpointHandleDrag(t,{handle:r}){const s=En(this.editor,t),{start:o,end:i}=pl(this.editor,t,s),a=C.Sub(i,o),l=C.Per(a),c=C.Med(i,o),u=C.Sub(c,l),d=C.Add(c,l),h=C.NearestPointOnLineSegment(u,d,r,!1);let f=C.Dist(h,c);return C.Clockwise(h,i,c)&&(f*=-1),{id:t.id,type:t.type,props:{bend:f}}}onElbowMidpointHandleDrag(t,{handle:r}){var w,v,P,T,I;const s=us(this.editor,t);if((s==null?void 0:s.type)!=="elbow")return;const o=this.editor.getShapePageTransform(t.id),i=o.applyToPoint(r),a=(w=s.route.midpointHandle)==null?void 0:w.axis;if(!a)return;const l=vh[a],c=s.elbow[l.midRange];if(!c)return;let u=C.Angle(o.applyToPoint(l.v(0,0)),o.applyToPoint(l.v(0,1)));u<0&&(u+=Math.PI);const d=ku(i,u),h=ku(o.applyToPoint(l.v(c.lo,0)),u),f=ku(o.applyToPoint(l.v(c.hi,0)),u),g=this.options.elbowMidpointSnapDistance/this.editor.getEfficientZoomLevel(),m=ku(o.applyToPoint(l.v(Ue(c.lo,c.hi,.5),0)),u);let y=m,S=Math.abs(m-d);for(const[k,A]of xge(this.editor)){const{isParallel:R,isFlippedParallel:D}=vge(u,k);if(R||D)for(const j of A){const _=j.startBoundShapeId&&(j.startBoundShapeId===((v=s.bindings.start)==null?void 0:v.toId)||j.startBoundShapeId===((P=s.bindings.end)==null?void 0:P.toId)),M=j.endBoundShapeId&&(j.endBoundShapeId===((T=s.bindings.start)==null?void 0:T.toId)||j.endBoundShapeId===((I=s.bindings.end)==null?void 0:I.toId));if(!_&&!M)continue;const O=D?-j.perpDistance:j.perpDistance,N=Math.abs(O-d);N<S&&(y=O,S=N)}}S>g&&(y=d);const b=Fe(nh(h,f,y),0,1);return{id:t.id,type:t.type,props:{elbowMidPoint:b}}}onTerminalHandleDrag(t,{handle:r,isPrecise:s},o){const i=En(this.editor,t),a={id:t.id,type:"arrow",props:{}},l=i[o],u=i[o==="start"?"end":"start"],d=LS({editor:this.editor,pointInPageSpace:this.editor.getShapePageTransform(t.id).applyToPoint(r),arrow:t,isPrecise:s,currentBinding:l,oppositeBinding:u});if(!d){wu(this.editor,t,o);const g=ws(new C(r.x,r.y),this.editor);return a.props[o]={x:g.x,y:g.y},a}const h={terminal:o,normalizedAnchor:d.normalizedAnchor,isPrecise:d.isPrecise,isExact:d.isExact,snap:d.snap};Wd(this.editor,t,d.target.id,h);const f=En(this.editor,t);return f.start&&f.end&&f.start.toId===f.end.toId&&C.Equals(f.start.props.normalizedAnchor,f.end.props.normalizedAnchor)&&Wd(this.editor,t,f.end.toId,{...f.end.props,normalizedAnchor:{x:f.end.props.normalizedAnchor.x+.05,y:f.end.props.normalizedAnchor.y}}),a}onTranslateStart(t){const r=En(this.editor,t);if(t.props.kind==="elbow"&&this.editor.getOnlySelectedShapeId()===t.id){const a=us(this.editor,t);if(!a)return;const l={id:t.id,type:"arrow",props:{}};return r.start&&(l.props.start={x:a.start.point.x,y:a.start.point.y},wu(this.editor,t,"start")),r.end&&(l.props.end={x:a.end.point.x,y:a.end.point.y},wu(this.editor,t,"end")),l}const s=pl(this.editor,t,r),o=this.editor.getShapePageTransform(t.id),i=this.editor.getSelectedShapeIds();if(!(r.start&&(i.includes(r.start.toId)||this.editor.isAncestorSelected(r.start.toId))||r.end&&(i.includes(r.end.toId)||this.editor.isAncestorSelected(r.end.toId)))){i_.set(t,{pagePosition:o.applyToPoint(t),terminalBindings:Ka(s,(a,l)=>{const c=r[a];return c?{binding:c,shapePosition:l,pagePosition:o.applyToPoint(l)}:null})}),r.start&&(vm({editor:this.editor,arrow:t,terminal:"start",useHandle:!0}),t=this.editor.getShape(t.id)),r.end&&vm({editor:this.editor,arrow:t,terminal:"end",useHandle:!0});for(const a of["start","end"]){const l=r[a];l&&this.editor.updateBinding({...l,props:{...l.props,isPrecise:!0}})}}}onTranslate(t,r){const s=i_.get(t);if(!s)return;const o=this.editor.getShapePageTransform(r.id),i=C.Sub(o.applyToPoint(r),s.pagePosition);for(const a of Object.values(s.terminalBindings)){if(!a)continue;const l=C.Add(a.pagePosition,C.Mul(i,.5)),c=this.editor.getShapeAtPoint(l,{hitInside:!0,hitFrameInside:!0,margin:0,filter:u=>!u.isLocked&&this.editor.canBindShapes({fromShape:r,toShape:u,binding:"arrow"})});if((c==null?void 0:c.id)===a.binding.toId){const u=J.ZeroFix(this.editor.getShapeGeometry(c).bounds),d=this.editor.getPointInShapeSpace(c,l),h={x:(d.x-u.minX)/u.width,y:(d.y-u.minY)/u.height};Wd(this.editor,r,c.id,{...a.binding.props,normalizedAnchor:h,isPrecise:!0})}else wu(this.editor,r,a.binding.props.terminal)}}onResize(t,r){const{scaleX:s,scaleY:o}=r,i=this._resizeInitialBindings.get(t,()=>En(this.editor,t)),a=pl(this.editor,t,i),{start:l,end:c}=Ft(t.props);let{bend:u}=t.props;i.start||(l.x=a.start.x*s,l.y=a.start.y*o),i.end||(c.x=a.end.x*s,c.y=a.end.y*o);const d=Math.abs(s),h=Math.abs(o),f=i!=null&&i.start?C.From(i.start.props.normalizedAnchor):null,g=i!=null&&i.end?C.From(i.end.props.normalizedAnchor):null;return s<0&&o>=0?(u!==0&&(u*=-1,u*=Math.max(d,h)),f&&(f.x=1-f.x),g&&(g.x=1-g.x)):s>=0&&o<0?(u!==0&&(u*=-1,u*=Math.max(d,h)),f&&(f.y=1-f.y),g&&(g.y=1-g.y)):s>=0&&o>=0?u!==0&&(u*=Math.max(d,h)):s<0&&o<0&&(u!==0&&(u*=Math.max(d,h)),f&&(f.x=1-f.x,f.y=1-f.y),g&&(g.x=1-g.x,g.y=1-g.y)),i.start&&f&&Wd(this.editor,t,i.start.toId,{...i.start.props,normalizedAnchor:f.toJson()}),i.end&&g&&Wd(this.editor,t,i.end.toId,{...i.end.props,normalizedAnchor:g.toJson()}),{props:{start:l,end:c,bend:u}}}onDoubleClickHandle(t,r){switch(r.id){case"start":return{id:t.id,type:t.type,props:{...t.props,arrowheadStart:t.props.arrowheadStart==="none"?"arrow":"none"}};case"end":return{id:t.id,type:t.type,props:{...t.props,arrowheadEnd:t.props.arrowheadEnd==="none"?"arrow":"none"}}}}component(t){const r=Zs(),s=this.editor.getOnlySelectedShape(),o=this.editor.isInAny("select.idle","select.pointing_handle","select.dragging_handle","select.translating","arrow.dragging")&&!this.editor.getIsReadonly(),i=us(this.editor,t);if(!(i!=null&&i.isValid))return null;const a=tg(this.editor,t),l=t.id===this.editor.getOnlySelectedShapeId(),u=this.editor.getEditingShapeId()===t.id||!Wt(t.props.richText);return p.jsxs(p.Fragment,{children:[p.jsxs(Ra,{style:{minWidth:50,minHeight:50},children:[p.jsx(o_,{shape:t,shouldDisplayHandles:o&&(s==null?void 0:s.id)===t.id}),t.props.kind==="elbow"&&Dt.debugElbowArrows.get()&&p.jsx(mge,{arrow:t})]}),u&&p.jsx(FS,{shapeId:t.id,type:"arrow",font:t.props.font,fontSize:iv(t),lineHeight:Dr.lineHeight,align:"middle",verticalAlign:"middle",labelColor:st(r,t.props.labelColor,"solid"),richText:t.props.richText,textWidth:a.box.w-U0*2*t.props.scale,isSelected:l,padding:0,showTextOutline:this.options.showTextOutline,style:{transform:`translate(${a.box.center.x}px, ${a.box.center.y}px)`}})]})}indicator(t){const r=qh(t.id),s=fo(t.id+"_clip"),o=us(this.editor,t);if(!o)return null;const{start:i,end:a}=pl(this.editor,t,o==null?void 0:o.bindings),l=this.editor.getShapeGeometry(t),c=l.bounds,u=Wt(t.props.richText),d=r||!u?l.children[1]:null;if(C.Equals(i,a))return null;const h=Gt[t.props.size]*t.props.scale,f=o.start.arrowhead&&Oc(o,"start",h),g=o.end.arrowhead&&Oc(o,"end",h),m=f&&o.start.arrowhead!=="arrow"||g&&o.end.arrowhead!=="arrow"||!!d,y=d?d.getBounds():new J(0,0,0,0);if(r&&d)return p.jsx("rect",{x:$(y.x),y:$(y.y),width:y.w,height:y.h,rx:3.5*t.props.scale,ry:3.5*t.props.scale});const S=!(o.start.arrowhead==="none"||o.start.arrowhead==="arrow"),b=!(o.end.arrowhead==="none"||o.end.arrowhead==="arrow");return p.jsxs("g",{children:[m&&p.jsx("defs",{children:p.jsx(i$,{radius:3.5*t.props.scale,hasText:!u,bounds:c,labelBounds:y,as:S&&f?f:"",ae:b&&g?g:""})}),p.jsxs("g",{style:{clipPath:m?`url(#${s})`:void 0,WebkitClipPath:m?`url(#${s})`:void 0},children:[m&&p.jsx("rect",{x:c.minX-100,y:c.minY-100,width:c.width+200,height:c.height+200,opacity:0}),t$(t,o,t.props.dash==="draw"?{style:"draw",randomSeed:t.id,strokeWidth:1,passes:1,offset:0,roundness:h*2,props:{strokeWidth:void 0}}:{style:"solid",strokeWidth:1,props:{strokeWidth:void 0}})]}),f&&p.jsx("path",{d:f}),g&&p.jsx("path",{d:g}),d&&p.jsx("rect",{x:$(y.x),y:$(y.y),width:y.w,height:y.h,rx:3.5,ry:3.5})]})}useLegacyIndicator(){return!1}getIndicatorPath(t){const r=us(this.editor,t);if(!r)return;const s=this.editor.getEditingShapeId()===t.id,{start:o,end:i}=pl(this.editor,t,r==null?void 0:r.bindings),a=this.editor.getShapeGeometry(t),l=Wt(t.props.richText),c=s||!l?a.children[1]:null;if(C.Equals(o,i))return;const u=Gt[t.props.size]*t.props.scale;if(s&&c){const v=c.getBounds(),P=new Path2D;return P.roundRect(v.x,v.y,v.w,v.h,3.5*t.props.scale),P}const d=this.editor.getEfficientZoomLevel()<t.props.scale*.25,f=e$(r).toPath2D(t.props.dash==="draw"&&!d?{style:"draw",randomSeed:t.id,strokeWidth:1,passes:1,offset:0,roundness:u*2}:{style:"solid",strokeWidth:1}),g=r.start.arrowhead&&Oc(r,"start",u),m=r.end.arrowhead&&Oc(r,"end",u),y=!!(g&&r.start.arrowhead!=="arrow"),S=!!(m&&r.end.arrowhead!=="arrow");if(c||y||S){const v=a.bounds,P=new Path2D;if(P.rect(v.minX-100,v.minY-100,v.width+200,v.height+200),c){const I=c.getBounds(),k=3.5*t.props.scale,A=I;P.moveTo(A.x,A.y+k),P.lineTo(A.x,A.maxY-k),P.arcTo(A.x,A.maxY,A.x+k,A.maxY,k),P.lineTo(A.maxX-k,A.maxY),P.arcTo(A.maxX,A.maxY,A.maxX,A.maxY-k,k),P.lineTo(A.maxX,A.y+k),P.arcTo(A.maxX,A.y,A.maxX-k,A.y,k),P.lineTo(A.x+k,A.y),P.arcTo(A.x,A.y,A.x,A.y+k,k),P.closePath()}y&&g&&P.addPath(new Path2D(g)),S&&m&&P.addPath(new Path2D(m));const T=[];if(g&&T.push(new Path2D(g)),m&&T.push(new Path2D(m)),c){const I=c.getBounds(),k=new Path2D;k.roundRect(I.x,I.y,I.w,I.h,3.5),T.push(k)}return{path:f,clipPath:P,additionalPaths:T}}const w=new Path2D;return w.addPath(f),g&&w.addPath(new Path2D(g)),m&&w.addPath(new Path2D(m)),w}onEditStart(t){if(Wt(t.props.richText)){const r=s$(this.editor,t);this.editor.updateShape({id:t.id,type:t.type,props:{labelPosition:r}})}}toSvg(t,r){r.addExportDef(mP(t.props.fill));const s=Ga(r),o=1/t.props.scale;return p.jsxs("g",{transform:`scale(${o})`,children:[p.jsx(o_,{shape:t,shouldDisplayHandles:!1}),p.jsx(BS,{fontSize:iv(t),font:t.props.font,align:"middle",verticalAlign:"middle",labelColor:st(s,t.props.labelColor,"solid"),richText:t.props.richText,bounds:tg(this.editor,t).box.clone().expandBy(-U0*t.props.scale),padding:0,showTextOutline:this.options.showTextOutline})]})}getCanvasSvgDefs(){return[yP(),{key:"arrow:dot",component:bge},{key:"arrow:cross",component:wge}]}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,scale:Ue(t.props.scale,r.props.scale,s),start:{x:Ue(t.props.start.x,r.props.start.x,s),y:Ue(t.props.start.y,r.props.start.y,s)},end:{x:Ue(t.props.end.x,r.props.end.x,s),y:Ue(t.props.end.y,r.props.end.y,s)},bend:Ue(t.props.bend,r.props.bend,s),labelPosition:Ue(t.props.labelPosition,r.props.labelPosition,s)}}}E(ng,"type","arrow"),E(ng,"props",RM),E(ng,"migrations",LM);const o_=rn(function({shape:e,shouldDisplayHandles:t}){const r=K(),s=Zs(),o=us(r,e),i=Ah(e.props.scale*.25),a=fo(e.id+"_clip"),l=fo("arrowhead-dot"),c=fo("arrowhead-cross"),u=qh(e.id),d=r.getShapeGeometry(e);if(!d)return null;const h=J.ZeroFix(d.bounds),f=En(r,e),g=Wt(e.props.richText);if(!(o!=null&&o.isValid))return null;const m=Gt[e.props.size]*e.props.scale,y=o.start.arrowhead&&Oc(o,"start",m),S=o.end.arrowhead&&Oc(o,"end",m);let b=null;t&&(f.start||f.end)&&(b=sge(o,{style:"dashed",start:"skip",end:"skip",lengthRatio:2.5,strokeWidth:2/r.getEfficientZoomLevel(),props:{className:"tl-arrow-hint",markerStart:f.start?f.start.props.isExact?"":f.start.props.isPrecise?`url(#${c})`:`url(#${l})`:"",markerEnd:f.end?f.end.props.isExact?"":f.end.props.isPrecise?`url(#${c})`:`url(#${l})`:"",opacity:.16}}));const w=tg(r,e),v=!(o.start.arrowhead==="none"||o.start.arrowhead==="arrow"),P=!(o.end.arrowhead==="none"||o.end.arrowhead==="arrow");return p.jsxs(p.Fragment,{children:[p.jsx("defs",{children:p.jsx("clipPath",{id:a,children:p.jsx(i$,{radius:3.5*e.props.scale,hasText:u||!g,bounds:h,labelBounds:w.box,as:v&&y?y:"",ae:P&&S?S:""})})}),p.jsxs("g",{fill:"none",stroke:st(s,e.props.color,"solid"),strokeWidth:m,strokeLinejoin:"round",strokeLinecap:"round",pointerEvents:"none",children:[b,p.jsxs("g",{style:{clipPath:`url(#${a})`,WebkitClipPath:`url(#${a})`},children:[p.jsx("rect",{x:$(h.minX-100),y:$(h.minY-100),width:$(h.width+200),height:$(h.height+200),opacity:0}),t$(e,o,{style:e.props.dash,strokeWidth:m,forceSolid:i,randomSeed:e.id})]}),y&&v&&e.props.fill!=="none"&&p.jsx(Mh,{theme:s,d:y,color:e.props.color,fill:e.props.fill,scale:e.props.scale}),S&&P&&e.props.fill!=="none"&&p.jsx(Mh,{theme:s,d:S,color:e.props.color,fill:e.props.fill,scale:e.props.scale}),y&&p.jsx("path",{d:y}),S&&p.jsx("path",{d:S})]})]})});function i$({radius:n,hasText:e,bounds:t,labelBounds:r,as:s,ae:o}){const i=x.useMemo(()=>{const a=new ct;return a.moveTo(t.left-100,t.top-100).lineTo(t.right+100,t.top-100).lineTo(t.right+100,t.bottom+100).lineTo(t.left-100,t.bottom+100).close(),e&&a.moveTo(r.left,r.top+n).lineTo(r.left,r.bottom-n).circularArcTo(n,!1,!1,r.left+n,r.bottom).lineTo(r.right-n,r.bottom).circularArcTo(n,!1,!1,r.right,r.bottom-n).lineTo(r.right,r.top+n).circularArcTo(n,!1,!1,r.right-n,r.top).lineTo(r.left+n,r.top).circularArcTo(n,!1,!1,r.left,r.top+n).close(),a.toD()},[n,e,t.bottom,t.left,t.right,t.top,r.bottom,r.left,r.right,r.top]);return p.jsx("path",{d:`${i}${s}${o}`})}const i_=new WeakMap;function bge(){const n=fo("arrowhead-dot");return p.jsx("marker",{id:n,className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"0",children:p.jsx("circle",{cx:"3",cy:"3",r:"2",strokeDasharray:"100%"})})}function wge(){const n=fo("arrowhead-cross");return p.jsxs("marker",{id:n,className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"auto",children:[p.jsx("line",{x1:"1.5",y1:"1.5",x2:"4.5",y2:"4.5",strokeDasharray:"100%"}),p.jsx("line",{x1:"1.5",y1:"4.5",x2:"4.5",y2:"1.5",strokeDasharray:"100%"})]})}function vge(n,e,t=1e-4){const r=Math.abs(n-e),s=r<t,o=Math.abs(r-Math.PI)<t,i=Math.abs(r-vt)<t;return{isParallel:s||i,isFlippedParallel:o}}const a_="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' fill='none'%3E%3Cpath stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M13 5H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6M19 5h6m0 0v6m0-6L13 17'/%3E%3C/svg%3E";function hd({url:n}){const e=K(),t=Ah(),r=x.useCallback(s=>{e.inputs.getShiftKey()||e.markEventAsHandled(s)},[e]);return p.jsx("a",{className:xe("tl-hyperlink-button",{"tl-hyperlink-button__hidden":t}),href:n,target:"_blank",rel:"noopener noreferrer",onPointerDown:r,onPointerUp:r,title:n,draggable:!1,children:p.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${a_}") center 100% / 100% no-repeat`,WebkitMask:`url("${a_}") center 100% / 100% no-repeat`}})})}const l_="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' fill='none'%3E%3Cpath stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M13 5H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6M19 5h6m0 0v6m0-6L13 17'/%3E%3C/svg%3E",Cge=[{offsetX:0,offsetY:2,blur:4,spread:0,color:"#00000029"},{offsetX:0,offsetY:3,blur:6,spread:0,color:"#0000001f"}];function Qm(n){return Cge.map(t=>{const{offsetX:r,offsetY:s,blur:o,spread:i,color:a}=t,l=new C(r,s),{x:c,y:u}=l.rot(-n);return`${c}px ${u}px ${o}px ${i}px ${a}`}).join(", ")}class rg extends Gs{canResize(){return!1}hideSelectionBoundsFg(){return!0}getText(e){return e.props.url}getAriaDescriptor(e){const t=e.props.assetId?this.editor.getAsset(e.props.assetId):null;if(t!=null&&t.props.title)return zz(t.props.title)+(t.props.description?", "+t.props.description:"")}getDefaultProps(){return{url:"",w:Wc,h:W1,assetId:null}}component(e){const{assetId:t,url:r,h:s}=e.props,o=this.editor.getShapePageTransform(e).rotation();return p.jsx(l$,{assetId:t,url:r,h:s,rotation:o})}indicator(e){return p.jsx(a$,{w:e.props.w,h:e.props.h})}useLegacyIndicator(){return!1}getIndicatorPath(e){const t=new Path2D;return t.roundRect(0,0,e.props.w,e.props.h,6),t}onBeforeCreate(e){return TE(this.editor,e)}onBeforeUpdate(e,t){if(e.props.url!==t.props.url)if(bs.isValid(t.props.url))pQ(this.editor,t);else return{...t,props:{...t.props,url:e.props.url}};if(e.props.assetId!==t.props.assetId)return TE(this.editor,t)}getInterpolatedProps(e,t,r){return{...r>.5?t.props:e.props,w:Ue(e.props.w,t.props.w,r),h:Ue(e.props.h,t.props.h,r)}}}E(rg,"type","bookmark"),E(rg,"props",$M),E(rg,"migrations",HM);function a$({w:n,h:e}){return p.jsx("rect",{width:$(n),height:$(e),rx:"6",ry:"6"})}function l$({assetId:n,rotation:e,url:t,h:r,showImageContainer:s=!0}){const o=K(),i=n?o.getAsset(n):null,a=!!Hh()&&dt.isSafari,l=hQ(t),[c,u]=x.useState(!0),d=()=>u(!1),h=x.useCallback(f=>{o.inputs.getShiftKey()||o.markEventAsHandled(f)},[o]);return p.jsx(Jr,{children:p.jsxs("div",{className:xe("tl-bookmark__container",a&&"tl-bookmark__container--safariExport"),style:{boxShadow:a?void 0:Qm(e),maxHeight:r},children:[s&&(!i||i.props.image)&&p.jsxs("div",{className:"tl-bookmark__image_container",children:[i?p.jsx("img",{className:"tl-bookmark__image",draggable:!1,referrerPolicy:"strict-origin-when-cross-origin",src:i==null?void 0:i.props.image,alt:(i==null?void 0:i.props.title)||""}):p.jsx("div",{className:"tl-bookmark__placeholder"}),(i==null?void 0:i.props.image)&&p.jsx(hd,{url:t})]}),p.jsxs("div",{className:"tl-bookmark__copy_container",children:[i!=null&&i.props.title?p.jsx("a",{className:"tl-bookmark__link",href:t||"",target:"_blank",rel:"noopener noreferrer",draggable:!1,onPointerDown:h,onPointerUp:h,children:p.jsx("h2",{className:"tl-bookmark__heading",children:zz(i.props.title)})}):null,i!=null&&i.props.description&&(i!=null&&i.props.image)?p.jsx("p",{className:"tl-bookmark__description",children:i.props.description}):null,p.jsxs("a",{className:"tl-bookmark__link",href:t||"",target:"_blank",rel:"noopener noreferrer",draggable:!1,onPointerDown:h,onPointerUp:h,children:[c&&(i!=null&&i.props.favicon)?p.jsx("img",{className:"tl-bookmark__favicon",src:i==null?void 0:i.props.favicon,referrerPolicy:"strict-origin-when-cross-origin",onError:d,alt:`favicon of ${l}`}):p.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${l_}") center 100% / 100% no-repeat`,WebkitMask:`url("${l_}") center 100% / 100% no-repeat`}}),p.jsx("span",{children:l})]})]})]})})}function Ul(n,e=!1){const t=n.length;if(t<2)return"";let r=n[0].point,s=n[1].point;if(t===2)return`M${jn(r)}L${jn(s)}`;let o="";for(let i=2,a=t-1;i<a;i++)r=n[i].point,s=n[i+1].point,o+=Vr(r,s);return e?`M${Vr(n[0].point,n[1].point)}Q${jn(n[1].point)}${Vr(n[1].point,n[2].point)}T${o}${Vr(n[t-1].point,n[0].point)}${Vr(n[0].point,n[1].point)}Z`:`M${jn(n[0].point)}Q${jn(n[1].point)}${Vr(n[1].point,n[2].point)}${n.length>3?"T":""}${o}L${jn(n[t-1].point)}`}function Pge(n,e={}){const{start:t={},end:r={}}=e,{cap:s=!0}=t,{cap:o=!0}=r;be(!t.taper&&!r.taper,"cap taper not supported here"),be(!t.easing&&!r.easing,"cap easing not supported here"),be(s&&o,"cap must be true");const i=zi(n,e);eP(i,e);const a=Tge(i);let l="";for(const c of a)l+=Ege(c,e);return l}function Tge(n){if(n.length<=2)return[n];const e=[];let t=[n[0]],r=C.Sub(n[1].point,n[0].point).uni(),s,o,i,a,l;for(let c=1,u=n.length;c<u-1;c++){if(i=n[c-1],a=n[c],l=n[c+1],s=C.Sub(l.point,a.point).uni(),o=C.Dpr(r,s),r=s,o<-.8){const d={...a,point:a.input};t.push(d),e.push(Kb(t)),t=[d];continue}if(t.push(a),!(o>.7)&&(C.Dist2(i.point,a.point)+C.Dist2(a.point,l.point))/((i.radius+a.radius+l.radius)/3)**2<1.5){t.push(a),e.push(Kb(t)),t=[a];continue}}return t.push(n[n.length-1]),e.push(Kb(t)),e}function Kb(n){const e=n[0];let t;for(;n.length>2&&(t=n[1],C.Dist2(e.point,t.point)<((e.radius+t.radius)/2*.5)**2);)n.splice(1,1);const r=n[n.length-1];let s;for(;n.length>2&&(s=n[n.length-2],C.Dist2(r.point,s.point)<((r.radius+s.radius)/2*.5)**2);)n.splice(n.length-2,1);return n.length>1&&(n[0]={...n[0],vector:C.Sub(n[0].point,n[1].point).uni()},n[n.length-1]={...n[n.length-1],vector:C.Sub(n[n.length-2].point,n[n.length-1].point).uni()}),n}function Ige(n,e,t){return"M "+n+" "+e+" m -"+t+", 0 a "+t+","+t+" 0 1,1 "+t*2+",0 a "+t+","+t+" 0 1,1 -"+t*2+",0"}function Ege(n,e={}){if(n.length===0)return"";if(n.length===1)return Ige(n[0].point.x,n[0].point.y,n[0].radius);const{left:t,right:r}=az(n,e);r.reverse();let s=`M${jn(t[0])}T`;for(let o=1;o<t.length;o++)s+=Vr(t[o-1],t[o]);{const o=n[n.length-1],i=o.radius,a=o.vector.clone().per().neg(),l=C.Add(o.point,C.Mul(a,i)),c=C.Add(o.point,C.Mul(a,-i));s+=`${jn(l)}A${$(i)},${$(i)} 0 0 1 ${jn(c)}T`}for(let o=1;o<r.length;o++)s+=Vr(r[o-1],r[o]);{const o=n[0],i=o.radius,a=o.vector.clone().per(),l=C.Add(o.point,C.Mul(a,i)),c=C.Add(o.point,C.Mul(a,-i));s+=`${jn(l)}A${$(i)},${$(i)} 0 0 1 ${jn(c)}Z`}return s}const c$=(n,e,t)=>{const r=[],s=[];n.forEach(c=>r.push(...ot.decodePoints(c.path))),e.forEach(c=>s.push(...ot.decodePoints(c.path)));const o=Math.max(r.length,s.length),i=[],a=[];for(let c=0;c<o;c++)i.push(r[c]||r[r.length-1]),a.push(s[c]||s[s.length-1]);const l=i.map((c,u)=>{let d=.5;return a[u].z!==void 0&&c.z!==void 0&&(d=Ue(c.z,a[u].z,t)),{x:Ue(c.x,a[u].x,t),y:Ue(c.y,a[u].y,t),z:d}});return[{type:"free",path:ot.encodePoints(l)}]};class sg extends go{constructor(){super(...arguments);E(this,"options",{maxPointsPerShape:600})}hideResizeHandles(t){return Wb(t)}hideRotateHandle(t){return Wb(t)}hideSelectionBoundsFg(t){return Wb(t)}getDefaultProps(){return{segments:[],color:"black",fill:"none",dash:"draw",size:"m",isComplete:!1,isClosed:!1,isPen:!1,scale:1,scaleX:1,scaleY:1}}getGeometry(t){const r=Ma(t.props.segments,t.props.scaleX,t.props.scaleY),s=(Gt[t.props.size]+1)*t.props.scale;if(t.props.segments.length===1){const i=J.FromPoints(r);if(i.width<s*2&&i.height<s*2)return new Gg({x:-s,y:-s,radius:s,isFilled:!0})}const o=zi(r,Wf(t.props,s,t.props.isPen,!0)).map(i=>i.point);return t.props.isClosed&&o.length>2?new ah({points:o,isFilled:t.props.fill!=="none"}):o.length===1?new Gg({x:-s,y:-s,radius:s,isFilled:!0}):new $h({points:o})}component(t){return p.jsx(Ra,{children:p.jsx(c_,{shape:t})})}indicator(t){var u;const r=Ma(t.props.segments,t.props.scaleX,t.props.scaleY);let s=(Gt[t.props.size]+1)*t.props.scale;!W("force solid",()=>{const d=this.editor.getEfficientZoomLevel();return d<.5&&d<1.5/s},[this.editor,s])&&!t.props.isPen&&t.props.dash==="draw"&&r.length===1&&(s+=Aa(t.id)()*(s/6));const i=t.props.isComplete||((u=gs(t.props.segments))==null?void 0:u.type)==="straight",a=Wf(t.props,s,i,!0),l=zi(r,a),c=l.length>1?Ul(l,t.props.isClosed):av(r[0],s);return p.jsx("path",{d:c})}useLegacyIndicator(){return!1}getIndicatorPath(t){var d;const r=Ma(t.props.segments,t.props.scaleX,t.props.scaleY);let s=(Gt[t.props.size]+1)*t.props.scale;const o=this.editor.getEfficientZoomLevel();!(o<.5&&o<1.5/s)&&!t.props.isPen&&t.props.dash==="draw"&&r.length===1&&(s+=Aa(t.id)()*(s/6));const a=t.props.isComplete||((d=gs(t.props.segments))==null?void 0:d.type)==="straight",l=Wf(t.props,s,a,!0),c=zi(r,l),u=c.length>1?Ul(c,t.props.isClosed):av(r[0],s);return new Path2D(u)}toSvg(t,r){r.addExportDef(mP(t.props.fill));const s=1/t.props.scale;return p.jsx("g",{transform:`scale(${s})`,children:p.jsx(c_,{shape:t,zoomOverride:1})})}getCanvasSvgDefs(){return[yP()]}onResize(t,r){const{scaleX:s,scaleY:o}=r;return{props:{scaleX:s*t.props.scaleX,scaleY:o*t.props.scaleY}}}expandSelectionOutlinePx(t){const r=t.props.dash==="draw"?1.6:1;return Gt[t.props.size]*r/2*t.props.scale}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,segments:c$(t.props.segments,r.props.segments,s),scale:Ue(t.props.scale,r.props.scale,s)}}}E(sg,"type","draw"),E(sg,"props",VM),E(sg,"migrations",GM);function av(n,e){const t=(e+1)*.5;return`M ${n.x} ${n.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function Wb(n){return n.props.segments.length===1&&n.props.segments[0].path.length<24}function c_({shape:n,zoomOverride:e}){var f;const t=Zs(),r=K(),s=Ma(n.props.segments,n.props.scaleX,n.props.scaleY),o=n.props.isComplete||((f=gs(n.props.segments))==null?void 0:f.type)==="straight";let i=(Gt[n.props.size]+1)*n.props.scale;const a=W("force solid",()=>{const g=e??r.getEfficientZoomLevel();return g<.5&&g<1.5/i},[r,i,e]),l=W("dot adjustment",()=>(e??r.getEfficientZoomLevel())<.2?9:.1,[r,e]);!a&&!n.props.isPen&&n.props.dash==="draw"&&s.length===1&&(i+=Aa(n.id)()*(i/6));const c=Wf(n.props,i,o,a);if(!a&&n.props.dash==="draw")return p.jsxs(p.Fragment,{children:[n.props.isClosed&&n.props.fill&&s.length>1?p.jsx(Mh,{d:Ul(zi(s,c),n.props.isClosed),theme:t,color:n.props.color,fill:n.props.isClosed?n.props.fill:"none",scale:n.props.scale}):null,p.jsx("path",{d:Pge(s,c),strokeLinecap:"round",fill:st(t,n.props.color,"solid")})]});const u=zi(s,c),d=u.length<2,h=d?av(s[0],0):Ul(u,n.props.isClosed);return p.jsxs(p.Fragment,{children:[p.jsx(Mh,{d:h,theme:t,color:n.props.color,fill:d||n.props.isClosed?n.props.fill:"none",scale:n.props.scale}),p.jsx("path",{d:h,strokeLinecap:"round",fill:d?st(t,n.props.color,"solid"):"none",stroke:st(t,n.props.color,"solid"),strokeWidth:i,strokeDasharray:d?"none":tQ(n,i,l),strokeDashoffset:"0"})]})}function kge(n){if(typeof n!="string")throw new TypeError("Expected a string");return n.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function _ge(n,e){const t=ze(e);if(!t)return;const r=t.host.replace("www.","");for(const s of n)if(d$(s.hostnames,r)){const o=s.fromEmbedUrl(e);if(o)return{definition:s,url:o,embedUrl:e}}}const Mge=n=>n.split("*").map(e=>kge(e)).join(".+"),d$=(n,e)=>!!n.find(t=>{const r=new RegExp(Mge(t));return e.match(r)});function Age(n,e){const t=ze(e);if(!t)return;const r=t.host.replace("www.","");for(const s of n)if(d$(s.hostnames,r)){const o=s.toEmbedUrl(e);if(o)return{definition:s,embedUrl:o,url:e}}}function Dge(n,e){try{return Age(n,e)??_ge(n,e)}catch{return}}const Oge=n=>Object.entries(n).filter(([e,t])=>t).map(([e])=>e).join(" "),Mi=class Mi extends Gs{canEditWhileLocked(e){const t=this.getEmbedDefinition(e.props.url);return t?t.definition.canEditWhileLocked??!0:!0}static setEmbedDefinitions(e){Mi.embedDefinitions=e}getEmbedDefinitions(){return Mi.embedDefinitions}getEmbedDefinition(e){return Dge(Mi.embedDefinitions,e)}getText(e){return e.props.url}getAriaDescriptor(e){const t=this.getEmbedDefinition(e.props.url);return t==null?void 0:t.definition.title}hideSelectionBoundsFg(e){return!this.canResize(e)}canEdit(){return!0}canResize(e){var t,r;return!!((r=(t=this.getEmbedDefinition(e.props.url))==null?void 0:t.definition)!=null&&r.doesResize)}canEditInReadonly(){return!0}getDefaultProps(){return{w:300,h:300,url:""}}getGeometry(e){const t=this.getEmbedDefinition(e.props.url);return t!=null&&t.definition?super.getGeometry(e):new bo({width:Wc,height:Vf,isFilled:!0})}isAspectRatioLocked(e){const t=this.getEmbedDefinition(e.props.url);return(t==null?void 0:t.definition.isAspectRatioLocked)??!1}onResize(e,t){const r=this.isAspectRatioLocked(e),s=this.getEmbedDefinition(e.props.url);let o=(s==null?void 0:s.definition.minWidth)??200,i=(s==null?void 0:s.definition.minHeight)??200;if(r){const a=e.props.w/e.props.h;a>1?o*=a:i/=a}return ky(e,t,{minWidth:o,minHeight:i})}component(e){const t=Hh(),{w:r,h:s,url:o}=e.props,i=qh(e.id),a=this.getEmbedDefinition(o),l=W("is hovering",()=>{const{editingShapeId:f,hoveredShapeId:g}=this.editor.getCurrentPageState();if(f&&g!==f){const m=this.editor.getShape(f);if(m&&this.editor.isShapeOfType(m,"embed"))return!0}return!1},[]),c=this.editor.getShapePageTransform(e).rotation();if(t)return p.jsx(Jr,{className:"tl-embed-container",id:e.id,children:p.jsx("div",{className:"tl-embed",style:{border:0,boxShadow:Qm(c),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:(a==null?void 0:a.definition.backgroundColor)??"var(--tl-color-background)",width:r,height:s}})});const u=i||l;if(typeof window<"u"&&(window!==window.top||window.self!==window.parent)&&(a==null?void 0:a.definition.type)==="tldraw")return null;if((a==null?void 0:a.definition.type)==="github_gist"){const f=a.url.split("/").pop();if(!f)throw Error("No gist id!");return p.jsx(Jr,{className:"tl-embed-container",id:e.id,children:p.jsx(Rge,{id:f,width:$(r),height:$(s),isInteractive:u,pageRotation:c})})}const h=Oge({...gie,...(a==null?void 0:a.definition.overridePermissions)??{}});return p.jsx(Jr,{className:"tl-embed-container",id:e.id,children:a!=null&&a.definition?p.jsx("iframe",{className:"tl-embed",sandbox:h,src:a.embedUrl,width:$(r),height:$(s),draggable:!1,frameBorder:"0",referrerPolicy:"no-referrer-when-downgrade",tabIndex:i?0:-1,allowFullScreen:!0,style:{border:0,pointerEvents:u?"auto":"none",zIndex:u?"":"-1",boxShadow:Qm(c),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:a==null?void 0:a.definition.backgroundColor}}):p.jsx(l$,{url:o,h:s,rotation:c,assetId:null,showImageContainer:!1})})}indicator(e){const t=this.getEmbedDefinition(e.props.url);return t!=null&&t.definition?p.jsx("rect",{width:$(e.props.w),height:$(e.props.h),rx:(t==null?void 0:t.definition.overrideOutlineRadius)??8,ry:(t==null?void 0:t.definition.overrideOutlineRadius)??8}):p.jsx(a$,{w:Wc,h:Vf})}useLegacyIndicator(){return!1}getIndicatorPath(e){const t=new Path2D,r=this.getEmbedDefinition(e.props.url);if(r!=null&&r.definition){const s=r.definition.overrideOutlineRadius??8;t.roundRect(0,0,e.props.w,e.props.h,s)}else t.roundRect(0,0,Wc,Vf,6);return t}getInterpolatedProps(e,t,r){return{...r>.5?t.props:e.props,w:Ue(e.props.w,t.props.w,r),h:Ue(e.props.h,t.props.h,r)}}};E(Mi,"type","embed"),E(Mi,"props",YM),E(Mi,"migrations",XM),E(Mi,"embedDefinitions",NC);let ey=Mi;function Rge({id:n,isInteractive:e,width:t,height:r,style:s,pageRotation:o}){if(!n.match(/^[0-9a-f]+$/))throw Error("No gist id!");return p.jsx("iframe",{className:"tl-embed",draggable:!1,width:$(t),height:$(r),frameBorder:"0",scrolling:"no",referrerPolicy:"no-referrer-when-downgrade",tabIndex:e?0:-1,style:{...s,pointerEvents:e?"all":"none",zIndex:e?"":"-1",boxShadow:Qm(o)},srcDoc:`
519
+ <html>
520
+ <head>
521
+ <base target="_blank">
522
+ </head>
523
+ <body>
524
+ <script src=${`https://gist.github.com/${n}.js`}><\/script>
525
+ <style type="text/css">
526
+ * { margin: 0px; }
527
+ table { height: 100%; background-color: red; }
528
+ .gist { background-color: none; height: 100%; }
529
+ .gist .gist-file { height: calc(100vh - 2px); padding: 0px; display: grid; grid-template-rows: 1fr auto; }
530
+ </style>
531
+ </body>
532
+ </html>`})}function Lge(n){return n.replace(/\s/g," ")}function jge(n,e,t){const{padding:r=0}=t;if(e.length===0)return null;const s=J.From(e[0].box);for(const{box:c}of e)s.union(c);const o=r+(t.offsetX??0),i=(t.offsetY??0)+t.fontSize/2+(t.verticalTextAlign==="start"?r:t.verticalTextAlign==="end"?t.height-r-s.height:(Math.ceil(t.height)-s.height)/2);let a=null;const l=[];for(const{text:c,box:u}of e)a!==null&&u.y>a&&l.push(p.jsx("tspan",{alignmentBaseline:"mathematical",x:o,y:u.y+i,children:`
533
+ `},l.length)),l.push(p.jsx("tspan",{alignmentBaseline:"mathematical",x:u.x+o,y:u.y+i,unicodeBidi:"plaintext",children:Lge(c)},l.length)),a=u.y;return p.jsx("text",{fontSize:t.fontSize,fontFamily:t.fontFamily,fontStyle:t.fontStyle,fontWeight:t.fontWeight,dominantBaseline:"mathematical",alignmentBaseline:"mathematical",stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,children:l})}function lv(n,e){const s=((Fg(n.getShapePageTransform(e.id).rotation())+Math.PI/4)*(2/Math.PI)+4)%4;return Math.floor(s)}const d_=new WeakMap;function u_(n,e,t){let r=d_.get(e.props);if(!r){const s=xP(e.props.name,"Frame")+"​",o=n.textMeasure.measureTextSpans(s,t),i=o[0],a=gs(o);r=a.box.w+a.box.x-i.box.x,d_.set(e.props,r)}return new J(0,-t.height,r,t.height)}function h_(n,e){return{fontSize:12,fontFamily:e?"Arial":"Inter, sans-serif",textAlign:"start",width:n,height:24,padding:0,lineHeight:1,fontStyle:"normal",fontWeight:"normal",overflow:"truncate-ellipsis",verticalTextAlign:"middle",offsetY:-34,offsetX:0}}function u$(n,e,t){const r=t?"":"px",s=t?"":"deg";let o;switch(e){case 0:o="";break;case 3:o=`translate(${$(n.props.w)}${r}, 0${r}) rotate(90${s})`;break;case 2:o=`translate(${$(n.props.w)}${r}, ${$(n.props.h)}${r}) rotate(180${s})`;break;case 1:o=`translate(0${r}, ${$(n.props.h)}${r}) rotate(270${s})`;break;default:throw Error("labelSide out of bounds")}return o}const Nge=x.forwardRef(({id:n,name:e,isEditing:t},r)=>{const s=K(),o=Gn(),i=W("isCoarsePointer",()=>s.getInstanceState().isCoarsePointer,[s]),a=o<Ot.TABLET_SM&&i,l=x.useRef(!1),c=Se(),u=x.useCallback(m=>{t&&s.markEventAsHandled(m)},[s,t]),d=x.useCallback(m=>{m.key==="Enter"&&!m.nativeEvent.isComposing&&(s.markEventAsHandled(m),m.currentTarget.blur(),s.setEditingShape(null))},[s]),h=x.useCallback(m=>{const y=s.getShape(n);!y||y.props.name===m||s.updateShapes([{id:n,type:"frame",props:{name:m}}])},[n,s]),f=x.useCallback(m=>{h(m.currentTarget.value)},[h]),g=x.useCallback(m=>{h(m.currentTarget.value)},[h]);return x.useEffect(()=>{if(!t){l.current=!1;return}if(t&&a&&!l.current){l.current=!0;const m=s.getShape(n),y=(m==null?void 0:m.props.name)??"",S=window.prompt(c("action.rename"),y);l.current=!1,S!==null&&h(S),s.setEditingShape(null)}},[t,a,n,c,h,s]),p.jsxs("div",{className:`tl-frame-label ${t&&!a?"tl-frame-label__editing":""}`,children:[p.jsx("input",{className:"tl-frame-name-input",ref:r,disabled:!t||a,readOnly:!t||a,style:{display:t?void 0:"none"},value:e,autoFocus:!a,onKeyDown:d,onBlur:f,onChange:g,onPointerDown:u,draggable:!1}),xP(e,"Frame")+"​"]})}),Fge=x.memo(function({id:e,name:t,width:r,height:s,fill:o,stroke:i,color:a,offsetX:l,showColors:c}){const u=K(),{side:d,translation:h}=W("shape rotation",()=>{const m=u.getShape(e);if(!m)return{side:0,translation:"translate(0, 0)"};const y=lv(u,m);return{side:y,translation:u$(m,y,!1)}},[u,l,e]),f=x.useRef(null),g=qh(e);return x.useEffect(()=>{const m=f.current;m&&g&&(m.focus(),m.select())},[f,g]),p.jsx("div",{className:"tl-frame-heading",style:{overflow:g?"visible":"hidden",maxWidth:`calc(var(--tl-zoom) * ${Math.ceil(d===0||d===2?r:s)}px + ${c?"0px":"var(--tl-frame-offset-width)"})`,bottom:"100%",transform:`${h} scale(min(var(--tl-scale), 3.5)) translateX(${l}px)`},children:p.jsx("div",{className:"tl-frame-heading-hit-area",style:{color:a,backgroundColor:o,boxShadow:`inset 0px 0px 0px 1px ${i}`},children:p.jsx(Nge,{ref:f,id:e,name:t,isEditing:g})})})}),Bge=12,zge=32,$ge=-7,Hge=4;function xP(n,e){return n.match(/^\s*$/)?e:n}class og extends Gs{constructor(){super(...arguments);E(this,"options",{showColors:!1,resizeChildren:!1})}static configure(t){const r=super.configure.call(this,t);return t.showColors&&(r.props={...r.props,color:Rr}),r}canEdit(t,r){return r.type==="click-header"||r.type==="unknown"}canResize(){return!0}canResizeChildren(){return this.options.resizeChildren}isExportBoundsContainer(){return!0}getDefaultProps(){return{w:320,h:180,name:"",color:"black"}}getAriaDescriptor(t){return t.props.name}getGeometry(t){const{editor:r}=this,s=r.getEfficientZoomLevel(),o=lv(r,t),i=o%2===1,a=i?t.props.h:t.props.w,l=h_(a,!1),c=u_(r,t,l),u=this.options.showColors,d=Bge/s,h=zge/s,f=a+(u?1:d),g=c.w/s,m=c.h/s,y=Fe(g+d,h,f),S=(u?-1:$ge)/s,b=Hge/s,w=i?m:y,v=i?y:m;let P,T;switch(o){case 0:{P=S,T=-(m+b);break}case 1:{P=-(m+b),T=t.props.h-(S+y);break}case 2:{P=t.props.w-(S+y),T=t.props.h+b;break}case 3:{P=t.props.w+b,T=S;break}}return new es({children:[new bo({width:t.props.w,height:t.props.h,isFilled:!1}),new bo({x:P,y:T,width:w,height:v,isFilled:!0,isLabel:!0,excludeFromShapeBounds:!0})]})}getText(t){return t.props.name}component(t){const r=Zs(),s=W("is creating this shape",()=>{const h=this.editor.getStateDescendant("select.resizing");if(!h||!h.getIsActive())return!1;const f=h==null?void 0:h.info;return f?f.isCreating&&this.editor.getOnlySelectedShapeId()===t.id:!1},[t.id]),o=this.options.showColors,i=o?t.props.color:"black",a=st(r,i,"frameFill"),l=st(r,i,"frameStroke"),c=o?st(r,i,"frameHeadingStroke"):r.background,u=o?st(r,i,"frameHeadingFill"):r.background,d=st(r,i,"frameText");return p.jsxs(p.Fragment,{children:[p.jsx(Ra,{children:p.jsx("rect",{className:xe("tl-frame__body",{"tl-frame__creating":s}),fill:a,stroke:l,style:{width:`calc(${t.props.w}px + 1px / var(--tl-zoom))`,height:`calc(${t.props.h}px + 1px / var(--tl-zoom))`,transform:"translate(calc(-0.5px / var(--tl-zoom)), calc(-0.5px / var(--tl-zoom)))"}})}),s?null:p.jsx(Fge,{id:t.id,name:t.props.name,fill:u,stroke:c,color:d,width:t.props.w,height:t.props.h,offsetX:o?-1:-7,showColors:this.options.showColors})]})}toSvg(t,r){const s=Ga({isDarkMode:r.isDarkMode}),o=lv(this.editor,t),a=o%2===1?t.props.h:t.props.w,l=u$(t,o,!0),c=h_(a-12,!0),u=xP(t.props.name,"Frame")+"​",d=u_(this.editor,t,c),h=this.editor.textMeasure.measureTextSpans(u,c),f=jge(this.editor,h,c),g=this.options.showColors,m=g?t.props.color:"black",y=st(s,m,"frameFill"),S=st(s,m,"frameStroke"),b=g?st(s,m,"frameHeadingStroke"):s.background,w=g?st(s,m,"frameHeadingFill"):s.background,v=st(s,m,"frameText");return p.jsxs(p.Fragment,{children:[p.jsx("rect",{width:t.props.w,height:t.props.h,fill:y,stroke:S,strokeWidth:1,x:0,rx:0,ry:0}),p.jsxs("g",{fill:v,transform:l,children:[p.jsx("rect",{x:d.x-(g?0:6),y:d.y-6,width:Math.min(a,d.width+12),height:d.height,fill:w,stroke:b,rx:4,ry:4}),p.jsx("g",{transform:`translate(${g?8:0}, 4)`,children:f})]})]})}indicator(t){return p.jsx("rect",{width:$(t.props.w),height:$(t.props.h)})}useLegacyIndicator(){return!1}getIndicatorPath(t){const r=new Path2D;return r.rect(0,0,t.props.w,t.props.h),r}providesBackgroundForChildren(){return!0}getClipPath(t){return this.editor.getShapeGeometry(t.id).vertices}canReceiveNewChildrenOfType(t){return!t.isLocked}onResize(t,r){return ky(t,r)}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,w:Ue(t.props.w,r.props.w,s),h:Ue(t.props.h,r.props.h,s)}}onDoubleClickEdge(t,r){if(r.target!=="selection")return;const{handle:s}=r;if(!s)return;const o=s==="left"||s==="right",i=s==="top"||s==="bottom",a=this.editor.getSortedChildIdsForParent(t.id),l=Le(a.map(f=>this.editor.getShape(f)));if(!l.length)return;const{dx:c,dy:u,w:d,h}=Qj(l,this.editor,{padding:10});return this.editor.run(()=>{const f=a.map(g=>{const m=this.editor.getShape(g);return{id:m.id,type:m.type,x:o?m.x+c:m.x,y:i?m.y+u:m.y}});this.editor.updateShapes(f)}),{id:t.id,type:t.type,props:{w:o?d:t.props.w,h:i?h:t.props.h}}}onDoubleClickCorner(t){return eN(this.editor,t.id,{padding:10}),{id:t.id,type:t.type}}onDragShapesIn(t,r,{initialParentIds:s,initialIndices:o}){const{editor:i}=this;if(r.every(c=>c.parentId===t.id))return;let a=!1;const l=r.filter(c=>t.id===s.get(c.id));if(l.length>0){const c=Le(i.getSortedChildIdsForParent(t).map(u=>i.getShape(u)));l.every(u=>!c.find(d=>d.index===u.index))&&(a=!0)}if(!r.some(c=>i.hasAncestor(t,c.id))&&(i.reparentShapes(r,t.id),a))for(const c of l)i.updateShape({id:c.id,type:c.type,index:o.get(c.id)})}onDragShapesOut(t,r,s){const{editor:o}=this;s.nextDraggingOverShapeId||o.reparentShapes(r.filter(i=>i.parentId===t.id&&this.canReceiveNewChildrenOfType(i)),o.getCurrentPageId())}}E(og,"type","frame"),E(og,"props",qM),E(og,"migrations",ZM);const Uge=new Vn;function ig(n){return Uge.get(n,Kge)}function Kge(n){const e=Math.max(1,n.props.w),t=Math.max(1,n.props.h+n.props.growY),r=e/2,s=t/2,o=qr[n.props.size]*n.props.scale,i=n.props.fill!=="none";switch(n.props.geo){case"arrow-down":{const a=e*.16,l=Math.min(e,t)*.38;return new ct().moveTo(a,0,{geometry:{isFilled:i}}).lineTo(e-a,0).lineTo(e-a,t-l).lineTo(e,t-l).lineTo(e/2,t).lineTo(0,t-l).lineTo(a,t-l).close()}case"arrow-left":{const a=Math.min(e,t)*.38,l=t*.16;return new ct().moveTo(a,0,{geometry:{isFilled:i}}).lineTo(a,l).lineTo(e,l).lineTo(e,t-l).lineTo(a,t-l).lineTo(a,t).lineTo(0,t/2).close()}case"arrow-right":{const a=Math.min(e,t)*.38,l=t*.16;return new ct().moveTo(0,l,{geometry:{isFilled:i}}).lineTo(e-a,l).lineTo(e-a,0).lineTo(e,t/2).lineTo(e-a,t).lineTo(e-a,t-l).lineTo(0,t-l).close()}case"arrow-up":{const a=e*.16,l=Math.min(e,t)*.38;return new ct().moveTo(e/2,0,{geometry:{isFilled:i}}).lineTo(e,l).lineTo(e-a,l).lineTo(e-a,t).lineTo(a,t).lineTo(a,l).lineTo(0,l).close()}case"check-box":{const a=Math.min(e,t)*.82,l=(e-a)/2,c=(t-a)/2;return new ct().moveTo(0,0,{geometry:{isFilled:i}}).lineTo(e,0).lineTo(e,t).lineTo(0,t).close().moveTo(Fe(l+a*.25,0,e),Fe(c+a*.52,0,t),{geometry:{isInternal:!0,isFilled:!1},offset:0}).lineTo(Fe(l+a*.45,0,e),Fe(c+a*.82,0,t)).lineTo(Fe(l+a*.82,0,e),Fe(c+a*.22,0,t),{offset:0})}case"diamond":return new ct().moveTo(r,0,{geometry:{isFilled:i}}).lineTo(e,s).lineTo(r,t).lineTo(0,s).close();case"ellipse":return new ct().moveTo(0,s,{geometry:{isFilled:i}}).arcTo(r,s,!1,!0,0,e,s).arcTo(r,s,!1,!0,0,0,s).close();case"heart":{const a=e/4,l=t/4;return new ct().moveTo(r,t,{geometry:{isFilled:i}}).cubicBezierTo(0,l*1.2,a*1.5,l*3,0,l*2.5).cubicBezierTo(r,l*.9,0,-l*.32,a*1.85,-l*.32).cubicBezierTo(e,l*1.2,a*2.15,-l*.32,e,-l*.32).cubicBezierTo(r,t,e,l*2.5,a*2.5,l*3).close()}case"hexagon":return ct.lineThroughPoints(Ex(e,t,6),{geometry:{isFilled:i}}).close();case"octagon":return ct.lineThroughPoints(Ex(e,t,8),{geometry:{isFilled:i}}).close();case"oval":return Vge(e,t,i);case"pentagon":return ct.lineThroughPoints(Ex(e,t,5),{geometry:{isFilled:i}}).close();case"rectangle":return new ct().moveTo(0,0,{geometry:{isFilled:i}}).lineTo(e,0).lineTo(e,t).lineTo(0,t).close();case"rhombus":{const a=Math.min(e*.38,t*.38);return new ct().moveTo(a,0,{geometry:{isFilled:i}}).lineTo(e,0).lineTo(e-a,t).lineTo(0,t).close()}case"rhombus-2":{const a=Math.min(e*.38,t*.38);return new ct().moveTo(0,0,{geometry:{isFilled:i}}).lineTo(e-a,0).lineTo(e,t).lineTo(a,t).close()}case"star":return Gge(e,t,i);case"trapezoid":{const a=Math.min(e*.38,t*.38);return new ct().moveTo(a,0,{geometry:{isFilled:i}}).lineTo(e-a,0).lineTo(e,t).lineTo(0,t).close()}case"triangle":return new ct().moveTo(r,0,{geometry:{isFilled:i}}).lineTo(e,t).lineTo(0,t).close();case"x-box":return Wge(e,t,o,n.props.dash,i);case"cloud":return Zge(e,t,n.id,n.props.size,n.props.scale,i);default:it(n.props.geo)}}function Wge(n,e,t,r,s){const o=n/2,i=e/2,a=new ct().moveTo(0,0,{geometry:{isFilled:s}}).lineTo(n,0).lineTo(n,e).lineTo(0,e).close();if(r==="dashed"||r==="dotted")return a.moveTo(0,0,{geometry:{isInternal:!0,isFilled:!1},dashStart:"skip",dashEnd:"outset"}).lineTo(o,i).moveTo(n,e,{geometry:{isInternal:!0,isFilled:!1},dashStart:"skip",dashEnd:"outset"}).lineTo(o,i).moveTo(0,e,{geometry:{isInternal:!0,isFilled:!1},dashStart:"skip",dashEnd:"outset"}).lineTo(o,i).moveTo(n,0,{geometry:{isInternal:!0,isFilled:!1},dashStart:"skip",dashEnd:"outset"}).lineTo(o,i);const l=r==="draw"?.62:0;return a.moveTo(Fe(t*l,0,n),Fe(t*l,0,e),{geometry:{isInternal:!0,isFilled:!1}}).lineTo(Fe(n-t*l,0,n),Fe(e-t*l,0,e)).moveTo(Fe(n-t*l,0,n),Fe(t*l,0,e)).lineTo(Fe(t*l,0,n),Fe(e-t*l,0,e)),a}function Vge(n,e,t){if(e>n){const s=n/2;return new ct().moveTo(0,s,{geometry:{isFilled:t}}).arcTo(s,s,!1,!0,0,n,s).lineTo(n,e-s).arcTo(s,s,!1,!0,0,0,e-s).close()}const r=e/2;return new ct().moveTo(r,e,{geometry:{isFilled:t}}).arcTo(r,r,!1,!0,0,r,0).lineTo(n-r,0).arcTo(r,r,!1,!0,0,n-r,e).close()}function Gge(n,e,t){const s=vt/5/2,o=Math.floor(5/4)*2,i=10-o,a=0,l=Math.floor(5/2)*2,c=Math.cos(-Bt+o*s)*n/2,u=Math.cos(-Bt+i*s)*n/2,d=Math.sin(-Bt+a*s)*e/2,h=Math.sin(-Bt+l*s)*e/2,f=n-Math.abs(c-u),g=e-Math.abs(h-d),m=n/2+u-(n/2-c),y=e/2+d-(e/2-h),S=1,b=(n-m)/2,w=(e-y)/2,v=(n+f)/2,P=(e+g)/2,T=v*S/2,I=P*S/2;return ct.lineThroughPoints(Array.from(Array(10),(k,A)=>{const R=-Bt+A*s;return new C(b+(A%2?T:v)*Math.cos(R),w+(A%2?I:P)*Math.sin(R))}),{geometry:{isFilled:t}}).close()}function p_(n,e){return n>e?(ht*(e/2)+(n-e))*2:(ht*(n/2)+(e-n))*2}function Yge(n,e,t){const r=Math.min(n,e)/2,s=Math.max(n,e)-r*2,i=(Math.PI*(r*2)+2*s)/t,a=n>e?[{type:"straight",start:new C(r,0),delta:new C(1,0)},{type:"arc",center:new C(n-r,r),startAngle:-ht/2},{type:"straight",start:new C(n-r,e),delta:new C(-1,0)},{type:"arc",center:new C(r,r),startAngle:ht/2}]:[{type:"straight",start:new C(n,r),delta:new C(0,1)},{type:"arc",center:new C(r,e-r),startAngle:0},{type:"straight",start:new C(0,e-r),delta:new C(0,-1)},{type:"arc",center:new C(r,r),startAngle:ht}];let l=0;const c=[];for(let u=0;u<t;u++){const d=a[0];d.type==="straight"?c.push(C.Add(d.start,C.Mul(d.delta,l))):c.push(Uv(d.center,r,d.startAngle+l/r)),l+=i;let h=d.type==="straight"?s:ht*r;for(;l>h;)l-=h,a.push(a.shift()),h=a[0].type==="straight"?s:ht*r}return c}const Xge={s:50,m:70,l:100,xl:130},qge=.2;function Zge(n,e,t,r,s,o){const i=new ct,a=Aa(t),l=p_(n,e),c=Math.max(Math.ceil(l/Xge[r]),6,Math.ceil(l/Math.min(n,e))),u=l/c*qge,d=Math.max(n-u*2,1),h=Math.max(e-u*2,1),g=p_(d,h)/c,m=(n-d)/2,y=(e-h)/2,S=Yge(d,h,c).map(P=>P.addXY(m,y)),b=n<20?0:u*.3,w=e<20?0:u*.3,v=S.slice(0);for(let P=0;P<Math.floor(c/2);P++)v[P]=C.AddXY(v[P],a()*b*s,a()*w*s),v[c-P-1]=C.AddXY(v[c-P-1],a()*b*s,a()*w*s);for(let P=0;P<v.length;P++){const T=P===v.length-1?0:P+1,I=v[P],k=v[T],A=S[P],R=S[T],D=C.Dist(A,R),j=g-D,M=C.Dist(I,k)/D,O=(Math.max(m,y)+j)*M,N=C.Lrp(A,R,.5).add(C.Sub(R,A).uni().per().mul(O));N.x<0?N.x=0:N.x>n&&(N.x=n),N.y<0?N.y=0:N.y>e&&(N.y=e);const B=gA(I,k,N),H=C.Dist(B||C.Average([I,k]),I);P===0&&i.moveTo(I.x,I.y,{geometry:{isFilled:o}}),i.circularArcTo(H,!1,!0,k.x,k.y)}return i.close()}function f_({shape:n,shouldScale:e,forceSolid:t}){const r=e?n.props.scale:1,s=Zs(),{props:o}=n,{color:i,fill:a,dash:l,size:c}=o,u=Gt[c]*r,d=ig(n),h=l==="draw"&&!t?d.toDrawD({strokeWidth:u,randomSeed:n.id,passes:1,offset:0,onlyFilled:!0}):d.toD({onlyFilled:!0});return p.jsxs(p.Fragment,{children:[p.jsx(Mh,{theme:s,d:h,color:i,fill:a,scale:r}),d.toSvg({style:l,strokeWidth:u,forceSolid:t,randomSeed:n.id,props:{fill:"none",stroke:st(s,i,"solid")}})]})}const Rc=51;class ag extends Gs{constructor(){super(...arguments);E(this,"options",{showTextOutline:!0})}canEdit(){return!0}getDefaultProps(){return{w:100,h:100,geo:"rectangle",dash:"draw",growY:0,url:"",scale:1,color:"black",labelColor:"black",fill:"none",size:"m",font:"draw",align:"middle",verticalAlign:"middle",richText:Kn("")}}getGeometry(t){const{props:r}=t,{scale:s}=r,i=ig(t).toGeometry(),a=Math.max(1,r.w),l=Math.max(1,r.h+r.growY),c=a/s,u=l/s,d=Wt(r.richText),h=d?eme:Vb(this.editor,t),f=tme(c,u,h,r.size,r.align,r.verticalAlign,s);return new es({children:[i,new bo({...f,isFilled:!0,isLabel:!0,excludeFromShapeBounds:!0,isEmptyLabel:d})]})}getHandleSnapGeometry(t){const r=this.getGeometry(t),s=r.children[0];switch(t.props.geo){case"arrow-down":case"arrow-left":case"arrow-right":case"arrow-up":case"check-box":case"diamond":case"hexagon":case"octagon":case"pentagon":case"rectangle":case"rhombus":case"rhombus-2":case"star":case"trapezoid":case"triangle":case"x-box":return{outline:s,points:[...s.vertices,r.bounds.center]};case"cloud":case"ellipse":case"heart":case"oval":return{outline:s,points:[r.bounds.center]};default:it(t.props.geo)}}getText(t){return Hl(this.editor,t.props.richText)}getFontFaces(t){return Wt(t.props.richText)?Yt:Gy(this.editor,t.props.richText,{family:`tldraw_${t.props.font}`,weight:"normal",style:"normal"})}component(t){const{id:r,type:s,props:o}=t,{fill:i,font:a,align:l,verticalAlign:c,size:u,richText:d}=o,h=Zs(),{editor:f}=this,g=W("isGeoOnlySelected",()=>t.id===f.getOnlySelectedShapeId(),[f]),m=gP(f,t.id),y=Wt(t.props.richText),S=m||!y,b=Ah(t.props.scale*.25);return p.jsxs(p.Fragment,{children:[p.jsx(Ra,{children:p.jsx(f_,{shape:t,shouldScale:!0,forceSolid:b})}),S&&p.jsx(Jr,{style:{overflow:"hidden",width:t.props.w,height:t.props.h+o.growY},children:p.jsx(FS,{shapeId:r,type:s,font:a,fontSize:$a[u]*t.props.scale,lineHeight:Dr.lineHeight,padding:Ir*t.props.scale,fill:i,align:l,verticalAlign:c,richText:d,isSelected:g,labelColor:st(h,o.labelColor,"solid"),wrap:!0,showTextOutline:this.options.showTextOutline})}),t.props.url&&p.jsx(hd,{url:t.props.url})]})}indicator(t){const r=Ah(t.props.scale*.25),{size:s,dash:o,scale:i}=t.props,a=Gt[s];return ig(t).toSvg({style:o==="draw"?"draw":"solid",strokeWidth:1,passes:1,randomSeed:t.id,offset:0,roundness:a*2*i,props:{strokeWidth:void 0},forceSolid:r})}useLegacyIndicator(){return!1}getIndicatorPath(t){const r=this.editor.getEfficientZoomLevel()<t.props.scale*.25,{size:s,dash:o,scale:i}=t.props,a=Gt[s];return ig(t).toPath2D({style:o==="draw"?"draw":"solid",strokeWidth:1,passes:1,randomSeed:t.id,offset:0,roundness:a*2*i,forceSolid:r})}toSvg(t,r){const s=t.props.scale,o={...t,props:{...t.props,w:t.props.w/s,h:(t.props.h+t.props.growY)/s,growY:0}},i=o.props;r.addExportDef(mP(i.fill));let a;if(!Wt(i.richText)){const l=Ga(r),c=new J(0,0,i.w,(t.props.h+t.props.growY)/s);a=p.jsx(BS,{fontSize:$a[i.size],font:i.font,align:i.align,verticalAlign:i.verticalAlign,richText:i.richText,labelColor:st(l,i.labelColor,"solid"),bounds:c,padding:Ir,showTextOutline:this.options.showTextOutline})}return p.jsxs(p.Fragment,{children:[p.jsx(f_,{shouldScale:!1,shape:o,forceSolid:!1}),a]})}getCanvasSvgDefs(){return[yP()]}onResize(t,{handle:r,newPoint:s,scaleX:o,scaleY:i,initialShape:a}){const l=m_(a.props);let c=l.w*o,u=(l.h+l.growY)*i,d=0,h=0;if(!Wt(t.props.richText)){const b=Math.abs(c),w=Math.abs(u),v=Math.max(b,Rc),P=Math.max(w,Rc),T=h$(this.editor,{...t,props:{...t.props,w:v*t.props.scale,h:P*t.props.scale}}),I=Math.max(b,T.w),k=Math.max(w,T.h);d=I-b,h=k-w,c=I*Math.sign(c||1),u=k*Math.sign(u||1)}const f=c*t.props.scale,g=u*t.props.scale,m=new C(0,0);o<0&&(m.x+=f),(r==="left"||r==="top_left"||r==="bottom_left")&&(m.x+=o<0?d:-d),i<0&&(m.y+=g),(r==="top"||r==="top_left"||r==="top_right")&&(m.y+=i<0?h:-h);const{x:y,y:S}=m.rot(t.rotation).add(s);return{x:y,y:S,props:{w:Math.max(Math.abs(f),1),h:Math.max(Math.abs(g),1),growY:0}}}onBeforeCreate(t){const{props:r}=t;if(Wt(r.richText))return r.growY!==0?{...t,props:{...r,growY:0}}:void 0;const s=r.h/r.scale,o=Vb(this.editor,t).h,i=y_(s,o,r.growY/r.scale);if(i!==null)return{...t,props:{...r,growY:i*r.scale}}}onBeforeUpdate(t,r){const{props:s}=t,{props:o}=r;if(So(s.richText,o.richText)&&s.font===o.font&&s.size===o.size)return;const i=Wt(s.richText),a=Wt(o.richText);if(i&&a)return;if(a)return o.growY!==0?{...r,props:{...o,growY:0}}:void 0;const l=m_(s),c=Vb(this.editor,r),{scale:u}=o;if(i&&!a){const g=nme(l.w,l.h,c);return{...r,props:{...o,w:g.w*u,h:g.h*u,growY:0}}}const d=r.props.w/u,h=c.w>d,f=y_(l.h,c.h,l.growY);if(f!==null||h)return{...r,props:{...o,growY:(f??l.growY)*u,w:Math.max(d,c.w)*u}}}onDoubleClick(t){if(this.editor.inputs.getAltKey())switch(t.props.geo){case"rectangle":return{...t,props:{geo:"check-box"}};case"check-box":return{...t,props:{geo:"rectangle"}}}}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,w:Ue(t.props.w,r.props.w,s),h:Ue(t.props.h,r.props.h,s),scale:Ue(t.props.scale,r.props.scale,s)}}}E(ag,"type","geo"),E(ag,"props",JM),E(ag,"migrations",QM);const Jge=Object.freeze({s:12,m:14,l:16,xl:20}),Qge=Object.freeze({s:2,m:3.5,l:5,xl:10}),eme=Object.freeze({w:0,h:0}),g_=8;function tme(n,e,t,r,s,o,i){const a=Math.min(100,n/2),l=Math.min($a[r]*Dr.lineHeight+Ir*2,e/2),c=Math.min(n,Math.max(t.w,Math.min(a,Math.max(1,n-g_)))),u=Math.min(e,Math.max(t.h,Math.min(l,Math.max(1,e-g_)))),d=s==="start"?0:s==="end"?n-c:(n-c)/2,h=o==="start"?0:o==="end"?e-u:(e-u)/2;return{x:d*i,y:h*i,width:c*i,height:u*i}}function m_(n){const{w:e,h:t,growY:r,scale:s}=n;return{w:e/s,h:t/s,growY:r/s}}function y_(n,e,t){return e>n?e-n:t>0?0:null}function nme(n,e,t){let r=Math.max(n,t.w),s=Math.max(e,t.h);if(n<Rc&&e<Rc){r=Math.max(r,Rc),s=Math.max(s,Rc);const o=Math.max(r,s);r=o,s=o}return{w:r,h:s}}const rme=new Vn;function Vb(n,e){return rme.get(e,()=>h$(n,e))}function h$(n,e){const{richText:t,font:r,size:s,w:o}=e.props,i=Jge[s],a=_h(n,t),l=n.textMeasure.measureHtml(a,{...Dr,fontFamily:Ha[r],fontSize:$a[s],minWidth:i,maxWidth:Math.max(0,Math.ceil(i+Qge[s]),Math.ceil(o/e.props.scale-Ir*2))});return{w:l.w+Ir*2,h:l.h+Ir*2}}function sme(){const[n,e]=x.useState(!1);return x.useEffect(()=>{const r=CSS.supports("color","color(display-p3 1 1 1)"),s=matchMedia("(color-gamut: p3)");e(r&&s.matches);const o=()=>e(r&&s.matches);return s.addEventListener("change",o),()=>s.removeEventListener("change",o)},[]),W(Dt.forceSrgb)||!n?"srgb":"p3"}class lg extends go{constructor(){super(...arguments);E(this,"options",{maxPointsPerShape:600,underlayOpacity:.82,overlayOpacity:.35})}hideResizeHandles(t){return Af(t)}hideRotateHandle(t){return Af(t)}hideSelectionBoundsFg(t){return Af(t)}getDefaultProps(){return{segments:[],color:"black",size:"m",isComplete:!1,isPen:!1,scale:1,scaleX:1,scaleY:1}}getGeometry(t){const r=ha(t);if(Af(t))return new Gg({x:-r/2,y:-r/2,radius:r/2,isFilled:!0});const{strokePoints:s,sw:o}=Gb(t,r,!0),i=H1({strokeWidth:o,showAsComplete:!0});return eP(s,i),new ah({points:lz(s,i),isFilled:!0})}component(t){const r=Yb(this.editor,t),s=ha(t);return p.jsx(Ra,{children:p.jsx(Df,{shape:t,forceSolid:r,strokeWidth:s,opacity:this.options.overlayOpacity})})}backgroundComponent(t){const r=Yb(this.editor,t),s=ha(t);return p.jsx(Ra,{children:p.jsx(Df,{shape:t,forceSolid:r,strokeWidth:s,opacity:this.options.underlayOpacity})})}indicator(t){const r=Yb(this.editor,t),s=ha(t),{strokePoints:o,sw:i}=Gb(t,s,r),a=Ma(t.props.segments,t.props.scaleX,t.props.scaleY);let l;return o.length<2?l=S_(a[0],i):l=Ul(o,!1),p.jsx("path",{d:l})}useLegacyIndicator(){return!1}getIndicatorPath(t){const r=ha(t),s=this.editor.getEfficientZoomLevel(),o=r/s<1.5,{strokePoints:i,sw:a}=Gb(t,r,o),l=Ma(t.props.segments,t.props.scaleX,t.props.scaleY);let c;return i.length<2?c=S_(l[0],a):c=Ul(i,!1),new Path2D(c)}toSvg(t){const r=ha(t),s=r<1.5,o=1/t.props.scale;return p.jsx("g",{transform:`scale(${o})`,children:p.jsx(Df,{forceSolid:s,strokeWidth:r,shape:t,opacity:this.options.overlayOpacity})})}toBackgroundSvg(t){const r=ha(t),s=r<1.5,o=1/t.props.scale;return p.jsx("g",{transform:`scale(${o})`,children:p.jsx(Df,{forceSolid:s,strokeWidth:r,shape:t,opacity:this.options.underlayOpacity})})}onResize(t,r){const{scaleX:s,scaleY:o}=r;return{props:{scaleX:s*t.props.scaleX,scaleY:o*t.props.scaleY}}}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,...r.props,segments:c$(t.props.segments,r.props.segments,s),scale:Ue(t.props.scale,r.props.scale,s)}}}E(lg,"type","highlight"),E(lg,"props",nA),E(lg,"migrations",rA);function ome(n){return`M ${n.x} ${n.y} m -${.1}, 0 a ${.1},${.1} 0 1,0 ${.1*2},0 a ${.1},${.1} 0 1,0 -${.1*2},0`}function S_(n,e){const t=e/2;return`M ${n.x} ${n.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function Gb(n,e,t){var l;const r=Ma(n.props.segments,n.props.scaleX,n.props.scaleY),s=n.props.isComplete||((l=gs(n.props.segments))==null?void 0:l.type)==="straight";let o=e;!t&&!n.props.isPen&&r.length===1&&(o+=Aa(n.id)()*(e/6));const i=H1({strokeWidth:o,showAsComplete:s});return{strokePoints:zi(r,i),sw:o}}function ha(n){return dd[n.props.size]*1.12*n.props.scale}function Af(n){return n.props.segments.length===1&&n.props.segments[0].path.length<24}function Df({strokeWidth:n,forceSolid:e,shape:t,opacity:r}){var h;const s=Zs(),o=Ma(t.props.segments,t.props.scaleX,t.props.scaleY);let i=n;!e&&!t.props.isPen&&o.length===1&&(i+=Aa(t.id)()*(i/6));const a=H1({strokeWidth:i,showAsComplete:t.props.isComplete||((h=gs(t.props.segments))==null?void 0:h.type)==="straight"}),l=zi(o,a),c=l.length>1?Ul(l,!1):ome(o[0]),u=sme(),d=st(s,t.props.color,u==="p3"?"highlightP3":"highlightSrgb");return p.jsx("path",{d:c,strokeLinecap:"round",fill:"none",pointerEvents:"all",stroke:d,strokeWidth:i,opacity:r})}function Yb(n,e){return W("forceSolid",()=>{const t=ha(e),r=n.getEfficientZoomLevel();return t/r<1.5},[n])}function p$(){return p.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 30 30",xmlns:"http://www.w3.org/2000/svg",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",children:[p.jsx("path",{d:"M3,11 L3,3 11,3",strokeWidth:"2"}),p.jsx("path",{d:"M19,27 L27,27 L27,19",strokeWidth:"2"}),p.jsx("path",{d:"M27,3 L3,27",strokeWidth:"2"})]})}function f$({shapeId:n,assetId:e,width:t}){const r=K(),s=Hh(),o=i9(),[i,a]=x.useState(()=>({asset:e?r.getAsset(e)??null:null,url:null})),l=x.useRef(!1),c=x.useRef(null),u=x.useRef(!1),d=x.useRef(null);return x.useEffect(()=>{const h=c.current!==e;if(c.current=e,h&&(u.current=!0),!e)return;let f=!1,g;const m=Mr("update state",()=>{if(!s&&n&&r.getCulledShapes().has(n))return;const y=r.getAsset(e);if(!y){a(w=>({...w,asset:null,url:null}));return}if(!y.props.src){const w=r.getTemporaryAssetPreview(y.id);if(w){d.current!==w&&(d.current=w,a(v=>({...v,isPlaceholder:!0,url:w})),o());return}}const S=s?s.scale*(t/y.props.w):r.getEfficientZoomLevel()*(t/y.props.w);function b(w,v){f||d.current!==v&&(l.current=!0,d.current=v,a({asset:w,url:v}),o())}if(l.current&&!u.current){let w=0;const v=()=>{w++,w>500/16&&(x_(r,e,S,s,P=>b(y,P)),g==null||g())};g==null||g(),r.on("tick",v),g=()=>r.off("tick",v)}else g==null||g(),x_(r,e,S,s,w=>b(y,w)),u.current=!1});return()=>{m(),g==null||g(),f=!0}},[r,e,s,o,n,t]),i}function x_(n,e,t,r,s){n.resolveAssetUrl(e,{screenScale:t,shouldResolveToOriginal:r?r.pixelRatio===null:!1,dpr:(r==null?void 0:r.pixelRatio)??void 0}).then(o=>{s(o)})}async function ime(n){const t=await(await $i(n)).blob();return ir.blobToDataUrl(t)}const ame=new Vn;class cg extends Gs{isAspectRatioLocked(){return!0}canCrop(){return!0}isExportBoundsContainer(){return!0}getDefaultProps(){return{w:100,h:100,assetId:null,playing:!0,url:"",crop:null,flipX:!1,flipY:!1,altText:""}}getGeometry(e){var t;return(t=e.props.crop)!=null&&t.isCircle?new BG({width:e.props.w,height:e.props.h,isFilled:!0}):new bo({width:e.props.w,height:e.props.h,isFilled:!0})}getAriaDescriptor(e){return e.props.altText}onResize(e,t){let r=ky(e,t);const{flipX:s,flipY:o}=t.initialShape.props,{scaleX:i,scaleY:a,mode:l}=t;if(r={...r,props:{...r.props,flipX:i<0!==s,flipY:a<0!==o}},!e.props.crop)return r;const c=l==="scale_shape"&&i===-1||l==="resize_bounds"&&s!==r.props.flipX,u=l==="scale_shape"&&a===-1||l==="resize_bounds"&&o!==r.props.flipY,{topLeft:d,bottomRight:h}=e.props.crop;return r.props.crop={topLeft:{x:c?1-h.x:d.x,y:u?1-h.y:d.y},bottomRight:{x:c?1-d.x:h.x,y:u?1-d.y:h.y},isCircle:e.props.crop.isCircle},r}component(e){return p.jsx(lme,{shape:e})}indicator(e){var r;return this.editor.getCroppingShapeId()===e.id?null:(r=e.props.crop)!=null&&r.isCircle?p.jsx("ellipse",{cx:$(e.props.w/2),cy:$(e.props.h/2),rx:$(e.props.w/2),ry:$(e.props.h/2)}):p.jsx("rect",{width:$(e.props.w),height:$(e.props.h)})}useLegacyIndicator(){return!1}getIndicatorPath(e){var r;if(this.editor.getCroppingShapeId()===e.id)return;const t=new Path2D;if((r=e.props.crop)!=null&&r.isCircle){const s=e.props.w/2,o=e.props.h/2;t.ellipse(s,o,s,o,0,0,Math.PI*2)}else t.rect(0,0,e.props.w,e.props.h);return t}async toSvg(e,t){const r=e.props;if(!r.assetId)return null;const s=this.editor.getAsset(r.assetId);if(!s)return null;const{w:o}=Po(e.props,r.crop),i=await ame.get(s,async()=>{let a=await t.resolveAssetUrl(s.id,o);if(!a)return null;if((a.startsWith("blob:")||a.startsWith("http")||a.startsWith("/")||a.startsWith("./"))&&(a=await ime(a)||""),g$(this.editor,s.id)){const{promise:l}=y$(a);a=await l}return a});return i?p.jsx(cme,{shape:e,src:i}):null}onDoubleClickEdge(e){const t=e.props;if(!t||this.editor.getCroppingShapeId()!==e.id)return;const r=Ft(t.crop)||{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},{w:s,h:o}=Po(e.props,r),i=new C(r.topLeft.x*s,r.topLeft.y*o).rot(e.rotation),a={id:e.id,type:e.type,x:e.x-i.x,y:e.y-i.y,props:{crop:{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},w:s,h:o}};this.editor.updateShapes([a])}getInterpolatedProps(e,t,r){function s(o,i){var d,h,f,g;if(o.props.crop===null&&i.props.crop===null)return null;const a=((d=o.props.crop)==null?void 0:d.topLeft)||{x:0,y:0},l=((h=o.props.crop)==null?void 0:h.bottomRight)||{x:1,y:1},c=((f=i.props.crop)==null?void 0:f.topLeft)||{x:0,y:0},u=((g=i.props.crop)==null?void 0:g.bottomRight)||{x:1,y:1};return{topLeft:{x:Ue(a.x,c.x,r),y:Ue(a.y,c.y,r)},bottomRight:{x:Ue(l.x,u.x,r),y:Ue(l.y,u.y,r)}}}return{...r>.5?t.props:e.props,w:Ue(e.props.w,t.props.w,r),h:Ue(e.props.h,t.props.h,r),crop:s(e,t)}}}E(cg,"type","image"),E(cg,"props",sA),E(cg,"migrations",oA);const lme=x.memo(function({shape:e}){var b,w;const t=K(),{w:r}=Po(e.props,e.props.crop),{asset:s,url:o}=f$({shapeId:e.id,assetId:e.props.assetId,width:r}),i=Wj(),[a,l]=x.useState(""),[c,u]=x.useState(null),d=s&&g$(t,s.id);x.useEffect(()=>{if(o&&d){const{promise:v,cancel:P}=y$(o);return v.then(T=>{l(T),u(o)}),()=>{P()}}},[t,d,i,o]);const h=W("show crop preview",()=>e.id===t.getOnlySelectedShapeId()&&t.getCroppingShapeId()===e.id&&t.isIn("select.crop"),[t,e.id]),f=i&&(((b=s==null?void 0:s.props.mimeType)==null?void 0:b.includes("video"))||d),g=m$(e),m=o===c?null:o,y=f?a:c;if(!o&&!(s!=null&&s.props.src))return p.jsxs(Jr,{id:e.id,style:{overflow:"hidden",width:e.props.w,height:e.props.h,color:"var(--tl-color-text-3)",backgroundColor:"var(--tl-color-low)",border:"1px solid var(--tl-color-low-border)"},children:[p.jsx("div",{className:xe("tl-image-container",s&&"tl-image-container-loading"),style:g,children:s?null:p.jsx(p$,{})}),"url"in e.props&&e.props.url&&p.jsx(hd,{url:e.props.url})]});const S=d?"anonymous":void 0;return p.jsxs(p.Fragment,{children:[h&&y&&p.jsx("div",{style:g,children:p.jsx("img",{className:"tl-image",style:{...Zu(e),opacity:.1},crossOrigin:S,src:y,referrerPolicy:"strict-origin-when-cross-origin",draggable:!1,alt:""})}),p.jsxs(Jr,{id:e.id,style:{overflow:"hidden",width:e.props.w,height:e.props.h,borderRadius:(w=e.props.crop)!=null&&w.isCircle?"50%":void 0},children:[p.jsxs("div",{className:xe("tl-image-container"),style:g,children:[y&&p.jsx("img",{className:"tl-image",style:Zu(e),crossOrigin:S,src:y,referrerPolicy:"strict-origin-when-cross-origin",draggable:!1,alt:""},y),m&&p.jsx("img",{className:"tl-image",style:Zu(e),crossOrigin:S,src:m,referrerPolicy:"strict-origin-when-cross-origin",draggable:!1,alt:e.props.altText,onLoad:()=>u(m)},m)]}),e.props.url&&p.jsx(hd,{url:e.props.url})]})]})});function g$(n,e){const t=e?n.getAsset(e):void 0;return t?"mimeType"in t.props&&fs.isAnimatedImageType(t==null?void 0:t.props.mimeType)||"isAnimated"in t.props&&t.props.isAnimated:!1}function m$(n){const e=n.props.crop,t=e==null?void 0:e.topLeft;if(!t)return{width:n.props.w,height:n.props.h};const{w:r,h:s}=Po(n.props,e),o=-t.x*r,i=-t.y*s;return{transform:`translate(${o}px, ${i}px)`,width:r,height:s}}function Zu(n,e){const{flipX:t,flipY:r,crop:s}=n.props;if(!t&&!r)return;let o,i;if(s){const{w:c,h:u}=Po(n.props,s),d=s.bottomRight.x-s.topLeft.x,h=s.bottomRight.y-s.topLeft.y;o=xo(s.topLeft.x,[0,1-d],[0,c-n.props.w]),i=xo(s.topLeft.y,[0,1-h],[0,u-n.props.h])}const a=`scale(${t?-1:1}, ${r?-1:1})`;return{transform:`${e?`translate(${(t?e.width:0)-(o||0)}px,
534
+ ${(r?e.height:0)-(i||0)}px)`:""} ${a}`,transformOrigin:e?"0 0":"center center"}}function cme({shape:n,src:e}){const t=Yl(),r=m$(n),s=n.props.crop;if(r.transform&&s){const{transform:o,width:i,height:a}=r,l=(s.bottomRight.x-s.topLeft.x)*i,c=(s.bottomRight.y-s.topLeft.y)*a,u=[new C(0,0),new C(l,0),new C(l,c),new C(0,c)],d=Zu(n,{width:i,height:a});return p.jsxs(p.Fragment,{children:[p.jsx("defs",{children:p.jsx("clipPath",{id:t,children:s.isCircle?p.jsx("ellipse",{cx:l/2,cy:c/2,rx:l/2,ry:c/2}):p.jsx("polygon",{points:u.map(h=>`${h.x},${h.y}`).join(" ")})})}),p.jsx("g",{clipPath:`url(#${t})`,children:p.jsx("image",{href:e,width:i,height:a,"aria-label":n.props.altText,style:d?{...d}:{transform:o}})})]})}else return p.jsx("image",{href:e,width:n.props.w,height:n.props.h,"aria-label":n.props.altText,style:Zu(n,{width:n.props.w,height:n.props.h})})}function y$(n){let e=!1;return{promise:new Promise(r=>{const s=th();s.onload=()=>{if(e)return;const o=document.createElement("canvas");o.width=s.width,o.height=s.height;const i=o.getContext("2d");i&&(i.drawImage(s,0,0),r(o.toDataURL()))},s.crossOrigin="anonymous",s.src=n}),cancel:()=>e=!0}}const dme=new Vn;class dg extends go{hideResizeHandles(){return!0}hideRotateHandle(){return!0}hideSelectionBoundsFg(){return!0}hideSelectionBoundsBg(){return!0}hideInMinimap(){return!0}getDefaultProps(){const[e,t]=rh(2);return{dash:"draw",size:"m",color:"black",spline:"line",points:{[e]:{id:e,index:e,x:0,y:0},[t]:{id:t,index:t,x:.1,y:.1}},scale:1}}getGeometry(e){const t=ug(e).toGeometry();return be(t instanceof h0),t}getHandles(e){return dme.get(e.props,()=>{const t=this.getGeometry(e),r=_u(e),s=r.map(o=>({...o,id:o.index,type:"vertex",canSnap:!0}));for(let o=0;o<r.length-1;o++){const i=Xc(r[o].index,r[o+1].index),l=t.getSegments()[o].interpolateAlongEdge(.5);s.push({id:i,type:"create",index:i,x:l.x,y:l.y,canSnap:!0})}return s.sort(Tn)})}onResize(e,t){const{scaleX:r,scaleY:s}=t;return{props:{points:Ka(e.props.points,(o,{id:i,index:a,x:l,y:c})=>({id:i,index:a,x:l*r,y:c*s}))}}}onBeforeCreate(e){const{props:{points:t}}=e,r=Object.keys(t);if(r.length<2)return;const s=t[r[0]];if(r.every(i=>{const a=t[i];return a.x===s.x&&a.y===s.y})){const i=r[r.length-1];return t[i]={...t[i],x:t[i].x+.1,y:t[i].y+.1},e}}onHandleDrag(e,{handle:t}){const r=ws(new C(t.x,t.y),this.editor);return{...e,props:{...e.props,points:{...e.props.points,[t.id]:{id:t.id,index:t.index,x:r.x,y:r.y}}}}}onHandleDragStart(e,{handle:t}){if(t.type==="create")return{...e,props:{...e.props,points:{...e.props.points,[t.index]:{id:t.index,index:t.index,x:t.x,y:t.y}}}}}component(e){return p.jsx(Ra,{style:{minWidth:50,minHeight:50},children:p.jsx(b_,{shape:e})})}indicator(e){const t=qr[e.props.size]*e.props.scale,r=ug(e),{dash:s}=e.props;return r.toSvg({style:s==="draw"?"draw":"solid",strokeWidth:1,passes:1,randomSeed:e.id,offset:0,roundness:t*2,props:{strokeWidth:void 0}})}useLegacyIndicator(){return!1}getIndicatorPath(e){const t=qr[e.props.size]*e.props.scale,r=ug(e),{dash:s}=e.props;return r.toPath2D({style:s==="draw"?"draw":"solid",strokeWidth:1,passes:1,randomSeed:e.id,offset:0,roundness:t*2})}toSvg(e){return p.jsx(b_,{shouldScale:!0,shape:e})}getHandleSnapGeometry(e){const t=_u(e);return{points:t,getSelfSnapPoints:r=>{const s=this.getHandles(e).filter(o=>o.type==="vertex").findIndex(o=>o.id===r.id);return t.filter((o,i)=>Math.abs(i-s)>1).map(C.From)},getSelfSnapOutline:r=>{const s=this.getHandles(e).filter(i=>i.type==="vertex").findIndex(i=>i.id===r.id),o=this.getGeometry(e).getSegments().filter((i,a)=>a!==s-1&&a!==s);return o.length?new es({children:o}):null}}}getInterpolatedProps(e,t,r){const s=_u(e),o=_u(t),i=[],a=[];let l=fv;if(s.length>o.length)for(let c=0;c<s.length;c++)i[c]={...s[c]},o[c]===void 0?a[c]={...o[o.length-1],id:l}:a[c]={...o[c],id:l},l=Ns(l);else if(o.length>s.length)for(let c=0;c<o.length;c++)a[c]={...o[c]},s[c]===void 0?i[c]={...s[s.length-1],id:l}:i[c]={...s[c],id:l},l=Ns(l);else for(let c=0;c<o.length;c++)i[c]=s[c],a[c]=o[c];return{...r>.5?t.props:e.props,points:Object.fromEntries(i.map((c,u)=>{const d=a[u];return[c.id,{...c,x:Ue(c.x,d.x,r),y:Ue(c.y,d.y,r)}]})),scale:Ue(e.props.scale,t.props.scale,r)}}}E(dg,"type","line"),E(dg,"props",iA),E(dg,"migrations",aA);function _u(n){return Object.values(n.props.points).sort(Tn)}const ume=new Vn;function ug(n){return ume.get(n,()=>{const e=_u(n).map(C.From);switch(n.props.spline){case"cubic":return ct.cubicSplineThroughPoints(e,{endOffsets:0});case"line":return ct.lineThroughPoints(e,{endOffsets:0})}})}function b_({shape:n,shouldScale:e=!1,forceSolid:t=!1}){const r=Zs(),s=ug(n),{dash:o,color:i,size:a}=n.props,l=1/n.props.scale,c=e?l:1,u=qr[a]*n.props.scale;return s.toSvg({style:o,strokeWidth:u,forceSolid:t,randomSeed:n.id,props:{transform:`scale(${c})`,stroke:st(r,i,"solid"),fill:"none"}})}class hg extends go{constructor(){super(...arguments);E(this,"options",{resizeMode:"none"})}canEdit(){return!0}hideResizeHandles(){const{resizeMode:t}=this.options;switch(t){case"none":return!0;case"scale":return!1;default:throw it(t)}}isAspectRatioLocked(){return this.options.resizeMode==="scale"}hideSelectionBoundsFg(){return!1}getDefaultProps(){return{color:"black",richText:Kn(""),size:"m",font:"draw",align:"middle",verticalAlign:"middle",labelColor:"black",growY:0,fontSizeAdjustment:0,url:"",scale:1}}getGeometry(t){const{labelHeight:r,labelWidth:s}=S$(this.editor,t),{scale:o}=t.props,i=r*o,a=s*o,l=yt*o,c=Zd(t);return new es({children:[new bo({width:l,height:c,isFilled:!0}),new bo({x:t.props.align==="start"?0:t.props.align==="end"?l-a:(l-a)/2,y:t.props.verticalAlign==="start"?0:t.props.verticalAlign==="end"?c-i:(c-i)/2,width:a,height:i,isFilled:!0,isLabel:!0,excludeFromShapeBounds:!0})]})}getHandles(t){const{scale:r}=t.props;if(this.editor.getInstanceState().isCoarsePointer)return[];const o=this.editor.getEfficientZoomLevel();if(o*r<.25)return[];const i=Zd(t),a=yt*r,l=Ffe/o*r;return o*r<.5?[{id:"bottom",index:"a3",type:"clone",x:a/2,y:i+l}]:[{id:"top",index:"a1",type:"clone",x:a/2,y:-l},{id:"right",index:"a2",type:"clone",x:a+l,y:i/2},{id:"bottom",index:"a3",type:"clone",x:a/2,y:i+l},{id:"left",index:"a4",type:"clone",x:-l,y:i/2}]}onResize(t,r){const{resizeMode:s}=this.options;switch(s){case"none":return;case"scale":return LR(t,r);default:throw it(s)}}getText(t){return Hl(this.editor,t.props.richText)}getFontFaces(t){return Wt(t.props.richText)?Yt:Gy(this.editor,t.props.richText,{family:`tldraw_${t.props.font}`,weight:"normal",style:"normal"})}component(t){const{id:r,type:s,props:{labelColor:o,scale:i,color:a,font:l,size:c,align:u,richText:d,verticalAlign:h,fontSizeAdjustment:f}}=t,g=fme(r),m=Zs(),y=yt*i,S=Zd(t),b=W("shape rotation",()=>{var k;return((k=this.editor.getShapePageTransform(r))==null?void 0:k.rotation())??0},[this.editor]),w=W("dark mode",()=>this.editor.user.getIsDarkMode(),[this.editor]);let v=Ah(i*.25);w&&(v=!0);const P=t.id===this.editor.getOnlySelectedShapeId(),T=gP(this.editor,t.id),I=Wt(d);return p.jsxs(p.Fragment,{children:[p.jsx("div",{id:r,className:"tl-note__container",style:{width:y,height:S,backgroundColor:st(m,a,"noteFill"),borderBottom:v?w?`${2*i}px solid rgb(20, 20, 20)`:`${2*i}px solid rgb(144, 144, 144)`:"none",boxShadow:v?"none":gme(t.id,b,i)},children:(P||T||!I)&&p.jsx(FS,{shapeId:r,type:s,font:l,fontSize:(f||$a[c])*i,lineHeight:Dr.lineHeight,align:u,verticalAlign:h,richText:d,isSelected:P,labelColor:o==="black"?st(m,a,"noteText"):st(m,o,"fill"),wrap:!0,padding:Ir*i,hasCustomTabBehavior:!0,showTextOutline:!1,onKeyDown:g})}),"url"in t.props&&t.props.url&&p.jsx(hd,{url:t.props.url})]})}indicator(t){const{scale:r}=t.props;return p.jsx("rect",{rx:r,width:$(yt*r),height:$(Zd(t))})}useLegacyIndicator(){return!1}getIndicatorPath(t){const{scale:r}=t.props,s=new Path2D;return s.roundRect(0,0,yt*r,Zd(t),r),s}toSvg(t,r){const s=Ga({isDarkMode:r.isDarkMode}),o=mme(t),i=p.jsx(BS,{fontSize:t.props.fontSizeAdjustment||$a[t.props.size],font:t.props.font,align:t.props.align,verticalAlign:t.props.verticalAlign,richText:t.props.richText,labelColor:st(s,t.props.color,"noteText"),bounds:o,padding:Ir,showTextOutline:!1});return p.jsxs(p.Fragment,{children:[p.jsx("rect",{x:5,y:5,rx:1,width:yt-10,height:o.h,fill:"rgba(0,0,0,.1)"}),p.jsx("rect",{rx:1,width:yt,height:o.h,fill:st(s,t.props.color,"noteFill")}),i]})}onBeforeCreate(t){return w_(this.editor,t)}onBeforeUpdate(t,r){if(!(So(t.props.richText,r.props.richText)&&t.props.font===r.props.font&&t.props.size===r.props.size))return w_(this.editor,r)}getInterpolatedProps(t,r,s){return{...s>.5?r.props:t.props,scale:Ue(t.props.scale,r.props.scale,s)}}}E(hg,"type","note"),E(hg,"props",lA),E(hg,"migrations",cA);function w_(n,e){const{labelHeight:t,fontSizeAdjustment:r}=S$(n,e),s=Math.max(0,t-yt);if(s!==e.props.growY||r!==e.props.fontSizeAdjustment)return{...e,props:{...e.props,growY:s,fontSizeAdjustment:r}}}function hme(n,e){const{richText:t}=e.props;if(Wt(t))return{labelHeight:$a[e.props.size]*Dr.lineHeight+Ir*2,labelWidth:100,fontSizeAdjustment:0};const r=$a[e.props.size];let s=0,o=0,i=yt,a=yt;const l=1;do{s=Math.min(r,r-o);const c=_h(n,t),u=n.textMeasure.measureHtml(c,{...Dr,fontFamily:Ha[e.props.font],fontSize:s,maxWidth:yt-Ir*2-l,disableOverflowWrapBreaking:!0,measureScrollWidth:!0});if(i=u.h+Ir*2,a=u.w+Ir*2,s<=14){const d=_h(n,t),h=n.textMeasure.measureHtml(d,{...Dr,fontFamily:Ha[e.props.font],fontSize:s,maxWidth:yt-Ir*2-l});i=h.h+Ir*2,a=h.w+Ir*2;break}if(u.scrollWidth.toFixed(0)===u.w.toFixed(0))break}while(o++<50);return{labelHeight:i,labelWidth:a,fontSizeAdjustment:s}}const pme=new Vn;function S$(n,e){return pme.get(e,()=>hme(n,e))}function fme(n){const e=K(),t=x.useContext(K1);return x.useCallback(r=>{const s=e.getShape(n);if(!s)return;const o=r.key==="Tab",i=(r.metaKey||r.ctrlKey)&&r.key==="Enter";if(o||i){r.preventDefault();const a=e.getShapePageTransform(n),l=a.rotation(),c=!!((t==null?void 0:t.dir)==="rtl"||Fz(Hl(e,s.props.richText))),u=(yt+e.options.adjacentShapeMargin+(i&&!r.shiftKey?s.props.growY:0))*s.props.scale,d=new C(o?r.shiftKey!=c?-1:1:0,i?r.shiftKey?-1:1:0).mul(u).add(NS.clone().mul(s.props.scale)).rot(l).add(a.point()),h=Yz(e,s,d,l);h&&Nr(e,h,{selectAll:!0})}},[n,e,t==null?void 0:t.dir])}function Zd(n){return(yt+n.props.growY)*n.props.scale}function gme(n,e,t){const r=Aa(n),s=Math.abs(r())+.5,o=Math.cos(e),i=5*t,a=4*t,l=6*t,c=7*t;return`0px ${i-s}px ${i}px -${i}px rgba(15, 23, 31, .6),
535
+ 0px ${(a+s*c)*Math.max(0,o)}px ${l+s*c}px -${a+s*l}px rgba(15, 23, 31, ${(.3+s*.1).toFixed(2)}),
536
+ 0px ${48*t}px ${10*t}px -${10*t}px inset rgba(15, 23, 44, ${((.022+r()*.005)*((1+o)/2)).toFixed(2)})`}function mme(n){return new J(0,0,yt,yt+n.props.growY)}const yme=Rh("text size",(n,e)=>(n.fonts.trackFontsForShape(e),x$(n,e.props)),{areRecordsEqual:(n,e)=>n.props===e.props});class pg extends go{constructor(){super(...arguments);E(this,"options",{extraArrowHorizontalPadding:10,showTextOutline:!0})}getDefaultProps(){return{color:"black",size:"m",w:8,font:"draw",textAlign:"start",autoSize:!0,scale:1,richText:Kn("")}}getMinDimensions(t){return yme.get(this.editor,t.id)}getGeometry(t,r){const{scale:s}=t.props,{width:o,height:i}=this.getMinDimensions(t),a=(r==null?void 0:r.context)??"none";return new bo({x:(a==="@tldraw/arrow-without-arrowhead"?-this.options.extraArrowHorizontalPadding:0)*s,width:(o+(a==="@tldraw/arrow-without-arrowhead"?this.options.extraArrowHorizontalPadding*2:0))*s,height:i*s,isFilled:!0,isLabel:!0})}getFontFaces(t){return Gy(this.editor,t.props.richText,{family:`tldraw_${t.props.font}`,weight:"normal",style:"normal"})}getText(t){return Hl(this.editor,t.props.richText)}canEdit(){return!0}isAspectRatioLocked(){return!0}component(t){const{id:r,props:{font:s,size:o,richText:i,color:a,scale:l,textAlign:c}}=t,{width:u,height:d}=this.getMinDimensions(t),h=t.id===this.editor.getOnlySelectedShapeId(),f=Zs(),g=Sme(r);return p.jsx(FS,{shapeId:r,classNamePrefix:"tl-text-shape",type:"text",font:s,fontSize:dd[o],lineHeight:Dr.lineHeight,align:c,verticalAlign:"middle",richText:i,labelColor:st(f,a,"solid"),isSelected:h,textWidth:u,textHeight:d,showTextOutline:this.options.showTextOutline,style:{transform:`scale(${l})`,transformOrigin:"top left"},wrap:!0,onKeyDown:g})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds,s=K();return t.props.autoSize&&s.getEditingShapeId()===t.id?null:p.jsx("rect",{width:$(r.width),height:$(r.height)})}useLegacyIndicator(){return!1}getIndicatorPath(t){if(t.props.autoSize&&this.editor.getEditingShapeId()===t.id)return;const r=this.editor.getShapeGeometry(t).bounds,s=new Path2D;return s.rect(0,0,r.width,r.height),s}toSvg(t,r){const s=this.editor.getShapeGeometry(t).bounds,o=s.width/(t.props.scale??1),i=s.height/(t.props.scale??1),a=Ga(r),l=new J(0,0,o,i);return p.jsx(BS,{fontSize:dd[t.props.size],font:t.props.font,align:t.props.textAlign,verticalAlign:"middle",richText:t.props.richText,labelColor:st(a,t.props.color,"solid"),bounds:l,padding:0,showTextOutline:this.options.showTextOutline})}onResize(t,r){const{newPoint:s,initialBounds:o,initialShape:i,scaleX:a,handle:l}=r;if(r.mode==="scale_shape"||l!=="right"&&l!=="left")return{id:t.id,type:t.type,...LR(t,r)};{const c=Math.max(1,Math.abs(o.width*a)),{x:u,y:d}=a<0?C.Sub(s,C.FromAngle(t.rotation).mul(c)):s;return{id:t.id,type:t.type,x:u,y:d,props:{w:c/i.props.scale,autoSize:!1}}}}onEditEnd(t){Hl(this.editor,t.props.richText).trimEnd().length===0&&this.editor.deleteShapes([t.id])}onBeforeUpdate(t,r){if(!r.props.autoSize)return;const s=t.props.size!==r.props.size||t.props.textAlign!==r.props.textAlign||t.props.font!==r.props.font||t.props.scale!==1&&r.props.scale===1,o=!So(t.props.richText,r.props.richText);if(!s&&!o)return;const i=this.getMinDimensions(t),a=x$(this.editor,r.props),l=i.width*t.props.scale,c=i.height*t.props.scale,u=a.width*r.props.scale,d=a.height*r.props.scale;let h;switch(r.props.textAlign){case"middle":{h=new C((u-l)/2,o?0:(d-c)/2);break}case"end":{h=new C(u-l,o?0:(d-c)/2);break}default:{if(o)break;h=new C(0,(d-c)/2);break}}if(h){h.rot(r.rotation);const{x:f,y:g}=r;return{...r,x:f-h.x,y:g-h.y,props:{...r.props,w:u}}}else return{...r,props:{...r.props,w:u}}}}E(pg,"type","text"),E(pg,"props",dA),E(pg,"migrations",uA);function x$(n,e){const{font:t,richText:r,size:s,w:o}=e,i=16,a=dd[s],l=e.autoSize?null:Math.max(i,Math.floor(o)),c=_h(n,r),u=n.textMeasure.measureHtml(c,{...Dr,fontFamily:Ha[t],fontSize:a,maxWidth:l});return{width:l??Math.max(i,u.w+1),height:Math.max(a,u.h)}}function Sme(n){const e=K();return x.useCallback(t=>{if(e.getEditingShapeId()===n)switch(t.key){case"Enter":{(t.ctrlKey||t.metaKey)&&e.complete();break}}},[e,n])}const xme=new Vn;class fg extends Gs{constructor(){super(...arguments);E(this,"options",{autoplay:!0})}canEdit(){return!0}isAspectRatioLocked(){return!0}getDefaultProps(){return{w:100,h:100,assetId:null,autoplay:this.options.autoplay,url:"",altText:"",time:0,playing:!0}}getAriaDescriptor(t){return t.props.altText}component(t){return p.jsx(bme,{shape:t})}indicator(t){return p.jsx("rect",{width:$(t.props.w),height:$(t.props.h)})}useLegacyIndicator(){return!1}getIndicatorPath(t){const r=new Path2D;return r.rect(0,0,t.props.w,t.props.h),r}async toSvg(t,r){const s=t.props;if(!s.assetId)return null;const o=this.editor.getAsset(s.assetId);if(!o)return null;const i=await xme.get(o,async()=>{const a=await r.resolveAssetUrl(o.id,s.w);if(!a)return null;const l=await fs.loadVideo(a);return await fs.getVideoFrameAsDataUrl(l,0)});return i?p.jsx("image",{href:i,width:s.w,height:s.h,"aria-label":t.props.altText}):null}}E(fg,"type","video"),E(fg,"props",hA),E(fg,"migrations",pA);const bme=x.memo(function({shape:e}){const t=K(),r=t.getShapeGeometry(e).bounds.w*t.getEfficientZoomLevel()>=110,s=qh(e.id),o=Wj(),{Spinner:i}=xt(),{asset:a,url:l}=f$({shapeId:e.id,assetId:e.props.assetId,width:e.props.w}),c=x.useRef(null),[u,d]=x.useState(!1),h=x.useCallback(m=>{m.currentTarget&&d(!0)},[]),[f,g]=x.useState(!1);return x.useEffect(()=>{const m=()=>g(document.fullscreenElement===c.current);return document.addEventListener("fullscreenchange",m),()=>document.removeEventListener("fullscreenchange",m)}),x.useEffect(()=>{const m=c.current;m&&s&&document.activeElement!==m&&m.focus()},[s,u]),p.jsxs(p.Fragment,{children:[p.jsx(Jr,{id:e.id,style:{color:"var(--tl-color-text-3)",backgroundColor:a?"transparent":"var(--tl-color-low)",border:a?"none":"1px solid var(--tl-color-low-border)"},children:p.jsx("div",{className:"tl-counter-scaled",children:p.jsx("div",{className:"tl-video-container",children:a?i&&!a.props.src?p.jsx(i,{}):l?p.jsxs(p.Fragment,{children:[p.jsx("video",{ref:c,style:s?{pointerEvents:"all"}:u?void 0:{display:"none"},className:xe("tl-video",`tl-video-shape-${e.id.split(":")[1]}`,{"tl-video-is-fullscreen":f}),width:"100%",height:"100%",draggable:!1,playsInline:!0,autoPlay:e.props.autoplay&&!o,muted:!0,loop:!0,disableRemotePlayback:!0,disablePictureInPicture:!0,controls:s&&r,onLoadedData:h,hidden:!u,"aria-label":e.props.altText,children:p.jsx("source",{src:l})},l),!u&&i&&p.jsx(i,{})]}):null:p.jsx(p$,{})})})}),"url"in e.props&&e.props.url&&p.jsx(hd,{url:e.props.url})]})}),b$=[pg,rg,sg,ag,hg,dg,og,ng,lg,ey,cg,fg];function wme(n){return n.sideEffects.register({instance:{afterChange:(e,t)=>{e.cameraState!==t.cameraState&&t.cameraState==="idle"&&Uo(n)}},instance_page_state:{afterChange:(e,t)=>{if(e.croppingShapeId!==t.croppingShapeId){const r=n.isIn("select.crop");!e.croppingShapeId&&t.croppingShapeId?r||n.setCurrentTool("select.crop.idle"):e.croppingShapeId&&!t.croppingShapeId&&r&&n.setCurrentTool("select.idle")}if(e.editingShapeId!==t.editingShapeId)if(!e.editingShapeId&&t.editingShapeId){if(!n.isIn("select.editing_shape")){const r=n.getEditingShape();r&&r.type==="text"&&n.isInAny("text.pointing","select.resizing")&&n.getInstanceState().isToolLocked?n.setCurrentTool("select.editing_shape",{target:"shape",shape:r,isCreatingTextWhileToolLocked:!0}):n.setCurrentTool("select.editing_shape",{target:"shape",shape:r})}}else e.editingShapeId&&!t.editingShapeId&&n.isIn("select.editing_shape")&&n.setCurrentTool("select.idle")}}})}class w$ extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"scribbleId","id");E(this,"markId","");E(this,"excludedShapeIds",new Set);E(this,"_isHoldingAccelKey",!1);E(this,"_firstErasingShapeId",null);E(this,"_erasingShapeIds",[])}onEnter(t){this._isHoldingAccelKey=Jt(this.editor.inputs),this._firstErasingShapeId=this.editor.getErasingShapeIds()[0],this._erasingShapeIds=this.editor.getErasingShapeIds(),this.markId=this.editor.markHistoryStoppingPoint("erase scribble begin"),this.info=t;const r=this.editor.inputs.getOriginPagePoint();this.excludedShapeIds=new Set(this.editor.getCurrentPageShapes().filter(o=>{if(this.editor.isShapeOrAncestorLocked(o))return!0;if(this.editor.isShapeOfType(o,"group")||this.editor.isShapeOfType(o,"frame")){const i=this.editor.getPointInShapeSpace(o,r);return this.editor.getShapeGeometry(o).bounds.containsPoint(i)}return!1}).map(o=>o.id));const s=this.editor.scribbles.addScribble({color:"muted-1",size:12});this.scribbleId=s.id,this.update()}pushPointToScribble(){const{x:t,y:r}=this.editor.inputs.getCurrentPagePoint();this.editor.scribbles.addPoint(this.scribbleId,t,r)}onExit(){this.editor.setErasingShapes([]),this.editor.scribbles.stop(this.scribbleId)}onPointerMove(){this.update()}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onKeyUp(){this._isHoldingAccelKey=Jt(this.editor.inputs),this.update()}onKeyDown(){this._isHoldingAccelKey=Jt(this.editor.inputs),this.update()}update(){const{editor:t,excludedShapeIds:r}=this,s=t.getErasingShapeIds(),o=t.getZoomLevel(),i=t.inputs.getCurrentPagePoint(),a=t.inputs.getPreviousPagePoint();this.pushPointToScribble();const l=new Set(s),c=this.editor.options.hitTestMargin/o,u=J.FromPoints([a,i]).expandBy(c),d=t.getShapeIdsInsideBounds(u);if(d.size===0){t.setErasingShapes(Array.from(l));return}const f=t.getCurrentPageRenderingShapesSorted().filter(g=>d.has(g.id));for(const g of f){if(t.isShapeOfType(g,"group"))continue;const m=t.getShapeMask(g.id);if(m&&!kr(i,m))continue;const y=t.getShapeGeometry(g),S=t.getShapePageTransform(g);if(!y||!S)continue;const b=S.clone().invert(),w=b.applyToPoint(a),v=b.applyToPoint(i),{bounds:P}=y;P.minX-c>Math.max(w.x,v.x)||P.minY-c>Math.max(w.y,v.y)||P.maxX+c<Math.min(w.x,v.x)||P.maxY+c<Math.min(w.y,v.y)||(y.hitTestLineSegment(w,v,c)&&l.add(t.getOutermostSelectableShape(g).id),this._erasingShapeIds=[...l])}if(this._isHoldingAccelKey&&this._firstErasingShapeId){const g=this._firstErasingShapeId;g&&this.editor.getShape(g)&&t.setErasingShapes([g]);return}this.editor.setErasingShapes(this._erasingShapeIds.filter(g=>!r.has(g)))}complete(){const{editor:t}=this;t.deleteShapes(t.getCurrentPageState().erasingShapeIds),this.parent.transition("idle"),this._erasingShapeIds=[],this._firstErasingShapeId=null}cancel(){const{editor:t}=this;t.bailToMark(this.markId),this.parent.transition("idle",this.info)}}E(w$,"id","erasing");var cw;let vme=(cw=class extends ve{onPointerDown(e){this.parent.transition("pointing",e)}onCancel(){this.editor.setCurrentTool("select")}},E(cw,"id","idle"),cw);var dw;let Cme=(dw=class extends ve{constructor(){super(...arguments);E(this,"_isHoldingAccelKey",!1)}onEnter(){this._isHoldingAccelKey=Jt(this.editor.inputs);const t=this.editor.getZoomLevel(),r=this.editor.getCurrentPageRenderingShapesSorted(),s=this.editor.inputs.getCurrentPagePoint(),o=new Set,i=o.size;for(let a=r.length,l=a-1;l>=0;l--){const c=r[l];if(!(this.editor.isShapeOrAncestorLocked(c)||this.editor.isShapeOfType(c,"group"))&&this.editor.isPointInShape(c,s,{hitInside:!1,margin:this.editor.options.hitTestMargin/t})){const u=this.editor.getOutermostSelectableShape(c);if(this.editor.isShapeOfType(u,"frame")&&o.size>i||(o.add(u.id),this._isHoldingAccelKey))break}}this.editor.setErasingShapes([...o])}onKeyUp(){this._isHoldingAccelKey=Jt(this.editor.inputs)}onKeyDown(){this._isHoldingAccelKey=Jt(this.editor.inputs)}onLongPress(t){this.startErasing(t)}onExit(t,r){r!=="erasing"&&this.editor.setErasingShapes([])}onPointerMove(t){this._isHoldingAccelKey||this.editor.inputs.getIsDragging()&&this.startErasing(t)}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.cancel()}startErasing(t){this.parent.transition("erasing",t)}complete(){const t=this.editor.getErasingShapeIds();t.length&&(this.editor.markHistoryStoppingPoint("erase end"),this.editor.deleteShapes(t)),this.parent.transition("idle")}cancel(){this.parent.transition("idle")}},E(dw,"id","pointing"),dw);class gg extends ve{static children(){return[vme,Cme,w$]}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}}E(gg,"id","eraser"),E(gg,"initial","idle"),E(gg,"isLockable",!1);class v$ extends ve{constructor(){super(...arguments);E(this,"initialCamera",new C)}onEnter(){this.initialCamera=C.From(this.editor.getCamera()),this.update()}onPointerMove(){this.update()}onPointerUp(){this.complete()}onCancel(){this.parent.transition("idle")}onComplete(){this.complete()}update(){const{initialCamera:t,editor:r}=this,s=r.inputs.getCurrentScreenPoint(),o=r.inputs.getOriginScreenPoint(),i=C.Sub(s,o).div(r.getZoomLevel());i.len2()!==0&&r.setCamera(t.clone().add(i))}complete(){const{editor:t}=this,r=t.inputs.getPointerVelocity(),s=Math.min(r.len(),2);s>.1&&this.editor.slideCamera({speed:s,direction:r}),this.parent.transition("idle")}}E(v$,"id","dragging");var uw;let Pme=(uw=class extends ve{onEnter(){this.editor.setCursor({type:"grab",rotation:0})}onPointerDown(e){this.parent.transition("pointing",e)}onCancel(){this.editor.setCurrentTool("select")}},E(uw,"id","idle"),uw);var hw;let Tme=(hw=class extends ve{onEnter(){this.editor.stopCameraAnimation(),this.editor.setCursor({type:"grabbing",rotation:0})}onLongPress(){this.startDragging()}onPointerMove(){this.editor.inputs.getIsDragging()&&this.startDragging()}startDragging(){this.parent.transition("dragging")}onPointerUp(){this.complete()}onCancel(){this.complete()}onComplete(){this.complete()}onInterrupt(){this.complete()}complete(){this.parent.transition("idle")}},E(hw,"id","pointing"),hw);class mg extends ve{static children(){return[Pme,Tme,v$]}onDoubleClick(e){if(e.phase==="settle"){const t=this.editor.inputs.getCurrentScreenPoint();this.editor.zoomIn(t,{animation:{duration:220,easing:ar.easeOutQuint}})}}onTripleClick(e){if(e.phase==="settle"){const t=this.editor.inputs.getCurrentScreenPoint();this.editor.zoomOut(t,{animation:{duration:320,easing:ar.easeOutQuint}})}}onQuadrupleClick(e){if(e.phase==="settle"){const t=this.editor.getZoomLevel(),r=this.editor.inputs.getCurrentScreenPoint();t===1?this.editor.zoomToFit({animation:{duration:400,easing:ar.easeOutQuint}}):this.editor.resetZoom(r,{animation:{duration:320,easing:ar.easeOutQuint}})}}}E(mg,"id","hand"),E(mg,"initial","idle"),E(mg,"isLockable",!1);var pw;let Ime=(pw=class extends ve{onPointerDown(){const e=this.parent.getSessionId(),t=this.editor.scribbles.addScribbleToSession(e,{color:"laser",opacity:.7,size:4,taper:!1});this.parent.transition("lasering",{sessionId:e,scribbleId:t.id})}},E(pw,"id","idle"),pw);class C$ extends ve{constructor(){super(...arguments);E(this,"scribbleId","");E(this,"sessionId","")}onEnter(t){this.sessionId=t.sessionId,this.scribbleId=t.scribbleId,this.pushPointToScribble()}onPointerMove(){this.pushPointToScribble()}pushPointToScribble(){const{x:t,y:r}=this.editor.inputs.getCurrentPagePoint();this.editor.scribbles.addPointToSession(this.sessionId,this.scribbleId,t,r)}onTick(){this.editor.scribbles.extendSession(this.sessionId)}onPointerUp(){this.complete()}onCancel(){this.onComplete()}onComplete(){this.complete()}complete(){this.editor.scribbles.complete(this.scribbleId),this.parent.transition("idle")}}E(C$,"id","lasering");class yg extends ve{constructor(){super(...arguments);E(this,"sessionId",null)}static children(){return[Ime,C$]}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onExit(){this.sessionId=null}onCancel(){this.sessionId&&this.editor.scribbles.isSessionActive(this.sessionId)?(this.editor.scribbles.clearSession(this.sessionId),this.sessionId=null,this.transition("idle")):this.editor.setCurrentTool("select")}getSessionId(){return this.sessionId&&this.editor.scribbles.isSessionActive(this.sessionId)?this.sessionId:(this.sessionId=this.editor.scribbles.startSession({selfConsume:!1,idleTimeoutMs:this.editor.options.laserDelayMs,fadeMode:"grouped",fadeEasing:"ease-in"}),this.sessionId)}}E(yg,"id","laser"),E(yg,"initial","idle"),E(yg,"isLockable",!1);class P$ extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"initialSelectedShapeIds",[]);E(this,"excludedShapeIds",new Set);E(this,"isWrapMode",!1);E(this,"viewportDidChange",!1)}cleanupViewportChangeReactor(){}onEnter(t){const{editor:r}=this,s=r.inputs.getAltKey();this.isWrapMode=r.user.getIsWrapMode(),this.viewportDidChange=!1;let o=!0;if(this.cleanupViewportChangeReactor=Mr("viewport change while brushing",()=>{r.getViewportPageBounds(),!o&&!this.viewportDidChange&&(this.viewportDidChange=!0)}),s){this.parent.transition("scribble_brushing",t);return}this.excludedShapeIds=new Set(r.getCurrentPageShapes().filter(i=>r.isShapeOfType(i,"group")||r.isShapeOrAncestorLocked(i)).map(i=>i.id)),this.info=t,this.initialSelectedShapeIds=r.getSelectedShapeIds().slice(),this.hitTestShapes(),o=!1}onExit(){this.initialSelectedShapeIds=[],this.editor.updateInstanceState({brush:null}),this.cleanupViewportChangeReactor()}onTick({elapsed:t}){const{editor:r}=this;!r.inputs.getIsDragging()||r.inputs.getIsPanning()||r.edgeScrollManager.updateEdgeScrolling(t)}onPointerMove(){this.hitTestShapes()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(t){this.editor.setSelectedShapes(this.initialSelectedShapeIds),this.parent.transition("idle",t)}onKeyDown(t){this.editor.inputs.getAltKey()?this.parent.transition("scribble_brushing",t):this.hitTestShapes()}onKeyUp(){this.hitTestShapes()}complete(){this.hitTestShapes(),this.parent.transition("idle")}hitTestShapes(){const{editor:t,excludedShapeIds:r,isWrapMode:s}=this,o=t.inputs.getOriginPagePoint(),i=t.inputs.getCurrentPagePoint(),a=t.inputs.getShiftKey(),l=t.inputs.getCtrlKey(),c=new Set(a?this.initialSelectedShapeIds:[]),u=s?!l:l,d=J.FromPoints([o,i]),{corners:h}=d;let f,g,m,y,S,b;const w=t.getViewportPageBounds().contains(d),v=t.getCurrentPageId(),P=t.getShapeIdsInsideBounds(d);if(P.size===0){const R=t.getInstanceState().brush;(!R||!d.equals(R))&&t.updateInstanceState({brush:{...d.toJson()}});const D=t.getSelectedShapeIds();(D.length!==c.size||D.some(j=>!c.has(j)))&&t.setSelectedShapes(Array.from(c));return}const I=(w&&!this.viewportDidChange?t.getCurrentPageRenderingShapesSorted():t.getCurrentPageShapesSorted()).filter(R=>P.has(R.id));e:for(let R=0,D=I.length;R<D;R++){if(m=I[R],r.has(m.id)||c.has(m.id)||(y=t.getShapePageBounds(m),!y))continue e;if(d.contains(y)){this.handleHit(m,i,v,c,h);continue e}if(u||t.isShapeOfType(m,"frame"))continue e;if(d.collides(y)){if(S=t.getShapePageTransform(m),!S)continue e;b=S.clone().invert().applyToPoints(h);const j=t.getShapeGeometry(m);t:for(let _=0;_<4;_++)if(f=b[_],g=b[(_+1)%4],j.hitTestLineSegment(f,g,0)){this.handleHit(m,i,v,c,h);break t}}}const k=t.getInstanceState().brush;(!k||!d.equals(k))&&t.updateInstanceState({brush:{...d.toJson()}});const A=t.getSelectedShapeIds();(A.length!==c.size||A.some(R=>!c.has(R)))&&t.setSelectedShapes(Array.from(c))}onInterrupt(){this.editor.updateInstanceState({brush:null})}handleHit(t,r,s,o,i){if(t.parentId===s){o.add(t.id);return}const a=this.editor.getOutermostSelectableShape(t),l=this.editor.getShapeMask(a.id);l&&!$A(l,i)&&!kr(r,l)||o.add(a.id)}}E(P$,"id","brushing");const pd={bottom:"ns-resize",top:"ns-resize",left:"ew-resize",right:"ew-resize",bottom_left:"nesw-resize",bottom_right:"nwse-resize",top_left:"nwse-resize",top_right:"nesw-resize",bottom_left_rotate:"swne-rotate",bottom_right_rotate:"senw-rotate",top_left_rotate:"nwse-rotate",top_right_rotate:"nesw-rotate",mobile_rotate:"grabbing"};class T$ extends ve{constructor(){super(...arguments);E(this,"info",{})}updateCursor(){const t=this.editor.getSelectedShapes(),r=pd[this.info.handle];this.editor.setCursor({type:r,rotation:t.length===1?this.editor.getSelectionRotation():0})}onEnter(t){this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.updateCursor()}onExit(){this.parent.setCurrentToolIdMask(void 0)}onPointerMove(){this.editor.inputs.getIsDragging()&&this.startResizing()}onLongPress(){this.startResizing()}startResizing(){this.editor.getIsReadonly()||this.parent.transition("resizing",this.info)}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}complete(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t();return}this.parent.transition("idle")}cancel(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t();return}this.parent.transition("idle")}}E(T$,"id","pointing_resize_handle");class bP extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"markId","");E(this,"snapshot",{})}onEnter(t){this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.markId=this.editor.markHistoryStoppingPoint("cropping"),this.snapshot=this.createSnapshot(),this.updateShapes()}onPointerMove(){this.updateShapes()}onKeyDown(){this.updateShapes()}onKeyUp(){this.updateShapes()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(){this.cancel()}onExit(){this.parent.setCurrentToolIdMask(void 0)}updateCursor(){if(!this.editor.getSelectedShapes()[0])return;const r=pd[this.info.handle];this.editor.setCursor({type:r,rotation:this.editor.getSelectionRotation()})}updateShapes(){var f;const{shape:t,cursorHandleOffset:r}=this.snapshot;if(!t)return;const s=this.editor.getShapeUtil(t.type);if(!s)return;const o=this.editor.inputs.getShiftKey(),i=this.editor.inputs.getCurrentPagePoint().clone().sub(r),a=this.editor.inputs.getOriginPagePoint().clone().sub(r),l=i.clone().sub(a).rot(-t.rotation),c=t.props.crop??po(),u=Po(t.props,c),h=(((f=s.onCrop)==null?void 0:f.bind(s))??Jce)(t,{handle:this.info.handle,change:l,crop:c,uncroppedSize:u,initialShape:this.snapshot.shape,aspectRatioLocked:o});h&&(this.editor.updateShapes([{id:t.id,type:t.type,...h}]),this.updateCursor())}complete(){this.updateShapes(),mt(this.editor,[this.snapshot.shape.id]);const{onInteractionEnd:t}=this.info;t?typeof t=="string"?this.editor.setCurrentTool(t,this.info):t():(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))}cancel(){this.editor.bailToMark(this.markId);const{onInteractionEnd:t}=this.info;t?typeof t=="string"?this.editor.setCurrentTool(t,this.info):t():(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))}createSnapshot(){const t=this.editor.getSelectionRotation(),r=this.editor.inputs.getOriginPagePoint(),s=this.editor.getOnlySelectedShape(),o=this.editor.getSelectionRotatedPageBounds(),i=C.RotWith(o.getHandlePoint(this.info.handle),o.point,t),a=C.Sub(r,i);return{shape:s,cursorHandleOffset:a}}}E(bP,"id","cropping");function wP(n,e=!1){const t=n.getZoomLevel(),r=n.inputs.getCurrentPagePoint();return n.getShapeAtPoint(r,{hitInside:!1,hitLabels:e,margin:n.options.hitTestMargin/t,renderingOnly:!0})??n.getSelectedShapeAtPoint(r)}function I$(n,e,t){if(!e)throw Error("Needs to translate a cropped shape!");const{crop:r}=e.props;if(!r)return;const s=n.inputs.getShiftKey()?Math.abs(t.x)<Math.abs(t.y)?"x":"y":null;s==="x"?t.x=0:s==="y"&&(t.y=0),t.rot(-e.rotation);const{w:o,h:i}=Po(e.props,r),a=r.bottomRight.x-r.topLeft.x,l=r.bottomRight.y-r.topLeft.y,c=Ft(r),u=1-a,d=1-l;return c.topLeft.x=Fe(c.topLeft.x-t.x/o,0,u),c.topLeft.y=Fe(c.topLeft.y-t.y/i,0,d),c.bottomRight.x=c.topLeft.x+a,c.bottomRight.y=c.topLeft.y+l,{id:e.id,type:e.type,props:{crop:c}}}var fw;let Eme=(fw=class extends ve{onEnter(){this.editor.setCursor({type:"default",rotation:0});const e=this.editor.getOnlySelectedShape();e&&this.editor.setCroppingShape(e.id)}onExit(){this.editor.setCursor({type:"default",rotation:0})}onCancel(){this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})}onPointerDown(e){var t;if(e.accelKey){this.cancel(),this.editor.root.handleEvent(e);return}switch(e.target){case"canvas":{const r=wP(this.editor);if(r&&!this.editor.isShapeOfType(r,"group")){this.onPointerDown({...e,shape:r,target:"shape"});return}this.cancel(),this.editor.root.handleEvent(e);break}case"shape":{if(e.shape.id===this.editor.getCroppingShapeId()){this.editor.setCurrentTool("select.crop.pointing_crop",e);return}else(t=this.editor.getShapeUtil(e.shape))!=null&&t.canCrop(e.shape)?(this.editor.setCroppingShape(e.shape.id),this.editor.setSelectedShapes([e.shape.id]),this.editor.setCurrentTool("select.crop.pointing_crop",e)):(this.cancel(),this.editor.root.handleEvent(e));break}case"selection":{switch(e.handle){case"mobile_rotate":case"top_left_rotate":case"top_right_rotate":case"bottom_left_rotate":case"bottom_right_rotate":{this.editor.setCurrentTool("select.pointing_rotate_handle",{...e,onInteractionEnd:"select.crop.idle"});break}case"top":case"right":case"bottom":case"left":case"top_left":case"top_right":case"bottom_left":case"bottom_right":{this.editor.setCurrentTool("select.crop.pointing_crop_handle",{...e,onInteractionEnd:"select.crop.idle"});break}default:this.cancel()}break}}}onDoubleClick(e){var o;if(this.editor.inputs.getShiftKey()||e.phase!=="up")return;const t=this.editor.getCroppingShapeId();if(!t)return;const r=this.editor.getShape(t);if(!r)return;const s=this.editor.getShapeUtil(r);if(s){if(e.target==="selection"){(o=s.onDoubleClickEdge)==null||o.call(s,r,e);return}this.cancel(),this.editor.root.handleEvent(e)}}onKeyDown(){this.nudgeCroppingImage(!1)}onKeyRepeat(){this.nudgeCroppingImage(!0)}onKeyUp(e){switch(e.key){case"Enter":{this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{});break}}}cancel(){this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})}nudgeCroppingImage(e=!1){const{editor:{inputs:{keys:t}}}=this,r=t.has("ShiftLeft"),s=new C(0,0);if(t.has("ArrowLeft")&&(s.x+=1),t.has("ArrowRight")&&(s.x-=1),t.has("ArrowUp")&&(s.y+=1),t.has("ArrowDown")&&(s.y-=1),s.equals(new C(0,0)))return;r&&s.mul(10);const o=this.editor.getShape(this.editor.getCroppingShapeId());if(!o)return;const i=I$(this.editor,o,s);i&&(e||this.editor.markHistoryStoppingPoint("translate crop"),this.editor.updateShapes([i]))}},E(fw,"id","idle"),fw);class E$ extends ve{onCancel(){this.editor.setCurrentTool("select.crop.idle",{})}onPointerMove(e){this.editor.inputs.getIsDragging()&&this.startDragging(e)}onLongPress(e){this.startDragging(e)}onPointerUp(e){this.editor.setCurrentTool("select.crop.idle",e)}startDragging(e){this.editor.setCurrentTool("select.crop.translating_crop",e)}}E(E$,"id","pointing_crop");class vP extends ve{constructor(){super(...arguments);E(this,"info",{})}onEnter(t){this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd);const r=this.editor.getSelectedShapes()[0];if(!r)return;const s=pd[this.info.handle];this.editor.setCursor({type:s,rotation:this.editor.getSelectionRotation()}),this.editor.setCroppingShape(r.id)}onExit(){this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0)}onPointerMove(){this.editor.inputs.getIsDragging()&&this.startCropping()}onLongPress(){this.startCropping()}startCropping(){this.editor.getIsReadonly()||this.parent.transition("cropping",{...this.info,onInteractionEnd:this.info.onInteractionEnd})}onPointerUp(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,this.info):t();return}this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle")}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}cancel(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,this.info):t();return}this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle")}}E(vP,"id","pointing_crop_handle");class k$ extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"markId","");E(this,"snapshot",{})}onEnter(t){this.info=t,this.snapshot=this.createSnapshot(),this.markId=this.editor.markHistoryStoppingPoint("translating_crop"),this.editor.setCursor({type:"move",rotation:0}),this.updateShapes()}onExit(){this.editor.setCursor({type:"default",rotation:0})}onPointerMove(){this.updateShapes()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(){this.cancel()}onKeyDown(t){switch(t.key){case"Alt":case"Shift":{this.updateShapes();return}}}onKeyUp(t){switch(t.key){case"Enter":{this.complete();return}case"Alt":case"Shift":this.updateShapes()}}complete(){this.updateShapes(),this.editor.setCurrentTool("select.crop.idle",this.info)}cancel(){this.editor.bailToMark(this.markId),this.editor.setCurrentTool("select.crop.idle",this.info)}createSnapshot(){return{shape:this.editor.getOnlySelectedShape()}}updateShapes(){const t=this.snapshot.shape;if(!t)return;const r=this.editor.inputs.getOriginPagePoint(),o=this.editor.inputs.getCurrentPagePoint().clone().sub(r),i=I$(this.editor,t,o);i&&this.editor.updateShapes([i])}}E(k$,"id","translating_crop");class cv extends ve{constructor(){super(...arguments);E(this,"markId","");E(this,"didExit",!1)}static children(){return[Eme,k$,E$,vP,bP]}onEnter(){this.didExit=!1,this.markId=this.editor.markHistoryStoppingPoint("crop")}onExit(){this.didExit||(this.didExit=!0,this.editor.squashToMark(this.markId))}onCancel(){this.didExit||(this.didExit=!0,this.editor.bailToMark(this.markId))}}E(cv,"id","crop"),E(cv,"initial","idle");class _$ extends ve{constructor(){super(...arguments);E(this,"shapeId");E(this,"initialHandle");E(this,"initialAdjacentHandle");E(this,"initialPagePoint");E(this,"markId");E(this,"initialPageTransform");E(this,"initialPageRotation");E(this,"info");E(this,"isPrecise",!1);E(this,"isPreciseId",null);E(this,"pointingId",null);E(this,"exactTimeout",-1)}onEnter(t){var h;const{shape:r,isCreating:s,creatingMarkId:o,handle:i}=t;if(this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.shapeId=r.id,this.markId="",s)if(o)this.markId=o;else{const f=this.editor.getMarkIdMatching(`creating:${this.editor.getOnlySelectedShapeId()}`);f&&(this.markId=f)}else this.markId=this.editor.markHistoryStoppingPoint("dragging handle");this.initialHandle=Ft(i),this.initialPageTransform=this.editor.getShapePageTransform(r),this.initialPageRotation=this.initialPageTransform.rotation(),this.initialPagePoint=this.editor.inputs.getOriginPagePoint().clone(),this.editor.setCursor({type:s?"cross":"grabbing",rotation:0});const a=this.editor.getShapeHandles(r).sort(Tn),l=a.findIndex(f=>f.id===t.handle.id);if(this.initialAdjacentHandle=null,t.handle.snapReferenceHandleId){const f=a.find(g=>g.id===t.handle.snapReferenceHandleId);f&&(this.initialAdjacentHandle=f)}if(!this.initialAdjacentHandle){for(let f=l+1;f<a.length;f++){const g=a[f];if(g.type==="vertex"&&g.id!=="middle"&&g.id!==t.handle.id){this.initialAdjacentHandle=g;break}}if(!this.initialAdjacentHandle)for(let f=a.length-1;f>=0;f--){const g=a[f];if(g.type==="vertex"&&g.id!=="middle"&&g.id!==t.handle.id){this.initialAdjacentHandle=g;break}}}if(this.editor.isShapeOfType(r,"arrow")){const f=En(this.editor,r)[t.handle.id];this.isPrecise=!1,f&&(this.isPrecise=f.props.isPrecise,this.isPrecise?this.isPreciseId=f.toId:this.resetExactTimeout())}const c={handle:this.initialHandle,isPrecise:this.isPrecise,isCreatingShape:!!this.info.isCreating,initial:r},u=this.editor.getShapeUtil(r),d=(h=u.onHandleDragStart)==null?void 0:h.call(u,r,c);d&&this.editor.updateShapes([{...d,id:r.id,type:r.type}]),this.update(),this.editor.select(this.shapeId)}resetExactTimeout(){const r=this.editor.getShapeUtil("arrow").options.pointingPreciseTimeout;this.exactTimeout!==-1&&this.clearExactTimeout(),this.exactTimeout=this.editor.timers.setTimeout(()=>{this.getIsActive()&&!this.isPrecise&&(this.isPrecise=!0,this.isPreciseId=this.pointingId,this.update()),this.exactTimeout=-1},r)}clearExactTimeout(){this.exactTimeout!==-1&&(clearTimeout(this.exactTimeout),this.exactTimeout=-1)}onPointerMove(){this.update()}onKeyDown(){this.update()}onKeyUp(){this.update()}onPointerUp(){this.complete()}onComplete(){this.update(),this.complete()}onCancel(){this.cancel()}onExit(){this.parent.setCurrentToolIdMask(void 0),QC(this.editor),this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0})}complete(){var s;this.editor.snaps.clearIndicators(),mt(this.editor,[this.shapeId]);const t=this.editor.getShape(this.shapeId);if(t){const o=this.editor.getShapeUtil(t),i={handle:this.initialHandle,isPrecise:this.isPrecise,isCreatingShape:!!this.info.isCreating,initial:this.info.shape},a=(s=o.onHandleDragEnd)==null?void 0:s.call(o,t,i);a&&this.editor.updateShapes([{...a,id:t.id}])}const{onInteractionEnd:r}=this.info;if(r)if(typeof r=="string"){if(this.editor.getInstanceState().isToolLocked&&r){this.editor.setCurrentTool(r,{shapeId:this.shapeId});return}}else{r==null||r();return}this.parent.transition("idle")}cancel(){var s;const t=this.editor.getShape(this.shapeId);if(t){const o=this.editor.getShapeUtil(t),i={handle:this.initialHandle,isPrecise:this.isPrecise,isCreatingShape:!!this.info.isCreating,initial:this.info.shape};(s=o.onHandleDragCancel)==null||s.call(o,t,i)}this.editor.bailToMark(this.markId),this.editor.snaps.clearIndicators();const{onInteractionEnd:r}=this.info;if(r){typeof r=="string"?this.editor.setCurrentTool(r,{shapeId:this.shapeId}):r==null||r();return}this.parent.transition("idle")}update(){var k;const{editor:t,shapeId:r,initialPagePoint:s}=this,{initialHandle:o,initialPageRotation:i,initialAdjacentHandle:a}=this,l=this.editor.user.getIsSnapMode(),{snaps:c}=t,u=t.inputs.getCurrentPagePoint(),d=t.inputs.getShiftKey(),h=t.inputs.getCtrlKey(),f=t.inputs.getAltKey(),g=t.inputs.getPointerVelocity(),m=this.info.shape,y=t.getShape(r);if(!y)return;const S=t.getShapeUtil(y),b=t.isShapeOfType(y,"arrow")?En(t,y)[o.id]:void 0;let w=u.clone().sub(s).rot(-i).add(o);if(d&&a&&o.id!=="middle"){const A=C.Angle(a,w),D=Bg(A,24)-A;w=C.RotWith(w,a,D)}t.snaps.clearIndicators();let v={...o,x:w.x,y:w.y},P=!1;if(o.canSnap&&o.snapType?i6("canSnap is deprecated. Cannot use both canSnap and snapType together - snapping disabled. Please use only snapType."):P=o.canSnap||o.snapType!==void 0,P&&(l?!h:h)){if(!t.getShapePageTransform(y.id))throw Error("Expected a page transform");const R=c.handles.snapHandle({currentShapeId:r,handle:v});R&&(R.nudge.rot(-t.getShapeParentTransform(y).rotation()),w.add(R.nudge),v={...o,x:w.x,y:w.y})}const T=(k=S.onHandleDrag)==null?void 0:k.call(S,y,{handle:v,isPrecise:this.isPrecise||f,isCreatingShape:!!this.info.isCreating,initial:m}),I={id:y.id,type:y.type,...T};if(o.type==="vertex"&&this.editor.isShapeOfType(y,"arrow")){const A=En(t,y)[o.id];A?(b==null?void 0:b.toId)!==A.toId&&(this.pointingId=A.toId,this.isPrecise=g.len()<.5||f,this.isPreciseId=this.isPrecise?A.toId:null,this.resetExactTimeout()):b&&(this.pointingId=null,this.isPrecise=!1,this.isPreciseId=null,this.resetExactTimeout())}T&&t.updateShapes([I])}}E(_$,"id","dragging_handle");function M$(n){return n.isLabel?[n]:n instanceof es?n.children.filter(e=>e.isLabel):[]}class A$ extends ve{constructor(){super(...arguments);E(this,"hitLabelOnShapeForPointerUp",null);E(this,"info",{});E(this,"didPointerDownOnEditingShape",!1)}isTextInputFocused(){var r,s,o;return this.editor.getContainer().contains(document.activeElement)&&(((r=document.activeElement)==null?void 0:r.nodeName)==="INPUT"||((s=document.activeElement)==null?void 0:s.nodeName)==="TEXTAREA"||((o=document.activeElement)==null?void 0:o.isContentEditable))}onEnter(t){const r=this.editor.getEditingShape();if(!r)throw Error("Entered editing state without an editing shape");this.hitLabelOnShapeForPointerUp=null,this.didPointerDownOnEditingShape=!1,this.info=t,t.isCreatingTextWhileToolLocked&&this.parent.setCurrentToolIdMask("text"),Uo(this.editor),this.editor.select(r)}onExit(){const{editingShapeId:t}=this.editor.getCurrentPageState();t&&(this.editor.setEditingShape(null),Uo.cancel(),this.info.isCreatingTextWhileToolLocked&&(this.parent.setCurrentToolIdMask(void 0),this.editor.setCurrentTool("text",{})))}onPointerMove(t){if(this.hitLabelOnShapeForPointerUp&&this.editor.inputs.getIsDragging()){if(this.editor.getIsReadonly()||this.hitLabelOnShapeForPointerUp.isLocked)return;this.editor.select(this.hitLabelOnShapeForPointerUp),this.parent.transition("translating",t),this.hitLabelOnShapeForPointerUp=null;return}if(this.didPointerDownOnEditingShape&&this.editor.inputs.isDragging){if(this.editor.getIsReadonly())return;const r=this.editor.getEditingShape();if(!r||r.isLocked)return;if(!this.isTextInputFocused()){this.editor.select(r),this.parent.transition("translating",t),this.didPointerDownOnEditingShape=!1;return}this.didPointerDownOnEditingShape=!1}switch(t.target){case"shape":case"canvas":{Uo(this.editor);return}}}onPointerDown(t){switch(this.hitLabelOnShapeForPointerUp=null,this.didPointerDownOnEditingShape=!1,t.target){case"canvas":{const r=wP(this.editor,!0);if(r){this.onPointerDown({...t,shape:r,target:"shape"});return}break}case"shape":{const{shape:r}=t,s=this.editor.getEditingShape();if(!s)throw Error("Expected an editing shape!");const o=this.editor.getShapeUtil(r).getGeometry(r),i=M$(o),a=i.length===1?i[0]:void 0,l=this.editor.isShapeOfType(s,"text")&&Hl(this.editor,s.props.richText).trim()==="";if(a&&!l){const c=this.editor.getPointInShapeSpace(r,this.editor.inputs.getCurrentPagePoint());if(a.bounds.containsPoint(c,0)&&a.hitTestPoint(c))if(r.id===s.id){this.didPointerDownOnEditingShape=!0;return}else{this.hitLabelOnShapeForPointerUp=r,this.editor.markHistoryStoppingPoint("editing on pointer up"),this.editor.select(r.id);return}}else{if(r.id===s.id)this.editor.isShapeOfType(r,"frame")&&(this.editor.setEditingShape(null),this.parent.transition("idle",t));else{this.parent.transition("pointing_shape",t);return}return}break}}this.parent.transition("idle",t),this.editor.root.handleEvent(t)}onPointerUp(t){var l;if(this.didPointerDownOnEditingShape&&(this.didPointerDownOnEditingShape=!1,!this.isTextInputFocused())){(l=this.editor.getRichTextEditor())==null||l.commands.focus("all");return}const r=this.hitLabelOnShapeForPointerUp;if(!r)return;this.hitLabelOnShapeForPointerUp=null;const s=this.editor.getShapeUtil(r);if(r.isLocked)return;if(this.editor.getIsReadonly()&&!s.canEditInReadonly(r)){this.parent.transition("pointing_shape",t);return}this.editor.select(r.id);const o=this.editor.getEditingShape(),i=o&&o.id!==r.id;this.editor.setEditingShape(r.id);const a=dt.isIos||dt.isAndroid;!a||!i?this.editor.emit("place-caret",{shapeId:r.id,point:t.point}):a&&i&&this.editor.emit("select-all-text",{shapeId:r.id}),Uo(this.editor)}onComplete(t){this.editor.getContainer().focus(),this.parent.transition("idle",t)}onCancel(t){this.editor.getContainer().focus(),this.parent.transition("idle",t)}}E(A$,"id","editing_shape");function ty(n,e){const t=n.getSelectedShapeIds(),r=n.inputs.getCurrentPagePoint(),{shiftKey:s,altKey:o,accelKey:i}=e,a=s||i,l=n.getShapeAtPoint(r,{hitInside:!1,margin:n.options.hitTestMargin/n.getZoomLevel(),hitLabels:!0,renderingOnly:!0,filter:c=>!c.isLocked});if(l){const c=n.getOutermostSelectableShape(l);if(a&&!o)n.cancelDoubleClick(),t.includes(c.id)?(n.markHistoryStoppingPoint("deselecting shape"),n.deselect(c)):(n.markHistoryStoppingPoint("shift selecting shape"),n.setSelectedShapes([...t,c.id]));else{let u;c===l||c.id===n.getFocusedGroupId()||t.includes(c.id)?u=l:u=c,u&&!t.includes(u.id)&&(n.markHistoryStoppingPoint("selecting shape"),n.select(u.id))}}else{if(a)return;{t.length>0&&(n.markHistoryStoppingPoint("selecting none"),n.selectNone());const c=n.getFocusedGroupId();if(Pr(c)){const u=n.getShape(c);n.isPointInShape(u,r,{margin:0,hitInside:!0})||n.setFocusedGroup(null)}}}}const kme=["Delete","Backspace","[","]","Enter"," ","Shift","Tab"];var gw;let _me=(gw=class extends ve{constructor(){super(...arguments);E(this,"selectedShapesOnKeyDown",[])}onEnter(){this.parent.setCurrentToolIdMask(void 0),Uo(this.editor),this.selectedShapesOnKeyDown=[],this.editor.setCursor({type:"default",rotation:0})}onExit(){Uo.cancel()}onPointerMove(){Uo(this.editor)}onPointerDown(t){switch(t.target){case"canvas":{const r=wP(this.editor);if(r&&!r.isLocked){this.onPointerDown({...t,shape:r,target:"shape"});return}const s=this.editor.getSelectedShapeIds(),o=this.editor.getOnlySelectedShape(),i=this.editor.inputs.getCurrentPagePoint();if((s.length>1||o&&!this.editor.getShapeUtil(o).hideSelectionBoundsBg(o))&&v_(this.editor,i)){this.onPointerDown({...t,target:"selection"});return}this.parent.transition("pointing_canvas",t);break}case"shape":{const{shape:r}=t;if(this.editor.isShapeOrAncestorLocked(r)){this.parent.transition("pointing_canvas",t);break}this.parent.transition("pointing_shape",t);break}case"handle":{if(this.editor.getIsReadonly())break;this.editor.inputs.getAltKey()?this.parent.transition("pointing_shape",t):this.parent.transition("pointing_handle",t);break}case"selection":{switch(t.handle){case"mobile_rotate":case"top_left_rotate":case"top_right_rotate":case"bottom_left_rotate":case"bottom_right_rotate":{if(t.accelKey){this.parent.transition("brushing",t);break}this.parent.transition("pointing_rotate_handle",t);break}case"top":case"right":case"bottom":case"left":case"top_left":case"top_right":case"bottom_left":case"bottom_right":{const r=this.editor.getOnlySelectedShape();if(t.ctrlKey&&this.editor.canCropShape(r))this.parent.transition("crop.pointing_crop_handle",t);else{if(t.accelKey){this.parent.transition("brushing",t);break}this.parent.transition("pointing_resize_handle",t)}break}default:{const r=this.editor.getHoveredShape();if(r&&!this.editor.getSelectedShapeIds().includes(r.id)&&!r.isLocked){this.onPointerDown({...t,shape:r,target:"shape"});return}this.parent.transition("pointing_selection",t)}}break}}}onDoubleClick(t){var r,s,o,i,a;if(!(this.editor.inputs.getShiftKey()||t.phase!=="up")&&!(t.ctrlKey||t.shiftKey))switch(t.target){case"canvas":{const l=this.editor.getHoveredShape(),c=this.editor.inputs.getCurrentPagePoint(),u=l&&!this.editor.isShapeOfType(l,"group")?l:this.editor.getSelectedShapeAtPoint(c)??this.editor.getShapeAtPoint(c,{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1}),d=this.editor.getFocusedGroupId();if(u){if(this.editor.isShapeOfType(u,"group")){ty(this.editor,t);return}else{const h=this.editor.getShape(u.parentId);if(h&&this.editor.isShapeOfType(h,"group")&&!(d&&h.id===d)){ty(this.editor,t);return}}this.onDoubleClick({...t,shape:u,target:"shape"});return}this.editor.inputs.getShiftKey()||this.handleDoubleClickOnCanvas(t);break}case"selection":{const l=this.editor.getOnlySelectedShape();if(l){const c=this.editor.getShapeUtil(l),u=t.handle==="right"||t.handle==="left"||t.handle==="top"||t.handle==="bottom",d=t.handle==="top_left"||t.handle==="top_right"||t.handle==="bottom_right"||t.handle==="bottom_left";if(this.editor.getIsReadonly()){this.editor.canEditShape(l,{type:d?"double-click-corner":u?"double-click-edge":"double-click"})&&this.startEditingShape(l,t,!0);break}if(u){const h=(r=c.onDoubleClickEdge)==null?void 0:r.call(c,l,t);if(h){this.editor.markHistoryStoppingPoint("double click edge"),this.editor.updateShapes([h]),mt(this.editor,[l.id]);return}}if(d){const h=(s=c.onDoubleClickCorner)==null?void 0:s.call(c,l,t);if(h){this.editor.markHistoryStoppingPoint("double click corner"),this.editor.updateShapes([h]),mt(this.editor,[l.id]);return}}if(this.editor.canCropShape(l)){this.parent.transition("crop",t);return}this.editor.canEditShape(l)&&this.startEditingShape(l,t,!0)}break}case"shape":{const{shape:l}=t,c=this.editor.getShapeUtil(l);if(l.type!=="video"&&l.type!=="embed"&&this.editor.getIsReadonly())break;if(c.onDoubleClick){const u=(o=c.onDoubleClick)==null?void 0:o.call(c,l);if(u){this.editor.updateShapes([u]);return}}if(c.canCrop(l)&&!this.editor.isShapeOrAncestorLocked(l)){this.editor.markHistoryStoppingPoint("select and crop"),this.editor.select((i=t.shape)==null?void 0:i.id),this.parent.transition("crop",t);return}this.editor.canEditShape(l)?this.startEditingShape(l,t,!0):this.handleDoubleClickOnCanvas(t);break}case"handle":{if(this.editor.getIsReadonly())break;const{shape:l,handle:c}=t,u=this.editor.getShapeUtil(l),d=(a=u.onDoubleClickHandle)==null?void 0:a.call(u,l,c);d?this.editor.updateShapes([d]):this.editor.canEditShape(l)&&this.startEditingShape(l,t,!0)}}}onRightClick(t){switch(t.target){case"canvas":{const r=this.editor.getHoveredShape(),s=r&&!this.editor.isShapeOfType(r,"group")?r:this.editor.getShapeAtPoint(this.editor.inputs.getCurrentPagePoint(),{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1,hitLabels:!0,hitLocked:!0,hitFrameInside:!0,renderingOnly:!0});if(s){this.onRightClick({...t,shape:s,target:"shape"});return}const o=this.editor.getSelectedShapeIds(),i=this.editor.getOnlySelectedShape(),a=this.editor.inputs.getCurrentPagePoint();if((o.length>1||i&&!this.editor.getShapeUtil(i).hideSelectionBoundsBg(i))&&v_(this.editor,a)){this.onRightClick({...t,target:"selection"});return}this.editor.selectNone();break}case"shape":{const{selectedShapeIds:r}=this.editor.getCurrentPageState(),{shape:s}=t,o=this.editor.getOutermostSelectableShape(s,i=>!r.includes(i.id));!r.includes(o.id)&&!this.editor.findShapeAncestor(o,i=>r.includes(i.id))&&(this.editor.markHistoryStoppingPoint("selecting shape"),this.editor.setSelectedShapes([o.id]));break}}}onCancel(){this.editor.getFocusedGroupId()!==this.editor.getCurrentPageId()&&this.editor.getSelectedShapeIds().length>0?this.editor.popFocusedGroupId():(this.editor.markHistoryStoppingPoint("clearing selection"),this.editor.selectNone())}onKeyDown(t){switch(this.selectedShapesOnKeyDown=this.editor.getSelectedShapes(),t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{if(t.accelKey){t.shiftKey?t.code==="ArrowDown"?this.editor.selectFirstChildShape():t.code==="ArrowUp"&&this.editor.selectParentShape():this.editor.selectAdjacentShape(t.code.replace("Arrow","").toLowerCase());return}this.nudgeSelectedShapes(!1);return}}if(Dt.editOnType.get()&&!kme.includes(t.key)&&!t.altKey&&!t.ctrlKey){const r=this.editor.getOnlySelectedShape();if(r&&this.editor.isShapeOfType(r,"note")&&this.editor.canEditShape(r)){this.startEditingShape(r,{...t,target:"shape",shape:r},!0);return}}}onKeyRepeat(t){switch(t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{if(t.accelKey){this.editor.selectAdjacentShape(t.code.replace("Arrow","").toLowerCase());return}this.nudgeSelectedShapes(!0);break}case"Tab":{this.editor.getSelectedShapes().length&&!t.altKey&&this.editor.selectAdjacentShape(t.shiftKey?"prev":"next");break}}}onKeyUp(t){switch(t.key){case"Enter":{if(!this.selectedShapesOnKeyDown.length)return;const r=this.editor.getSelectedShapes();if(r.every(o=>this.editor.isShapeOfType(o,"group"))){this.editor.setSelectedShapes(r.flatMap(o=>this.editor.getSortedChildIdsForParent(o.id)));return}const s=this.editor.getOnlySelectedShape();if(s&&this.editor.canEditShape(s,{type:"press_enter"})){this.startEditingShape(s,{...t,target:"shape",shape:s},!0);return}this.editor.canCropShape(s)&&this.parent.transition("crop",t);break}case"Tab":{this.editor.getSelectedShapes().length&&!t.altKey&&this.editor.selectAdjacentShape(t.shiftKey?"prev":"next");break}}}startEditingShape(t,r,s){const{editor:o}=this;this.editor.markHistoryStoppingPoint("editing shape"),Vj(t)?Nr(o,t,{selectAll:s}):o.setEditingShape(t),this.parent.transition("editing_shape",r)}isOverArrowLabelTest(t){return t?o$(this.editor,t):!1}handleDoubleClickOnCanvas(t){if(this.editor.getIsReadonly()||!this.editor.options.createTextOnCanvasDoubleClick)return;this.editor.markHistoryStoppingPoint("creating text shape");const r=St(),{x:s,y:o}=this.editor.inputs.getCurrentPagePoint();this.editor.createShapes([{id:r,type:"text",x:s,y:o,props:{richText:Kn(""),autoSize:!0}}]);const i=this.editor.getShape(r);i&&this.editor.canEditShape(i)&&Nr(this.editor,r,{info:t})}nudgeSelectedShapes(t=!1){const{editor:{inputs:{keys:r}}}=this,s=r.has("ShiftLeft"),o=new C(0,0);if(r.has("ArrowLeft")&&(o.x-=1),r.has("ArrowRight")&&(o.x+=1),r.has("ArrowUp")&&(o.y-=1),r.has("ArrowDown")&&(o.y+=1),o.equals(new C(0,0)))return;t||this.editor.markHistoryStoppingPoint("nudge shapes");const{gridSize:i}=this.editor.getDocumentSettings(),a=this.editor.getInstanceState().isGridMode?s?i*Dme:i:s?Mme:Ame,l=this.editor.getSelectedShapeIds();this.editor.nudgeShapes(l,o.mul(a)),mt(this.editor,l)}},E(gw,"id","idle"),gw);const Mme=10,Ame=1,Dme=5;function v_(n,e){const t=n.getSelectionRotatedPageBounds();if(!t)return!1;const r=n.getSelectionRotation();return r?kr(e,t.corners.map(s=>C.RotWith(s,t.point,r))):t.containsPoint(e)}class D$ extends ve{constructor(){super(...arguments);E(this,"shapeId","");E(this,"markId","");E(this,"wasAlreadySelected",!1);E(this,"didDrag",!1);E(this,"didCtrlOnEnter",!1);E(this,"info",{});E(this,"_labelDragOffset",new C(0,0))}updateCursor(){this.editor.setCursor({type:"grabbing",rotation:0})}onEnter(t){const{shape:r}=t;typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.info=t,this.shapeId=r.id,this.didDrag=!1,this.didCtrlOnEnter=t.accelKey,this.wasAlreadySelected=this.editor.getOnlySelectedShapeId()===r.id,this.updateCursor();const o=this.editor.getShapeGeometry(r).children[1];if(!o)throw Error(`Expected to find an arrow label geometry for shape: ${r.id}`);const i=this.editor.inputs.getCurrentPagePoint(),a=this.editor.getPointInShapeSpace(r,i);if(this._labelDragOffset=C.Sub(o.center,a),this.markId=this.editor.markHistoryStoppingPoint("label-drag start"),t.shiftKey||t.accelKey){const c=this.editor.getSelectedShapeIds();this.editor.setSelectedShapes([...c,this.shapeId]);return}this.editor.setSelectedShapes([this.shapeId])}onExit(){this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})}onPointerMove(){if(!this.editor.inputs.getIsDragging())return;if(this.didCtrlOnEnter){this.parent.transition("brushing",this.info);return}const r=this.editor.getShape(this.shapeId);if(!r)return;const s=this.editor.getShapeUtil("arrow").options,o=ud(this.editor,r),i=this.editor.getShapePageTransform(r.id),a=this.editor.getPointInShapeSpace(r,this.editor.inputs.getCurrentPagePoint()).add(this._labelDragOffset),l=s$(this.editor,r);let c=o.uninterpolateAlongEdge(a);isNaN(c)&&(c=l);const u=i.applyToPoint(o.interpolateAlongEdge(c)),d=i.applyToPoint(o.interpolateAlongEdge(l));C.DistMin(u,d,s.labelCenterSnapDistance/this.editor.getZoomLevel())&&(c=l),this.didDrag=!0,this.editor.updateShape({id:r.id,type:r.type,props:{labelPosition:c}})}onPointerUp(){const t=this.editor.getShape(this.shapeId);t&&(this.didDrag||!this.wasAlreadySelected?this.complete():this.editor.canEditShape(t)&&Nr(this.editor,t.id))}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}complete(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t();return}this.parent.transition("idle")}cancel(){this.editor.bailToMark(this.markId);const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t();return}this.parent.transition("idle")}}E(D$,"id","pointing_arrow_label");class O$ extends ve{onEnter(e){e.shiftKey||e.accelKey||this.editor.getSelectedShapeIds().length>0&&(this.editor.markHistoryStoppingPoint("selecting none"),this.editor.selectNone())}onPointerMove(e){this.editor.inputs.getIsDragging()&&this.parent.transition("brushing",e)}onPointerUp(e){ty(this.editor,e),this.complete()}onComplete(){this.complete()}onInterrupt(){this.parent.transition("idle")}complete(){this.parent.transition("idle")}}E(O$,"id","pointing_canvas");class R$ extends ve{constructor(){super(...arguments);E(this,"didCtrlOnEnter",!1);E(this,"info",{})}onEnter(t){this.info=t,this.didCtrlOnEnter=t.accelKey;const{shape:r}=t;if(this.editor.isShapeOfType(r,"arrow")){const s=En(this.editor,r),o=s[t.handle.id],i=s[t.handle.id==="start"?"end":"start"],a=this.editor.getShapePageTransform(r.id);o&&LS({editor:this.editor,pointInPageSpace:a.applyToPoint(t.handle),arrow:r,isPrecise:o.props.isPrecise,currentBinding:o,oppositeBinding:i})}this.editor.setCursor({type:"grabbing",rotation:0})}onExit(){this.editor.setHintingShapes([]),this.editor.setCursor({type:"default",rotation:0})}onPointerUp(){const{shape:t,handle:r}=this.info;if(this.editor.isShapeOfType(t,"note")){const{editor:s}=this,o=C_(s,t,r,!1);if(o){Nr(s,o,{selectAll:!0});return}}this.parent.transition("idle",this.info)}onPointerMove(t){const{editor:r}=this;r.inputs.getIsDragging()&&(this.didCtrlOnEnter?this.parent.transition("brushing",t):this.startDraggingHandle())}onLongPress(){this.startDraggingHandle()}startDraggingHandle(){const{editor:t}=this;if(t.getIsReadonly())return;const{shape:r,handle:s}=this.info;if(t.isShapeOfType(r,"note")){const o=C_(t,r,s,!0);if(o){const i=t.getPointInParentSpace(o,t.inputs.getOriginPagePoint()).sub(C.Rot(NS.clone().mul(r.props.scale),o.rotation));t.updateShape({...o,x:i.x,y:i.y}),t.setHoveredShape(o.id).select(o.id).setCurrentTool("select.translating",{...this.info,target:"shape",shape:t.getShape(o),onInteractionEnd:"note",isCreating:!0,onCreate:()=>{Nr(t,o,{selectAll:!0})}});return}}this.parent.transition("dragging_handle",this.info)}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}cancel(){this.parent.transition("idle")}}E(R$,"id","pointing_handle");function C_(n,e,t,r){const s=n.getShapePageTransform(e.id),o=s.point(),i=s.rotation(),l=Vz(n,o,i,e.props.growY*e.props.scale,0,e.props.scale)[t.index];if(l)return Yz(n,e,l,i,r)}class L$ extends ve{constructor(){super(...arguments);E(this,"info",{})}updateCursor(){this.editor.setCursor({type:pd[this.info.handle],rotation:this.editor.getSelectionRotation()})}onEnter(t){this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.updateCursor()}onExit(){this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})}onPointerMove(){this.editor.inputs.getIsDragging()&&this.startRotating()}onLongPress(){this.startRotating()}startRotating(){this.editor.getIsReadonly()||this.parent.transition("rotating",this.info)}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}complete(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t==null||t();return}this.parent.transition("idle")}cancel(){const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,{}):t();return}this.parent.transition("idle")}}E(L$,"id","pointing_rotate_handle");class j$ extends ve{constructor(){super(...arguments);E(this,"info",{})}onEnter(t){this.info=t}onPointerUp(t){ty(this.editor,t),this.parent.transition("idle",t)}onPointerMove(t){this.editor.inputs.getIsDragging()&&this.startTranslating(t)}onLongPress(t){this.startTranslating(t)}startTranslating(t){this.editor.getIsReadonly()||this.parent.transition("translating",t)}onDoubleClick(t){var o,i;const r=this.editor.getHoveredShape(),s=r&&!this.editor.isShapeOfType(r,"group")?r:this.editor.getShapeAtPoint(this.editor.inputs.getCurrentPagePoint(),{hitInside:!0,margin:0,renderingOnly:!0});if(s){this.parent.transition("idle"),(i=(o=this.parent).onDoubleClick)==null||i.call(o,{...t,target:"shape",shape:this.editor.getShape(s)});return}}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}cancel(){this.parent.transition("idle")}}E(j$,"id","pointing_selection");class N$ extends ve{constructor(){super(...arguments);E(this,"hitShape",{});E(this,"hitShapeForPointerUp",{});E(this,"isDoubleClick",!1);E(this,"didCtrlOnEnter",!1);E(this,"didSelectOnEnter",!1)}onEnter(t){const r=this.editor.getSelectedShapeIds(),s=this.editor.getSelectionRotatedPageBounds(),o=this.editor.getFocusedGroupId(),i=this.editor.inputs.getCurrentPagePoint(),{shiftKey:a,altKey:l,accelKey:c}=t;this.hitShape=t.shape,this.isDoubleClick=!1,this.didCtrlOnEnter=c;const u=this.editor.getOutermostSelectableShape(t.shape),d=this.editor.findShapeAncestor(u,h=>r.includes(h.id));if(this.didCtrlOnEnter||this.editor.getShapeUtil(t.shape).onClick||u.id===o||r.includes(u.id)||d||r.length>1&&(s!=null&&s.containsPoint(i))){this.didSelectOnEnter=!1,this.hitShapeForPointerUp=u;return}this.didSelectOnEnter=!0,a&&!l?(this.editor.cancelDoubleClick(),r.includes(u.id)||(this.editor.markHistoryStoppingPoint("shift selecting shape"),this.editor.setSelectedShapes([...r,u.id]))):(this.editor.markHistoryStoppingPoint("selecting shape"),this.editor.setSelectedShapes([u.id]))}onPointerUp(t){var u;const r=this.editor.getSelectedShapeIds(),s=this.editor.getFocusedGroupId(),o=this.editor.getZoomLevel(),i=this.editor.inputs.getCurrentPagePoint(),a=t.shiftKey||t.accelKey,l=this.editor.getShapeAtPoint(i,{margin:this.editor.options.hitTestMargin/o,hitInside:!0,renderingOnly:!0})??this.hitShape,c=l?this.editor.getOutermostSelectableShape(l):this.hitShapeForPointerUp;if(c){const d=this.editor.getShapeUtil(c);if(d.onClick){const h=(u=d.onClick)==null?void 0:u.call(d,c);if(h){this.editor.markHistoryStoppingPoint("shape on click"),this.editor.updateShapes([h]),this.parent.transition("idle",t);return}}if(c.id===s){r.length>0?(this.editor.markHistoryStoppingPoint("clearing shape ids"),this.editor.setSelectedShapes([])):this.editor.popFocusedGroupId(),this.parent.transition("idle",t);return}}if(!this.didSelectOnEnter){const d=this.editor.getOutermostSelectableShape(l,h=>!r.includes(h.id));if(r.includes(d.id))if(a)this.editor.markHistoryStoppingPoint("deselecting on pointer up"),this.editor.deselect(c);else if(r.includes(c.id)){if(r.length===1){const h=this.editor.getShapeUtil(c).getGeometry(c),f=M$(h),g=f.length===1?f[0]:void 0;if(g){const m=this.editor.getPointInShapeSpace(c,i);if(g.bounds.containsPoint(m,0)&&g.hitTestPoint(m)){this.editor.run(()=>{this.editor.markHistoryStoppingPoint("editing on pointer up"),this.editor.select(c.id),this.editor.canEditShape(c)&&(this.editor.setEditingShape(c.id),this.editor.setCurrentTool("select.editing_shape"),this.isDoubleClick?this.editor.emit("select-all-text",{shapeId:c.id}):this.editor.emit("place-caret",{shapeId:c.id,point:t.point}))});return}}}this.editor.markHistoryStoppingPoint("selecting on pointer up"),this.editor.select(c.id)}else this.editor.markHistoryStoppingPoint("selecting on pointer up"),this.editor.select(c);else if(a){const h=this.editor.getShapeAncestors(d);this.editor.markHistoryStoppingPoint("shift deselecting on pointer up"),this.editor.setSelectedShapes([...this.editor.getSelectedShapeIds().filter(f=>!h.find(g=>g.id===f)),d.id])}else this.editor.markHistoryStoppingPoint("selecting on pointer up"),this.editor.setSelectedShapes([d.id])}this.parent.transition("idle",t)}onDoubleClick(){this.isDoubleClick=!0}onPointerMove(t){if(this.editor.inputs.getIsDragging()){if(o$(this.editor,this.hitShape)){this.parent.transition("pointing_arrow_label",{...t,shape:this.hitShape});return}this.didCtrlOnEnter?this.parent.transition("brushing",t):this.startTranslating(t)}}onLongPress(t){this.startTranslating(t)}startTranslating(t){this.editor.getIsReadonly()||(this.editor.focus(),this.parent.transition("translating",t))}onCancel(){this.cancel()}onComplete(){this.cancel()}onInterrupt(){this.cancel()}cancel(){this.parent.transition("idle")}}E(N$,"id","pointing_shape");class F$ extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"markId","");E(this,"didHoldCommand",!1);E(this,"creationCursorOffset",{x:0,y:0});E(this,"snapshot",{})}onEnter(t){const{isCreating:r=!1,creatingMarkId:s,creationCursorOffset:o={x:0,y:0}}=t;this.info=t,this.didHoldCommand=!1,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.creationCursorOffset=o;try{this.snapshot=this._createSnapshot()}catch(i){console.error(i),this.cancel();return}if(this.markId="",r)if(s)this.markId=s;else{const i=this.editor.getMarkIdMatching(`creating:${this.editor.getOnlySelectedShapeId()}`);i&&(this.markId=i)}else this.markId=this.editor.markHistoryStoppingPoint("starting resizing");r&&this.editor.setCursor({type:"cross",rotation:0}),this.handleResizeStart(),this.updateShapes()}onTick({elapsed:t}){const{editor:r}=this;!r.inputs.getIsDragging()||r.inputs.getIsPanning()||r.edgeScrollManager.updateEdgeScrolling(t)}onPointerMove(){this.updateShapes()}onKeyDown(){this.updateShapes()}onKeyUp(){this.updateShapes()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(){this.cancel()}cancel(){const{shapeSnapshots:t}=this.snapshot;t.forEach(({shape:s})=>{var i;const o=this.editor.getShape(s.id);if(o){const a=this.editor.getShapeUtil(s);(i=a.onResizeCancel)==null||i.call(a,s,o)}}),this.editor.bailToMark(this.markId);const{onInteractionEnd:r}=this.info;if(r){typeof r=="string"?this.editor.setCurrentTool(r,{}):r();return}this.parent.transition("idle")}complete(){var r,s;if(mt(this.editor,this.snapshot.selectedShapeIds),this.handleResizeEnd(),this.info.isCreating&&this.info.onCreate){(s=(r=this.info).onCreate)==null||s.call(r,this.editor.getOnlySelectedShape());return}const{onInteractionEnd:t}=this.info;if(t)if(typeof t=="string"){if(this.editor.getInstanceState().isToolLocked){this.editor.setCurrentTool(t,{});return}}else{t();return}this.parent.transition("idle")}handleResizeStart(){const{shapeSnapshots:t}=this.snapshot,r=[];t.forEach(({shape:s})=>{var a;const o=this.editor.getShapeUtil(s),i=(a=o.onResizeStart)==null?void 0:a.call(o,s);i&&r.push(i)}),r.length>0&&this.editor.updateShapes(r)}handleResizeEnd(){const{shapeSnapshots:t}=this.snapshot,r=[];t.forEach(({shape:s})=>{var l;const o=this.editor.getShape(s.id),i=this.editor.getShapeUtil(s),a=(l=i.onResizeEnd)==null?void 0:l.call(i,s,o);a&&r.push(a)}),r.length>0&&this.editor.updateShapes(r)}updateShapes(){const t=this.editor.inputs.getAltKey(),r=this.editor.inputs.getShiftKey(),{frames:s,shapeSnapshots:o,selectionBounds:i,cursorHandleOffset:a,selectedShapeIds:l,selectionRotation:c,canShapesDeform:u}=this.snapshot;let d=r||!u;if(o.size===1){const k=[...o.values()][0];this.editor.isShapeOfType(k.shape,"text")&&(d=!(this.info.handle==="left"||this.info.handle==="right"))}const h=Jt(this.editor.inputs),f=this.editor.inputs.getCurrentPagePoint().clone().sub(a).sub(this.creationCursorOffset),g=this.editor.inputs.getOriginPagePoint().clone().sub(a);if(this.editor.getInstanceState().isGridMode&&!h){const{gridSize:k}=this.editor.getDocumentSettings();f.snapToGrid(k)}const m=this.info.handle,y=P_(m,Math.PI);if(this.editor.snaps.clearIndicators(),(this.editor.user.getIsSnapMode()?!h:h)&&c%Bt===0){const{nudge:k}=this.editor.snaps.shapeBounds.snapResizeShapes({dragDelta:C.Sub(f,g),initialSelectionPageBounds:this.snapshot.initialSelectionPageBounds,handle:P_(m,c),isAspectRatioLocked:d,isResizingFromCenter:t});f.add(k)}const b=C.RotWith(t?i.center:i.getHandlePoint(y),i.point,c),w=C.Sub(f,b).rot(-c),v=C.Sub(g,b).rot(-c),P=C.DivV(w,v);Number.isFinite(P.x)||(P.x=1),Number.isFinite(P.y)||(P.y=1);const T=m==="top"||m==="bottom",I=m==="left"||m==="right";d?I?P.y=Math.abs(P.x):T?P.x=Math.abs(P.y):Math.abs(P.x)>Math.abs(P.y)?P.y=Math.abs(P.x)*(P.y<0?-1:1):P.x=Math.abs(P.y)*(P.x<0?-1:1):(T&&(P.x=1),I&&(P.y=1)),this.info.isCreating||this.updateCursor({dragHandle:m,isFlippedX:P.x<0,isFlippedY:P.y<0,rotation:c});for(const k of o.keys()){const A=o.get(k);this.editor.resizeShape(k,P,{initialShape:A.shape,initialBounds:A.bounds,initialPageTransform:A.pageTransform,dragHandle:m,mode:l.length===1&&k===l[0]?"resize_bounds":"scale_shape",scaleOrigin:b,isAspectRatioLocked:d,scaleAxisRotation:c,skipStartAndEndCallbacks:!0})}if(h){this.didHoldCommand=!0;for(const{id:k,children:A}of s){if(!A.length)continue;const R=o.get(k).shape,D=this.editor.getShape(k);if(!(R&&D))continue;const j=D.x-R.x,_=D.y-R.y,M=new C(j,_).rot(-R.rotation);if(M.x!==0||M.y!==0)for(const O of A)this.editor.updateShape({id:O.id,type:O.type,x:O.x-M.x,y:O.y-M.y})}}else if(this.didHoldCommand){this.didHoldCommand=!1;for(const{children:k}of s)if(k.length)for(const A of k)this.editor.updateShape({id:A.id,type:A.type,x:A.x,y:A.y})}}updateCursor({dragHandle:t,isFlippedX:r,isFlippedY:s,rotation:o}){const i={...this.editor.getInstanceState().cursor};switch(t){case"top_left":case"bottom_right":{i.type="nwse-resize",r!==s&&(i.type="nesw-resize");break}case"top_right":case"bottom_left":{i.type="nesw-resize",r!==s&&(i.type="nwse-resize");break}}i.rotation=o,this.editor.setCursor(i)}onExit(){this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0}),this.editor.snaps.clearIndicators()}_createSnapshot(){const{editor:t}=this,r=t.getSelectedShapeIds(),s=t.getSelectionRotation(),o=t.inputs.getOriginPagePoint(),i=t.getSelectionRotatedPageBounds();if(!i)throw Error("Resizing but nothing is selected");const a=C.RotWith(i.getHandlePoint(this.info.handle),i.point,s),l=C.Sub(o,a),c=new Map,u=[],d=f=>{const g=t.getShape(f);if(!g)return!1;const m=t.getShapeUtil(g);if(m.canResize(g)){const y=t.getShapePageTransform(g);c.set(g.id,{shape:g,bounds:t.getShapeGeometry(g).bounds,pageTransform:y,pageRotation:Q.Decompose(y).rotation,isAspectRatioLocked:m.isAspectRatioLocked(g)})}if(t.isShapeOfType(g,"frame")&&u.push({id:g.id,children:Le(t.getSortedChildIdsForParent(g).map(y=>t.getShape(y)))}),!m.canResizeChildren(g))return!1};r.forEach(f=>{d(f)!==!1&&t.visitDescendants(f,d)});const h=![...c.values()].some(f=>!fA(f.pageRotation,s)||f.isAspectRatioLocked);return{shapeSnapshots:c,selectionBounds:i,cursorHandleOffset:l,selectionRotation:s,selectedShapeIds:r,canShapesDeform:h,initialSelectionPageBounds:this.editor.getSelectionPageBounds(),frames:u}}}E(F$,"id","resizing");const Xb=["top","top_right","right","bottom_right","bottom","bottom_left","left","top_left"];function P_(n,e){e=e%vt;const t=Math.round(e/(ht/4)),r=Xb.indexOf(n);return Xb[(r+t)%Xb.length]}const T_=Math.PI/180;class B$ extends ve{constructor(){super(...arguments);E(this,"snapshot",{});E(this,"info",{});E(this,"markId","")}onEnter(t){this.info=t,typeof t.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.markId=this.editor.markHistoryStoppingPoint("rotate start");const r=S2({editor:this.editor,ids:this.editor.getSelectedShapeIds()});if(!r)return this.parent.transition("idle",this.info);this.snapshot=r;const s=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Bf({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!1}),snapshot:this.snapshot,stage:"start"}),this.editor.setCursor({type:pd[this.info.handle],rotation:s+this.snapshot.initialShapesRotation})}onExit(){this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0),this.snapshot={}}onPointerMove(){this.update()}onKeyDown(){this.update()}onKeyUp(){this.update()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(){this.cancel()}update(){const t=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Bf({editor:this.editor,delta:t,snapshot:this.snapshot,stage:"update"}),this.editor.setCursor({type:pd[this.info.handle],rotation:t+this.snapshot.initialShapesRotation})}cancel(){const{shapeSnapshots:t}=this.snapshot;t.forEach(({shape:s})=>{var i;const o=this.editor.getShape(s.id);if(o){const a=this.editor.getShapeUtil(s);(i=a.onRotateCancel)==null||i.call(a,s,o)}}),this.editor.bailToMark(this.markId);const{onInteractionEnd:r}=this.info;if(r){typeof r=="string"?this.editor.setCurrentTool(r,this.info):r();return}this.parent.transition("idle",this.info)}complete(){Bf({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!0}),snapshot:this.snapshot,stage:"end"}),mt(this.editor,this.snapshot.shapeSnapshots.map(r=>r.shape.id));const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t,this.info):t();return}this.parent.transition("idle",this.info)}_getRotationFromPointerPosition({snapToNearestDegree:t}){const r=this.editor.inputs.getShiftKey(),s=this.editor.inputs.getCurrentPagePoint(),{initialCursorAngle:o,initialShapesRotation:i,initialPageCenter:a}=this.snapshot,l=a.angle(s)-o;let c=i+l;if(r)c=Bg(c,24);else if(t&&(c=Math.round(c/T_)*T_,this.editor.getInstanceState().isCoarsePointer)){const u=Bg(c,4),d=jf(c,u);Math.abs(d)<jU(5)&&(c=u)}return c-i}}E(B$,"id","rotating");class z$ extends ve{constructor(){super(...arguments);E(this,"hits",new Set);E(this,"size",0);E(this,"scribbleId","id");E(this,"initialSelectedShapeIds",new Set);E(this,"newlySelectedShapeIds",new Set)}onEnter(){this.initialSelectedShapeIds=new Set(this.editor.inputs.getShiftKey()?this.editor.getSelectedShapeIds():[]),this.newlySelectedShapeIds=new Set,this.size=0,this.hits.clear();const t=this.editor.scribbles.addScribble({color:"selection-stroke",opacity:.32,size:12});this.scribbleId=t.id,this.updateScribbleSelection(!0),this.editor.updateInstanceState({brush:null})}onExit(){this.editor.scribbles.stop(this.scribbleId)}onPointerMove(){this.updateScribbleSelection(!0)}onPointerUp(){this.complete()}onKeyDown(){this.updateScribbleSelection(!1)}onKeyUp(){this.editor.inputs.getAltKey()?this.updateScribbleSelection(!1):this.parent.transition("brushing")}onCancel(){this.cancel()}onComplete(){this.complete()}pushPointToScribble(){const{x:t,y:r}=this.editor.inputs.getCurrentPagePoint();this.editor.scribbles.addPoint(this.scribbleId,t,r)}updateScribbleSelection(t){const{editor:r}=this,s=this.editor.inputs.getShiftKey(),o=this.editor.inputs.getOriginPagePoint(),i=this.editor.inputs.getPreviousPagePoint(),a=this.editor.inputs.getCurrentPagePoint(),{newlySelectedShapeIds:l,initialSelectedShapeIds:c}=this;t&&this.pushPointToScribble();const u=0,d=J.FromPoints([i,a]).expandBy(u),h=r.getShapeIdsInsideBounds(d);if(h.size===0){const T=r.getSelectedShapeIds(),I=new Set(s?[...l,...c]:[...l]);(T.length!==I.size||T.some(k=>!I.has(k)))&&this.editor.setSelectedShapes(Array.from(I));return}const m=this.editor.getCurrentPageRenderingShapesSorted().filter(T=>h.has(T.id));let y,S,b,w;for(let T=0,I=m.length;T<I;T++){if(y=m[T],r.isShapeOfType(y,"group")||l.has(y.id)||r.isShapeOrAncestorLocked(y)||(S=r.getShapeGeometry(y),r.isShapeOfType(y,"frame")&&S.bounds.containsPoint(r.getPointInShapeSpace(y,o))))continue;const k=r.getShapePageTransform(y);if(!S||!k)continue;const A=k.clone().invert();b=A.applyToPoint(i),w=A.applyToPoint(a);const{bounds:R}=S;if(!(R.minX-u>Math.max(b.x,w.x)||R.minY-u>Math.max(b.y,w.y)||R.maxX+u<Math.min(b.x,w.x)||R.maxY+u<Math.min(b.y,w.y))&&S.hitTestLineSegment(b,w,u)){const D=this.editor.getOutermostSelectableShape(y),j=this.editor.getShapeMask(D.id);if(j&&zA(i,a,j)!==null&&!kr(a,j))continue;l.add(D.id)}}const v=r.getSelectedShapeIds(),P=new Set(s?[...l,...c]:[...l]);(v.length!==P.size||v.some(T=>!P.has(T)))&&this.editor.setSelectedShapes(Array.from(P))}complete(){this.updateScribbleSelection(!0),this.parent.transition("idle")}cancel(){this.editor.setSelectedShapes([...this.initialSelectedShapeIds]),this.parent.transition("idle")}}E(z$,"id","scribble_brushing");var Ome=Object.create,$$=Object.defineProperty,Rme=Object.getOwnPropertyDescriptor,Lme=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),H$=n=>{throw TypeError(n)},U$=(n,e,t)=>e in n?$$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,jme=n=>[,,,Ome(null)],K$=["class","method","getter","setter","accessor","field","value","get","set"],W$=n=>n!==void 0&&typeof n!="function"?H$("Function expected"):n,Nme=(n,e,t,r,s)=>({kind:K$[n],name:e,metadata:r,addInitializer:o=>t._?H$("Already initialized"):s.push(W$(o||null))}),Fme=(n,e)=>U$(e,Lme("metadata"),n[3]),Bme=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},zme=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=K$[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,Rme(s,t)),S=r.length-1;S>=0;S--)l=Nme(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,W$(i)&&(y[g]=i);return y&&$$(s,t,y),s},Pi=(n,e,t)=>U$(n,typeof e!="symbol"?e+"":e,t),V$,zS;const $me=320,Hme=60;V$=[Xr];class CP{constructor(e){this.editor=e,Bme(zS,5,this),Pi(this,"shapesToActuallyMove",[]),Pi(this,"draggedOverShapeIds",new Set),Pi(this,"initialGroupIds",new Map),Pi(this,"initialParentIds",new Map),Pi(this,"initialIndices",new Map),Pi(this,"initialDraggingOverShape"),Pi(this,"prevDraggingOverShape"),Pi(this,"prevPagePoint",new C),Pi(this,"intervalTimerId",-1),e.disposables.add(this.dispose)}startDraggingShapes(e,t,r){const{editor:s}=this;if(this.intervalTimerId!==-1)return;const o=new Set(e),i=new Set;for(const c of o){const u=s.getShapeParent(c);u&&s.isShapeOfType(u,"group")&&(i.has(u)||i.add(u))}for(const c of i){const u=Le(s.getSortedChildIdsForParent(c).map(d=>s.getShape(d)));o.add(c);for(const d of u)o.delete(d)}this.initialParentIds.clear();for(const c of o){const u=s.getShapeParent(c);u&&this.initialParentIds.set(c.id,u.id),this.initialIndices.set(c.id,c.index);const d=s.findShapeAncestor(c,h=>s.isShapeOfType(h,"group"));d&&this.initialGroupIds.set(c.id,d.id)}const a=s.getCurrentPageShapesSorted();this.shapesToActuallyMove=Array.from(o).filter(c=>!c.isLocked).sort((c,u)=>a.indexOf(c)-a.indexOf(u)),this.initialDraggingOverShape=s.getDraggingOverShape(t,this.shapesToActuallyMove),this.prevDraggingOverShape=this.initialDraggingOverShape,this.updateDraggingShapes(t,r);let l=0;this.intervalTimerId=this.editor.timers.setInterval(()=>{l++,!(l%3&&this.editor.inputs.getPointerVelocity().len()>.5)&&this.updateDraggingShapes(s.inputs.getCurrentPagePoint(),r)},e.length>10?$me:Hme)}dropShapes(e){var o,i;const{editor:t}=this,r=t.inputs.getCurrentPagePoint();this.updateDraggingShapes(r);const s=t.getDraggingOverShape(r,e);if(s){const a=t.getShapeUtil(s);(i=a.onDropShapesOver)==null||i.call(a,s,e,{initialDraggingOverShapeId:((o=this.initialDraggingOverShape)==null?void 0:o.id)??null,initialParentIds:this.initialParentIds,initialIndices:this.initialIndices})}this.dispose()}clear(){clearInterval(this.intervalTimerId),this.intervalTimerId=-1,this.initialParentIds.clear(),this.initialIndices.clear(),this.shapesToActuallyMove=[],this.initialDraggingOverShape=void 0,this.prevDraggingOverShape=void 0,this.editor.setHintingShapes([])}dispose(){this.clear()}updateDraggingShapes(e,t){const{editor:r}=this,s=Le(this.shapesToActuallyMove.map(l=>r.getShape(l)));if(!s.length)return;const o=r.getDraggingOverShape(e,this.shapesToActuallyMove),i=r.inputs.getCurrentPagePoint(),a=!this.prevPagePoint.equals(i);this.prevPagePoint.setTo(i),r.run(()=>{var l,c,u,d,h,f,g,m;if(((l=this.prevDraggingOverShape)==null?void 0:l.id)===(o==null?void 0:o.id)){if(a&&o&&Pr(o.id)&&!r.inputs.getPreviousPagePoint().equals(i)){const y=r.getShapeUtil(o);(u=y.onDragShapesOver)==null||u.call(y,o,s,{initialDraggingOverShapeId:((c=this.initialDraggingOverShape)==null?void 0:c.id)??null,initialParentIds:this.initialParentIds,initialIndices:this.initialIndices})}return}if(this.prevDraggingOverShape){const y=r.getShapeUtil(this.prevDraggingOverShape);(h=y.onDragShapesOut)==null||h.call(y,this.editor.getShape(this.prevDraggingOverShape),s,{nextDraggingOverShapeId:(o==null?void 0:o.id)??null,initialDraggingOverShapeId:((d=this.initialDraggingOverShape)==null?void 0:d.id)??null,initialParentIds:this.initialParentIds,initialIndices:this.initialIndices})}if(o){const y=r.getShapeUtil(o);(m=y.onDragShapesIn)==null||m.call(y,o,s,{initialDraggingOverShapeId:((f=this.initialDraggingOverShape)==null?void 0:f.id)??null,prevDraggingOverShapeId:((g=this.prevDraggingOverShape)==null?void 0:g.id)??null,initialParentIds:this.initialParentIds,initialIndices:this.initialIndices}),r.setHintingShapes([o.id])}else this.prevDraggingOverShape&&r.setHintingShapes([]);t==null||t()}),this.prevDraggingOverShape=o}}zS=jme();zme(zS,1,"dispose",V$,CP);Fme(zS,CP);var Ume=Object.create,G$=Object.defineProperty,Kme=Object.getOwnPropertyDescriptor,Y$=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),X$=n=>{throw TypeError(n)},q$=(n,e,t)=>e in n?G$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Wme=n=>[,,,Ume((n==null?void 0:n[Y$("metadata")])??null)],Z$=["class","method","getter","setter","accessor","field","value","get","set"],J$=n=>n!==void 0&&typeof n!="function"?X$("Function expected"):n,Vme=(n,e,t,r,s)=>({kind:Z$[n],name:e,metadata:r,addInitializer:o=>t._?X$("Already initialized"):s.push(J$(o||null))}),Gme=(n,e)=>q$(e,Y$("metadata"),n[3]),Yme=(n,e,t,r)=>{for(var s=0,o=n[e>>1],i=o&&o.length;s<i;s++)o[s].call(t);return r},Xme=(n,e,t,r,s,o)=>{for(var i,a,l,c,u=e&7,d=!1,h=!1,f=2,g=Z$[u+5],m=n[f]||(n[f]=[]),y=(s=s.prototype,Kme(s,t)),S=r.length-1;S>=0;S--)l=Vme(u,t,a={},n[3],m),l.static=d,l.private=h,c=l.access={has:b=>t in b},c.get=b=>b[t],i=(0,r[S])(y[g],l),a._=1,J$(i)&&(y[g]=i);return y&&G$(s,t,y),s},pa=(n,e,t)=>q$(n,typeof e!="symbol"?e+"":e,t),Q$,dv,$S;class HS extends(dv=ve,Q$=[Xr],dv){constructor(){super(...arguments),Yme($S,5,this),pa(this,"info",{}),pa(this,"selectionSnapshot",{}),pa(this,"snapshot",{}),pa(this,"markId",""),pa(this,"isCloning",!1),pa(this,"isCreating",!1),pa(this,"dragAndDropManager",new CP(this.editor))}onCreate(e){}onEnter(e){var o;const{isCreating:t=!1,creatingMarkId:r,onCreate:s=()=>{}}=e;if(!((o=this.editor.getSelectedShapeIds())!=null&&o.length)){this.parent.transition("idle");return}if(this.info=e,typeof e.onInteractionEnd=="string"&&this.parent.setCurrentToolIdMask(e.onInteractionEnd),this.isCreating=t,this.markId="",t)if(r)this.markId=r;else{const i=this.editor.getMarkIdMatching(`creating:${this.editor.getOnlySelectedShapeId()}`);i&&(this.markId=i)}else this.markId=this.editor.markHistoryStoppingPoint("translating");this.onCreate=s,this.isCloning=!1,this.info=e,this.editor.setCursor({type:"move",rotation:0}),this.selectionSnapshot=I_(this.editor),!(!this.isCreating&&this.editor.inputs.getAltKey()&&(this.startCloning(),this.isCloning))&&(this.snapshot=this.selectionSnapshot,this.handleStart(),this.updateShapes())}onExit(){this.parent.setCurrentToolIdMask(void 0),this.selectionSnapshot={},this.snapshot={},this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0}),this.dragAndDropManager.clear()}onTick({elapsed:e}){const{editor:t}=this;!t.inputs.getIsDragging()||t.inputs.getIsPanning()||t.edgeScrollManager.updateEdgeScrolling(e)}onPointerMove(){this.updateShapes()}onKeyDown(){this.editor.inputs.getAltKey()&&!this.isCloning&&(this.startCloning(),this.isCloning)||this.updateShapes()}onKeyUp(){if(!this.editor.inputs.getAltKey()&&this.isCloning){this.stopCloning();return}this.updateShapes()}onPointerUp(){this.complete()}onComplete(){this.complete()}onCancel(){this.cancel()}startCloning(){if(this.isCreating)return;const e=Array.from(this.editor.getSelectedShapeIds());this.editor.canCreateShapes(e)&&(this.isCloning=!0,this.reset(),this.markId=this.editor.markHistoryStoppingPoint("translate cloning"),this.editor.duplicateShapes(Array.from(this.editor.getSelectedShapeIds())),this.snapshot=I_(this.editor),this.handleStart(),this.updateShapes())}stopCloning(){this.isCloning=!1,this.snapshot=this.selectionSnapshot,this.reset(),this.markId=this.editor.markHistoryStoppingPoint("translate"),this.updateShapes()}reset(){this.editor.bailToMark(this.markId)}complete(){var t;this.updateShapes(),this.dragAndDropManager.dropShapes(this.snapshot.movingShapes),this.handleEnd(),mt(this.editor,this.snapshot.movingShapes.map(r=>r.id));const{onInteractionEnd:e}=this.info;if(e)if(typeof e=="string"){if(this.editor.getInstanceState().isToolLocked){this.editor.setCurrentTool(e);return}}else{e();return}this.isCreating?(t=this.onCreate)==null||t.call(this,this.editor.getOnlySelectedShape()):this.parent.transition("idle")}cancel(){const{movingShapes:e}=this.snapshot;e.forEach(r=>{var o;const s=this.editor.getShape(r.id);if(s){const i=this.editor.getShapeUtil(r);(o=i.onTranslateCancel)==null||o.call(i,r,s)}}),this.reset();const{onInteractionEnd:t}=this.info;if(t){typeof t=="string"?this.editor.setCurrentTool(t):t();return}this.parent.transition("idle",this.info)}handleStart(){const{movingShapes:e}=this.snapshot,t=[];e.forEach(r=>{var i;const s=this.editor.getShapeUtil(r),o=(i=s.onTranslateStart)==null?void 0:i.call(s,r);o&&t.push(o)}),t.length>0&&this.editor.updateShapes(t),this.dragAndDropManager.startDraggingShapes(Le(this.snapshot.movingShapes.map(r=>this.editor.getShape(r.id))),this.editor.inputs.getOriginPagePoint(),this.updateParentTransforms),this.editor.setHoveredShape(null)}handleEnd(){const{movingShapes:e}=this.snapshot;if(this.isCloning&&e.length>0){const r=C.Average(e.map(o=>this.editor.getShapePageTransform(o.id).point())),s=C.Sub(r,this.selectionSnapshot.averagePagePoint);C.IsNaN(s)||this.editor.updateInstanceState({duplicateProps:{shapeIds:e.map(o=>o.id),offset:{x:s.x,y:s.y}}})}const t=[];e.forEach(r=>{var a;const s=this.editor.getShape(r.id),o=this.editor.getShapeUtil(r),i=(a=o.onTranslateEnd)==null?void 0:a.call(o,r,s);i&&t.push(i)}),t.length>0&&this.editor.updateShapes(t)}updateShapes(){const{snapshot:e}=this;this.dragAndDropManager.startDraggingShapes(e.movingShapes,this.editor.inputs.getOriginPagePoint(),this.updateParentTransforms),qme({editor:this.editor,snapshot:e});const{movingShapes:t}=e,r=[];t.forEach(s=>{var l;const o=this.editor.getShape(s.id),i=this.editor.getShapeUtil(s),a=(l=i.onTranslate)==null?void 0:l.call(i,s,o);a&&r.push(a)}),r.length>0&&this.editor.updateShapes(r)}updateParentTransforms(){const{editor:e,snapshot:{shapeSnapshots:t}}=this;t.forEach(r=>{const s=e.getShape(r.shape.id);if(!s)return null;const o=On(s.parentId)?null:Q.Inverse(e.getShapePageTransform(s.parentId));r.parentTransform=o})}}$S=Wme(dv);Xme($S,1,"updateParentTransforms",Q$,HS);Gme($S,HS);pa(HS,"id","translating");function I_(n){var d;const e=[],t=[],r=n.getSelectedShapeIds(),s=Le(r.map(h=>{const f=n.getShape(h);if(!f)return null;e.push(f);const g=n.getShapePageTransform(h),m=g.point(),y=g.rotation();t.push(m);const S=Ar.isId(f.parentId)?null:Q.Inverse(n.getShapePageTransform(f.parentId));return{shape:f,pagePoint:m,pageRotation:y,parentTransform:S}})),o=n.getOnlySelectedShape();let i=[];if(o)i=n.snaps.shapeBounds.getSnapPoints(o.id);else{const h=n.getSelectionPageBounds();h&&(i=h.cornersAndCenter.map((f,g)=>({id:"selection:"+g,x:f.x,y:f.y})))}let a,l;const c=n.inputs.getOriginPagePoint(),u=s.filter(h=>n.isShapeOfType(h.shape,"note")&&n.isPointInShape(h.shape,c));if(u.length!==0)if(u.length===1)l=u[0];else{const h=n.getCurrentPageShapesSorted();l=(d=u.map(f=>({snapshot:f,index:h.findIndex(g=>g.id===f.shape.id)})).sort((f,g)=>g.index-f.index)[0])==null?void 0:d.snapshot}return l&&(a=Gz(n,l.pageRotation,l.shape.props.scale,l.shape.props.growY??0)),{averagePagePoint:C.Average(t),movingShapes:e,shapeSnapshots:s,initialPageBounds:n.getSelectionPageBounds(),initialSnapPoints:i,noteAdjacentPositions:a,noteSnapshot:l}}function qme({editor:n,snapshot:e}){const{inputs:t}=n,{noteSnapshot:r,noteAdjacentPositions:s,initialPageBounds:o,initialSnapPoints:i,shapeSnapshots:a,averagePagePoint:l}=e,c=n.inputs.getShiftKey(),u=n.inputs.getAccelKey(),d=n.getInstanceState().isGridMode,h=n.getDocumentSettings().gridSize,f=C.Sub(t.getCurrentPagePoint(),t.getOriginPagePoint()),g=c?Math.abs(f.x)<Math.abs(f.y)?"x":"y":null;g==="x"?f.x=0:g==="y"&&(f.y=0),n.snaps.clearIndicators();const m=n.user.getIsSnapMode()?!u:u;let y=!1;if(m&&n.inputs.getPointerVelocity().len()<.5){const{nudge:v}=n.snaps.shapeBounds.snapTranslateShapes({dragDelta:f,initialSelectionPageBounds:o,lockedAxis:g,initialSelectionSnapPoints:i});f.add(v)}else if(r&&s){const{scale:v}=r.shape.props,P=r.pagePoint.clone().add(f).add(NS.clone().mul(v).rot(r.pageRotation));let T=Wz/n.getZoomLevel(),I=new C(0,0);for(const k of s){const A=C.Sub(P,k),R=A.len();R<T&&(y=!0,T=R,I=A)}f.sub(I)}const S=C.Add(l,f),b=n.snaps.getIndicators();d&&!u&&!y&&b.length===0&&S.snapToGrid(h);const w=C.Sub(S,l);n.updateShapes(Le(a.map(({shape:v,pagePoint:P,parentTransform:T})=>{const I=C.Add(P,w),k=T?Q.applyToPoint(T,I):I;return{id:v.id,type:v.type,x:k.x,y:k.y}})))}class Sg extends ve{constructor(){super(...arguments);E(this,"reactor")}static children(){return[cv,bP,_me,O$,N$,HS,P$,z$,vP,j$,T$,A$,F$,B$,L$,D$,R$,_$]}cleanUpDuplicateProps(){const t=this.editor.getSelectedShapeIds(),r=this.editor.getInstanceState();if(!r.duplicateProps)return;const s=new Set(r.duplicateProps.shapeIds);t.length===s.size&&t.every(o=>s.has(o))||this.editor.updateInstanceState({duplicateProps:null})}onEnter(){this.reactor=Mr("clean duplicate props",()=>{try{this.cleanUpDuplicateProps()}catch(t){console.error(t)}})}onExit(){var t;(t=this.reactor)==null||t.call(this),this.editor.getCurrentPageState().editingShapeId&&this.editor.setEditingShape(null)}}E(Sg,"id","select"),E(Sg,"initial","idle"),E(Sg,"isLockable",!1);class e4 extends ve{constructor(){super(...arguments);E(this,"info",{})}onEnter(t){this.info=t}onPointerDown(){this.parent.transition("pointing",this.info)}onKeyDown(t){t.key==="Shift"&&this.parent.transition("zoom_quick",this.info)}}E(e4,"id","idle");class t4 extends ve{constructor(){super(...arguments);E(this,"info",{})}onEnter(t){this.info=t}onPointerUp(){this.complete()}onPointerMove(){this.editor.inputs.getIsDragging()&&this.parent.transition("zoom_brushing",this.info)}onCancel(){this.cancel()}complete(){const t=this.editor.inputs.getCurrentScreenPoint();this.editor.inputs.getAltKey()?this.editor.zoomOut(t,{animation:{duration:220}}):this.editor.zoomIn(t,{animation:{duration:220}}),this.parent.transition("idle",this.info)}cancel(){this.parent.transition("idle",this.info)}}E(t4,"id","pointing");class n4 extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"zoomBrush",new J)}onEnter(t){this.info=t,this.update()}onExit(){this.editor.updateInstanceState({zoomBrush:null})}onPointerMove(){this.update()}onPointerUp(){this.complete()}onCancel(){this.cancel()}update(){const t=this.editor.inputs.getOriginPagePoint(),r=this.editor.inputs.getCurrentPagePoint();this.zoomBrush.setTo(J.FromPoints([t,r])),this.editor.updateInstanceState({zoomBrush:this.zoomBrush.toJson()})}cancel(){this.parent.transition("idle",this.info)}complete(){const{zoomBrush:t}=this,r=8/this.editor.getZoomLevel();if(t.width<r&&t.height<r){const s=this.editor.inputs.getCurrentScreenPoint();this.editor.inputs.getAltKey()?this.editor.zoomOut(s,{animation:{duration:220}}):this.editor.zoomIn(s,{animation:{duration:220}})}else{const s=this.editor.inputs.getAltKey()?this.editor.getZoomLevel()/2:void 0;this.editor.zoomToBounds(t,{targetZoom:s,animation:{duration:220}})}this.parent.transition("idle",this.info)}}E(n4,"id","zoom_brushing");class r4 extends ve{constructor(){super(...arguments);E(this,"info",{});E(this,"qzState","idle");E(this,"initialVpb",new J);E(this,"initialPp",new C);E(this,"overviewZoom",1);E(this,"nextVpb",new J)}cleanupZoomReactor(){}onEnter(t){const{editor:r}=this;this.info=t,this.qzState="idle",this.initialVpb=r.getViewportPageBounds(),this.initialPp=C.From(r.inputs.getCurrentPagePoint()),r.setCursor({type:"zoom-in",rotation:0});const s=this.initialVpb,o=r.getCurrentPageBounds(),i=o?J.Expand(s,o):s.clone(),a=r.getViewportScreenBounds(),l=r.inputs.getCurrentScreenPoint(),c=l.x-a.x,u=l.y-a.y,{x:d,y:h}=this.initialPp,f=d-i.minX,g=i.maxX-d,m=h-i.minY,y=i.maxY-h;let S=r.getCamera().z;f>0&&(S=Math.min(S,c/f)),g>0&&(S=Math.min(S,(a.w-c)/g)),m>0&&(S=Math.min(S,u/m)),y>0&&(S=Math.min(S,(a.h-u)/y)),S*=.85,S=Math.max(r.getCameraOptions().zoomSteps[0],S),this.overviewZoom=S,r.options.quickZoomPreservesScreenBounds&&(this.cleanupZoomReactor=Mr("zoom change in quick zoom",()=>{r.getZoomLevel(),this.updateBrush()}));const{x:b,y:w,z:v}=r.getCamera(),P=v/S;r.setCamera(new C((b+d)*P-d,(w+h)*P-h,S)),r.options.quickZoomPreservesScreenBounds||this.updateBrush()}onExit(){this.cleanupZoomReactor(),this.zoomToNewViewport(),this.editor.updateInstanceState({zoomBrush:null})}onPointerUp(){var r;const t=((r=this.info.onInteractionEnd)==null?void 0:r.split(".")[0])??"select";this.editor.setCurrentTool(t)}onCancel(){var r;this.qzState="idle";const t=((r=this.info.onInteractionEnd)==null?void 0:r.split(".")[0])??"select";this.editor.setCurrentTool(t)}onKeyUp(t){t.key==="Shift"&&this.parent.transition("idle",this.info)}updateBrush(){const{editor:t}=this,r=this.getNextVpb();this.nextVpb.setTo(r),t.updateInstanceState({zoomBrush:r.toJson()})}zoomToNewViewport(){const{editor:t}=this;switch(this.qzState){case"idle":t.zoomToBounds(this.initialVpb,{inset:0});break;case"moving":t.zoomToBounds(this.nextVpb,{inset:0});break}}onPointerMove(){this.qzState==="moving"&&this.updateBrush()}onTick(){const{editor:t}=this;switch(this.qzState){case"idle":{const r=t.getZoomLevel();C.Dist2(t.inputs.getCurrentPagePoint(),this.initialPp)*r>t.options.dragDistanceSquared/r&&(this.qzState="moving",this.updateBrush());break}}}getNextVpb(){const{editor:t}=this;let r,s;if(t.options.quickZoomPreservesScreenBounds){const d=this.overviewZoom/t.getCamera().z;r=this.initialVpb.w*d,s=this.initialVpb.h*d}else r=this.initialVpb.w,s=this.initialVpb.h;const{x:o,y:i}=t.inputs.getCurrentPagePoint(),a=t.getViewportScreenBounds(),l=t.inputs.getCurrentScreenPoint(),{x:c,y:u}=new C((l.x-a.x)/a.w,(l.y-a.y)/a.h);return new J(o-c*r,i-u*s,r,s)}}E(r4,"id","zoom_quick");class xg extends ve{constructor(){super(...arguments);E(this,"info",{})}static children(){return[e4,t4,n4,r4]}onEnter(t){var s;this.info=t;const r=(s=t.onInteractionEnd)==null?void 0:s.split(".")[0];this.parent.setCurrentToolIdMask(r),this.updateCursor()}onExit(){this.parent.setCurrentToolIdMask(void 0),this.editor.updateInstanceState({zoomBrush:null,cursor:{type:"default",rotation:0}})}onKeyDown(){this.updateCursor()}onKeyUp(t){this.updateCursor(),t.key.toLowerCase()==="z"&&this.complete()}onInterrupt(){this.complete()}complete(){var r;const t=((r=this.info.onInteractionEnd)==null?void 0:r.split(".")[0])??"select";this.editor.setCurrentTool(t)}updateCursor(){this.editor.inputs.getAltKey()&&!this.editor.isIn("zoom.zoom_quick")?this.editor.setCursor({type:"zoom-out",rotation:0}):this.editor.setCursor({type:"zoom-in",rotation:0})}}E(xg,"id","zoom"),E(xg,"initial","idle"),E(xg,"isLockable",!1);const Zme=[gg,mg,yg,xg,Sg],Jme=_e.forwardRef(function({isEditing:e,text:t,handleFocus:r,handleChange:s,handleKeyDown:o,handlePaste:i,handleBlur:a,handleInputPointerDown:l,handleDoubleClick:c},u){const d=K(),h=f=>{s({plaintext:f.target.value})};return p.jsx("textarea",{ref:u,className:"tl-text tl-text-input",name:"text",tabIndex:-1,disabled:!e,readOnly:!e,autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",autoSave:"off",placeholder:"",spellCheck:"true",wrap:"off",dir:"auto",defaultValue:t,onFocus:r,onChange:h,onKeyDown:f=>o(f.nativeEvent),onBlur:a,onTouchEnd:d.markEventAsHandled,onContextMenu:e?f=>f.stopPropagation():void 0,onPointerDown:l,onPaste:i,onDoubleClick:c,onDragStart:je})});_e.memo(function({shapeId:e,type:t,text:r,labelColor:s,font:o,fontSize:i,lineHeight:a,align:l,verticalAlign:c,wrap:u,isSelected:d,padding:h=0,onKeyDown:f,classNamePrefix:g,style:m,textWidth:y,textHeight:S,showTextOutline:b=!0}){const{rInput:w,isEmpty:v,isEditing:P,isReadyForEditing:T,...I}=qfe(e,t,r),k=Jm.normalizeTextForDom(r||""),A=k.length>0,R=Xz(l);if(!P&&!A)return null;const D=g||"tl-text";return p.jsx("div",{className:`${D}-label tl-text-wrapper tl-plain-text-wrapper`,"aria-hidden":!P,"data-font":o,"data-align":l,"data-hastext":!v,"data-isediting":P,"data-is-ready-for-editing":T,"data-textwrap":!!u,"data-isselected":d,style:{justifyContent:l==="middle"||R?"center":l,alignItems:c==="middle"?"center":c,padding:h,...m},children:p.jsxs("div",{className:`${D}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:a.toString(),minHeight:Math.floor(i*a)+"px",minWidth:Math.ceil(y||0),color:s,width:y?Math.ceil(y):void 0,height:S?Math.ceil(S):void 0},children:[p.jsx("div",{className:xe(`${D} tl-text tl-text-content`,b?"tl-text__outline":"tl-text__no-outline"),dir:"auto",children:k.split(`
537
+ `).map((j,_)=>p.jsx("div",{dir:"auto",children:j},_))}),(T||d)&&p.jsx(Jme,{ref:w,text:r,isEditing:P,shapeId:e,...I,handleKeyDown:f??I.handleKeyDown})]})})});let uv={fonts:{tldraw_mono:`${ln()}/fonts/IBMPlexMono-Medium.woff2`,tldraw_mono_italic:`${ln()}/fonts/IBMPlexMono-MediumItalic.woff2`,tldraw_mono_bold:`${ln()}/fonts/IBMPlexMono-Bold.woff2`,tldraw_mono_italic_bold:`${ln()}/fonts/IBMPlexMono-BoldItalic.woff2`,tldraw_serif:`${ln()}/fonts/IBMPlexSerif-Medium.woff2`,tldraw_serif_italic:`${ln()}/fonts/IBMPlexSerif-MediumItalic.woff2`,tldraw_serif_bold:`${ln()}/fonts/IBMPlexSerif-Bold.woff2`,tldraw_serif_italic_bold:`${ln()}/fonts/IBMPlexSerif-BoldItalic.woff2`,tldraw_sans:`${ln()}/fonts/IBMPlexSans-Medium.woff2`,tldraw_sans_italic:`${ln()}/fonts/IBMPlexSans-MediumItalic.woff2`,tldraw_sans_bold:`${ln()}/fonts/IBMPlexSans-Bold.woff2`,tldraw_sans_italic_bold:`${ln()}/fonts/IBMPlexSans-BoldItalic.woff2`,tldraw_draw:`${ln()}/fonts/Shantell_Sans-Informal_Regular.woff2`,tldraw_draw_italic:`${ln()}/fonts/Shantell_Sans-Informal_Regular_Italic.woff2`,tldraw_draw_bold:`${ln()}/fonts/Shantell_Sans-Informal_Bold.woff2`,tldraw_draw_italic_bold:`${ln()}/fonts/Shantell_Sans-Informal_Bold_Italic.woff2`}};function s4(n){return x.useMemo(()=>n?{fonts:{...uv.fonts,...n==null?void 0:n.fonts}}:uv,[n])}const Qme=["align-bottom","align-center-horizontal","align-center-vertical","align-left","align-right","align-top","alt","arrow-arc","arrow-cycle","arrow-elbow","arrow-left","arrowhead-arrow","arrowhead-bar","arrowhead-diamond","arrowhead-dot","arrowhead-none","arrowhead-square","arrowhead-triangle-inverted","arrowhead-triangle","blob","bold","bookmark","bring-forward","bring-to-front","broken","bulletList","check-circle","check","chevron-down","chevron-left","chevron-right","chevron-up","chevrons-ne","chevrons-sw","clipboard-copied","clipboard-copy","code","color","comment","corners","crop","cross-2","cross-circle","dash-dashed","dash-dotted","dash-draw","dash-solid","disconnected","discord","distribute-horizontal","distribute-vertical","dot","dots-horizontal","dots-vertical","download","drag-handle-dots","duplicate","edit","external-link","fill-fill","fill-lined-fill","fill-none","fill-pattern","fill-semi","fill-solid","follow","following","font-draw","font-mono","font-sans","font-serif","geo-arrow-down","geo-arrow-left","geo-arrow-right","geo-arrow-up","geo-check-box","geo-cloud","geo-diamond","geo-ellipse","geo-heart","geo-hexagon","geo-octagon","geo-oval","geo-pentagon","geo-rectangle","geo-rhombus-2","geo-rhombus","geo-star","geo-trapezoid","geo-triangle","geo-x-box","github","group","heading","help-circle","highlight","horizontal-align-end","horizontal-align-middle","horizontal-align-start","info-circle","italic","leading","link","list","lock","manual","menu","minus","mixed","pack","plus","question-mark-circle","question-mark","redo","reset-zoom","rotate-ccw","rotate-cw","send-backward","send-to-back","share-1","size-extra-large","size-large","size-medium","size-small","spline-cubic","spline-line","stack-horizontal","stack-vertical","status-offline","stretch-horizontal","stretch-vertical","strike","text-align-center","text-align-left","text-align-right","toggle-off","toggle-on","tool-arrow","tool-eraser","tool-frame","tool-hand","tool-highlight","tool-laser","tool-line","tool-media","tool-note","tool-pencil","tool-pointer","tool-screenshot","tool-text","trash","twitter","underline","undo","ungroup","unlock","vertical-align-end","vertical-align-middle","vertical-align-start","warning-triangle","zoom-in","zoom-out"];let Jd={...uv,icons:Object.fromEntries(Qme.map(n=>[n,`${ln()}/icons/icon/0_merged.svg#${n}`])),translations:Object.fromEntries(oh.map(n=>[n.locale,`${ln()}/translations/${n.locale}.json`])),embedIcons:Object.fromEntries(NC.map(n=>[n.type,`${ln()}/embed-icons/${n.type}.png`]))};function o4(n){return x.useMemo(()=>n?{fonts:Object.assign({...Jd.fonts},{...n==null?void 0:n.fonts}),icons:Object.assign({...Jd.icons},{...n==null?void 0:n.icons}),embedIcons:Object.assign({...Jd.embedIcons},{...n==null?void 0:n.embedIcons}),translations:Object.assign({...Jd.translations},{...n==null?void 0:n.translations})}:Jd,[n])}const eye=rn(function({overrides:e,components:t,assetUrls:r,onUiEvent:s,forceMobile:o,mediaMimeTypes:i,children:a}){const l=Xt();return p.jsx(e5.Provider,{value:i,children:p.jsx(Aie,{children:p.jsx(Yj,{assetUrls:o4(r),children:p.jsx(Xj,{overrides:n5(e),locale:(l==null?void 0:l.user.getLocale())??Cr.locale,children:p.jsx(Cie,{onEvent:s,children:p.jsx(Fie,{children:p.jsx(Nie,{context:"tla",children:p.jsx(nQ,{children:p.jsx(bie,{forceMobile:o,children:p.jsx(pue,{overrides:t,children:p.jsx(tye,{overrides:e,children:a})})})})})})})})})})})});function tye({overrides:n,children:e}){const t=uae(n);return p.jsx(gue,{overrides:t.actions,children:p.jsx(hae,{overrides:t.tools,children:e})})}function nye(){const n=K(),{addToast:e}=Xi();x.useEffect(()=>{function t({name:r,count:s}){e({title:"Maximum shapes reached",description:`You've reached the maximum number of shapes allowed on ${r} (${s}). Please delete some shapes or move to a different page to continue.`,severity:"warning"})}return n.addListener("max-shapes",t),()=>{n.removeListener("max-shapes",t)}},[n,e])}const rye=_e.memo(function({renderDebugMenuItems:e,children:t,hideUi:r,components:s,...o}){return p.jsx(eye,{...o,components:s,children:p.jsx(sye,{hideUi:r,renderDebugMenuItems:e,children:t})})}),sye=_e.memo(function({children:e,hideUi:t,...r}){return eue(),tae(),p.jsxs(p.Fragment,{children:[e,t?null:p.jsx(oye,{...r})]})}),oye=_e.memo(function(){const e=K(),t=Se(),r=Gn(),s=Ps(),o=W("focus",()=>e.getInstanceState().isFocusMode,[e]),i=W("debug",()=>e.getInstanceState().isDebugMode,[e]),{SharePanel:a,TopPanel:l,MenuPanel:c,StylePanel:u,Toolbar:d,HelpMenu:h,NavigationPanel:f,HelperButtons:g,DebugPanel:m,Toasts:y,Dialogs:S,A11y:b}=ti();nye();const w=x.useRef(!1),v=x.useRef(-1),[P,T]=x.useState(!1);iy("update hide toolbar while delayed",()=>{if(!(dt.isIos||dt.isAndroid))return;if(e.getEditingShapeId()===null){w.current&&(w.current=!1,clearTimeout(v.current),dt.isAndroid?v.current=e.timers.setTimeout(()=>{T(!1)},150):T(!1));return}w.current||(w.current=!0,clearTimeout(v.current),T(!0))},[]);const{"toggle-focus-mode":I}=ni(),{breakpointsAbove:k,breakpointsBelow:A}=x.useMemo(()=>{const R=[],D=[];for(let j=0;j<qf.length;j++)j<=r?R.push(j):D.push(j);return{breakpointsAbove:R,breakpointsBelow:D}},[r]);return p.jsxs("div",{className:xe("tlui-layout",{"tlui-layout__mobile":r<Ot.TABLET_SM}),"data-iseditinganything":P,"data-breakpoint":r,"data-breakpoints-above":k.join(" "),"data-breakpoints-below":A.join(" "),children:[p.jsx(aQ,{}),o?p.jsx("div",{className:"tlui-layout__top",children:p.jsx(Ye,{type:"icon",className:"tlui-focus-button",title:t("focus-mode.toggle-focus-mode"),onClick:()=>I.onSelect("menu"),children:p.jsx(Ae,{icon:"dot"})})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{className:"tlui-layout__top",children:[p.jsxs("div",{className:"tlui-layout__top__left",children:[c&&p.jsx(c,{}),g&&p.jsx(g,{})]}),p.jsx("div",{className:"tlui-layout__top__center",children:l&&p.jsx(l,{})}),p.jsxs("div",{className:"tlui-layout__top__right",children:[a&&p.jsx(a,{}),u&&r>=Ot.TABLET_SM&&!s&&p.jsx(u,{})]})]}),p.jsxs("div",{className:"tlui-layout__bottom",children:[p.jsxs("div",{className:"tlui-layout__bottom__main",children:[f&&p.jsx(f,{}),d&&p.jsx(d,{}),h&&p.jsx(h,{})]}),i&&m&&p.jsx(m,{}),b&&p.jsx(b,{})]})]}),y&&p.jsx(y,{}),S&&p.jsx(S,{})]})});function E_(){const{RichTextToolbar:n,ImageToolbar:e,VideoToolbar:t,CursorChatBubble:r,FollowingIndicator:s}=ti();return p.jsxs(p.Fragment,{children:[n&&p.jsx(n,{}),e&&p.jsx(e,{}),t&&p.jsx(t,{}),s&&p.jsx(s,{}),r&&p.jsx(r,{})]})}const iye=()=>{const{Spinner:n}=xt();return p.jsx(gR,{children:n?p.jsx(n,{}):null})},aye=[...Zme,...Gfe];function lye(n){var B;const{children:e,maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:s,acceptedVideoMimeTypes:o,onMount:i,components:a={},shapeUtils:l=[],bindingUtils:c=[],tools:u=[],embeds:d,options:h,textOptions:f,...g}=n,m=yd(a),y=a==null?void 0:a.InFrontOfTheCanvas,S=x.useMemo(()=>g.hideUi?y??null:y?()=>p.jsxs(p.Fragment,{children:[p.jsx(E_,{}),p.jsx(y,{})]}):E_,[g.hideUi,y]),b=x.useMemo(()=>({Scribble:Lk,ShapeIndicators:ohe,CollaboratorScribble:Lk,SelectionForeground:nhe,Handles:Vue,Overlays:que,Spinner:GB,LoadingScreen:iye,...m,InFrontOfTheCanvas:S}),[m,S]),w=Sa(l),v=x.useMemo(()=>Mu("type",w,b$),[w]),P=Sa(c),T=x.useMemo(()=>Mu("type",P,cz),[P]),I=Sa(u),k=x.useMemo(()=>Mu("id",I,aye),[I]),A=Sa(s??fd),R=Sa(o??sy),D=(h==null?void 0:h.text)??f,j=x.useMemo(()=>({addFontsFromNode:Nz,...D,tipTapConfig:{extensions:xp,...D==null?void 0:D.tipTapConfig}}),[D]),_=x.useMemo(()=>({...h,text:j}),[h,j]),M=x.useMemo(()=>[...A,...R],[A,R]),O=s4(g.assetUrls);return v.find(H=>H.type==="embed")&&d&&ey.setEmbedDefinitions(d),p.jsx(Yj,{assetUrls:o4(g.assetUrls),children:p.jsx(Xj,{overrides:n5(g.overrides),locale:((B=g.user)==null?void 0:B.userPreferences.get().locale)??Cr.locale,children:p.jsx(TW,{initialState:"select",...g,components:b,shapeUtils:v,bindingUtils:T,tools:k,options:_,assetUrls:O,children:p.jsxs(rye,{...g,components:b,mediaMimeTypes:M,children:[p.jsx(cye,{maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:A,acceptedVideoMimeTypes:R,onMount:i}),e]})})})})}function cye({maxImageDimension:n,maxAssetSize:e,acceptedImageMimeTypes:t,acceptedVideoMimeTypes:r,onMount:s}){const o=K(),i=Xi(),a=Se(),l=Rt();mR(()=>{const d=[];return d.push(wme(o)),o.fonts.requestFonts(sfe),o.once("edit",()=>l("edit",{source:"unknown"})),Sfe(o,{maxImageDimension:n,maxAssetSize:e,acceptedImageMimeTypes:t,acceptedVideoMimeTypes:r,toasts:i,msg:a}),d.push(o.store.props.onMount(o)),d.push(s==null?void 0:s(o)),()=>{d.forEach(h=>h==null?void 0:h())}});const{Canvas:c}=xt(),{ContextMenu:u}=ti();return u?p.jsx(u,{}):c?p.jsx(c,{}):null}const k_={text:{tipTapConfig:{extensions:xp},addFontsFromNode:Nz}};x.memo(function(e){const[t,r]=x.useState(null),[s,o]=x.useState(null),i=Sa(e.shapeUtils??[]),a=x.useMemo(()=>Mu("type",i,b$),[i]),l=Sa(e.bindingUtils??[]),c=x.useMemo(()=>Mu("type",l,cz),[l]),u=jG({snapshot:e.snapshot,shapeUtils:a}),{pageId:d,bounds:h,scale:f,pixelRatio:g,background:m,padding:y,darkMode:S,preserveAspectRatio:b,format:w="svg",licenseKey:v,assetUrls:P,options:T,textOptions:I}=e,k=x.useMemo(()=>({...k_,...T,text:{...k_.text,...(T==null?void 0:T.text)??I}}),[T,I]),A=s4(P);return x.useLayoutEffect(()=>{if(!s||!u)return;let R=!1;const D=document.createElement("div");s.appendChild(D),s.classList.add("tl-container","tl-theme__light");const j=new he({store:u,shapeUtils:a,bindingUtils:c,tools:[],getContainer:()=>D,licenseKey:v,fontAssetUrls:A.fonts,options:k});d&&j.setCurrentPage(d);const _=j.getCurrentPageShapeIds();async function M(){await j.fonts.loadRequiredFontsForCurrentPage(j.options.maxFontsToLoadBeforeRender);const O=await j.toImage([..._],{bounds:h,scale:f,background:m,padding:y,darkMode:S,preserveAspectRatio:b,format:w});if(!O||R)return;const N=URL.createObjectURL(O.blob);r(N),j.dispose()}return M(),()=>{R=!0}},[w,s,u,a,c,d,h,f,m,y,S,b,v,g,A,k]),x.useEffect(()=>()=>{t&&URL.revokeObjectURL(t)},[t]),p.jsx("div",{ref:o,style:{position:"relative",width:"100%",height:"100%"},children:t&&p.jsx("img",{src:t,referrerPolicy:"strict-origin-when-cross-origin",style:{width:"100%",height:"100%"}})})});x.memo(function({children:e}){const t=Se(),r=Gn(),s=x.useRef(null);Jo(s);const o=e??p.jsx(Ale,{});return r<Ot.MOBILE?null:p.jsx("div",{ref:s,className:"tlui-help-menu",children:p.jsxs(IS,{id:"help menu",children:[p.jsx(ES,{children:p.jsx(Ye,{type:"help",title:t("help-menu.title"),"data-testid":"help-menu.button",children:p.jsx(Ae,{icon:"question-mark",small:!0})})}),p.jsx(kS,{side:"top",align:"end",alignOffset:0,sideOffset:8,children:p.jsx(Fr,{type:"menu",sourceId:"help-menu",children:o})})]})})});x.forwardRef(function({children:e,className:t},r){return p.jsxs(Bse,{ref:r,className:xe("tlui-button tlui-select__trigger",t),children:[e,p.jsx(zse,{className:"tlui-select__chevron",children:p.jsx(Co,{icon:"chevron-down",label:"",small:!0})})]})});const dye=tt({schemaVersion:lr(1),storeVersion:Lf,recordVersions:Dg(Ke,tt({version:Lf,subTypeVersions:Dg(Ke,Lf).optional(),subTypeKey:Ke.optional()}))}),uye=tt({schemaVersion:lr(2),sequences:Dg(Ke,Lf)});tt({tldrawFileFormatVersion:iH,schema:aH("schemaVersion",{1:dye,2:uye}),records:Bn(tt({id:Ke,typeName:Ke}).allowUnknownProperties())});Wi("tldraw","4.4.0","esm");Wi("@tldraw/tldraw","4.4.0","esm");const mn={padding:12,borderRadius:8},Kl={session:"#a855f7",toolCall:"#f59e0b",toolResult:"#22c55e",textResponse:"#60a5fa",compaction:"#ef4444",statusline:"#ec4899"},__={Read:"📄",Write:"✏️",Edit:"🔧",Bash:"⌨️",Glob:"🔍",Grep:"🔎",Task:"🤖",WebSearch:"🌐",WebFetch:"📡",MultiEdit:"🔧",Skill:"⚡",AskUserQuestion:"❓",EnterPlanMode:"📋",ExitPlanMode:"✅",NotebookEdit:"📓",default:"🔹"};function hye(n){return __[n]||__.default}function PP(n,e){return n.length<=e?n:n.slice(0,e-1)+"…"}class i4 extends Gs{getDefaultProps(){return{w:280,h:84,model:"unknown",cwd:"",sessionId:"",toolCount:0}}component(e){const t=Kl.session;return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:"#1a1a2e",border:`2px solid ${t}`,borderRadius:mn.borderRadius,padding:mn.padding,fontFamily:"Inter, system-ui, sans-serif",display:"flex",flexDirection:"column",gap:4,pointerEvents:"all"},children:[p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p.jsx("span",{style:{background:t,color:"#0a0a0f",fontSize:9,fontWeight:800,padding:"2px 6px",borderRadius:3,letterSpacing:1},children:"SESSION"}),p.jsx("span",{style:{color:t,fontSize:13,fontWeight:700},children:e.props.model})]}),p.jsx("div",{style:{color:"#787882",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.props.cwd}),p.jsxs("div",{style:{color:"#505058",fontSize:10},children:[e.props.toolCount," tools available"]})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:mn.borderRadius,ry:mn.borderRadius})}}E(i4,"type","sessionNode");const pye={pending:"#f59e0b",running:"#60a5fa",complete:"#22c55e",denied:"#ef4444"};class a4 extends Gs{getDefaultProps(){return{w:260,h:72,toolName:"",toolInput:"",status:"complete"}}component(e){const t=Kl.toolCall,r=pye[e.props.status],s=hye(e.props.toolName);return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:"#141419",border:`1.5px solid ${t}40`,borderLeft:`3px solid ${t}`,borderRadius:mn.borderRadius,padding:mn.padding,fontFamily:"Inter, system-ui, sans-serif",display:"flex",flexDirection:"column",gap:4,pointerEvents:"all"},children:[p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p.jsx("span",{style:{fontSize:14},children:s}),p.jsx("span",{style:{color:t,fontSize:12,fontWeight:600},children:e.props.toolName}),p.jsx("span",{style:{marginLeft:"auto",fontSize:9,color:r,fontWeight:600,textTransform:"uppercase"},children:e.props.status})]}),p.jsx("div",{style:{color:"#787882",fontSize:10,fontFamily:"JetBrains Mono, monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:PP(e.props.toolInput,80)})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:mn.borderRadius,ry:mn.borderRadius})}}E(a4,"type","toolCallNode");class l4 extends Gs{getDefaultProps(){return{w:260,h:64,toolName:"",outputSummary:"",isError:!1}}component(e){const t=e.props.isError?Kl.compaction:Kl.toolResult;return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:"#141419",border:`1.5px solid ${t}30`,borderLeft:`3px solid ${t}`,borderRadius:mn.borderRadius,padding:mn.padding,fontFamily:"Inter, system-ui, sans-serif",display:"flex",flexDirection:"column",gap:4,pointerEvents:"all"},children:[p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p.jsx("span",{style:{fontSize:12},children:e.props.isError?"❌":"✅"}),p.jsxs("span",{style:{color:t,fontSize:11,fontWeight:600},children:[e.props.toolName," result"]})]}),p.jsx("div",{style:{color:"#787882",fontSize:10,fontFamily:"JetBrains Mono, monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:PP(e.props.outputSummary,100)})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:mn.borderRadius,ry:mn.borderRadius})}}E(l4,"type","toolResultNode");class c4 extends Gs{getDefaultProps(){return{w:280,h:72,text:""}}component(e){const t=Kl.textResponse;return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:"#141419",border:`1.5px solid ${t}30`,borderLeft:`3px solid ${t}`,borderRadius:mn.borderRadius,padding:mn.padding,fontFamily:"Inter, system-ui, sans-serif",display:"flex",flexDirection:"column",gap:4,overflow:"hidden",pointerEvents:"all"},children:[p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[p.jsx("span",{style:{fontSize:12},children:"💬"}),p.jsx("span",{style:{color:t,fontSize:11,fontWeight:600},children:"Claude Response"})]}),p.jsx("div",{style:{color:"#a0a0a8",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:PP(e.props.text,200)})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:mn.borderRadius,ry:mn.borderRadius})}}E(c4,"type","textResponseNode");class d4 extends Gs{getDefaultProps(){return{w:260,h:48,preTokens:0,trigger:"auto"}}component(e){const t=Kl.compaction,r=Math.round(e.props.preTokens/1e3);return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:`${t}15`,border:`1.5px dashed ${t}60`,borderRadius:mn.borderRadius,padding:"8px 12px",fontFamily:"Inter, system-ui, sans-serif",display:"flex",alignItems:"center",gap:8,pointerEvents:"all"},children:[p.jsx("span",{style:{fontSize:14},children:"⚠️"}),p.jsxs("div",{children:[p.jsx("div",{style:{color:t,fontSize:11,fontWeight:700},children:"CONTEXT COMPACTED"}),p.jsxs("div",{style:{color:"#787882",fontSize:10},children:["Was ",r,"k tokens — ",e.props.trigger]})]})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:mn.borderRadius,ry:mn.borderRadius})}}E(d4,"type","compactionNode");class u4 extends Gs{getDefaultProps(){return{w:220,h:140,model:"unknown",cost:"$0.00",tokensIn:"0",tokensOut:"0",contextPct:0,skill:"Idle",turns:0}}component(e){const{model:t,cost:r,tokensIn:s,tokensOut:o,contextPct:i,skill:a,turns:l}=e.props,c=Kl.statusline,u=i>90?"#dc2626":i>75?"#ef4444":i>40?"#fb923c":"#e4e4e7";return p.jsx(Jr,{children:p.jsxs("div",{style:{width:e.props.w,height:e.props.h,background:"#0a0a0f",border:`1.5px solid ${c}50`,borderRadius:10,padding:10,fontFamily:"JetBrains Mono, monospace",fontSize:10,display:"flex",flexDirection:"column",gap:3,pointerEvents:"all"},children:[p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginBottom:2},children:[p.jsx("span",{style:{background:c,color:"#0a0a0f",fontSize:8,fontWeight:800,padding:"1px 4px",borderRadius:2,letterSpacing:1},children:"UC"}),p.jsx("span",{style:{color:c,fontSize:10,fontWeight:600},children:"Statusline"})]}),p.jsx(Qd,{label:"Model",value:t,color:"#a855f7"}),p.jsx(Qd,{label:"Skill",value:a,color:c}),p.jsx(Qd,{label:"Tokens",value:`${s} + ${o}`,color:"#f59e0b"}),p.jsx(Qd,{label:"Cost",value:r,color:"#22c55e"}),p.jsx(Qd,{label:"Turns",value:String(l),color:"#787882"}),p.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,marginTop:2},children:[p.jsx("span",{style:{color:u,minWidth:28},children:"Ctx"}),p.jsx("div",{style:{flex:1,height:5,borderRadius:3,background:"#28282d",overflow:"hidden"},children:p.jsx("div",{style:{width:`${i}%`,height:"100%",background:u,borderRadius:3}})}),p.jsxs("span",{style:{color:u,minWidth:26,textAlign:"right"},children:[i,"%"]})]})]})})}indicator(e){return p.jsx("rect",{width:e.props.w,height:e.props.h,rx:10,ry:10})}}E(u4,"type","statuslineWidget");function Qd({label:n,value:e,color:t}){return p.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[p.jsx("span",{style:{color:"#505058"},children:n}),p.jsx("span",{style:{color:t,fontWeight:500},children:e})]})}const eu=120,fye=120,gye=100,mye=500,yye=60;function M_(n){var s;const{nodes:e}=j_.getState(),t=Of.getState(),r=new Set(n.getCurrentPageShapeIds());for(let o=0;o<e.length;o++){const i=e[o],a=`shape:${i.id}`;if(r.has(a))continue;const l=fye+o*gye;switch(i.type){case"session":n.createShape({id:a,type:"sessionNode",x:eu,y:l,props:{model:i.data.model||"unknown",cwd:i.data.cwd||"",sessionId:i.data.session_id||"",toolCount:((s=i.data.tools)==null?void 0:s.length)||0}});break;case"toolCall":n.createShape({id:a,type:"toolCallNode",x:eu,y:l,props:{toolName:i.data.name||"",toolInput:JSON.stringify(i.data.input||{}).slice(0,200),status:"complete"}});break;case"toolResult":n.createShape({id:a,type:"toolResultNode",x:eu+20,y:l,props:{toolName:i.data.toolName||"",outputSummary:String(i.data.content||"").slice(0,200),isError:!!i.data.is_error}});break;case"textResponse":n.createShape({id:a,type:"textResponseNode",x:eu,y:l,props:{text:i.data.text||""}});break;case"compaction":n.createShape({id:a,type:"compactionNode",x:eu,y:l,props:{preTokens:i.data.pre_tokens||0,trigger:i.data.trigger||"auto"}});break}}Sye(n,t)}function Sye(n,e){const t="shape:statusline-widget",r={model:e.model,cost:e.costFormatted,tokensIn:IP(e.tokensCumIn),tokensOut:IP(e.tokensCumOut),contextPct:e.contextPct,skill:e.skill,turns:e.numTurns};n.getShape(t)?n.updateShape({id:t,type:"statuslineWidget",props:r}):n.createShape({id:t,type:"statuslineWidget",x:mye,y:yye,props:r})}const xye=[i4,a4,l4,c4,d4,u4];function qye(){const n=x.useRef(null),e=j_(i=>i.nodes),t=Of(i=>i.contextPct),r=Of(i=>i.costFormatted),s=Of(i=>i.skill),o=x.useCallback(i=>{n.current=i,i.user.updateUserPreferences({colorScheme:"dark"}),M_(i)},[]);return x.useEffect(()=>{n.current&&M_(n.current)},[e,t,r,s]),p.jsx("div",{style:{width:"100%",height:"100%"},children:p.jsx(lye,{shapeUtils:xye,onMount:o})})}export{qye as CanvasPanel};
538
+ //# sourceMappingURL=CanvasPanel-B48gAKVY.js.map