From 66b865a47d6a74a12c82b873c4ccc13bd308a4dc Mon Sep 17 00:00:00 2001 From: Antonello Di Nunzio Date: Wed, 11 Sep 2024 10:44:40 +0200 Subject: [PATCH] Updates --- .../{index-B1SSDWRq.js => index-ZqMFXbLx.js} | 68 +++++++++---------- index.html | 2 +- 2 files changed, 35 insertions(+), 35 deletions(-) rename assets/{index-B1SSDWRq.js => index-ZqMFXbLx.js} (80%) diff --git a/assets/index-B1SSDWRq.js b/assets/index-ZqMFXbLx.js similarity index 80% rename from assets/index-B1SSDWRq.js rename to assets/index-ZqMFXbLx.js index 1de296b..315649f 100644 --- a/assets/index-B1SSDWRq.js +++ b/assets/index-ZqMFXbLx.js @@ -22,7 +22,7 @@ var P3=Object.defineProperty;var C3=(e,n,t)=>n in e?P3(e,n,{enumerable:!0,config * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */(function(e){function n(z,W){var Y=z.length;z.push(W);e:for(;0>>1,ae=z[q];if(0>>1;qs(J,Y))Ues(Oe,J)?(z[q]=Oe,z[Ue]=Y,q=Ue):(z[q]=J,z[we]=Y,q=we);else if(Ues(Oe,Y))z[q]=Oe,z[Ue]=Y,q=Ue;else break e}}return W}function s(z,W){var Y=z.sortIndex-W.sortIndex;return Y!==0?Y:z.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var i=Date,a=i.now();e.unstable_now=function(){return i.now()-a}}var l=[],c=[],u=1,h=null,p=3,f=!1,S=!1,m=!1,x=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(z){for(var W=t(c);W!==null;){if(W.callback===null)r(c);else if(W.startTime<=z)r(c),W.sortIndex=W.expirationTime,n(l,W);else break;W=t(c)}}function C(z){if(m=!1,w(z),!S)if(t(l)!==null)S=!0,K(E);else{var W=t(c);W!==null&&B(C,W.startTime-z)}}function E(z,W){S=!1,m&&(m=!1,y(_),_=-1),f=!0;var Y=p;try{for(w(W),h=t(l);h!==null&&(!(h.expirationTime>W)||z&&!D());){var q=h.callback;if(typeof q=="function"){h.callback=null,p=h.priorityLevel;var ae=q(h.expirationTime<=W);W=e.unstable_now(),typeof ae=="function"?h.callback=ae:h===t(l)&&r(l),w(W)}else r(l);h=t(l)}if(h!==null)var fe=!0;else{var we=t(c);we!==null&&B(C,we.startTime-W),fe=!1}return fe}finally{h=null,p=Y,f=!1}}var k=!1,I=null,_=-1,T=5,M=-1;function D(){return!(e.unstable_now()-Mz||125q?(z.sortIndex=Y,n(c,z),t(l)===null&&z===t(c)&&(m?(y(_),_=-1):m=!0,B(C,Y-q))):(z.sortIndex=ae,n(l,z),S||f||(S=!0,K(E))),z},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(z){var W=p;return function(){var Y=p;p=W;try{return z.apply(this,arguments)}finally{p=Y}}}})(NE);$E.exports=NE;var Y3=$E.exports;/** + */(function(e){function n(z,W){var Y=z.length;z.push(W);e:for(;0>>1,ae=z[q];if(0>>1;qs(J,Y))Ues(Oe,J)?(z[q]=Oe,z[Ue]=Y,q=Ue):(z[q]=J,z[we]=Y,q=we);else if(Ues(Oe,Y))z[q]=Oe,z[Ue]=Y,q=Ue;else break e}}return W}function s(z,W){var Y=z.sortIndex-W.sortIndex;return Y!==0?Y:z.id-W.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var i=Date,a=i.now();e.unstable_now=function(){return i.now()-a}}var l=[],c=[],u=1,h=null,p=3,f=!1,S=!1,y=!1,x=typeof setTimeout=="function"?setTimeout:null,m=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(z){for(var W=t(c);W!==null;){if(W.callback===null)r(c);else if(W.startTime<=z)r(c),W.sortIndex=W.expirationTime,n(l,W);else break;W=t(c)}}function C(z){if(y=!1,w(z),!S)if(t(l)!==null)S=!0,K(E);else{var W=t(c);W!==null&&B(C,W.startTime-z)}}function E(z,W){S=!1,y&&(y=!1,m(_),_=-1),f=!0;var Y=p;try{for(w(W),h=t(l);h!==null&&(!(h.expirationTime>W)||z&&!D());){var q=h.callback;if(typeof q=="function"){h.callback=null,p=h.priorityLevel;var ae=q(h.expirationTime<=W);W=e.unstable_now(),typeof ae=="function"?h.callback=ae:h===t(l)&&r(l),w(W)}else r(l);h=t(l)}if(h!==null)var fe=!0;else{var we=t(c);we!==null&&B(C,we.startTime-W),fe=!1}return fe}finally{h=null,p=Y,f=!1}}var k=!1,I=null,_=-1,T=5,M=-1;function D(){return!(e.unstable_now()-Mz||125q?(z.sortIndex=Y,n(c,z),t(l)===null&&z===t(c)&&(y?(m(_),_=-1):y=!0,B(C,Y-q))):(z.sortIndex=ae,n(l,z),S||f||(S=!0,K(E))),z},e.unstable_shouldYield=D,e.unstable_wrapCallback=function(z){var W=p;return function(){var Y=p;p=W;try{return z.apply(this,arguments)}finally{p=Y}}}})(NE);$E.exports=NE;var Y3=$E.exports;/** * @license React * react-dom.production.min.js * @@ -34,12 +34,12 @@ var P3=Object.defineProperty;var C3=(e,n,t)=>n in e?P3(e,n,{enumerable:!0,config `+em+e}var tm=!1;function nm(e,n){if(!e||tm)return"";tm=!0;var t=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(n)if(n=function(){throw Error()},Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(n,[])}catch(c){var r=c}Reflect.construct(e,[],n)}else{try{n.call()}catch(c){r=c}e.call(n.prototype)}else{try{throw Error()}catch(c){r=c}e()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var s=c.stack.split(` `),o=r.stack.split(` `),i=s.length-1,a=o.length-1;1<=i&&0<=a&&s[i]!==o[a];)a--;for(;1<=i&&0<=a;i--,a--)if(s[i]!==o[a]){if(i!==1||a!==1)do if(i--,a--,0>a||s[i]!==o[a]){var l=` -`+s[i].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=i&&0<=a);break}}}finally{tm=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?fc(e):""}function e5(e){switch(e.tag){case 5:return fc(e.type);case 16:return fc("Lazy");case 13:return fc("Suspense");case 19:return fc("SuspenseList");case 0:case 2:case 15:return e=nm(e.type,!1),e;case 11:return e=nm(e.type.render,!1),e;case 1:return e=nm(e.type,!0),e;default:return""}}function dS(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ea:return"Fragment";case Ia:return"Portal";case lS:return"Profiler";case xx:return"StrictMode";case cS:return"Suspense";case uS:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case BE:return(e.displayName||"Context")+".Consumer";case zE:return(e._context.displayName||"Context")+".Provider";case wx:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case bx:return n=e.displayName||null,n!==null?n:dS(e.type)||"Memo";case Co:n=e._payload,e=e._init;try{return dS(e(n))}catch{}}return null}function t5(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return dS(n);case 8:return n===xx?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function Vo(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function HE(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function n5(e){var n=HE(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var s=t.get,o=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return s.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function vd(e){e._valueTracker||(e._valueTracker=n5(e))}function KE(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=HE(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function yp(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function hS(e,n){var t=n.checked;return pt({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function X1(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=Vo(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function WE(e,n){n=n.checked,n!=null&&vx(e,"checked",n,!1)}function pS(e,n){WE(e,n);var t=Vo(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?fS(e,n.type,t):n.hasOwnProperty("defaultValue")&&fS(e,n.type,Vo(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function q1(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function fS(e,n,t){(n!=="number"||yp(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var gc=Array.isArray;function Va(e,n,t,r){if(e=e.options,n){n={};for(var s=0;s"+n.valueOf().toString()+"",n=xd.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function eu(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var Lc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},r5=["Webkit","ms","Moz","O"];Object.keys(Lc).forEach(function(e){r5.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Lc[n]=Lc[e]})});function XE(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||Lc.hasOwnProperty(e)&&Lc[e]?(""+n).trim():n+"px"}function qE(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,s=XE(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,s):e[t]=s}}var s5=pt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function yS(e,n){if(n){if(s5[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(X(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(X(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(X(61))}if(n.style!=null&&typeof n.style!="object")throw Error(X(62))}}function SS(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var vS=null;function Px(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var xS=null,Ya=null,Xa=null;function J1(e){if(e=Lu(e)){if(typeof xS!="function")throw Error(X(280));var n=e.stateNode;n&&(n=Nf(n),xS(e.stateNode,e.type,n))}}function ZE(e){Ya?Xa?Xa.push(e):Xa=[e]:Ya=e}function QE(){if(Ya){var e=Ya,n=Xa;if(Xa=Ya=null,J1(e),n)for(e=0;e>>=0,e===0?32:31-(g5(e)/m5|0)|0}var wd=64,bd=4194304;function mc(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wp(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,i=t&268435455;if(i!==0){var a=i&~s;a!==0?r=mc(a):(o&=i,o!==0&&(r=mc(o)))}else i=t&~s,i!==0?r=mc(i):o!==0&&(r=mc(o));if(r===0)return 0;if(n!==0&&n!==r&&!(n&s)&&(s=r&-r,o=n&-n,s>=o||s===16&&(o&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function Du(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ur(n),e[n]=t}function x5(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Nc),lb=" ",cb=!1;function S_(e,n){switch(e){case"keyup":return Y5.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function v_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _a=!1;function q5(e,n){switch(e){case"compositionend":return v_(n);case"keypress":return n.which!==32?null:(cb=!0,lb);case"textInput":return e=n.data,e===lb&&cb?null:e;default:return null}}function Z5(e,n){if(_a)return e==="compositionend"||!Ax&&S_(e,n)?(e=m_(),Ch=kx=To=null,_a=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=pb(t)}}function P_(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?P_(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function C_(){for(var e=window,n=yp();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=yp(e.document)}return n}function jx(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function i$(e){var n=C_(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&P_(t.ownerDocument.documentElement,t)){if(r!==null&&jx(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var s=t.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=fb(t,o);var i=fb(t,r);s&&i&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(n=n.createRange(),n.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(n),e.extend(i.node,i.offset)):(n.setEnd(i.node,i.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,ka=null,ES=null,zc=null,_S=!1;function gb(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;_S||ka==null||ka!==yp(r)||(r=ka,"selectionStart"in r&&jx(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),zc&&iu(zc,r)||(zc=r,r=Cp(ES,"onSelect"),0Aa||(e.current=OS[Aa],OS[Aa]=null,Aa--)}function Ge(e,n){Aa++,OS[Aa]=e.current,e.current=n}var Yo={},un=ri(Yo),zn=ri(!1),Di=Yo;function il(e,n){var t=e.type.contextTypes;if(!t)return Yo;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in t)s[o]=n[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=s),s}function Bn(e){return e=e.childContextTypes,e!=null}function Ep(){et(zn),et(un)}function bb(e,n,t){if(un.current!==Yo)throw Error(X(168));Ge(un,n),Ge(zn,t)}function O_(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var s in r)if(!(s in n))throw Error(X(108,t5(e)||"Unknown",s));return pt({},t,r)}function _p(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Yo,Di=un.current,Ge(un,e),Ge(zn,zn.current),!0}function Pb(e,n,t){var r=e.stateNode;if(!r)throw Error(X(169));t?(e=O_(e,n,Di),r.__reactInternalMemoizedMergedChildContext=e,et(zn),et(un),Ge(un,e)):et(zn),Ge(zn,t)}var Fs=null,Ff=!1,mm=!1;function D_(e){Fs===null?Fs=[e]:Fs.push(e)}function S$(e){Ff=!0,D_(e)}function si(){if(!mm&&Fs!==null){mm=!0;var e=0,n=$e;try{var t=Fs;for($e=1;e>=i,s-=i,Bs=1<<32-Ur(n)+s|t<_?(T=I,I=null):T=I.sibling;var M=p(y,I,w[_],C);if(M===null){I===null&&(I=T);break}e&&I&&M.alternate===null&&n(y,I),v=o(M,v,_),k===null?E=M:k.sibling=M,k=M,I=T}if(_===w.length)return t(y,I),rt&&wi(y,_),E;if(I===null){for(;__?(T=I,I=null):T=I.sibling;var D=p(y,I,M.value,C);if(D===null){I===null&&(I=T);break}e&&I&&D.alternate===null&&n(y,I),v=o(D,v,_),k===null?E=D:k.sibling=D,k=D,I=T}if(M.done)return t(y,I),rt&&wi(y,_),E;if(I===null){for(;!M.done;_++,M=w.next())M=h(y,M.value,C),M!==null&&(v=o(M,v,_),k===null?E=M:k.sibling=M,k=M);return rt&&wi(y,_),E}for(I=r(y,I);!M.done;_++,M=w.next())M=f(I,y,_,M.value,C),M!==null&&(e&&M.alternate!==null&&I.delete(M.key===null?_:M.key),v=o(M,v,_),k===null?E=M:k.sibling=M,k=M);return e&&I.forEach(function($){return n(y,$)}),rt&&wi(y,_),E}function x(y,v,w,C){if(typeof w=="object"&&w!==null&&w.type===Ea&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Sd:e:{for(var E=w.key,k=v;k!==null;){if(k.key===E){if(E=w.type,E===Ea){if(k.tag===7){t(y,k.sibling),v=s(k,w.props.children),v.return=y,y=v;break e}}else if(k.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Co&&Eb(E)===k.type){t(y,k.sibling),v=s(k,w.props),v.ref=Vl(y,k,w),v.return=y,y=v;break e}t(y,k);break}else n(y,k);k=k.sibling}w.type===Ea?(v=Mi(w.props.children,y.mode,C,w.key),v.return=y,y=v):(C=jh(w.type,w.key,w.props,null,y.mode,C),C.ref=Vl(y,v,w),C.return=y,y=C)}return i(y);case Ia:e:{for(k=w.key;v!==null;){if(v.key===k)if(v.tag===4&&v.stateNode.containerInfo===w.containerInfo&&v.stateNode.implementation===w.implementation){t(y,v.sibling),v=s(v,w.children||[]),v.return=y,y=v;break e}else{t(y,v);break}else n(y,v);v=v.sibling}v=Cm(w,y.mode,C),v.return=y,y=v}return i(y);case Co:return k=w._init,x(y,v,k(w._payload),C)}if(gc(w))return S(y,v,w,C);if(Ul(w))return m(y,v,w,C);Td(y,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,v!==null&&v.tag===6?(t(y,v.sibling),v=s(v,w),v.return=y,y=v):(t(y,v),v=Pm(w,y.mode,C),v.return=y,y=v),i(y)):t(y,v)}return x}var ll=N_(!0),F_=N_(!1),Mp=ri(null),Ap=null,Da=null,Lx=null;function $x(){Lx=Da=Ap=null}function Nx(e){var n=Mp.current;et(Mp),e._currentValue=n}function LS(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function Za(e,n){Ap=e,Lx=Da=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(Ln=!0),e.firstContext=null)}function _r(e){var n=e._currentValue;if(Lx!==e)if(e={context:e,memoizedValue:n,next:null},Da===null){if(Ap===null)throw Error(X(308));Da=e,Ap.dependencies={lanes:0,firstContext:e}}else Da=Da.next=e;return n}var Ii=null;function Fx(e){Ii===null?Ii=[e]:Ii.push(e)}function z_(e,n,t,r){var s=n.interleaved;return s===null?(t.next=t,Fx(n)):(t.next=s.next,s.next=t),n.interleaved=t,Qs(e,r)}function Qs(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Io=!1;function zx(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function B_(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ws(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Fo(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Te&2){var s=r.pending;return s===null?n.next=n:(n.next=s.next,s.next=n),r.pending=n,Qs(e,t)}return s=r.interleaved,s===null?(n.next=n,Fx(r)):(n.next=s.next,s.next=n),r.interleaved=n,Qs(e,t)}function Eh(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Ix(e,t)}}function _b(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var s=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var i={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?s=o=i:o=o.next=i,t=t.next}while(t!==null);o===null?s=o=n:o=o.next=n}else s=o=n;t={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function jp(e,n,t,r){var s=e.updateQueue;Io=!1;var o=s.firstBaseUpdate,i=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,i===null?o=c:i.next=c,i=l;var u=e.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==i&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(o!==null){var h=s.baseState;i=0,u=c=l=null,a=o;do{var p=a.lane,f=a.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var S=e,m=a;switch(p=n,f=t,m.tag){case 1:if(S=m.payload,typeof S=="function"){h=S.call(f,h,p);break e}h=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=m.payload,p=typeof S=="function"?S.call(f,h,p):S,p==null)break e;h=pt({},h,p);break e;case 2:Io=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,p=s.effects,p===null?s.effects=[a]:p.push(a))}else f={eventTime:f,lane:p,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=f,l=h):u=u.next=f,i|=p;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;p=a,a=p.next,p.next=null,s.lastBaseUpdate=p,s.shared.pending=null}}while(!0);if(u===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=u,n=s.shared.interleaved,n!==null){s=n;do i|=s.lane,s=s.next;while(s!==n)}else o===null&&(s.shared.lanes=0);$i|=i,e.lanes=i,e.memoizedState=h}}function kb(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=Sm.transition;Sm.transition={};try{e(!1),n()}finally{$e=t,Sm.transition=r}}function sk(){return kr().memoizedState}function b$(e,n,t){var r=Bo(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},ok(e))ik(n,t);else if(t=z_(e,n,t,r),t!==null){var s=yn();Hr(t,e,r,s),ak(t,n,r)}}function P$(e,n,t){var r=Bo(e),s={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(ok(e))ik(n,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=n.lastRenderedReducer,o!==null))try{var i=n.lastRenderedState,a=o(i,t);if(s.hasEagerState=!0,s.eagerState=a,Kr(a,i)){var l=n.interleaved;l===null?(s.next=s,Fx(n)):(s.next=l.next,l.next=s),n.interleaved=s;return}}catch{}finally{}t=z_(e,n,s,r),t!==null&&(s=yn(),Hr(t,e,r,s),ak(t,n,r))}}function ok(e){var n=e.alternate;return e===ht||n!==null&&n===ht}function ik(e,n){Bc=Dp=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ak(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Ix(e,t)}}var Rp={readContext:_r,useCallback:Jt,useContext:Jt,useEffect:Jt,useImperativeHandle:Jt,useInsertionEffect:Jt,useLayoutEffect:Jt,useMemo:Jt,useReducer:Jt,useRef:Jt,useState:Jt,useDebugValue:Jt,useDeferredValue:Jt,useTransition:Jt,useMutableSource:Jt,useSyncExternalStore:Jt,useId:Jt,unstable_isNewReconciler:!1},C$={readContext:_r,useCallback:function(e,n){return rs().memoizedState=[e,n===void 0?null:n],e},useContext:_r,useEffect:Mb,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,kh(4194308,4,J_.bind(null,n,e),t)},useLayoutEffect:function(e,n){return kh(4194308,4,e,n)},useInsertionEffect:function(e,n){return kh(4,2,e,n)},useMemo:function(e,n){var t=rs();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=rs();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=b$.bind(null,ht,e),[r.memoizedState,e]},useRef:function(e){var n=rs();return e={current:e},n.memoizedState=e},useState:Tb,useDebugValue:Yx,useDeferredValue:function(e){return rs().memoizedState=e},useTransition:function(){var e=Tb(!1),n=e[0];return e=w$.bind(null,e[1]),rs().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ht,s=rs();if(rt){if(t===void 0)throw Error(X(407));t=t()}else{if(t=n(),Ot===null)throw Error(X(349));Li&30||W_(r,n,t)}s.memoizedState=t;var o={value:t,getSnapshot:n};return s.queue=o,Mb(V_.bind(null,r,o,e),[e]),r.flags|=2048,fu(9,G_.bind(null,r,o,t,n),void 0,null),t},useId:function(){var e=rs(),n=Ot.identifierPrefix;if(rt){var t=Us,r=Bs;t=(r&~(1<<32-Ur(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=hu++,0")&&(l=l.replace("",e.displayName)),l}while(1<=i&&0<=a);break}}}finally{tm=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?fc(e):""}function e5(e){switch(e.tag){case 5:return fc(e.type);case 16:return fc("Lazy");case 13:return fc("Suspense");case 19:return fc("SuspenseList");case 0:case 2:case 15:return e=nm(e.type,!1),e;case 11:return e=nm(e.type.render,!1),e;case 1:return e=nm(e.type,!0),e;default:return""}}function dS(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ea:return"Fragment";case Ia:return"Portal";case lS:return"Profiler";case xx:return"StrictMode";case cS:return"Suspense";case uS:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case BE:return(e.displayName||"Context")+".Consumer";case zE:return(e._context.displayName||"Context")+".Provider";case wx:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case bx:return n=e.displayName||null,n!==null?n:dS(e.type)||"Memo";case Co:n=e._payload,e=e._init;try{return dS(e(n))}catch{}}return null}function t5(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return dS(n);case 8:return n===xx?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function Vo(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function HE(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function n5(e){var n=HE(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var s=t.get,o=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return s.call(this)},set:function(i){r=""+i,o.call(this,i)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function vd(e){e._valueTracker||(e._valueTracker=n5(e))}function KE(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=HE(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function yp(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function hS(e,n){var t=n.checked;return pt({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function X1(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=Vo(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function WE(e,n){n=n.checked,n!=null&&vx(e,"checked",n,!1)}function pS(e,n){WE(e,n);var t=Vo(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?fS(e,n.type,t):n.hasOwnProperty("defaultValue")&&fS(e,n.type,Vo(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function q1(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function fS(e,n,t){(n!=="number"||yp(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var gc=Array.isArray;function Va(e,n,t,r){if(e=e.options,n){n={};for(var s=0;s"+n.valueOf().toString()+"",n=xd.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function eu(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var Lc={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},r5=["Webkit","ms","Moz","O"];Object.keys(Lc).forEach(function(e){r5.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Lc[n]=Lc[e]})});function XE(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||Lc.hasOwnProperty(e)&&Lc[e]?(""+n).trim():n+"px"}function qE(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,s=XE(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,s):e[t]=s}}var s5=pt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function yS(e,n){if(n){if(s5[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(X(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(X(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(X(61))}if(n.style!=null&&typeof n.style!="object")throw Error(X(62))}}function SS(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var vS=null;function Px(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var xS=null,Ya=null,Xa=null;function J1(e){if(e=Lu(e)){if(typeof xS!="function")throw Error(X(280));var n=e.stateNode;n&&(n=Nf(n),xS(e.stateNode,e.type,n))}}function ZE(e){Ya?Xa?Xa.push(e):Xa=[e]:Ya=e}function QE(){if(Ya){var e=Ya,n=Xa;if(Xa=Ya=null,J1(e),n)for(e=0;e>>=0,e===0?32:31-(g5(e)/m5|0)|0}var wd=64,bd=4194304;function mc(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function wp(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,i=t&268435455;if(i!==0){var a=i&~s;a!==0?r=mc(a):(o&=i,o!==0&&(r=mc(o)))}else i=t&~s,i!==0?r=mc(i):o!==0&&(r=mc(o));if(r===0)return 0;if(n!==0&&n!==r&&!(n&s)&&(s=r&-r,o=n&-n,s>=o||s===16&&(o&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function Du(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Ur(n),e[n]=t}function x5(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Nc),lb=" ",cb=!1;function S_(e,n){switch(e){case"keyup":return Y5.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function v_(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _a=!1;function q5(e,n){switch(e){case"compositionend":return v_(n);case"keypress":return n.which!==32?null:(cb=!0,lb);case"textInput":return e=n.data,e===lb&&cb?null:e;default:return null}}function Z5(e,n){if(_a)return e==="compositionend"||!Ax&&S_(e,n)?(e=m_(),Ch=kx=To=null,_a=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=pb(t)}}function P_(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?P_(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function C_(){for(var e=window,n=yp();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=yp(e.document)}return n}function jx(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function i$(e){var n=C_(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&P_(t.ownerDocument.documentElement,t)){if(r!==null&&jx(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var s=t.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=fb(t,o);var i=fb(t,r);s&&i&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(n=n.createRange(),n.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(n),e.extend(i.node,i.offset)):(n.setEnd(i.node,i.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,ka=null,ES=null,zc=null,_S=!1;function gb(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;_S||ka==null||ka!==yp(r)||(r=ka,"selectionStart"in r&&jx(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),zc&&iu(zc,r)||(zc=r,r=Cp(ES,"onSelect"),0Aa||(e.current=OS[Aa],OS[Aa]=null,Aa--)}function Ge(e,n){Aa++,OS[Aa]=e.current,e.current=n}var Yo={},un=ri(Yo),zn=ri(!1),Di=Yo;function il(e,n){var t=e.type.contextTypes;if(!t)return Yo;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in t)s[o]=n[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=s),s}function Bn(e){return e=e.childContextTypes,e!=null}function Ep(){et(zn),et(un)}function bb(e,n,t){if(un.current!==Yo)throw Error(X(168));Ge(un,n),Ge(zn,t)}function O_(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var s in r)if(!(s in n))throw Error(X(108,t5(e)||"Unknown",s));return pt({},t,r)}function _p(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Yo,Di=un.current,Ge(un,e),Ge(zn,zn.current),!0}function Pb(e,n,t){var r=e.stateNode;if(!r)throw Error(X(169));t?(e=O_(e,n,Di),r.__reactInternalMemoizedMergedChildContext=e,et(zn),et(un),Ge(un,e)):et(zn),Ge(zn,t)}var Fs=null,Ff=!1,mm=!1;function D_(e){Fs===null?Fs=[e]:Fs.push(e)}function S$(e){Ff=!0,D_(e)}function si(){if(!mm&&Fs!==null){mm=!0;var e=0,n=$e;try{var t=Fs;for($e=1;e>=i,s-=i,Bs=1<<32-Ur(n)+s|t<_?(T=I,I=null):T=I.sibling;var M=p(m,I,w[_],C);if(M===null){I===null&&(I=T);break}e&&I&&M.alternate===null&&n(m,I),v=o(M,v,_),k===null?E=M:k.sibling=M,k=M,I=T}if(_===w.length)return t(m,I),rt&&wi(m,_),E;if(I===null){for(;__?(T=I,I=null):T=I.sibling;var D=p(m,I,M.value,C);if(D===null){I===null&&(I=T);break}e&&I&&D.alternate===null&&n(m,I),v=o(D,v,_),k===null?E=D:k.sibling=D,k=D,I=T}if(M.done)return t(m,I),rt&&wi(m,_),E;if(I===null){for(;!M.done;_++,M=w.next())M=h(m,M.value,C),M!==null&&(v=o(M,v,_),k===null?E=M:k.sibling=M,k=M);return rt&&wi(m,_),E}for(I=r(m,I);!M.done;_++,M=w.next())M=f(I,m,_,M.value,C),M!==null&&(e&&M.alternate!==null&&I.delete(M.key===null?_:M.key),v=o(M,v,_),k===null?E=M:k.sibling=M,k=M);return e&&I.forEach(function($){return n(m,$)}),rt&&wi(m,_),E}function x(m,v,w,C){if(typeof w=="object"&&w!==null&&w.type===Ea&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Sd:e:{for(var E=w.key,k=v;k!==null;){if(k.key===E){if(E=w.type,E===Ea){if(k.tag===7){t(m,k.sibling),v=s(k,w.props.children),v.return=m,m=v;break e}}else if(k.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Co&&Eb(E)===k.type){t(m,k.sibling),v=s(k,w.props),v.ref=Vl(m,k,w),v.return=m,m=v;break e}t(m,k);break}else n(m,k);k=k.sibling}w.type===Ea?(v=Mi(w.props.children,m.mode,C,w.key),v.return=m,m=v):(C=jh(w.type,w.key,w.props,null,m.mode,C),C.ref=Vl(m,v,w),C.return=m,m=C)}return i(m);case Ia:e:{for(k=w.key;v!==null;){if(v.key===k)if(v.tag===4&&v.stateNode.containerInfo===w.containerInfo&&v.stateNode.implementation===w.implementation){t(m,v.sibling),v=s(v,w.children||[]),v.return=m,m=v;break e}else{t(m,v);break}else n(m,v);v=v.sibling}v=Cm(w,m.mode,C),v.return=m,m=v}return i(m);case Co:return k=w._init,x(m,v,k(w._payload),C)}if(gc(w))return S(m,v,w,C);if(Ul(w))return y(m,v,w,C);Td(m,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,v!==null&&v.tag===6?(t(m,v.sibling),v=s(v,w),v.return=m,m=v):(t(m,v),v=Pm(w,m.mode,C),v.return=m,m=v),i(m)):t(m,v)}return x}var ll=N_(!0),F_=N_(!1),Mp=ri(null),Ap=null,Da=null,Lx=null;function $x(){Lx=Da=Ap=null}function Nx(e){var n=Mp.current;et(Mp),e._currentValue=n}function LS(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function Za(e,n){Ap=e,Lx=Da=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(Ln=!0),e.firstContext=null)}function _r(e){var n=e._currentValue;if(Lx!==e)if(e={context:e,memoizedValue:n,next:null},Da===null){if(Ap===null)throw Error(X(308));Da=e,Ap.dependencies={lanes:0,firstContext:e}}else Da=Da.next=e;return n}var Ii=null;function Fx(e){Ii===null?Ii=[e]:Ii.push(e)}function z_(e,n,t,r){var s=n.interleaved;return s===null?(t.next=t,Fx(n)):(t.next=s.next,s.next=t),n.interleaved=t,Qs(e,r)}function Qs(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Io=!1;function zx(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function B_(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ws(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Fo(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Te&2){var s=r.pending;return s===null?n.next=n:(n.next=s.next,s.next=n),r.pending=n,Qs(e,t)}return s=r.interleaved,s===null?(n.next=n,Fx(r)):(n.next=s.next,s.next=n),r.interleaved=n,Qs(e,t)}function Eh(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Ix(e,t)}}function _b(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var s=null,o=null;if(t=t.firstBaseUpdate,t!==null){do{var i={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};o===null?s=o=i:o=o.next=i,t=t.next}while(t!==null);o===null?s=o=n:o=o.next=n}else s=o=n;t={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function jp(e,n,t,r){var s=e.updateQueue;Io=!1;var o=s.firstBaseUpdate,i=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,i===null?o=c:i.next=c,i=l;var u=e.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==i&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(o!==null){var h=s.baseState;i=0,u=c=l=null,a=o;do{var p=a.lane,f=a.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var S=e,y=a;switch(p=n,f=t,y.tag){case 1:if(S=y.payload,typeof S=="function"){h=S.call(f,h,p);break e}h=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=y.payload,p=typeof S=="function"?S.call(f,h,p):S,p==null)break e;h=pt({},h,p);break e;case 2:Io=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,p=s.effects,p===null?s.effects=[a]:p.push(a))}else f={eventTime:f,lane:p,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=f,l=h):u=u.next=f,i|=p;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;p=a,a=p.next,p.next=null,s.lastBaseUpdate=p,s.shared.pending=null}}while(!0);if(u===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=u,n=s.shared.interleaved,n!==null){s=n;do i|=s.lane,s=s.next;while(s!==n)}else o===null&&(s.shared.lanes=0);$i|=i,e.lanes=i,e.memoizedState=h}}function kb(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=Sm.transition;Sm.transition={};try{e(!1),n()}finally{$e=t,Sm.transition=r}}function sk(){return kr().memoizedState}function b$(e,n,t){var r=Bo(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},ok(e))ik(n,t);else if(t=z_(e,n,t,r),t!==null){var s=yn();Hr(t,e,r,s),ak(t,n,r)}}function P$(e,n,t){var r=Bo(e),s={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(ok(e))ik(n,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=n.lastRenderedReducer,o!==null))try{var i=n.lastRenderedState,a=o(i,t);if(s.hasEagerState=!0,s.eagerState=a,Kr(a,i)){var l=n.interleaved;l===null?(s.next=s,Fx(n)):(s.next=l.next,l.next=s),n.interleaved=s;return}}catch{}finally{}t=z_(e,n,s,r),t!==null&&(s=yn(),Hr(t,e,r,s),ak(t,n,r))}}function ok(e){var n=e.alternate;return e===ht||n!==null&&n===ht}function ik(e,n){Bc=Dp=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function ak(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Ix(e,t)}}var Rp={readContext:_r,useCallback:Jt,useContext:Jt,useEffect:Jt,useImperativeHandle:Jt,useInsertionEffect:Jt,useLayoutEffect:Jt,useMemo:Jt,useReducer:Jt,useRef:Jt,useState:Jt,useDebugValue:Jt,useDeferredValue:Jt,useTransition:Jt,useMutableSource:Jt,useSyncExternalStore:Jt,useId:Jt,unstable_isNewReconciler:!1},C$={readContext:_r,useCallback:function(e,n){return rs().memoizedState=[e,n===void 0?null:n],e},useContext:_r,useEffect:Mb,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,kh(4194308,4,J_.bind(null,n,e),t)},useLayoutEffect:function(e,n){return kh(4194308,4,e,n)},useInsertionEffect:function(e,n){return kh(4,2,e,n)},useMemo:function(e,n){var t=rs();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=rs();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=b$.bind(null,ht,e),[r.memoizedState,e]},useRef:function(e){var n=rs();return e={current:e},n.memoizedState=e},useState:Tb,useDebugValue:Yx,useDeferredValue:function(e){return rs().memoizedState=e},useTransition:function(){var e=Tb(!1),n=e[0];return e=w$.bind(null,e[1]),rs().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ht,s=rs();if(rt){if(t===void 0)throw Error(X(407));t=t()}else{if(t=n(),Ot===null)throw Error(X(349));Li&30||W_(r,n,t)}s.memoizedState=t;var o={value:t,getSnapshot:n};return s.queue=o,Mb(V_.bind(null,r,o,e),[e]),r.flags|=2048,fu(9,G_.bind(null,r,o,t,n),void 0,null),t},useId:function(){var e=rs(),n=Ot.identifierPrefix;if(rt){var t=Us,r=Bs;t=(r&~(1<<32-Ur(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=hu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(t,{is:r.is}):(e=i.createElement(t),t==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,t),e[is]=n,e[cu]=r,yk(e,n,!1,!1),n.stateNode=e;e:{switch(i=SS(t,r),t){case"dialog":Qe("cancel",e),Qe("close",e),s=r;break;case"iframe":case"object":case"embed":Qe("load",e),s=r;break;case"video":case"audio":for(s=0;sdl&&(n.flags|=128,r=!0,Yl(o,!1),n.lanes=4194304)}else{if(!r)if(e=Op(i),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),Yl(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!rt)return en(n),null}else 2*vt()-o.renderingStartTime>dl&&t!==1073741824&&(n.flags|=128,r=!0,Yl(o,!1),n.lanes=4194304);o.isBackwards?(i.sibling=n.child,n.child=i):(t=o.last,t!==null?t.sibling=i:n.child=i,o.last=i)}return o.tail!==null?(n=o.tail,o.rendering=n,o.tail=n.sibling,o.renderingStartTime=vt(),n.sibling=null,t=lt.current,Ge(lt,r?t&1|2:t&1),n):(en(n),null);case 22:case 23:return e0(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?Zn&1073741824&&(en(n),n.subtreeFlags&6&&(n.flags|=8192)):en(n),null;case 24:return null;case 25:return null}throw Error(X(156,n.tag))}function j$(e,n){switch(Dx(n),n.tag){case 1:return Bn(n.type)&&Ep(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return cl(),et(zn),et(un),Hx(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return Ux(n),null;case 13:if(et(lt),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(X(340));al()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return et(lt),null;case 4:return cl(),null;case 10:return Nx(n.type._context),null;case 22:case 23:return e0(),null;case 24:return null;default:return null}}var Ad=!1,on=!1,O$=typeof WeakSet=="function"?WeakSet:Set,te=null;function Ra(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){mt(e,n,r)}else t.current=null}function WS(e,n,t){try{t()}catch(r){mt(e,n,r)}}var Bb=!1;function D$(e,n){if(kS=bp,e=C_(),jx(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var i=0,a=-1,l=-1,c=0,u=0,h=e,p=null;t:for(;;){for(var f;h!==t||s!==0&&h.nodeType!==3||(a=i+s),h!==o||r!==0&&h.nodeType!==3||(l=i+r),h.nodeType===3&&(i+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===e)break t;if(p===t&&++c===s&&(a=i),p===o&&++u===r&&(l=i),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(TS={focusedElem:e,selectionRange:t},bp=!1,te=n;te!==null;)if(n=te,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,te=e;else for(;te!==null;){n=te;try{var S=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var m=S.memoizedProps,x=S.memoizedState,y=n.stateNode,v=y.getSnapshotBeforeUpdate(n.elementType===n.type?m:Dr(n.type,m),x);y.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var w=n.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(X(163))}}catch(C){mt(n,n.return,C)}if(e=n.sibling,e!==null){e.return=n.return,te=e;break}te=n.return}return S=Bb,Bb=!1,S}function Uc(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&WS(n,t,o)}s=s.next}while(s!==r)}}function Uf(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function GS(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function xk(e){var n=e.alternate;n!==null&&(e.alternate=null,xk(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[is],delete n[cu],delete n[jS],delete n[m$],delete n[y$])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function wk(e){return e.tag===5||e.tag===3||e.tag===4}function Ub(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||wk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function VS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Ip));else if(r!==4&&(e=e.child,e!==null))for(VS(e,n,t),e=e.sibling;e!==null;)VS(e,n,t),e=e.sibling}function YS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(YS(e,n,t),e=e.sibling;e!==null;)YS(e,n,t),e=e.sibling}var zt=null,Rr=!1;function vo(e,n,t){for(t=t.child;t!==null;)bk(e,n,t),t=t.sibling}function bk(e,n,t){if(ps&&typeof ps.onCommitFiberUnmount=="function")try{ps.onCommitFiberUnmount(Df,t)}catch{}switch(t.tag){case 5:on||Ra(t,n);case 6:var r=zt,s=Rr;zt=null,vo(e,n,t),zt=r,Rr=s,zt!==null&&(Rr?(e=zt,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):zt.removeChild(t.stateNode));break;case 18:zt!==null&&(Rr?(e=zt,t=t.stateNode,e.nodeType===8?gm(e.parentNode,t):e.nodeType===1&&gm(e,t),su(e)):gm(zt,t.stateNode));break;case 4:r=zt,s=Rr,zt=t.stateNode.containerInfo,Rr=!0,vo(e,n,t),zt=r,Rr=s;break;case 0:case 11:case 14:case 15:if(!on&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,i=o.destroy;o=o.tag,i!==void 0&&(o&2||o&4)&&WS(t,n,i),s=s.next}while(s!==r)}vo(e,n,t);break;case 1:if(!on&&(Ra(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){mt(t,n,a)}vo(e,n,t);break;case 21:vo(e,n,t);break;case 22:t.mode&1?(on=(r=on)||t.memoizedState!==null,vo(e,n,t),on=r):vo(e,n,t);break;default:vo(e,n,t)}}function Hb(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new O$),n.forEach(function(r){var s=H$.bind(null,e,r);t.has(r)||(t.add(r),r.then(s,s))})}}function Or(e,n){var t=n.deletions;if(t!==null)for(var r=0;rs&&(s=i),r&=~o}if(r=s,r=vt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*L$(r/1960))-r,10e?16:e,Mo===null)var r=!1;else{if(e=Mo,Mo=null,Np=0,Te&6)throw Error(X(331));var s=Te;for(Te|=4,te=e.current;te!==null;){var o=te,i=o.child;if(te.flags&16){var a=o.deletions;if(a!==null){for(var l=0;lvt()-Qx?Ti(e,0):Zx|=t),Un(e,n)}function Mk(e,n){n===0&&(e.mode&1?(n=bd,bd<<=1,!(bd&130023424)&&(bd=4194304)):n=1);var t=yn();e=Qs(e,n),e!==null&&(Du(e,n,t),Un(e,t))}function U$(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),Mk(e,t)}function H$(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(t=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(X(314))}r!==null&&r.delete(n),Mk(e,t)}var Ak;Ak=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||zn.current)Ln=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return Ln=!1,M$(e,n,t);Ln=!!(e.flags&131072)}else Ln=!1,rt&&n.flags&1048576&&R_(n,Tp,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;Th(e,n),e=n.pendingProps;var s=il(n,un.current);Za(n,t),s=Wx(null,n,r,e,s,t);var o=Gx();return n.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Bn(r)?(o=!0,_p(n)):o=!1,n.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,zx(n),s.updater=Bf,n.stateNode=s,s._reactInternals=n,NS(n,r,e,t),n=BS(null,n,r,!0,o,t)):(n.tag=0,rt&&o&&Ox(n),gn(null,n,s,t),n=n.child),n;case 16:r=n.elementType;e:{switch(Th(e,n),e=n.pendingProps,s=r._init,r=s(r._payload),n.type=r,s=n.tag=W$(r),e=Dr(r,e),s){case 0:n=zS(null,n,r,e,t);break e;case 1:n=Nb(null,n,r,e,t);break e;case 11:n=Lb(null,n,r,e,t);break e;case 14:n=$b(null,n,r,Dr(r.type,e),t);break e}throw Error(X(306,r,""))}return n;case 0:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),zS(e,n,r,s,t);case 1:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Nb(e,n,r,s,t);case 3:e:{if(fk(n),e===null)throw Error(X(387));r=n.pendingProps,o=n.memoizedState,s=o.element,B_(e,n),jp(n,r,null,t);var i=n.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},n.updateQueue.baseState=o,n.memoizedState=o,n.flags&256){s=ul(Error(X(423)),n),n=Fb(e,n,r,t,s);break e}else if(r!==s){s=ul(Error(X(424)),n),n=Fb(e,n,r,t,s);break e}else for(er=No(n.stateNode.containerInfo.firstChild),tr=n,rt=!0,$r=null,t=F_(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(al(),r===s){n=Js(e,n,t);break e}gn(e,n,r,t)}n=n.child}return n;case 5:return U_(n),e===null&&RS(n),r=n.type,s=n.pendingProps,o=e!==null?e.memoizedProps:null,i=s.children,MS(r,s)?i=null:o!==null&&MS(r,o)&&(n.flags|=32),pk(e,n),gn(e,n,i,t),n.child;case 6:return e===null&&RS(n),null;case 13:return gk(e,n,t);case 4:return Bx(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=ll(n,null,r,t):gn(e,n,r,t),n.child;case 11:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Lb(e,n,r,s,t);case 7:return gn(e,n,n.pendingProps,t),n.child;case 8:return gn(e,n,n.pendingProps.children,t),n.child;case 12:return gn(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,s=n.pendingProps,o=n.memoizedProps,i=s.value,Ge(Mp,r._currentValue),r._currentValue=i,o!==null)if(Kr(o.value,i)){if(o.children===s.children&&!zn.current){n=Js(e,n,t);break e}}else for(o=n.child,o!==null&&(o.return=n);o!==null;){var a=o.dependencies;if(a!==null){i=o.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(o.tag===1){l=Ws(-1,t&-t),l.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}o.lanes|=t,l=o.alternate,l!==null&&(l.lanes|=t),LS(o.return,t,n),a.lanes|=t;break}l=l.next}}else if(o.tag===10)i=o.type===n.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(X(341));i.lanes|=t,a=i.alternate,a!==null&&(a.lanes|=t),LS(i,t,n),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===n){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}gn(e,n,s.children,t),n=n.child}return n;case 9:return s=n.type,r=n.pendingProps.children,Za(n,t),s=_r(s),r=r(s),n.flags|=1,gn(e,n,r,t),n.child;case 14:return r=n.type,s=Dr(r,n.pendingProps),s=Dr(r.type,s),$b(e,n,r,s,t);case 15:return dk(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Th(e,n),n.tag=1,Bn(r)?(e=!0,_p(n)):e=!1,Za(n,t),lk(n,r,s),NS(n,r,s,t),BS(null,n,r,!0,e,t);case 19:return mk(e,n,t);case 22:return hk(e,n,t)}throw Error(X(156,n.tag))};function jk(e,n){return o_(e,n)}function K$(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function br(e,n,t,r){return new K$(e,n,t,r)}function n0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function W$(e){if(typeof e=="function")return n0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===wx)return 11;if(e===bx)return 14}return 2}function Uo(e,n){var t=e.alternate;return t===null?(t=br(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function jh(e,n,t,r,s,o){var i=2;if(r=e,typeof e=="function")n0(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Ea:return Mi(t.children,s,o,n);case xx:i=8,s|=8;break;case lS:return e=br(12,t,n,s|2),e.elementType=lS,e.lanes=o,e;case cS:return e=br(13,t,n,s),e.elementType=cS,e.lanes=o,e;case uS:return e=br(19,t,n,s),e.elementType=uS,e.lanes=o,e;case UE:return Kf(t,s,o,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case zE:i=10;break e;case BE:i=9;break e;case wx:i=11;break e;case bx:i=14;break e;case Co:i=16,r=null;break e}throw Error(X(130,e==null?e:typeof e,""))}return n=br(i,t,n,s),n.elementType=e,n.type=r,n.lanes=o,n}function Mi(e,n,t,r){return e=br(7,e,r,n),e.lanes=t,e}function Kf(e,n,t,r){return e=br(22,e,r,n),e.elementType=UE,e.lanes=t,e.stateNode={isHidden:!1},e}function Pm(e,n,t){return e=br(6,e,null,n),e.lanes=t,e}function Cm(e,n,t){return n=br(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function G$(e,n,t,r,s){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=sm(0),this.expirationTimes=sm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function r0(e,n,t,r,s,o,i,a,l){return e=new G$(e,n,t,a,l),n===1?(n=1,o===!0&&(n|=8)):n=0,o=br(3,null,null,n),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},zx(o),e}function V$(e,n,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Lk)}catch(e){console.error(e)}}Lk(),LE.exports=cr;var ta=LE.exports;const Q$=ti(ta);var a0,Zb=ta;a0=Zb.createRoot,Zb.hydrateRoot;var ql=function(e){return e&&e.Math===Math&&e},xn=ql(typeof globalThis=="object"&&globalThis)||ql(typeof window=="object"&&window)||ql(typeof self=="object"&&self)||ql(typeof ln=="object"&&ln)||ql(typeof ln=="object"&&ln)||function(){return this}()||Function("return this")(),l0={},wn=function(e){try{return!!e()}catch{return!0}},J$=wn,oi=!J$(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),eN=wn,Xf=!eN(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),tN=Xf,Dd=Function.prototype.call,io=tN?Dd.bind(Dd):function(){return Dd.apply(Dd,arguments)},$k={},Nk={}.propertyIsEnumerable,Fk=Object.getOwnPropertyDescriptor,nN=Fk&&!Nk.call({1:2},1);$k.f=nN?function(n){var t=Fk(this,n);return!!t&&t.enumerable}:Nk;var zk=function(e,n){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:n}},Bk=Xf,Uk=Function.prototype,JS=Uk.call,rN=Bk&&Uk.bind.bind(JS,JS),Rt=Bk?rN:function(e){return function(){return JS.apply(e,arguments)}},Hk=Rt,sN=Hk({}.toString),oN=Hk("".slice),Il=function(e){return oN(sN(e),8,-1)},iN=Rt,aN=wn,lN=Il,Im=Object,cN=iN("".split),uN=aN(function(){return!Im("z").propertyIsEnumerable(0)})?function(e){return lN(e)==="String"?cN(e,""):Im(e)}:Im,qf=function(e){return e==null},dN=qf,hN=TypeError,El=function(e){if(dN(e))throw new hN("Can't call method on "+e);return e},pN=uN,fN=El,Zf=function(e){return pN(fN(e))},Em=typeof document=="object"&&document.all,bn=typeof Em>"u"&&Em!==void 0?function(e){return typeof e=="function"||e===Em}:function(e){return typeof e=="function"},gN=bn,na=function(e){return typeof e=="object"?e!==null:gN(e)},_m=xn,mN=bn,yN=function(e){return mN(e)?e:void 0},Qf=function(e,n){return arguments.length<2?yN(_m[e]):_m[e]&&_m[e][n]},SN=Rt,Kk=SN({}.isPrototypeOf),vN=xn,Qb=vN.navigator,Jb=Qb&&Qb.userAgent,xN=Jb?String(Jb):"",Wk=xn,km=xN,eP=Wk.process,tP=Wk.Deno,nP=eP&&eP.versions||tP&&tP.version,rP=nP&&nP.v8,Nr,Bp;rP&&(Nr=rP.split("."),Bp=Nr[0]>0&&Nr[0]<4?1:+(Nr[0]+Nr[1]));!Bp&&km&&(Nr=km.match(/Edge\/(\d+)/),(!Nr||Nr[1]>=74)&&(Nr=km.match(/Chrome\/(\d+)/),Nr&&(Bp=+Nr[1])));var wN=Bp,sP=wN,bN=wn,PN=xn,CN=PN.String,Gk=!!Object.getOwnPropertySymbols&&!bN(function(){var e=Symbol("symbol detection");return!CN(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&sP&&sP<41}),IN=Gk,Vk=IN&&!Symbol.sham&&typeof Symbol.iterator=="symbol",EN=Qf,_N=bn,kN=Kk,TN=Vk,MN=Object,Yk=TN?function(e){return typeof e=="symbol"}:function(e){var n=EN("Symbol");return _N(n)&&kN(n.prototype,MN(e))},AN=String,jN=function(e){try{return AN(e)}catch{return"Object"}},ON=bn,DN=jN,RN=TypeError,c0=function(e){if(ON(e))return e;throw new RN(DN(e)+" is not a function")},LN=c0,$N=qf,u0=function(e,n){var t=e[n];return $N(t)?void 0:LN(t)},Tm=io,Mm=bn,Am=na,NN=TypeError,FN=function(e,n){var t,r;if(n==="string"&&Mm(t=e.toString)&&!Am(r=Tm(t,e))||Mm(t=e.valueOf)&&!Am(r=Tm(t,e))||n!=="string"&&Mm(t=e.toString)&&!Am(r=Tm(t,e)))return r;throw new NN("Can't convert object to primitive value")},Xk={exports:{}},oP=xn,zN=Object.defineProperty,d0=function(e,n){try{zN(oP,e,{value:n,configurable:!0,writable:!0})}catch{oP[e]=n}return n},BN=xn,UN=d0,iP="__core-js_shared__",aP=Xk.exports=BN[iP]||UN(iP,{});(aP.versions||(aP.versions=[])).push({version:"3.38.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE",source:"https://github.com/zloirock/core-js"});var h0=Xk.exports,lP=h0,p0=function(e,n){return lP[e]||(lP[e]=n||{})},HN=El,KN=Object,Nu=function(e){return KN(HN(e))},WN=Rt,GN=Nu,VN=WN({}.hasOwnProperty),ii=Object.hasOwn||function(n,t){return VN(GN(n),t)},YN=Rt,XN=0,qN=Math.random(),ZN=YN(1 .toString),qk=function(e){return"Symbol("+(e===void 0?"":e)+")_"+ZN(++XN+qN,36)},QN=xn,JN=p0,cP=ii,eF=qk,tF=Gk,nF=Vk,$a=QN.Symbol,jm=JN("wks"),rF=nF?$a.for||$a:$a&&$a.withoutSetter||eF,ao=function(e){return cP(jm,e)||(jm[e]=tF&&cP($a,e)?$a[e]:rF("Symbol."+e)),jm[e]},sF=io,uP=na,dP=Yk,oF=u0,iF=FN,aF=ao,lF=TypeError,cF=aF("toPrimitive"),uF=function(e,n){if(!uP(e)||dP(e))return e;var t=oF(e,cF),r;if(t){if(n===void 0&&(n="default"),r=sF(t,e,n),!uP(r)||dP(r))return r;throw new lF("Can't convert object to primitive value")}return n===void 0&&(n="number"),iF(e,n)},dF=uF,hF=Yk,Zk=function(e){var n=dF(e,"string");return hF(n)?n:n+""},pF=xn,hP=na,ev=pF.document,fF=hP(ev)&&hP(ev.createElement),Qk=function(e){return fF?ev.createElement(e):{}},gF=oi,mF=wn,yF=Qk,Jk=!gF&&!mF(function(){return Object.defineProperty(yF("div"),"a",{get:function(){return 7}}).a!==7}),SF=oi,vF=io,xF=$k,wF=zk,bF=Zf,PF=Zk,CF=ii,IF=Jk,pP=Object.getOwnPropertyDescriptor;l0.f=SF?pP:function(n,t){if(n=bF(n),t=PF(t),IF)try{return pP(n,t)}catch{}if(CF(n,t))return wF(!vF(xF.f,n,t),n[t])};var _l={},EF=oi,_F=wn,e2=EF&&_F(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),kF=na,TF=String,MF=TypeError,ra=function(e){if(kF(e))return e;throw new MF(TF(e)+" is not an object")},AF=oi,jF=Jk,OF=e2,Rd=ra,fP=Zk,DF=TypeError,Om=Object.defineProperty,RF=Object.getOwnPropertyDescriptor,Dm="enumerable",Rm="configurable",Lm="writable";_l.f=AF?OF?function(n,t,r){if(Rd(n),t=fP(t),Rd(r),typeof n=="function"&&t==="prototype"&&"value"in r&&Lm in r&&!r[Lm]){var s=RF(n,t);s&&s[Lm]&&(n[t]=r.value,r={configurable:Rm in r?r[Rm]:s[Rm],enumerable:Dm in r?r[Dm]:s[Dm],writable:!1})}return Om(n,t,r)}:Om:function(n,t,r){if(Rd(n),t=fP(t),Rd(r),jF)try{return Om(n,t,r)}catch{}if("get"in r||"set"in r)throw new DF("Accessors not supported");return"value"in r&&(n[t]=r.value),n};var LF=oi,$F=_l,NF=zk,f0=LF?function(e,n,t){return $F.f(e,n,NF(1,t))}:function(e,n,t){return e[n]=t,e},t2={exports:{}},tv=oi,FF=ii,n2=Function.prototype,zF=tv&&Object.getOwnPropertyDescriptor,g0=FF(n2,"name"),BF=g0&&(function(){}).name==="something",UF=g0&&(!tv||tv&&zF(n2,"name").configurable),HF={EXISTS:g0,PROPER:BF,CONFIGURABLE:UF},KF=Rt,WF=bn,nv=h0,GF=KF(Function.toString);WF(nv.inspectSource)||(nv.inspectSource=function(e){return GF(e)});var r2=nv.inspectSource,VF=xn,YF=bn,gP=VF.WeakMap,XF=YF(gP)&&/native code/.test(String(gP)),qF=p0,ZF=qk,mP=qF("keys"),s2=function(e){return mP[e]||(mP[e]=ZF(e))},m0={},QF=XF,o2=xn,JF=na,e4=f0,$m=ii,Nm=h0,t4=s2,n4=m0,yP="Object already initialized",rv=o2.TypeError,r4=o2.WeakMap,Up,mu,Hp,s4=function(e){return Hp(e)?mu(e):Up(e,{})},o4=function(e){return function(n){var t;if(!JF(n)||(t=mu(n)).type!==e)throw new rv("Incompatible receiver, "+e+" required");return t}};if(QF||Nm.state){var ts=Nm.state||(Nm.state=new r4);ts.get=ts.get,ts.has=ts.has,ts.set=ts.set,Up=function(e,n){if(ts.has(e))throw new rv(yP);return n.facade=e,ts.set(e,n),n},mu=function(e){return ts.get(e)||{}},Hp=function(e){return ts.has(e)}}else{var da=t4("state");n4[da]=!0,Up=function(e,n){if($m(e,da))throw new rv(yP);return n.facade=e,e4(e,da,n),n},mu=function(e){return $m(e,da)?e[da]:{}},Hp=function(e){return $m(e,da)}}var i2={set:Up,get:mu,has:Hp,enforce:s4,getterFor:o4},y0=Rt,i4=wn,a4=bn,Ld=ii,sv=oi,l4=HF.CONFIGURABLE,c4=r2,a2=i2,u4=a2.enforce,d4=a2.get,SP=String,Oh=Object.defineProperty,h4=y0("".slice),p4=y0("".replace),f4=y0([].join),g4=sv&&!i4(function(){return Oh(function(){},"length",{value:8}).length!==8}),m4=String(String).split("String"),y4=t2.exports=function(e,n,t){h4(SP(n),0,7)==="Symbol("&&(n="["+p4(SP(n),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),t&&t.getter&&(n="get "+n),t&&t.setter&&(n="set "+n),(!Ld(e,"name")||l4&&e.name!==n)&&(sv?Oh(e,"name",{value:n,configurable:!0}):e.name=n),g4&&t&&Ld(t,"arity")&&e.length!==t.arity&&Oh(e,"length",{value:t.arity});try{t&&Ld(t,"constructor")&&t.constructor?sv&&Oh(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=u4(e);return Ld(r,"source")||(r.source=f4(m4,typeof n=="string"?n:"")),e};Function.prototype.toString=y4(function(){return a4(this)&&d4(this).source||c4(this)},"toString");var S4=t2.exports,v4=bn,x4=_l,w4=S4,b4=d0,l2=function(e,n,t,r){r||(r={});var s=r.enumerable,o=r.name!==void 0?r.name:n;if(v4(t)&&w4(t,o,r),r.global)s?e[n]=t:b4(n,t);else{try{r.unsafe?e[n]&&(s=!0):delete e[n]}catch{}s?e[n]=t:x4.f(e,n,{value:t,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},c2={},P4=Math.ceil,C4=Math.floor,I4=Math.trunc||function(n){var t=+n;return(t>0?C4:P4)(t)},E4=I4,sa=function(e){var n=+e;return n!==n||n===0?0:E4(n)},_4=sa,k4=Math.max,T4=Math.min,M4=function(e,n){var t=_4(e);return t<0?k4(t+n,0):T4(t,n)},A4=sa,j4=Math.min,u2=function(e){var n=A4(e);return n>0?j4(n,9007199254740991):0},O4=u2,Fu=function(e){return O4(e.length)},D4=Zf,R4=M4,L4=Fu,vP=function(e){return function(n,t,r){var s=D4(n),o=L4(s);if(o===0)return!e&&-1;var i=R4(r,o),a;if(e&&t!==t){for(;o>i;)if(a=s[i++],a!==a)return!0}else for(;o>i;i++)if((e||i in s)&&s[i]===t)return e||i||0;return!e&&-1}},$4={includes:vP(!0),indexOf:vP(!1)},N4=Rt,Fm=ii,F4=Zf,z4=$4.indexOf,B4=m0,xP=N4([].push),d2=function(e,n){var t=F4(e),r=0,s=[],o;for(o in t)!Fm(B4,o)&&Fm(t,o)&&xP(s,o);for(;n.length>r;)Fm(t,o=n[r++])&&(~z4(s,o)||xP(s,o));return s},S0=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],U4=d2,H4=S0,K4=H4.concat("length","prototype");c2.f=Object.getOwnPropertyNames||function(n){return U4(n,K4)};var h2={};h2.f=Object.getOwnPropertySymbols;var W4=Qf,G4=Rt,V4=c2,Y4=h2,X4=ra,q4=G4([].concat),Z4=W4("Reflect","ownKeys")||function(n){var t=V4.f(X4(n)),r=Y4.f;return r?q4(t,r(n)):t},wP=ii,Q4=Z4,J4=l0,ez=_l,tz=function(e,n,t){for(var r=Q4(n),s=ez.f,o=J4.f,i=0;ii;)wz.f(n,a=s[i++],r[a]);return n};var Iz=Qf,Ez=Iz("document","documentElement"),_z=ra,kz=p2,bP=S0,Tz=m0,Mz=Ez,Az=Qk,jz=s2,PP=">",CP="<",ov="prototype",iv="script",f2=jz("IE_PROTO"),zm=function(){},g2=function(e){return CP+iv+PP+e+CP+"/"+iv+PP},IP=function(e){e.write(g2("")),e.close();var n=e.parentWindow.Object;return e=null,n},Oz=function(){var e=Az("iframe"),n="java"+iv+":",t;return e.style.display="none",Mz.appendChild(e),e.src=String(n),t=e.contentWindow.document,t.open(),t.write(g2("document.F=Object")),t.close(),t.F},Nd,Dh=function(){try{Nd=new ActiveXObject("htmlfile")}catch{}Dh=typeof document<"u"?document.domain&&Nd?IP(Nd):Oz():IP(Nd);for(var e=bP.length;e--;)delete Dh[ov][bP[e]];return Dh()};Tz[f2]=!0;var m2=Object.create||function(n,t){var r;return n!==null?(zm[ov]=_z(n),r=new zm,zm[ov]=null,r[f2]=n):r=Dh(),t===void 0?r:kz.f(r,t)},Dz=ao,Rz=m2,Lz=_l.f,av=Dz("unscopables"),lv=Array.prototype;lv[av]===void 0&&Lz(lv,av,{configurable:!0,value:Rz(null)});var v0=function(e){lv[av][e]=!0},$z=kl,Nz=Nu,Fz=Fu,zz=sa,Bz=v0;$z({target:"Array",proto:!0},{at:function(n){var t=Nz(this),r=Fz(t),s=zz(n),o=s>=0?s:r+s;return o<0||o>=r?void 0:t[o]}});Bz("at");var Uz=xn,Hz=Rt,Bu=function(e,n){return Hz(Uz[e].prototype[n])},Kz=Bu;Kz("Array","at");var Wz=Il,y2=Array.isArray||function(n){return Wz(n)==="Array"},Gz=TypeError,Vz=9007199254740991,Yz=function(e){if(e>Vz)throw Gz("Maximum allowed index exceeded");return e},Xz=Il,qz=Rt,Zz=function(e){if(Xz(e)==="Function")return qz(e)},EP=Zz,Qz=c0,Jz=Xf,e6=EP(EP.bind),t6=function(e,n){return Qz(e),n===void 0?e:Jz?e6(e,n):function(){return e.apply(n,arguments)}},n6=y2,r6=Fu,s6=Yz,o6=t6,S2=function(e,n,t,r,s,o,i,a){for(var l=s,c=0,u=i?o6(i,a):!1,h,p;c0&&n6(h)?(p=r6(h),l=S2(e,n,h,p,l,o-1)-1):(s6(l+1),e[l]=h),l++),c++;return l},v2=S2,i6=ao,a6=i6("toStringTag"),x2={};x2[a6]="z";var l6=String(x2)==="[object z]",c6=l6,u6=bn,Rh=Il,d6=ao,h6=d6("toStringTag"),p6=Object,f6=Rh(function(){return arguments}())==="Arguments",g6=function(e,n){try{return e[n]}catch{}},w2=c6?Rh:function(e){var n,t,r;return e===void 0?"Undefined":e===null?"Null":typeof(t=g6(n=p6(e),h6))=="string"?t:f6?Rh(n):(r=Rh(n))==="Object"&&u6(n.callee)?"Arguments":r},m6=Rt,y6=wn,b2=bn,S6=w2,v6=Qf,x6=r2,P2=function(){},C2=v6("Reflect","construct"),x0=/^\s*(?:class|function)\b/,w6=m6(x0.exec),b6=!x0.test(P2),Zl=function(n){if(!b2(n))return!1;try{return C2(P2,[],n),!0}catch{return!1}},I2=function(n){if(!b2(n))return!1;switch(S6(n)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return b6||!!w6(x0,x6(n))}catch{return!0}};I2.sham=!0;var P6=!C2||y6(function(){var e;return Zl(Zl.call)||!Zl(Object)||!Zl(function(){e=!0})||e})?I2:Zl,_P=y2,C6=P6,I6=na,E6=ao,_6=E6("species"),kP=Array,k6=function(e){var n;return _P(e)&&(n=e.constructor,C6(n)&&(n===kP||_P(n.prototype))?n=void 0:I6(n)&&(n=n[_6],n===null&&(n=void 0))),n===void 0?kP:n},T6=k6,E2=function(e,n){return new(T6(e))(n===0?0:n)},M6=kl,A6=v2,j6=c0,O6=Nu,D6=Fu,R6=E2;M6({target:"Array",proto:!0},{flatMap:function(n){var t=O6(this),r=D6(t),s;return j6(n),s=R6(t,0),s.length=A6(s,t,t,r,0,1,n,arguments.length>1?arguments[1]:void 0),s}});var L6=v0;L6("flatMap");var $6=Bu;$6("Array","flatMap");var N6=kl,F6=v2,z6=Nu,B6=Fu,U6=sa,H6=E2;N6({target:"Array",proto:!0},{flat:function(){var n=arguments.length?arguments[0]:void 0,t=z6(this),r=B6(t),s=H6(t,0);return s.length=F6(s,t,t,r,0,n===void 0?1:U6(n)),s}});var K6=v0;K6("flat");var W6=Bu;W6("Array","flat");var G6=w2,V6=String,Uu=function(e){if(G6(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return V6(e)},Y6=kl,X6=Rt,q6=El,Z6=sa,Q6=Uu,J6=wn,e8=X6("".charAt),t8=J6(function(){return"𠮷".at(-2)!=="\uD842"});Y6({target:"String",proto:!0,forced:t8},{at:function(n){var t=Q6(q6(this)),r=t.length,s=Z6(n),o=s>=0?s:r+s;return o<0||o>=r?void 0:e8(t,o)}});var n8=Bu;n8("String","at");var r8=ra,_2=function(){var e=r8(this),n="";return e.hasIndices&&(n+="d"),e.global&&(n+="g"),e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.dotAll&&(n+="s"),e.unicode&&(n+="u"),e.unicodeSets&&(n+="v"),e.sticky&&(n+="y"),n},w0=wn,s8=xn,b0=s8.RegExp,P0=w0(function(){var e=b0("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),o8=P0||w0(function(){return!b0("a","y").sticky}),i8=P0||w0(function(){var e=b0("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),a8={BROKEN_CARET:i8,MISSED_STICKY:o8,UNSUPPORTED_Y:P0},l8=wn,c8=xn,u8=c8.RegExp,d8=l8(function(){var e=u8(".","s");return!(e.dotAll&&e.test(` -`)&&e.flags==="s")}),h8=wn,p8=xn,f8=p8.RegExp,g8=h8(function(){var e=f8("(?b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$c")!=="bc"}),Na=io,Jf=Rt,m8=Uu,y8=_2,S8=a8,v8=p0,x8=m2,w8=i2.get,b8=d8,P8=g8,C8=v8("native-string-replace",String.prototype.replace),Kp=RegExp.prototype.exec,cv=Kp,I8=Jf("".charAt),E8=Jf("".indexOf),_8=Jf("".replace),Bm=Jf("".slice),uv=function(){var e=/a/,n=/b*/g;return Na(Kp,e,"a"),Na(Kp,n,"a"),e.lastIndex!==0||n.lastIndex!==0}(),k2=S8.BROKEN_CARET,dv=/()??/.exec("")[1]!==void 0,k8=uv||dv||k2||b8||P8;k8&&(cv=function(n){var t=this,r=w8(t),s=m8(n),o=r.raw,i,a,l,c,u,h,p;if(o)return o.lastIndex=t.lastIndex,i=Na(cv,o,s),t.lastIndex=o.lastIndex,i;var f=r.groups,S=k2&&t.sticky,m=Na(y8,t),x=t.source,y=0,v=s;if(S&&(m=_8(m,"y",""),E8(m,"g")===-1&&(m+="g"),v=Bm(s,t.lastIndex),t.lastIndex>0&&(!t.multiline||t.multiline&&I8(s,t.lastIndex-1)!==` -`)&&(x="(?: "+x+")",v=" "+v,y++),a=new RegExp("^(?:"+x+")",m)),dv&&(a=new RegExp("^"+x+"$(?!\\s)",m)),uv&&(l=t.lastIndex),c=Na(Kp,S?a:t,v),S?c?(c.input=Bm(c.input,y),c[0]=Bm(c[0],y),c.index=t.lastIndex,t.lastIndex+=c[0].length):t.lastIndex=0:uv&&c&&(t.lastIndex=t.global?c.index+c[0].length:l),dv&&c&&c.length>1&&Na(C8,c[0],a,function(){for(u=1;u=o?e?"":void 0:(i=RP(r,s),i<55296||i>56319||s+1===o||(a=RP(r,s+1))<56320||a>57343?e?F8(r,s):i:e?z8(r,s,s+2):(i-55296<<10)+(a-56320)+65536)}},B8={codeAt:LP(!1),charAt:LP(!0)},U8=B8.charAt,H8=function(e,n,t){return n+(t?U8(e,n).length:1)},E0=Rt,K8=Nu,W8=Math.floor,Hm=E0("".charAt),G8=E0("".replace),Km=E0("".slice),V8=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Y8=/\$([$&'`]|\d{1,2})/g,A2=function(e,n,t,r,s,o){var i=t+e.length,a=r.length,l=Y8;return s!==void 0&&(s=K8(s),l=V8),G8(o,l,function(c,u){var h;switch(Hm(u,0)){case"$":return"$";case"&":return e;case"`":return Km(n,0,t);case"'":return Km(n,i);case"<":h=s[Km(u,1,-1)];break;default:var p=+u;if(p===0)return c;if(p>a){var f=W8(p/10);return f===0?c:f<=a?r[f-1]===void 0?Hm(u,1):r[f-1]+Hm(u,1):c}h=r[p-1]}return h===void 0?"":h})},$P=io,X8=ra,q8=bn,Z8=Il,Q8=C0,J8=TypeError,eB=function(e,n){var t=e.exec;if(q8(t)){var r=$P(t,e,n);return r!==null&&X8(r),r}if(Z8(e)==="RegExp")return $P(Q8,e,n);throw new J8("RegExp#exec called on incompatible receiver")},tB=A8,NP=io,eg=Rt,nB=R8,rB=wn,sB=ra,oB=bn,iB=qf,aB=sa,lB=u2,ha=Uu,cB=El,uB=H8,dB=u0,hB=A2,pB=eB,fB=ao,hv=fB("replace"),gB=Math.max,mB=Math.min,yB=eg([].concat),Wm=eg([].push),FP=eg("".indexOf),zP=eg("".slice),SB=function(e){return e===void 0?e:String(e)},vB=function(){return"a".replace(/./,"$0")==="$0"}(),BP=function(){return/./[hv]?/./[hv]("a","$0")==="":!1}(),xB=!rB(function(){var e=/./;return e.exec=function(){var n=[];return n.groups={a:"7"},n},"".replace(e,"$")!=="7"});nB("replace",function(e,n,t){var r=BP?"$":"$0";return[function(o,i){var a=cB(this),l=iB(o)?void 0:dB(o,hv);return l?NP(l,o,a,i):NP(n,ha(a),o,i)},function(s,o){var i=sB(this),a=ha(s);if(typeof o=="string"&&FP(o,r)===-1&&FP(o,"$<")===-1){var l=t(n,i,a,o);if(l.done)return l.value}var c=oB(o);c||(o=ha(o));var u=i.global,h;u&&(h=i.unicode,i.lastIndex=0);for(var p=[],f;f=pB(i,a),!(f===null||(Wm(p,f),!u));){var S=ha(f[0]);S===""&&(i.lastIndex=uB(a,lB(i.lastIndex),h))}for(var m="",x=0,y=0;y=x&&(m+=zP(a,x,w)+E,x=w+v.length)}return m+zP(a,x)}]},!xB||!vB||BP);var wB=na,bB=Il,PB=ao,CB=PB("match"),IB=function(e){var n;return wB(e)&&((n=e[CB])!==void 0?!!n:bB(e)==="RegExp")},EB=io,_B=ii,kB=Kk,TB=_2,UP=RegExp.prototype,MB=function(e){var n=e.flags;return n===void 0&&!("flags"in UP)&&!_B(e,"flags")&&kB(UP,e)?EB(TB,e):n},AB=kl,jB=io,_0=Rt,HP=El,OB=bn,DB=qf,RB=IB,Ql=Uu,LB=u0,$B=MB,NB=A2,FB=ao,zB=FB("replace"),BB=TypeError,Gm=_0("".indexOf);_0("".replace);var KP=_0("".slice),UB=Math.max;AB({target:"String",proto:!0},{replaceAll:function(n,t){var r=HP(this),s,o,i,a,l,c,u,h,p,f,S=0,m="";if(!DB(n)){if(s=RB(n),s&&(o=Ql(HP($B(n))),!~Gm(o,"g")))throw new BB("`.replaceAll` does not allow non-global regexes");if(i=LB(n,zB),i)return jB(i,n,r,t)}for(a=Ql(r),l=Ql(n),c=OB(t),c||(t=Ql(t)),u=l.length,h=UB(1,u),p=Gm(a,l);p!==-1;)f=c?Ql(t(l,p,a)):NB(l,a,p,[],void 0,t),m+=KP(a,S,p)+f,S=p+u,p=p+h>a.length?-1:Gm(a,l,p+h);return S{if(e.children.remove(n)&&e.children.isEmpty&&j2(e))for(let t=0,r=e.parents.length;t{if(e.children.add(n)&&j2(e))for(let t=0,r=e.parents.length;tObject.freeze([])),WP=8;class Gp{constructor(){g(this,"arraySize",0);g(this,"array",Array(WP));g(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(n){if(this.array)return this.array.indexOf(n)!==-1?!1:this.arraySize=c)return[];if(l<=n&&n({stack:null}));function Fd(e){const n=nt.stack;nt.stack=null;try{return e()}finally{nt.stack=n}}function L2(e){nt.stack=new KB(nt.stack,e),e.parentSet.clear()}function $2(){const e=nt.stack;if(nt.stack=e.below,e.offset{this._isActivelyListening&&this.execute()});this.name=n,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!==Mn()){if(this.parents.length&&!O2(this)){this.lastReactedEpoch=Mn();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let n=0,t=this.parents.length;nWB);function oa(e,n,t){const r=new Tl(e,n,t);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function GB(e,n,t){const r=new Tl(e,n,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()}}}class VB{constructor(n){g(this,"initialAtomValues",new Map);this.parent=n}get isRoot(){return this.parent===null}commit(){this.isRoot?N2(this.initialAtomValues.keys()):this.initialAtomValues.forEach((n,t)=>{this.parent.initialAtomValues.has(t)||this.parent.initialAtomValues.set(t,n)})}abort(){Fe.globalEpoch++,this.initialAtomValues.forEach((n,t)=>{var r;t.set(n),(r=t.historyBuffer)==null||r.clear()}),this.commit()}}const Fe=ai("transactions",()=>({globalEpoch:Ao+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null,reactionEpoch:Ao+1}));function YB(){return Fe.reactionEpoch}function Mn(){return Fe.globalEpoch}function XB(){return Fe.globalIsReacting}function T0(e,n){n.lastTraversedEpoch!==Fe.globalEpoch&&(n.lastTraversedEpoch=Fe.globalEpoch,n instanceof Tl?e.add(n):n.children.visit(t=>T0(e,t)))}function N2(e){var n;if(Fe.globalIsReacting)throw new Error("cannot change atoms during reaction cycle");try{Fe.globalIsReacting=!0,Fe.reactionEpoch=Fe.globalEpoch;const t=new Set;for(const s of e)s.children.visit(o=>T0(t,o));for(const s of t)s.maybeScheduleEffect();let r=0;for(;(n=Fe.cleanupReactors)!=null&&n.size;){if(r++>1e3)throw new Error("Reaction update depth limit exceeded");const s=Fe.cleanupReactors;Fe.cleanupReactors=null;for(const o of s)o.maybeScheduleEffect()}}finally{Fe.cleanupReactors=null,Fe.globalIsReacting=!1}}function qB(e,n){if(Fe.globalIsReacting){const t=Fe.cleanupReactors??(Fe.cleanupReactors=new Set);e.children.visit(r=>T0(t,r))}else Fe.currentTransaction?Fe.currentTransaction.initialAtomValues.has(e)||Fe.currentTransaction.initialAtomValues.set(e,n):N2([e])}function ZB(){Fe.globalEpoch++}function QB(e){const n=new VB(Fe.currentTransaction);Fe.currentTransaction=n;try{let t,r=!1;try{t=e(()=>r=!0)}catch(s){throw n.abort(),s}return r?n.abort():n.commit(),t}finally{Fe.currentTransaction=Fe.currentTransaction.parent}}function gs(e){return Fe.currentTransaction?e():QB(e)}class JB{constructor(n,t,r){g(this,"isEqual");g(this,"computeDiff");g(this,"lastChangedEpoch",Mn());g(this,"children",new Gp);g(this,"historyBuffer");this.name=n,this.current=t,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new R2(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(n){return this.current}get(){return Vp(this),this.current}set(n,t){var s,o;if(((s=this.isEqual)==null?void 0:s.call(this,this.current,n))??D2(this.current,n))return this.current;ZB(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,Mn(),t??((o=this.computeDiff)==null?void 0:o.call(this,this.current,n,this.lastChangedEpoch,Mn()))??nr),this.lastChangedEpoch=Mn();const r=this.current;return this.current=n,qB(this,r),n}update(n){return this.set(n(this.current))}getDiffSince(n){var t;return Vp(this),n>=this.lastChangedEpoch?Gs:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??nr}}const eU=ai("Atom",()=>JB);function Mt(e,n,t){return new eU(e,n,t)}let GP=!1;function tU(){GP||(GP=!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. +`+o.stack}return{value:e,source:n,stack:s,digest:null}}function wm(e,n,t){return{value:e,source:null,stack:t??null,digest:n??null}}function FS(e,n){try{console.error(n.value)}catch(t){setTimeout(function(){throw t})}}var _$=typeof WeakMap=="function"?WeakMap:Map;function ck(e,n,t){t=Ws(-1,t),t.tag=3,t.payload={element:null};var r=n.value;return t.callback=function(){$p||($p=!0,XS=r),FS(e,n)},t}function uk(e,n,t){t=Ws(-1,t),t.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r=="function"){var s=n.value;t.payload=function(){return r(s)},t.callback=function(){FS(e,n)}}var o=e.stateNode;return o!==null&&typeof o.componentDidCatch=="function"&&(t.callback=function(){FS(e,n),typeof r!="function"&&(zo===null?zo=new Set([this]):zo.add(this));var i=n.stack;this.componentDidCatch(n.value,{componentStack:i!==null?i:""})}),t}function Ob(e,n,t){var r=e.pingCache;if(r===null){r=e.pingCache=new _$;var s=new Set;r.set(n,s)}else s=r.get(n),s===void 0&&(s=new Set,r.set(n,s));s.has(t)||(s.add(t),e=B$.bind(null,e,n,t),n.then(e,e))}function Db(e){do{var n;if((n=e.tag===13)&&(n=e.memoizedState,n=n!==null?n.dehydrated!==null:!0),n)return e;e=e.return}while(e!==null);return null}function Rb(e,n,t,r,s){return e.mode&1?(e.flags|=65536,e.lanes=s,e):(e===n?e.flags|=65536:(e.flags|=128,t.flags|=131072,t.flags&=-52805,t.tag===1&&(t.alternate===null?t.tag=17:(n=Ws(-1,1),n.tag=2,Fo(t,n,1))),t.lanes|=1),e)}var k$=oo.ReactCurrentOwner,Ln=!1;function gn(e,n,t,r){n.child=e===null?F_(n,null,t,r):ll(n,e.child,t,r)}function Lb(e,n,t,r,s){t=t.render;var o=n.ref;return Za(n,s),r=Wx(e,n,t,r,o,s),t=Gx(),e!==null&&!Ln?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~s,Js(e,n,s)):(rt&&t&&Ox(n),n.flags|=1,gn(e,n,r,s),n.child)}function $b(e,n,t,r,s){if(e===null){var o=t.type;return typeof o=="function"&&!n0(o)&&o.defaultProps===void 0&&t.compare===null&&t.defaultProps===void 0?(n.tag=15,n.type=o,dk(e,n,o,r,s)):(e=jh(t.type,null,r,n,n.mode,s),e.ref=n.ref,e.return=n,n.child=e)}if(o=e.child,!(e.lanes&s)){var i=o.memoizedProps;if(t=t.compare,t=t!==null?t:iu,t(i,r)&&e.ref===n.ref)return Js(e,n,s)}return n.flags|=1,e=Uo(o,r),e.ref=n.ref,e.return=n,n.child=e}function dk(e,n,t,r,s){if(e!==null){var o=e.memoizedProps;if(iu(o,r)&&e.ref===n.ref)if(Ln=!1,n.pendingProps=r=o,(e.lanes&s)!==0)e.flags&131072&&(Ln=!0);else return n.lanes=e.lanes,Js(e,n,s)}return zS(e,n,t,r,s)}function hk(e,n,t){var r=n.pendingProps,s=r.children,o=e!==null?e.memoizedState:null;if(r.mode==="hidden")if(!(n.mode&1))n.memoizedState={baseLanes:0,cachePool:null,transitions:null},Ge(La,Zn),Zn|=t;else{if(!(t&1073741824))return e=o!==null?o.baseLanes|t:t,n.lanes=n.childLanes=1073741824,n.memoizedState={baseLanes:e,cachePool:null,transitions:null},n.updateQueue=null,Ge(La,Zn),Zn|=e,null;n.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=o!==null?o.baseLanes:t,Ge(La,Zn),Zn|=r}else o!==null?(r=o.baseLanes|t,n.memoizedState=null):r=t,Ge(La,Zn),Zn|=r;return gn(e,n,s,t),n.child}function pk(e,n){var t=n.ref;(e===null&&t!==null||e!==null&&e.ref!==t)&&(n.flags|=512,n.flags|=2097152)}function zS(e,n,t,r,s){var o=Bn(t)?Di:un.current;return o=il(n,o),Za(n,s),t=Wx(e,n,t,r,o,s),r=Gx(),e!==null&&!Ln?(n.updateQueue=e.updateQueue,n.flags&=-2053,e.lanes&=~s,Js(e,n,s)):(rt&&r&&Ox(n),n.flags|=1,gn(e,n,t,s),n.child)}function Nb(e,n,t,r,s){if(Bn(t)){var o=!0;_p(n)}else o=!1;if(Za(n,s),n.stateNode===null)Th(e,n),lk(n,t,r),NS(n,t,r,s),r=!0;else if(e===null){var i=n.stateNode,a=n.memoizedProps;i.props=a;var l=i.context,c=t.contextType;typeof c=="object"&&c!==null?c=_r(c):(c=Bn(t)?Di:un.current,c=il(n,c));var u=t.getDerivedStateFromProps,h=typeof u=="function"||typeof i.getSnapshotBeforeUpdate=="function";h||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(a!==r||l!==c)&&jb(n,i,r,c),Io=!1;var p=n.memoizedState;i.state=p,jp(n,r,i,s),l=n.memoizedState,a!==r||p!==l||zn.current||Io?(typeof u=="function"&&($S(n,t,u,r),l=n.memoizedState),(a=Io||Ab(n,t,a,r,p,l,c))?(h||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount()),typeof i.componentDidMount=="function"&&(n.flags|=4194308)):(typeof i.componentDidMount=="function"&&(n.flags|=4194308),n.memoizedProps=r,n.memoizedState=l),i.props=r,i.state=l,i.context=c,r=a):(typeof i.componentDidMount=="function"&&(n.flags|=4194308),r=!1)}else{i=n.stateNode,B_(e,n),a=n.memoizedProps,c=n.type===n.elementType?a:Dr(n.type,a),i.props=c,h=n.pendingProps,p=i.context,l=t.contextType,typeof l=="object"&&l!==null?l=_r(l):(l=Bn(t)?Di:un.current,l=il(n,l));var f=t.getDerivedStateFromProps;(u=typeof f=="function"||typeof i.getSnapshotBeforeUpdate=="function")||typeof i.UNSAFE_componentWillReceiveProps!="function"&&typeof i.componentWillReceiveProps!="function"||(a!==h||p!==l)&&jb(n,i,r,l),Io=!1,p=n.memoizedState,i.state=p,jp(n,r,i,s);var S=n.memoizedState;a!==h||p!==S||zn.current||Io?(typeof f=="function"&&($S(n,t,f,r),S=n.memoizedState),(c=Io||Ab(n,t,c,r,p,S,l)||!1)?(u||typeof i.UNSAFE_componentWillUpdate!="function"&&typeof i.componentWillUpdate!="function"||(typeof i.componentWillUpdate=="function"&&i.componentWillUpdate(r,S,l),typeof i.UNSAFE_componentWillUpdate=="function"&&i.UNSAFE_componentWillUpdate(r,S,l)),typeof i.componentDidUpdate=="function"&&(n.flags|=4),typeof i.getSnapshotBeforeUpdate=="function"&&(n.flags|=1024)):(typeof i.componentDidUpdate!="function"||a===e.memoizedProps&&p===e.memoizedState||(n.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&p===e.memoizedState||(n.flags|=1024),n.memoizedProps=r,n.memoizedState=S),i.props=r,i.state=S,i.context=l,r=c):(typeof i.componentDidUpdate!="function"||a===e.memoizedProps&&p===e.memoizedState||(n.flags|=4),typeof i.getSnapshotBeforeUpdate!="function"||a===e.memoizedProps&&p===e.memoizedState||(n.flags|=1024),r=!1)}return BS(e,n,t,r,o,s)}function BS(e,n,t,r,s,o){pk(e,n);var i=(n.flags&128)!==0;if(!r&&!i)return s&&Pb(n,t,!1),Js(e,n,o);r=n.stateNode,k$.current=n;var a=i&&typeof t.getDerivedStateFromError!="function"?null:r.render();return n.flags|=1,e!==null&&i?(n.child=ll(n,e.child,null,o),n.child=ll(n,null,a,o)):gn(e,n,a,o),n.memoizedState=r.state,s&&Pb(n,t,!0),n.child}function fk(e){var n=e.stateNode;n.pendingContext?bb(e,n.pendingContext,n.pendingContext!==n.context):n.context&&bb(e,n.context,!1),Bx(e,n.containerInfo)}function Fb(e,n,t,r,s){return al(),Rx(s),n.flags|=256,gn(e,n,t,r),n.child}var US={dehydrated:null,treeContext:null,retryLane:0};function HS(e){return{baseLanes:e,cachePool:null,transitions:null}}function gk(e,n,t){var r=n.pendingProps,s=lt.current,o=!1,i=(n.flags&128)!==0,a;if((a=i)||(a=e!==null&&e.memoizedState===null?!1:(s&2)!==0),a?(o=!0,n.flags&=-129):(e===null||e.memoizedState!==null)&&(s|=1),Ge(lt,s&1),e===null)return RS(n),e=n.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(n.mode&1?e.data==="$!"?n.lanes=8:n.lanes=1073741824:n.lanes=1,null):(i=r.children,e=r.fallback,o?(r=n.mode,o=n.child,i={mode:"hidden",children:i},!(r&1)&&o!==null?(o.childLanes=0,o.pendingProps=i):o=Kf(i,r,0,null),e=Mi(e,r,t,null),o.return=n,e.return=n,o.sibling=e,n.child=o,n.child.memoizedState=HS(t),n.memoizedState=US,e):Xx(n,i));if(s=e.memoizedState,s!==null&&(a=s.dehydrated,a!==null))return T$(e,n,i,r,a,s,t);if(o){o=r.fallback,i=n.mode,s=e.child,a=s.sibling;var l={mode:"hidden",children:r.children};return!(i&1)&&n.child!==s?(r=n.child,r.childLanes=0,r.pendingProps=l,n.deletions=null):(r=Uo(s,l),r.subtreeFlags=s.subtreeFlags&14680064),a!==null?o=Uo(a,o):(o=Mi(o,i,t,null),o.flags|=2),o.return=n,r.return=n,r.sibling=o,n.child=r,r=o,o=n.child,i=e.child.memoizedState,i=i===null?HS(t):{baseLanes:i.baseLanes|t,cachePool:null,transitions:i.transitions},o.memoizedState=i,o.childLanes=e.childLanes&~t,n.memoizedState=US,r}return o=e.child,e=o.sibling,r=Uo(o,{mode:"visible",children:r.children}),!(n.mode&1)&&(r.lanes=t),r.return=n,r.sibling=null,e!==null&&(t=n.deletions,t===null?(n.deletions=[e],n.flags|=16):t.push(e)),n.child=r,n.memoizedState=null,r}function Xx(e,n){return n=Kf({mode:"visible",children:n},e.mode,0,null),n.return=e,e.child=n}function Md(e,n,t,r){return r!==null&&Rx(r),ll(n,e.child,null,t),e=Xx(n,n.pendingProps.children),e.flags|=2,n.memoizedState=null,e}function T$(e,n,t,r,s,o,i){if(t)return n.flags&256?(n.flags&=-257,r=wm(Error(X(422))),Md(e,n,i,r)):n.memoizedState!==null?(n.child=e.child,n.flags|=128,null):(o=r.fallback,s=n.mode,r=Kf({mode:"visible",children:r.children},s,0,null),o=Mi(o,s,i,null),o.flags|=2,r.return=n,o.return=n,r.sibling=o,n.child=r,n.mode&1&&ll(n,e.child,null,i),n.child.memoizedState=HS(i),n.memoizedState=US,o);if(!(n.mode&1))return Md(e,n,i,null);if(s.data==="$!"){if(r=s.nextSibling&&s.nextSibling.dataset,r)var a=r.dgst;return r=a,o=Error(X(419)),r=wm(o,r,void 0),Md(e,n,i,r)}if(a=(i&e.childLanes)!==0,Ln||a){if(r=Ot,r!==null){switch(i&-i){case 4:s=2;break;case 16:s=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:s=32;break;case 536870912:s=268435456;break;default:s=0}s=s&(r.suspendedLanes|i)?0:s,s!==0&&s!==o.retryLane&&(o.retryLane=s,Qs(e,s),Hr(r,e,s,-1))}return t0(),r=wm(Error(X(421))),Md(e,n,i,r)}return s.data==="$?"?(n.flags|=128,n.child=e.child,n=U$.bind(null,e),s._reactRetry=n,null):(e=o.treeContext,er=No(s.nextSibling),tr=n,rt=!0,$r=null,e!==null&&(Sr[vr++]=Bs,Sr[vr++]=Us,Sr[vr++]=Ri,Bs=e.id,Us=e.overflow,Ri=n),n=Xx(n,r.children),n.flags|=4096,n)}function zb(e,n,t){e.lanes|=n;var r=e.alternate;r!==null&&(r.lanes|=n),LS(e.return,n,t)}function bm(e,n,t,r,s){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:n,rendering:null,renderingStartTime:0,last:r,tail:t,tailMode:s}:(o.isBackwards=n,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=t,o.tailMode=s)}function mk(e,n,t){var r=n.pendingProps,s=r.revealOrder,o=r.tail;if(gn(e,n,r.children,t),r=lt.current,r&2)r=r&1|2,n.flags|=128;else{if(e!==null&&e.flags&128)e:for(e=n.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&zb(e,t,n);else if(e.tag===19)zb(e,t,n);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===n)break e;for(;e.sibling===null;){if(e.return===null||e.return===n)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(Ge(lt,r),!(n.mode&1))n.memoizedState=null;else switch(s){case"forwards":for(t=n.child,s=null;t!==null;)e=t.alternate,e!==null&&Op(e)===null&&(s=t),t=t.sibling;t=s,t===null?(s=n.child,n.child=null):(s=t.sibling,t.sibling=null),bm(n,!1,s,t,o);break;case"backwards":for(t=null,s=n.child,n.child=null;s!==null;){if(e=s.alternate,e!==null&&Op(e)===null){n.child=s;break}e=s.sibling,s.sibling=t,t=s,s=e}bm(n,!0,t,null,o);break;case"together":bm(n,!1,null,null,void 0);break;default:n.memoizedState=null}return n.child}function Th(e,n){!(n.mode&1)&&e!==null&&(e.alternate=null,n.alternate=null,n.flags|=2)}function Js(e,n,t){if(e!==null&&(n.dependencies=e.dependencies),$i|=n.lanes,!(t&n.childLanes))return null;if(e!==null&&n.child!==e.child)throw Error(X(153));if(n.child!==null){for(e=n.child,t=Uo(e,e.pendingProps),n.child=t,t.return=n;e.sibling!==null;)e=e.sibling,t=t.sibling=Uo(e,e.pendingProps),t.return=n;t.sibling=null}return n.child}function M$(e,n,t){switch(n.tag){case 3:fk(n),al();break;case 5:U_(n);break;case 1:Bn(n.type)&&_p(n);break;case 4:Bx(n,n.stateNode.containerInfo);break;case 10:var r=n.type._context,s=n.memoizedProps.value;Ge(Mp,r._currentValue),r._currentValue=s;break;case 13:if(r=n.memoizedState,r!==null)return r.dehydrated!==null?(Ge(lt,lt.current&1),n.flags|=128,null):t&n.child.childLanes?gk(e,n,t):(Ge(lt,lt.current&1),e=Js(e,n,t),e!==null?e.sibling:null);Ge(lt,lt.current&1);break;case 19:if(r=(t&n.childLanes)!==0,e.flags&128){if(r)return mk(e,n,t);n.flags|=128}if(s=n.memoizedState,s!==null&&(s.rendering=null,s.tail=null,s.lastEffect=null),Ge(lt,lt.current),r)break;return null;case 22:case 23:return n.lanes=0,hk(e,n,t)}return Js(e,n,t)}var yk,KS,Sk,vk;yk=function(e,n){for(var t=n.child;t!==null;){if(t.tag===5||t.tag===6)e.appendChild(t.stateNode);else if(t.tag!==4&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===n)break;for(;t.sibling===null;){if(t.return===null||t.return===n)return;t=t.return}t.sibling.return=t.return,t=t.sibling}};KS=function(){};Sk=function(e,n,t,r){var s=e.memoizedProps;if(s!==r){e=n.stateNode,Ei(fs.current);var o=null;switch(t){case"input":s=hS(e,s),r=hS(e,r),o=[];break;case"select":s=pt({},s,{value:void 0}),r=pt({},r,{value:void 0}),o=[];break;case"textarea":s=gS(e,s),r=gS(e,r),o=[];break;default:typeof s.onClick!="function"&&typeof r.onClick=="function"&&(e.onclick=Ip)}yS(t,r);var i;t=null;for(c in s)if(!r.hasOwnProperty(c)&&s.hasOwnProperty(c)&&s[c]!=null)if(c==="style"){var a=s[c];for(i in a)a.hasOwnProperty(i)&&(t||(t={}),t[i]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(Jc.hasOwnProperty(c)?o||(o=[]):(o=o||[]).push(c,null));for(c in r){var l=r[c];if(a=s!=null?s[c]:void 0,r.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(i in a)!a.hasOwnProperty(i)||l&&l.hasOwnProperty(i)||(t||(t={}),t[i]="");for(i in l)l.hasOwnProperty(i)&&a[i]!==l[i]&&(t||(t={}),t[i]=l[i])}else t||(o||(o=[]),o.push(c,t)),t=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(o=o||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(o=o||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(Jc.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&Qe("scroll",e),o||a===l||(o=[])):(o=o||[]).push(c,l))}t&&(o=o||[]).push("style",t);var c=o;(n.updateQueue=c)&&(n.flags|=4)}};vk=function(e,n,t,r){t!==r&&(n.flags|=4)};function Yl(e,n){if(!rt)switch(e.tailMode){case"hidden":n=e.tail;for(var t=null;n!==null;)n.alternate!==null&&(t=n),n=n.sibling;t===null?e.tail=null:t.sibling=null;break;case"collapsed":t=e.tail;for(var r=null;t!==null;)t.alternate!==null&&(r=t),t=t.sibling;r===null?n||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function en(e){var n=e.alternate!==null&&e.alternate.child===e.child,t=0,r=0;if(n)for(var s=e.child;s!==null;)t|=s.lanes|s.childLanes,r|=s.subtreeFlags&14680064,r|=s.flags&14680064,s.return=e,s=s.sibling;else for(s=e.child;s!==null;)t|=s.lanes|s.childLanes,r|=s.subtreeFlags,r|=s.flags,s.return=e,s=s.sibling;return e.subtreeFlags|=r,e.childLanes=t,n}function A$(e,n,t){var r=n.pendingProps;switch(Dx(n),n.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return en(n),null;case 1:return Bn(n.type)&&Ep(),en(n),null;case 3:return r=n.stateNode,cl(),et(zn),et(un),Hx(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(kd(n)?n.flags|=4:e===null||e.memoizedState.isDehydrated&&!(n.flags&256)||(n.flags|=1024,$r!==null&&(QS($r),$r=null))),KS(e,n),en(n),null;case 5:Ux(n);var s=Ei(du.current);if(t=n.type,e!==null&&n.stateNode!=null)Sk(e,n,t,r,s),e.ref!==n.ref&&(n.flags|=512,n.flags|=2097152);else{if(!r){if(n.stateNode===null)throw Error(X(166));return en(n),null}if(e=Ei(fs.current),kd(n)){r=n.stateNode,t=n.type;var o=n.memoizedProps;switch(r[is]=n,r[cu]=o,e=(n.mode&1)!==0,t){case"dialog":Qe("cancel",r),Qe("close",r);break;case"iframe":case"object":case"embed":Qe("load",r);break;case"video":case"audio":for(s=0;s<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(t,{is:r.is}):(e=i.createElement(t),t==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,t),e[is]=n,e[cu]=r,yk(e,n,!1,!1),n.stateNode=e;e:{switch(i=SS(t,r),t){case"dialog":Qe("cancel",e),Qe("close",e),s=r;break;case"iframe":case"object":case"embed":Qe("load",e),s=r;break;case"video":case"audio":for(s=0;sdl&&(n.flags|=128,r=!0,Yl(o,!1),n.lanes=4194304)}else{if(!r)if(e=Op(i),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),Yl(o,!0),o.tail===null&&o.tailMode==="hidden"&&!i.alternate&&!rt)return en(n),null}else 2*vt()-o.renderingStartTime>dl&&t!==1073741824&&(n.flags|=128,r=!0,Yl(o,!1),n.lanes=4194304);o.isBackwards?(i.sibling=n.child,n.child=i):(t=o.last,t!==null?t.sibling=i:n.child=i,o.last=i)}return o.tail!==null?(n=o.tail,o.rendering=n,o.tail=n.sibling,o.renderingStartTime=vt(),n.sibling=null,t=lt.current,Ge(lt,r?t&1|2:t&1),n):(en(n),null);case 22:case 23:return e0(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?Zn&1073741824&&(en(n),n.subtreeFlags&6&&(n.flags|=8192)):en(n),null;case 24:return null;case 25:return null}throw Error(X(156,n.tag))}function j$(e,n){switch(Dx(n),n.tag){case 1:return Bn(n.type)&&Ep(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return cl(),et(zn),et(un),Hx(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return Ux(n),null;case 13:if(et(lt),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(X(340));al()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return et(lt),null;case 4:return cl(),null;case 10:return Nx(n.type._context),null;case 22:case 23:return e0(),null;case 24:return null;default:return null}}var Ad=!1,on=!1,O$=typeof WeakSet=="function"?WeakSet:Set,te=null;function Ra(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){mt(e,n,r)}else t.current=null}function WS(e,n,t){try{t()}catch(r){mt(e,n,r)}}var Bb=!1;function D$(e,n){if(kS=bp,e=C_(),jx(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{t.nodeType,o.nodeType}catch{t=null;break e}var i=0,a=-1,l=-1,c=0,u=0,h=e,p=null;t:for(;;){for(var f;h!==t||s!==0&&h.nodeType!==3||(a=i+s),h!==o||r!==0&&h.nodeType!==3||(l=i+r),h.nodeType===3&&(i+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===e)break t;if(p===t&&++c===s&&(a=i),p===o&&++u===r&&(l=i),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(TS={focusedElem:e,selectionRange:t},bp=!1,te=n;te!==null;)if(n=te,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,te=e;else for(;te!==null;){n=te;try{var S=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var y=S.memoizedProps,x=S.memoizedState,m=n.stateNode,v=m.getSnapshotBeforeUpdate(n.elementType===n.type?y:Dr(n.type,y),x);m.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var w=n.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(X(163))}}catch(C){mt(n,n.return,C)}if(e=n.sibling,e!==null){e.return=n.return,te=e;break}te=n.return}return S=Bb,Bb=!1,S}function Uc(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&WS(n,t,o)}s=s.next}while(s!==r)}}function Uf(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function GS(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function xk(e){var n=e.alternate;n!==null&&(e.alternate=null,xk(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[is],delete n[cu],delete n[jS],delete n[m$],delete n[y$])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function wk(e){return e.tag===5||e.tag===3||e.tag===4}function Ub(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||wk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function VS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Ip));else if(r!==4&&(e=e.child,e!==null))for(VS(e,n,t),e=e.sibling;e!==null;)VS(e,n,t),e=e.sibling}function YS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(YS(e,n,t),e=e.sibling;e!==null;)YS(e,n,t),e=e.sibling}var zt=null,Rr=!1;function vo(e,n,t){for(t=t.child;t!==null;)bk(e,n,t),t=t.sibling}function bk(e,n,t){if(ps&&typeof ps.onCommitFiberUnmount=="function")try{ps.onCommitFiberUnmount(Df,t)}catch{}switch(t.tag){case 5:on||Ra(t,n);case 6:var r=zt,s=Rr;zt=null,vo(e,n,t),zt=r,Rr=s,zt!==null&&(Rr?(e=zt,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):zt.removeChild(t.stateNode));break;case 18:zt!==null&&(Rr?(e=zt,t=t.stateNode,e.nodeType===8?gm(e.parentNode,t):e.nodeType===1&&gm(e,t),su(e)):gm(zt,t.stateNode));break;case 4:r=zt,s=Rr,zt=t.stateNode.containerInfo,Rr=!0,vo(e,n,t),zt=r,Rr=s;break;case 0:case 11:case 14:case 15:if(!on&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,i=o.destroy;o=o.tag,i!==void 0&&(o&2||o&4)&&WS(t,n,i),s=s.next}while(s!==r)}vo(e,n,t);break;case 1:if(!on&&(Ra(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){mt(t,n,a)}vo(e,n,t);break;case 21:vo(e,n,t);break;case 22:t.mode&1?(on=(r=on)||t.memoizedState!==null,vo(e,n,t),on=r):vo(e,n,t);break;default:vo(e,n,t)}}function Hb(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new O$),n.forEach(function(r){var s=H$.bind(null,e,r);t.has(r)||(t.add(r),r.then(s,s))})}}function Or(e,n){var t=n.deletions;if(t!==null)for(var r=0;rs&&(s=i),r&=~o}if(r=s,r=vt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*L$(r/1960))-r,10e?16:e,Mo===null)var r=!1;else{if(e=Mo,Mo=null,Np=0,Te&6)throw Error(X(331));var s=Te;for(Te|=4,te=e.current;te!==null;){var o=te,i=o.child;if(te.flags&16){var a=o.deletions;if(a!==null){for(var l=0;lvt()-Qx?Ti(e,0):Zx|=t),Un(e,n)}function Mk(e,n){n===0&&(e.mode&1?(n=bd,bd<<=1,!(bd&130023424)&&(bd=4194304)):n=1);var t=yn();e=Qs(e,n),e!==null&&(Du(e,n,t),Un(e,t))}function U$(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),Mk(e,t)}function H$(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(t=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(X(314))}r!==null&&r.delete(n),Mk(e,t)}var Ak;Ak=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||zn.current)Ln=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return Ln=!1,M$(e,n,t);Ln=!!(e.flags&131072)}else Ln=!1,rt&&n.flags&1048576&&R_(n,Tp,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;Th(e,n),e=n.pendingProps;var s=il(n,un.current);Za(n,t),s=Wx(null,n,r,e,s,t);var o=Gx();return n.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Bn(r)?(o=!0,_p(n)):o=!1,n.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,zx(n),s.updater=Bf,n.stateNode=s,s._reactInternals=n,NS(n,r,e,t),n=BS(null,n,r,!0,o,t)):(n.tag=0,rt&&o&&Ox(n),gn(null,n,s,t),n=n.child),n;case 16:r=n.elementType;e:{switch(Th(e,n),e=n.pendingProps,s=r._init,r=s(r._payload),n.type=r,s=n.tag=W$(r),e=Dr(r,e),s){case 0:n=zS(null,n,r,e,t);break e;case 1:n=Nb(null,n,r,e,t);break e;case 11:n=Lb(null,n,r,e,t);break e;case 14:n=$b(null,n,r,Dr(r.type,e),t);break e}throw Error(X(306,r,""))}return n;case 0:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),zS(e,n,r,s,t);case 1:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Nb(e,n,r,s,t);case 3:e:{if(fk(n),e===null)throw Error(X(387));r=n.pendingProps,o=n.memoizedState,s=o.element,B_(e,n),jp(n,r,null,t);var i=n.memoizedState;if(r=i.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},n.updateQueue.baseState=o,n.memoizedState=o,n.flags&256){s=ul(Error(X(423)),n),n=Fb(e,n,r,t,s);break e}else if(r!==s){s=ul(Error(X(424)),n),n=Fb(e,n,r,t,s);break e}else for(er=No(n.stateNode.containerInfo.firstChild),tr=n,rt=!0,$r=null,t=F_(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(al(),r===s){n=Js(e,n,t);break e}gn(e,n,r,t)}n=n.child}return n;case 5:return U_(n),e===null&&RS(n),r=n.type,s=n.pendingProps,o=e!==null?e.memoizedProps:null,i=s.children,MS(r,s)?i=null:o!==null&&MS(r,o)&&(n.flags|=32),pk(e,n),gn(e,n,i,t),n.child;case 6:return e===null&&RS(n),null;case 13:return gk(e,n,t);case 4:return Bx(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=ll(n,null,r,t):gn(e,n,r,t),n.child;case 11:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Lb(e,n,r,s,t);case 7:return gn(e,n,n.pendingProps,t),n.child;case 8:return gn(e,n,n.pendingProps.children,t),n.child;case 12:return gn(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,s=n.pendingProps,o=n.memoizedProps,i=s.value,Ge(Mp,r._currentValue),r._currentValue=i,o!==null)if(Kr(o.value,i)){if(o.children===s.children&&!zn.current){n=Js(e,n,t);break e}}else for(o=n.child,o!==null&&(o.return=n);o!==null;){var a=o.dependencies;if(a!==null){i=o.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(o.tag===1){l=Ws(-1,t&-t),l.tag=2;var c=o.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}o.lanes|=t,l=o.alternate,l!==null&&(l.lanes|=t),LS(o.return,t,n),a.lanes|=t;break}l=l.next}}else if(o.tag===10)i=o.type===n.type?null:o.child;else if(o.tag===18){if(i=o.return,i===null)throw Error(X(341));i.lanes|=t,a=i.alternate,a!==null&&(a.lanes|=t),LS(i,t,n),i=o.sibling}else i=o.child;if(i!==null)i.return=o;else for(i=o;i!==null;){if(i===n){i=null;break}if(o=i.sibling,o!==null){o.return=i.return,i=o;break}i=i.return}o=i}gn(e,n,s.children,t),n=n.child}return n;case 9:return s=n.type,r=n.pendingProps.children,Za(n,t),s=_r(s),r=r(s),n.flags|=1,gn(e,n,r,t),n.child;case 14:return r=n.type,s=Dr(r,n.pendingProps),s=Dr(r.type,s),$b(e,n,r,s,t);case 15:return dk(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,s=n.pendingProps,s=n.elementType===r?s:Dr(r,s),Th(e,n),n.tag=1,Bn(r)?(e=!0,_p(n)):e=!1,Za(n,t),lk(n,r,s),NS(n,r,s,t),BS(null,n,r,!0,e,t);case 19:return mk(e,n,t);case 22:return hk(e,n,t)}throw Error(X(156,n.tag))};function jk(e,n){return o_(e,n)}function K$(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function br(e,n,t,r){return new K$(e,n,t,r)}function n0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function W$(e){if(typeof e=="function")return n0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===wx)return 11;if(e===bx)return 14}return 2}function Uo(e,n){var t=e.alternate;return t===null?(t=br(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function jh(e,n,t,r,s,o){var i=2;if(r=e,typeof e=="function")n0(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case Ea:return Mi(t.children,s,o,n);case xx:i=8,s|=8;break;case lS:return e=br(12,t,n,s|2),e.elementType=lS,e.lanes=o,e;case cS:return e=br(13,t,n,s),e.elementType=cS,e.lanes=o,e;case uS:return e=br(19,t,n,s),e.elementType=uS,e.lanes=o,e;case UE:return Kf(t,s,o,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case zE:i=10;break e;case BE:i=9;break e;case wx:i=11;break e;case bx:i=14;break e;case Co:i=16,r=null;break e}throw Error(X(130,e==null?e:typeof e,""))}return n=br(i,t,n,s),n.elementType=e,n.type=r,n.lanes=o,n}function Mi(e,n,t,r){return e=br(7,e,r,n),e.lanes=t,e}function Kf(e,n,t,r){return e=br(22,e,r,n),e.elementType=UE,e.lanes=t,e.stateNode={isHidden:!1},e}function Pm(e,n,t){return e=br(6,e,null,n),e.lanes=t,e}function Cm(e,n,t){return n=br(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function G$(e,n,t,r,s){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=sm(0),this.expirationTimes=sm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sm(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function r0(e,n,t,r,s,o,i,a,l){return e=new G$(e,n,t,a,l),n===1?(n=1,o===!0&&(n|=8)):n=0,o=br(3,null,null,n),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},zx(o),e}function V$(e,n,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Lk)}catch(e){console.error(e)}}Lk(),LE.exports=cr;var ta=LE.exports;const Q$=ti(ta);var a0,Zb=ta;a0=Zb.createRoot,Zb.hydrateRoot;var ql=function(e){return e&&e.Math===Math&&e},xn=ql(typeof globalThis=="object"&&globalThis)||ql(typeof window=="object"&&window)||ql(typeof self=="object"&&self)||ql(typeof ln=="object"&&ln)||ql(typeof ln=="object"&&ln)||function(){return this}()||Function("return this")(),l0={},wn=function(e){try{return!!e()}catch{return!0}},J$=wn,oi=!J$(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),eN=wn,Xf=!eN(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),tN=Xf,Dd=Function.prototype.call,io=tN?Dd.bind(Dd):function(){return Dd.apply(Dd,arguments)},$k={},Nk={}.propertyIsEnumerable,Fk=Object.getOwnPropertyDescriptor,nN=Fk&&!Nk.call({1:2},1);$k.f=nN?function(n){var t=Fk(this,n);return!!t&&t.enumerable}:Nk;var zk=function(e,n){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:n}},Bk=Xf,Uk=Function.prototype,JS=Uk.call,rN=Bk&&Uk.bind.bind(JS,JS),Rt=Bk?rN:function(e){return function(){return JS.apply(e,arguments)}},Hk=Rt,sN=Hk({}.toString),oN=Hk("".slice),Il=function(e){return oN(sN(e),8,-1)},iN=Rt,aN=wn,lN=Il,Im=Object,cN=iN("".split),uN=aN(function(){return!Im("z").propertyIsEnumerable(0)})?function(e){return lN(e)==="String"?cN(e,""):Im(e)}:Im,qf=function(e){return e==null},dN=qf,hN=TypeError,El=function(e){if(dN(e))throw new hN("Can't call method on "+e);return e},pN=uN,fN=El,Zf=function(e){return pN(fN(e))},Em=typeof document=="object"&&document.all,bn=typeof Em>"u"&&Em!==void 0?function(e){return typeof e=="function"||e===Em}:function(e){return typeof e=="function"},gN=bn,na=function(e){return typeof e=="object"?e!==null:gN(e)},_m=xn,mN=bn,yN=function(e){return mN(e)?e:void 0},Qf=function(e,n){return arguments.length<2?yN(_m[e]):_m[e]&&_m[e][n]},SN=Rt,Kk=SN({}.isPrototypeOf),vN=xn,Qb=vN.navigator,Jb=Qb&&Qb.userAgent,xN=Jb?String(Jb):"",Wk=xn,km=xN,eP=Wk.process,tP=Wk.Deno,nP=eP&&eP.versions||tP&&tP.version,rP=nP&&nP.v8,Nr,Bp;rP&&(Nr=rP.split("."),Bp=Nr[0]>0&&Nr[0]<4?1:+(Nr[0]+Nr[1]));!Bp&&km&&(Nr=km.match(/Edge\/(\d+)/),(!Nr||Nr[1]>=74)&&(Nr=km.match(/Chrome\/(\d+)/),Nr&&(Bp=+Nr[1])));var wN=Bp,sP=wN,bN=wn,PN=xn,CN=PN.String,Gk=!!Object.getOwnPropertySymbols&&!bN(function(){var e=Symbol("symbol detection");return!CN(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&sP&&sP<41}),IN=Gk,Vk=IN&&!Symbol.sham&&typeof Symbol.iterator=="symbol",EN=Qf,_N=bn,kN=Kk,TN=Vk,MN=Object,Yk=TN?function(e){return typeof e=="symbol"}:function(e){var n=EN("Symbol");return _N(n)&&kN(n.prototype,MN(e))},AN=String,jN=function(e){try{return AN(e)}catch{return"Object"}},ON=bn,DN=jN,RN=TypeError,c0=function(e){if(ON(e))return e;throw new RN(DN(e)+" is not a function")},LN=c0,$N=qf,u0=function(e,n){var t=e[n];return $N(t)?void 0:LN(t)},Tm=io,Mm=bn,Am=na,NN=TypeError,FN=function(e,n){var t,r;if(n==="string"&&Mm(t=e.toString)&&!Am(r=Tm(t,e))||Mm(t=e.valueOf)&&!Am(r=Tm(t,e))||n!=="string"&&Mm(t=e.toString)&&!Am(r=Tm(t,e)))return r;throw new NN("Can't convert object to primitive value")},Xk={exports:{}},oP=xn,zN=Object.defineProperty,d0=function(e,n){try{zN(oP,e,{value:n,configurable:!0,writable:!0})}catch{oP[e]=n}return n},BN=xn,UN=d0,iP="__core-js_shared__",aP=Xk.exports=BN[iP]||UN(iP,{});(aP.versions||(aP.versions=[])).push({version:"3.38.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE",source:"https://github.com/zloirock/core-js"});var h0=Xk.exports,lP=h0,p0=function(e,n){return lP[e]||(lP[e]=n||{})},HN=El,KN=Object,Nu=function(e){return KN(HN(e))},WN=Rt,GN=Nu,VN=WN({}.hasOwnProperty),ii=Object.hasOwn||function(n,t){return VN(GN(n),t)},YN=Rt,XN=0,qN=Math.random(),ZN=YN(1 .toString),qk=function(e){return"Symbol("+(e===void 0?"":e)+")_"+ZN(++XN+qN,36)},QN=xn,JN=p0,cP=ii,eF=qk,tF=Gk,nF=Vk,$a=QN.Symbol,jm=JN("wks"),rF=nF?$a.for||$a:$a&&$a.withoutSetter||eF,ao=function(e){return cP(jm,e)||(jm[e]=tF&&cP($a,e)?$a[e]:rF("Symbol."+e)),jm[e]},sF=io,uP=na,dP=Yk,oF=u0,iF=FN,aF=ao,lF=TypeError,cF=aF("toPrimitive"),uF=function(e,n){if(!uP(e)||dP(e))return e;var t=oF(e,cF),r;if(t){if(n===void 0&&(n="default"),r=sF(t,e,n),!uP(r)||dP(r))return r;throw new lF("Can't convert object to primitive value")}return n===void 0&&(n="number"),iF(e,n)},dF=uF,hF=Yk,Zk=function(e){var n=dF(e,"string");return hF(n)?n:n+""},pF=xn,hP=na,ev=pF.document,fF=hP(ev)&&hP(ev.createElement),Qk=function(e){return fF?ev.createElement(e):{}},gF=oi,mF=wn,yF=Qk,Jk=!gF&&!mF(function(){return Object.defineProperty(yF("div"),"a",{get:function(){return 7}}).a!==7}),SF=oi,vF=io,xF=$k,wF=zk,bF=Zf,PF=Zk,CF=ii,IF=Jk,pP=Object.getOwnPropertyDescriptor;l0.f=SF?pP:function(n,t){if(n=bF(n),t=PF(t),IF)try{return pP(n,t)}catch{}if(CF(n,t))return wF(!vF(xF.f,n,t),n[t])};var _l={},EF=oi,_F=wn,e2=EF&&_F(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),kF=na,TF=String,MF=TypeError,ra=function(e){if(kF(e))return e;throw new MF(TF(e)+" is not an object")},AF=oi,jF=Jk,OF=e2,Rd=ra,fP=Zk,DF=TypeError,Om=Object.defineProperty,RF=Object.getOwnPropertyDescriptor,Dm="enumerable",Rm="configurable",Lm="writable";_l.f=AF?OF?function(n,t,r){if(Rd(n),t=fP(t),Rd(r),typeof n=="function"&&t==="prototype"&&"value"in r&&Lm in r&&!r[Lm]){var s=RF(n,t);s&&s[Lm]&&(n[t]=r.value,r={configurable:Rm in r?r[Rm]:s[Rm],enumerable:Dm in r?r[Dm]:s[Dm],writable:!1})}return Om(n,t,r)}:Om:function(n,t,r){if(Rd(n),t=fP(t),Rd(r),jF)try{return Om(n,t,r)}catch{}if("get"in r||"set"in r)throw new DF("Accessors not supported");return"value"in r&&(n[t]=r.value),n};var LF=oi,$F=_l,NF=zk,f0=LF?function(e,n,t){return $F.f(e,n,NF(1,t))}:function(e,n,t){return e[n]=t,e},t2={exports:{}},tv=oi,FF=ii,n2=Function.prototype,zF=tv&&Object.getOwnPropertyDescriptor,g0=FF(n2,"name"),BF=g0&&(function(){}).name==="something",UF=g0&&(!tv||tv&&zF(n2,"name").configurable),HF={EXISTS:g0,PROPER:BF,CONFIGURABLE:UF},KF=Rt,WF=bn,nv=h0,GF=KF(Function.toString);WF(nv.inspectSource)||(nv.inspectSource=function(e){return GF(e)});var r2=nv.inspectSource,VF=xn,YF=bn,gP=VF.WeakMap,XF=YF(gP)&&/native code/.test(String(gP)),qF=p0,ZF=qk,mP=qF("keys"),s2=function(e){return mP[e]||(mP[e]=ZF(e))},m0={},QF=XF,o2=xn,JF=na,e4=f0,$m=ii,Nm=h0,t4=s2,n4=m0,yP="Object already initialized",rv=o2.TypeError,r4=o2.WeakMap,Up,mu,Hp,s4=function(e){return Hp(e)?mu(e):Up(e,{})},o4=function(e){return function(n){var t;if(!JF(n)||(t=mu(n)).type!==e)throw new rv("Incompatible receiver, "+e+" required");return t}};if(QF||Nm.state){var ts=Nm.state||(Nm.state=new r4);ts.get=ts.get,ts.has=ts.has,ts.set=ts.set,Up=function(e,n){if(ts.has(e))throw new rv(yP);return n.facade=e,ts.set(e,n),n},mu=function(e){return ts.get(e)||{}},Hp=function(e){return ts.has(e)}}else{var da=t4("state");n4[da]=!0,Up=function(e,n){if($m(e,da))throw new rv(yP);return n.facade=e,e4(e,da,n),n},mu=function(e){return $m(e,da)?e[da]:{}},Hp=function(e){return $m(e,da)}}var i2={set:Up,get:mu,has:Hp,enforce:s4,getterFor:o4},y0=Rt,i4=wn,a4=bn,Ld=ii,sv=oi,l4=HF.CONFIGURABLE,c4=r2,a2=i2,u4=a2.enforce,d4=a2.get,SP=String,Oh=Object.defineProperty,h4=y0("".slice),p4=y0("".replace),f4=y0([].join),g4=sv&&!i4(function(){return Oh(function(){},"length",{value:8}).length!==8}),m4=String(String).split("String"),y4=t2.exports=function(e,n,t){h4(SP(n),0,7)==="Symbol("&&(n="["+p4(SP(n),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),t&&t.getter&&(n="get "+n),t&&t.setter&&(n="set "+n),(!Ld(e,"name")||l4&&e.name!==n)&&(sv?Oh(e,"name",{value:n,configurable:!0}):e.name=n),g4&&t&&Ld(t,"arity")&&e.length!==t.arity&&Oh(e,"length",{value:t.arity});try{t&&Ld(t,"constructor")&&t.constructor?sv&&Oh(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=u4(e);return Ld(r,"source")||(r.source=f4(m4,typeof n=="string"?n:"")),e};Function.prototype.toString=y4(function(){return a4(this)&&d4(this).source||c4(this)},"toString");var S4=t2.exports,v4=bn,x4=_l,w4=S4,b4=d0,l2=function(e,n,t,r){r||(r={});var s=r.enumerable,o=r.name!==void 0?r.name:n;if(v4(t)&&w4(t,o,r),r.global)s?e[n]=t:b4(n,t);else{try{r.unsafe?e[n]&&(s=!0):delete e[n]}catch{}s?e[n]=t:x4.f(e,n,{value:t,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},c2={},P4=Math.ceil,C4=Math.floor,I4=Math.trunc||function(n){var t=+n;return(t>0?C4:P4)(t)},E4=I4,sa=function(e){var n=+e;return n!==n||n===0?0:E4(n)},_4=sa,k4=Math.max,T4=Math.min,M4=function(e,n){var t=_4(e);return t<0?k4(t+n,0):T4(t,n)},A4=sa,j4=Math.min,u2=function(e){var n=A4(e);return n>0?j4(n,9007199254740991):0},O4=u2,Fu=function(e){return O4(e.length)},D4=Zf,R4=M4,L4=Fu,vP=function(e){return function(n,t,r){var s=D4(n),o=L4(s);if(o===0)return!e&&-1;var i=R4(r,o),a;if(e&&t!==t){for(;o>i;)if(a=s[i++],a!==a)return!0}else for(;o>i;i++)if((e||i in s)&&s[i]===t)return e||i||0;return!e&&-1}},$4={includes:vP(!0),indexOf:vP(!1)},N4=Rt,Fm=ii,F4=Zf,z4=$4.indexOf,B4=m0,xP=N4([].push),d2=function(e,n){var t=F4(e),r=0,s=[],o;for(o in t)!Fm(B4,o)&&Fm(t,o)&&xP(s,o);for(;n.length>r;)Fm(t,o=n[r++])&&(~z4(s,o)||xP(s,o));return s},S0=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],U4=d2,H4=S0,K4=H4.concat("length","prototype");c2.f=Object.getOwnPropertyNames||function(n){return U4(n,K4)};var h2={};h2.f=Object.getOwnPropertySymbols;var W4=Qf,G4=Rt,V4=c2,Y4=h2,X4=ra,q4=G4([].concat),Z4=W4("Reflect","ownKeys")||function(n){var t=V4.f(X4(n)),r=Y4.f;return r?q4(t,r(n)):t},wP=ii,Q4=Z4,J4=l0,ez=_l,tz=function(e,n,t){for(var r=Q4(n),s=ez.f,o=J4.f,i=0;ii;)wz.f(n,a=s[i++],r[a]);return n};var Iz=Qf,Ez=Iz("document","documentElement"),_z=ra,kz=p2,bP=S0,Tz=m0,Mz=Ez,Az=Qk,jz=s2,PP=">",CP="<",ov="prototype",iv="script",f2=jz("IE_PROTO"),zm=function(){},g2=function(e){return CP+iv+PP+e+CP+"/"+iv+PP},IP=function(e){e.write(g2("")),e.close();var n=e.parentWindow.Object;return e=null,n},Oz=function(){var e=Az("iframe"),n="java"+iv+":",t;return e.style.display="none",Mz.appendChild(e),e.src=String(n),t=e.contentWindow.document,t.open(),t.write(g2("document.F=Object")),t.close(),t.F},Nd,Dh=function(){try{Nd=new ActiveXObject("htmlfile")}catch{}Dh=typeof document<"u"?document.domain&&Nd?IP(Nd):Oz():IP(Nd);for(var e=bP.length;e--;)delete Dh[ov][bP[e]];return Dh()};Tz[f2]=!0;var m2=Object.create||function(n,t){var r;return n!==null?(zm[ov]=_z(n),r=new zm,zm[ov]=null,r[f2]=n):r=Dh(),t===void 0?r:kz.f(r,t)},Dz=ao,Rz=m2,Lz=_l.f,av=Dz("unscopables"),lv=Array.prototype;lv[av]===void 0&&Lz(lv,av,{configurable:!0,value:Rz(null)});var v0=function(e){lv[av][e]=!0},$z=kl,Nz=Nu,Fz=Fu,zz=sa,Bz=v0;$z({target:"Array",proto:!0},{at:function(n){var t=Nz(this),r=Fz(t),s=zz(n),o=s>=0?s:r+s;return o<0||o>=r?void 0:t[o]}});Bz("at");var Uz=xn,Hz=Rt,Bu=function(e,n){return Hz(Uz[e].prototype[n])},Kz=Bu;Kz("Array","at");var Wz=Il,y2=Array.isArray||function(n){return Wz(n)==="Array"},Gz=TypeError,Vz=9007199254740991,Yz=function(e){if(e>Vz)throw Gz("Maximum allowed index exceeded");return e},Xz=Il,qz=Rt,Zz=function(e){if(Xz(e)==="Function")return qz(e)},EP=Zz,Qz=c0,Jz=Xf,e6=EP(EP.bind),t6=function(e,n){return Qz(e),n===void 0?e:Jz?e6(e,n):function(){return e.apply(n,arguments)}},n6=y2,r6=Fu,s6=Yz,o6=t6,S2=function(e,n,t,r,s,o,i,a){for(var l=s,c=0,u=i?o6(i,a):!1,h,p;c0&&n6(h)?(p=r6(h),l=S2(e,n,h,p,l,o-1)-1):(s6(l+1),e[l]=h),l++),c++;return l},v2=S2,i6=ao,a6=i6("toStringTag"),x2={};x2[a6]="z";var l6=String(x2)==="[object z]",c6=l6,u6=bn,Rh=Il,d6=ao,h6=d6("toStringTag"),p6=Object,f6=Rh(function(){return arguments}())==="Arguments",g6=function(e,n){try{return e[n]}catch{}},w2=c6?Rh:function(e){var n,t,r;return e===void 0?"Undefined":e===null?"Null":typeof(t=g6(n=p6(e),h6))=="string"?t:f6?Rh(n):(r=Rh(n))==="Object"&&u6(n.callee)?"Arguments":r},m6=Rt,y6=wn,b2=bn,S6=w2,v6=Qf,x6=r2,P2=function(){},C2=v6("Reflect","construct"),x0=/^\s*(?:class|function)\b/,w6=m6(x0.exec),b6=!x0.test(P2),Zl=function(n){if(!b2(n))return!1;try{return C2(P2,[],n),!0}catch{return!1}},I2=function(n){if(!b2(n))return!1;switch(S6(n)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return b6||!!w6(x0,x6(n))}catch{return!0}};I2.sham=!0;var P6=!C2||y6(function(){var e;return Zl(Zl.call)||!Zl(Object)||!Zl(function(){e=!0})||e})?I2:Zl,_P=y2,C6=P6,I6=na,E6=ao,_6=E6("species"),kP=Array,k6=function(e){var n;return _P(e)&&(n=e.constructor,C6(n)&&(n===kP||_P(n.prototype))?n=void 0:I6(n)&&(n=n[_6],n===null&&(n=void 0))),n===void 0?kP:n},T6=k6,E2=function(e,n){return new(T6(e))(n===0?0:n)},M6=kl,A6=v2,j6=c0,O6=Nu,D6=Fu,R6=E2;M6({target:"Array",proto:!0},{flatMap:function(n){var t=O6(this),r=D6(t),s;return j6(n),s=R6(t,0),s.length=A6(s,t,t,r,0,1,n,arguments.length>1?arguments[1]:void 0),s}});var L6=v0;L6("flatMap");var $6=Bu;$6("Array","flatMap");var N6=kl,F6=v2,z6=Nu,B6=Fu,U6=sa,H6=E2;N6({target:"Array",proto:!0},{flat:function(){var n=arguments.length?arguments[0]:void 0,t=z6(this),r=B6(t),s=H6(t,0);return s.length=F6(s,t,t,r,0,n===void 0?1:U6(n)),s}});var K6=v0;K6("flat");var W6=Bu;W6("Array","flat");var G6=w2,V6=String,Uu=function(e){if(G6(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return V6(e)},Y6=kl,X6=Rt,q6=El,Z6=sa,Q6=Uu,J6=wn,e8=X6("".charAt),t8=J6(function(){return"𠮷".at(-2)!=="\uD842"});Y6({target:"String",proto:!0,forced:t8},{at:function(n){var t=Q6(q6(this)),r=t.length,s=Z6(n),o=s>=0?s:r+s;return o<0||o>=r?void 0:e8(t,o)}});var n8=Bu;n8("String","at");var r8=ra,_2=function(){var e=r8(this),n="";return e.hasIndices&&(n+="d"),e.global&&(n+="g"),e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.dotAll&&(n+="s"),e.unicode&&(n+="u"),e.unicodeSets&&(n+="v"),e.sticky&&(n+="y"),n},w0=wn,s8=xn,b0=s8.RegExp,P0=w0(function(){var e=b0("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),o8=P0||w0(function(){return!b0("a","y").sticky}),i8=P0||w0(function(){var e=b0("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),a8={BROKEN_CARET:i8,MISSED_STICKY:o8,UNSUPPORTED_Y:P0},l8=wn,c8=xn,u8=c8.RegExp,d8=l8(function(){var e=u8(".","s");return!(e.dotAll&&e.test(` +`)&&e.flags==="s")}),h8=wn,p8=xn,f8=p8.RegExp,g8=h8(function(){var e=f8("(?b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$c")!=="bc"}),Na=io,Jf=Rt,m8=Uu,y8=_2,S8=a8,v8=p0,x8=m2,w8=i2.get,b8=d8,P8=g8,C8=v8("native-string-replace",String.prototype.replace),Kp=RegExp.prototype.exec,cv=Kp,I8=Jf("".charAt),E8=Jf("".indexOf),_8=Jf("".replace),Bm=Jf("".slice),uv=function(){var e=/a/,n=/b*/g;return Na(Kp,e,"a"),Na(Kp,n,"a"),e.lastIndex!==0||n.lastIndex!==0}(),k2=S8.BROKEN_CARET,dv=/()??/.exec("")[1]!==void 0,k8=uv||dv||k2||b8||P8;k8&&(cv=function(n){var t=this,r=w8(t),s=m8(n),o=r.raw,i,a,l,c,u,h,p;if(o)return o.lastIndex=t.lastIndex,i=Na(cv,o,s),t.lastIndex=o.lastIndex,i;var f=r.groups,S=k2&&t.sticky,y=Na(y8,t),x=t.source,m=0,v=s;if(S&&(y=_8(y,"y",""),E8(y,"g")===-1&&(y+="g"),v=Bm(s,t.lastIndex),t.lastIndex>0&&(!t.multiline||t.multiline&&I8(s,t.lastIndex-1)!==` +`)&&(x="(?: "+x+")",v=" "+v,m++),a=new RegExp("^(?:"+x+")",y)),dv&&(a=new RegExp("^"+x+"$(?!\\s)",y)),uv&&(l=t.lastIndex),c=Na(Kp,S?a:t,v),S?c?(c.input=Bm(c.input,m),c[0]=Bm(c[0],m),c.index=t.lastIndex,t.lastIndex+=c[0].length):t.lastIndex=0:uv&&c&&(t.lastIndex=t.global?c.index+c[0].length:l),dv&&c&&c.length>1&&Na(C8,c[0],a,function(){for(u=1;u=o?e?"":void 0:(i=RP(r,s),i<55296||i>56319||s+1===o||(a=RP(r,s+1))<56320||a>57343?e?F8(r,s):i:e?z8(r,s,s+2):(i-55296<<10)+(a-56320)+65536)}},B8={codeAt:LP(!1),charAt:LP(!0)},U8=B8.charAt,H8=function(e,n,t){return n+(t?U8(e,n).length:1)},E0=Rt,K8=Nu,W8=Math.floor,Hm=E0("".charAt),G8=E0("".replace),Km=E0("".slice),V8=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Y8=/\$([$&'`]|\d{1,2})/g,A2=function(e,n,t,r,s,o){var i=t+e.length,a=r.length,l=Y8;return s!==void 0&&(s=K8(s),l=V8),G8(o,l,function(c,u){var h;switch(Hm(u,0)){case"$":return"$";case"&":return e;case"`":return Km(n,0,t);case"'":return Km(n,i);case"<":h=s[Km(u,1,-1)];break;default:var p=+u;if(p===0)return c;if(p>a){var f=W8(p/10);return f===0?c:f<=a?r[f-1]===void 0?Hm(u,1):r[f-1]+Hm(u,1):c}h=r[p-1]}return h===void 0?"":h})},$P=io,X8=ra,q8=bn,Z8=Il,Q8=C0,J8=TypeError,eB=function(e,n){var t=e.exec;if(q8(t)){var r=$P(t,e,n);return r!==null&&X8(r),r}if(Z8(e)==="RegExp")return $P(Q8,e,n);throw new J8("RegExp#exec called on incompatible receiver")},tB=A8,NP=io,eg=Rt,nB=R8,rB=wn,sB=ra,oB=bn,iB=qf,aB=sa,lB=u2,ha=Uu,cB=El,uB=H8,dB=u0,hB=A2,pB=eB,fB=ao,hv=fB("replace"),gB=Math.max,mB=Math.min,yB=eg([].concat),Wm=eg([].push),FP=eg("".indexOf),zP=eg("".slice),SB=function(e){return e===void 0?e:String(e)},vB=function(){return"a".replace(/./,"$0")==="$0"}(),BP=function(){return/./[hv]?/./[hv]("a","$0")==="":!1}(),xB=!rB(function(){var e=/./;return e.exec=function(){var n=[];return n.groups={a:"7"},n},"".replace(e,"$")!=="7"});nB("replace",function(e,n,t){var r=BP?"$":"$0";return[function(o,i){var a=cB(this),l=iB(o)?void 0:dB(o,hv);return l?NP(l,o,a,i):NP(n,ha(a),o,i)},function(s,o){var i=sB(this),a=ha(s);if(typeof o=="string"&&FP(o,r)===-1&&FP(o,"$<")===-1){var l=t(n,i,a,o);if(l.done)return l.value}var c=oB(o);c||(o=ha(o));var u=i.global,h;u&&(h=i.unicode,i.lastIndex=0);for(var p=[],f;f=pB(i,a),!(f===null||(Wm(p,f),!u));){var S=ha(f[0]);S===""&&(i.lastIndex=uB(a,lB(i.lastIndex),h))}for(var y="",x=0,m=0;m=x&&(y+=zP(a,x,w)+E,x=w+v.length)}return y+zP(a,x)}]},!xB||!vB||BP);var wB=na,bB=Il,PB=ao,CB=PB("match"),IB=function(e){var n;return wB(e)&&((n=e[CB])!==void 0?!!n:bB(e)==="RegExp")},EB=io,_B=ii,kB=Kk,TB=_2,UP=RegExp.prototype,MB=function(e){var n=e.flags;return n===void 0&&!("flags"in UP)&&!_B(e,"flags")&&kB(UP,e)?EB(TB,e):n},AB=kl,jB=io,_0=Rt,HP=El,OB=bn,DB=qf,RB=IB,Ql=Uu,LB=u0,$B=MB,NB=A2,FB=ao,zB=FB("replace"),BB=TypeError,Gm=_0("".indexOf);_0("".replace);var KP=_0("".slice),UB=Math.max;AB({target:"String",proto:!0},{replaceAll:function(n,t){var r=HP(this),s,o,i,a,l,c,u,h,p,f,S=0,y="";if(!DB(n)){if(s=RB(n),s&&(o=Ql(HP($B(n))),!~Gm(o,"g")))throw new BB("`.replaceAll` does not allow non-global regexes");if(i=LB(n,zB),i)return jB(i,n,r,t)}for(a=Ql(r),l=Ql(n),c=OB(t),c||(t=Ql(t)),u=l.length,h=UB(1,u),p=Gm(a,l);p!==-1;)f=c?Ql(t(l,p,a)):NB(l,a,p,[],void 0,t),y+=KP(a,S,p)+f,S=p+u,p=p+h>a.length?-1:Gm(a,l,p+h);return S{if(e.children.remove(n)&&e.children.isEmpty&&j2(e))for(let t=0,r=e.parents.length;t{if(e.children.add(n)&&j2(e))for(let t=0,r=e.parents.length;tObject.freeze([])),WP=8;class Gp{constructor(){g(this,"arraySize",0);g(this,"array",Array(WP));g(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(n){if(this.array)return this.array.indexOf(n)!==-1?!1:this.arraySize=c)return[];if(l<=n&&n({stack:null}));function Fd(e){const n=nt.stack;nt.stack=null;try{return e()}finally{nt.stack=n}}function L2(e){nt.stack=new KB(nt.stack,e),e.parentSet.clear()}function $2(){const e=nt.stack;if(nt.stack=e.below,e.offset{this._isActivelyListening&&this.execute()});this.name=n,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!==Mn()){if(this.parents.length&&!O2(this)){this.lastReactedEpoch=Mn();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let n=0,t=this.parents.length;nWB);function oa(e,n,t){const r=new Tl(e,n,t);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function GB(e,n,t){const r=new Tl(e,n,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()}}}class VB{constructor(n){g(this,"initialAtomValues",new Map);this.parent=n}get isRoot(){return this.parent===null}commit(){this.isRoot?N2(this.initialAtomValues.keys()):this.initialAtomValues.forEach((n,t)=>{this.parent.initialAtomValues.has(t)||this.parent.initialAtomValues.set(t,n)})}abort(){Fe.globalEpoch++,this.initialAtomValues.forEach((n,t)=>{var r;t.set(n),(r=t.historyBuffer)==null||r.clear()}),this.commit()}}const Fe=ai("transactions",()=>({globalEpoch:Ao+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null,reactionEpoch:Ao+1}));function YB(){return Fe.reactionEpoch}function Mn(){return Fe.globalEpoch}function XB(){return Fe.globalIsReacting}function T0(e,n){n.lastTraversedEpoch!==Fe.globalEpoch&&(n.lastTraversedEpoch=Fe.globalEpoch,n instanceof Tl?e.add(n):n.children.visit(t=>T0(e,t)))}function N2(e){var n;if(Fe.globalIsReacting)throw new Error("cannot change atoms during reaction cycle");try{Fe.globalIsReacting=!0,Fe.reactionEpoch=Fe.globalEpoch;const t=new Set;for(const s of e)s.children.visit(o=>T0(t,o));for(const s of t)s.maybeScheduleEffect();let r=0;for(;(n=Fe.cleanupReactors)!=null&&n.size;){if(r++>1e3)throw new Error("Reaction update depth limit exceeded");const s=Fe.cleanupReactors;Fe.cleanupReactors=null;for(const o of s)o.maybeScheduleEffect()}}finally{Fe.cleanupReactors=null,Fe.globalIsReacting=!1}}function qB(e,n){if(Fe.globalIsReacting){const t=Fe.cleanupReactors??(Fe.cleanupReactors=new Set);e.children.visit(r=>T0(t,r))}else Fe.currentTransaction?Fe.currentTransaction.initialAtomValues.has(e)||Fe.currentTransaction.initialAtomValues.set(e,n):N2([e])}function ZB(){Fe.globalEpoch++}function QB(e){const n=new VB(Fe.currentTransaction);Fe.currentTransaction=n;try{let t,r=!1;try{t=e(()=>r=!0)}catch(s){throw n.abort(),s}return r?n.abort():n.commit(),t}finally{Fe.currentTransaction=Fe.currentTransaction.parent}}function gs(e){return Fe.currentTransaction?e():QB(e)}class JB{constructor(n,t,r){g(this,"isEqual");g(this,"computeDiff");g(this,"lastChangedEpoch",Mn());g(this,"children",new Gp);g(this,"historyBuffer");this.name=n,this.current=t,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new R2(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(n){return this.current}get(){return Vp(this),this.current}set(n,t){var s,o;if(((s=this.isEqual)==null?void 0:s.call(this,this.current,n))??D2(this.current,n))return this.current;ZB(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,Mn(),t??((o=this.computeDiff)==null?void 0:o.call(this,this.current,n,this.lastChangedEpoch,Mn()))??nr),this.lastChangedEpoch=Mn();const r=this.current;return this.current=n,qB(this,r),n}update(n){return this.set(n(this.current))}getDiffSince(n){var t;return Vp(this),n>=this.lastChangedEpoch?Gs:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??nr}}const eU=ai("Atom",()=>JB);function Mt(e,n,t){return new eU(e,n,t)}let GP=!1;function tU(){GP||(GP=!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. // Before @computed @@ -52,10 +52,10 @@ get foo() { getFoo() { return 'foo' } -`))}const Sc=Symbol.for("com.tldraw.state/UNINITIALIZED"),Ai=e=>e===Sc,pv=ai("WithDiff",()=>class{constructor(n,t){this.value=n,this.diff=t}});function vc(e,n){return new pv(e,n)}class nU{constructor(n,t,r){g(this,"lastChangedEpoch",Ao);g(this,"lastTraversedEpoch",Ao);g(this,"lastCheckedEpoch",Ao);g(this,"parentSet",new Gp);g(this,"parents",[]);g(this,"parentEpochs",[]);g(this,"children",new Gp);g(this,"historyBuffer");g(this,"state",Sc);g(this,"error",null);g(this,"computeDiff");g(this,"isEqual");this.name=n,this.derive=t,r!=null&&r.historyLength&&(this.historyBuffer=new R2(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??D2}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(n){var s;const t=this.lastChangedEpoch===Ao,r=Mn();if(!t&&(this.lastCheckedEpoch===r||this.isActivelyListening&&XB()&&this.lastTraversedEpoch=this.lastChangedEpoch?Gs:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??nr}}const M0=ai("Computed",()=>nU);function rU(e={},n,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 M0(t,s.bind(this),e),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[oU]=!0,r}function VP(e={},n,t,r){return r.get?(tU(),sU(e,n,t,r)):rU(e,n,t,r)}function sU(e={},n,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 M0(t,s.bind(this),e),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}const oU="@@__isComputedMethod__@@";function G(){if(arguments.length===1){const e=arguments[0];return(n,t,r)=>VP(e,n,t,r)}else return typeof arguments[0]=="string"?new M0(arguments[0],arguments[1],arguments[2]):VP(void 0,arguments[0],arguments[1],arguments[2])}const F2=1,iU=ai("apiVersion",()=>F2);if(iU!==F2)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");var z2="Expected a function",YP=NaN,aU="[object Symbol]",lU=/^\s+|\s+$/g,cU=/^[-+]0x[0-9a-f]+$/i,uU=/^0b[01]+$/i,dU=/^0o[0-7]+$/i,hU=parseInt,pU=typeof ln=="object"&&ln&&ln.Object===Object&&ln,fU=typeof self=="object"&&self&&self.Object===Object&&self,gU=pU||fU||Function("return this")(),mU=Object.prototype,yU=mU.toString,SU=Math.max,vU=Math.min,Vm=function(){return gU.Date.now()};function xU(e,n,t){var r,s,o,i,a,l,c=0,u=!1,h=!1,p=!0;if(typeof e!="function")throw new TypeError(z2);n=XP(n)||0,Yp(t)&&(u=!!t.leading,h="maxWait"in t,o=h?SU(XP(t.maxWait)||0,n):o,p="trailing"in t?!!t.trailing:p);function f(k){var I=r,_=s;return r=s=void 0,c=k,i=e.apply(_,I),i}function S(k){return c=k,a=setTimeout(y,n),u?f(k):i}function m(k){var I=k-l,_=k-c,T=n-I;return h?vU(T,o-_):T}function x(k){var I=k-l,_=k-c;return l===void 0||I>=n||I<0||h&&_>=o}function y(){var k=Vm();if(x(k))return v(k);a=setTimeout(y,m(k))}function v(k){return a=void 0,p&&r?f(k):(r=s=void 0,i)}function w(){a!==void 0&&clearTimeout(a),c=0,r=l=s=a=void 0}function C(){return a===void 0?i:v(Vm())}function E(){var k=Vm(),I=x(k);if(r=arguments,s=this,l=k,I){if(a===void 0)return S(l);if(h)return a=setTimeout(y,n),f(l)}return a===void 0&&(a=setTimeout(y,n)),i}return E.cancel=w,E.flush=C,E}function wU(e,n,t){var r=!0,s=!0;if(typeof e!="function")throw new TypeError(z2);return Yp(t)&&(r="leading"in t?!!t.leading:r,s="trailing"in t?!!t.trailing:s),xU(e,n,{leading:r,maxWait:n,trailing:s})}function Yp(e){var n=typeof e;return!!e&&(n=="object"||n=="function")}function bU(e){return!!e&&typeof e=="object"}function PU(e){return typeof e=="symbol"||bU(e)&&yU.call(e)==aU}function XP(e){if(typeof e=="number")return e;if(PU(e))return YP;if(Yp(e)){var n=typeof e.valueOf=="function"?e.valueOf():e;e=Yp(n)?n+"":n}if(typeof e!="string")return e===0?e:+e;e=e.replace(lU,"");var t=uU.test(e);return t||dU.test(e)?hU(e.slice(2),t?2:8):cU.test(e)?YP:+e}var CU=wU;const B2=ti(CU);var IU=200,A0="__lodash_hash_undefined__",EU=1/0,_U="[object Function]",kU="[object GeneratorFunction]",TU=/[\\^$.*+?()[\]{}|]/g,MU=/^\[object .+?Constructor\]$/,AU=typeof ln=="object"&&ln&&ln.Object===Object&&ln,jU=typeof self=="object"&&self&&self.Object===Object&&self,j0=AU||jU||Function("return this")();function OU(e,n){var t=e?e.length:0;return!!t&&RU(e,n,0)>-1}function DU(e,n,t,r){for(var s=e.length,o=t+-1;++o-1}function t9(e,n){var t=this.__data__,r=tg(t,e);return r<0?t.push([e,n]):t[r][1]=n,this}Ml.prototype.clear=ZU;Ml.prototype.delete=QU;Ml.prototype.get=JU;Ml.prototype.has=e9;Ml.prototype.set=t9;function Al(e){var n=-1,t=e?e.length:0;for(this.clear();++n=IU){var c=d9(e);if(c)return U2(c);i=!1,s=$U,l=new Xp}else l=a;e:for(;++r{this.frames++,this.started&&(this.frame=requestAnimationFrame(this.recordFrame))})}start(n){this.name=n,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 n=(performance.now()-this.startTime)/1e3,t=n===0?0:Math.floor(this.frames/n),r=t>55?xc.Good:t>30?xc.Mid:xc.Poor,s=r===xc.Mid?"black":"white",o=this.name[0].toUpperCase()+this.name.slice(1);console.debug(`%cPerf%c ${o} %c${t}%c fps`,`color: white; background: ${w9};padding: 2px;border-radius: 3px;`,"font-weight: normal",`font-weight: bold; padding: 2px; background: ${r};color: ${s};`,"font-weight: normal")}isStarted(){return this.started}}function R0(e,n){const t=[];e:for(const r of e){for(const s of t)if(n?n(r,s):r===s)continue e;t.push(r)}return t}function me(e){return e.filter(n=>n!=null)}function Ut(e){return e[e.length-1]}function b9(e,n){let t,r=1/0;for(const s of e){const o=n(s);o{try{return e(...t)}catch(r){throw r instanceof Error&&Error.captureStackTrace&&Error.captureStackTrace(r,n),r}};return n}const Su=()=>{},Ho={ok(e){return{ok:!0,value:e}},err(e){return{ok:!1,error:e}}};function cn(e,n){const t=n&&e&&typeof e=="object"&&n in e?e[n]:e;throw new Error(`Unknown switch case ${t}`)}const Ye=V2((e,n)=>{if(!e)throw new Error(n||"Assertion Error")}),xr=V2((e,n)=>{if(e==null)throw new Error(n??"value must be defined");return e});function Y2(e,n){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(e(...o.latestArgs))}catch(i){o.reject(i)}},n),t.promise);return r.cancel=()=>{t&&clearTimeout(t.timeout)},r}const ZP=new WeakMap;function L0(e,n){if(typeof e!="object"||e===null)return;let t=ZP.get(e);t||(t={tags:{},extras:{}},ZP.set(e,t)),n.tags&&(t.tags={...t.tags,...n.tags}),n.extras&&(t.extras={...t.extras,...n.extras})}async function vs(e,n){return window.fetch(e,{referrerPolicy:"strict-origin-when-cross-origin",...n})}const hl=(e,n)=>{const t=new window.Image(e,n);return t.referrerPolicy="strict-origin-when-cross-origin",t};class ji{static async dataUrlToArrayBuffer(n){return vs(n).then(function(t){return t.arrayBuffer()})}static async blobToDataUrl(n){return await new Promise((t,r)=>{if(n){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsDataURL(n)}})}static async blobToText(n){return await new Promise((t,r)=>{if(n){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsText(n)}})}}function fv(e){let n=0;for(let t=0;te===Sc,pv=ai("WithDiff",()=>class{constructor(n,t){this.value=n,this.diff=t}});function vc(e,n){return new pv(e,n)}class nU{constructor(n,t,r){g(this,"lastChangedEpoch",Ao);g(this,"lastTraversedEpoch",Ao);g(this,"lastCheckedEpoch",Ao);g(this,"parentSet",new Gp);g(this,"parents",[]);g(this,"parentEpochs",[]);g(this,"children",new Gp);g(this,"historyBuffer");g(this,"state",Sc);g(this,"error",null);g(this,"computeDiff");g(this,"isEqual");this.name=n,this.derive=t,r!=null&&r.historyLength&&(this.historyBuffer=new R2(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??D2}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(n){var s;const t=this.lastChangedEpoch===Ao,r=Mn();if(!t&&(this.lastCheckedEpoch===r||this.isActivelyListening&&XB()&&this.lastTraversedEpoch=this.lastChangedEpoch?Gs:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??nr}}const M0=ai("Computed",()=>nU);function rU(e={},n,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 M0(t,s.bind(this),e),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[oU]=!0,r}function VP(e={},n,t,r){return r.get?(tU(),sU(e,n,t,r)):rU(e,n,t,r)}function sU(e={},n,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 M0(t,s.bind(this),e),Object.defineProperty(this,o,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}const oU="@@__isComputedMethod__@@";function G(){if(arguments.length===1){const e=arguments[0];return(n,t,r)=>VP(e,n,t,r)}else return typeof arguments[0]=="string"?new M0(arguments[0],arguments[1],arguments[2]):VP(void 0,arguments[0],arguments[1],arguments[2])}const F2=1,iU=ai("apiVersion",()=>F2);if(iU!==F2)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");var z2="Expected a function",YP=NaN,aU="[object Symbol]",lU=/^\s+|\s+$/g,cU=/^[-+]0x[0-9a-f]+$/i,uU=/^0b[01]+$/i,dU=/^0o[0-7]+$/i,hU=parseInt,pU=typeof ln=="object"&&ln&&ln.Object===Object&&ln,fU=typeof self=="object"&&self&&self.Object===Object&&self,gU=pU||fU||Function("return this")(),mU=Object.prototype,yU=mU.toString,SU=Math.max,vU=Math.min,Vm=function(){return gU.Date.now()};function xU(e,n,t){var r,s,o,i,a,l,c=0,u=!1,h=!1,p=!0;if(typeof e!="function")throw new TypeError(z2);n=XP(n)||0,Yp(t)&&(u=!!t.leading,h="maxWait"in t,o=h?SU(XP(t.maxWait)||0,n):o,p="trailing"in t?!!t.trailing:p);function f(k){var I=r,_=s;return r=s=void 0,c=k,i=e.apply(_,I),i}function S(k){return c=k,a=setTimeout(m,n),u?f(k):i}function y(k){var I=k-l,_=k-c,T=n-I;return h?vU(T,o-_):T}function x(k){var I=k-l,_=k-c;return l===void 0||I>=n||I<0||h&&_>=o}function m(){var k=Vm();if(x(k))return v(k);a=setTimeout(m,y(k))}function v(k){return a=void 0,p&&r?f(k):(r=s=void 0,i)}function w(){a!==void 0&&clearTimeout(a),c=0,r=l=s=a=void 0}function C(){return a===void 0?i:v(Vm())}function E(){var k=Vm(),I=x(k);if(r=arguments,s=this,l=k,I){if(a===void 0)return S(l);if(h)return a=setTimeout(m,n),f(l)}return a===void 0&&(a=setTimeout(m,n)),i}return E.cancel=w,E.flush=C,E}function wU(e,n,t){var r=!0,s=!0;if(typeof e!="function")throw new TypeError(z2);return Yp(t)&&(r="leading"in t?!!t.leading:r,s="trailing"in t?!!t.trailing:s),xU(e,n,{leading:r,maxWait:n,trailing:s})}function Yp(e){var n=typeof e;return!!e&&(n=="object"||n=="function")}function bU(e){return!!e&&typeof e=="object"}function PU(e){return typeof e=="symbol"||bU(e)&&yU.call(e)==aU}function XP(e){if(typeof e=="number")return e;if(PU(e))return YP;if(Yp(e)){var n=typeof e.valueOf=="function"?e.valueOf():e;e=Yp(n)?n+"":n}if(typeof e!="string")return e===0?e:+e;e=e.replace(lU,"");var t=uU.test(e);return t||dU.test(e)?hU(e.slice(2),t?2:8):cU.test(e)?YP:+e}var CU=wU;const B2=ti(CU);var IU=200,A0="__lodash_hash_undefined__",EU=1/0,_U="[object Function]",kU="[object GeneratorFunction]",TU=/[\\^$.*+?()[\]{}|]/g,MU=/^\[object .+?Constructor\]$/,AU=typeof ln=="object"&&ln&&ln.Object===Object&&ln,jU=typeof self=="object"&&self&&self.Object===Object&&self,j0=AU||jU||Function("return this")();function OU(e,n){var t=e?e.length:0;return!!t&&RU(e,n,0)>-1}function DU(e,n,t,r){for(var s=e.length,o=t+-1;++o-1}function t9(e,n){var t=this.__data__,r=tg(t,e);return r<0?t.push([e,n]):t[r][1]=n,this}Ml.prototype.clear=ZU;Ml.prototype.delete=QU;Ml.prototype.get=JU;Ml.prototype.has=e9;Ml.prototype.set=t9;function Al(e){var n=-1,t=e?e.length:0;for(this.clear();++n=IU){var c=d9(e);if(c)return U2(c);i=!1,s=$U,l=new Xp}else l=a;e:for(;++r{this.frames++,this.started&&(this.frame=requestAnimationFrame(this.recordFrame))})}start(n){this.name=n,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 n=(performance.now()-this.startTime)/1e3,t=n===0?0:Math.floor(this.frames/n),r=t>55?xc.Good:t>30?xc.Mid:xc.Poor,s=r===xc.Mid?"black":"white",o=this.name[0].toUpperCase()+this.name.slice(1);console.debug(`%cPerf%c ${o} %c${t}%c fps`,`color: white; background: ${w9};padding: 2px;border-radius: 3px;`,"font-weight: normal",`font-weight: bold; padding: 2px; background: ${r};color: ${s};`,"font-weight: normal")}isStarted(){return this.started}}function R0(e,n){const t=[];e:for(const r of e){for(const s of t)if(n?n(r,s):r===s)continue e;t.push(r)}return t}function me(e){return e.filter(n=>n!=null)}function Ut(e){return e[e.length-1]}function b9(e,n){let t,r=1/0;for(const s of e){const o=n(s);o{try{return e(...t)}catch(r){throw r instanceof Error&&Error.captureStackTrace&&Error.captureStackTrace(r,n),r}};return n}const Su=()=>{},Ho={ok(e){return{ok:!0,value:e}},err(e){return{ok:!1,error:e}}};function cn(e,n){const t=n&&e&&typeof e=="object"&&n in e?e[n]:e;throw new Error(`Unknown switch case ${t}`)}const Ye=V2((e,n)=>{if(!e)throw new Error(n||"Assertion Error")}),xr=V2((e,n)=>{if(e==null)throw new Error(n??"value must be defined");return e});function Y2(e,n){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(e(...o.latestArgs))}catch(i){o.reject(i)}},n),t.promise);return r.cancel=()=>{t&&clearTimeout(t.timeout)},r}const ZP=new WeakMap;function L0(e,n){if(typeof e!="object"||e===null)return;let t=ZP.get(e);t||(t={tags:{},extras:{}},ZP.set(e,t)),n.tags&&(t.tags={...t.tags,...n.tags}),n.extras&&(t.extras={...t.extras,...n.extras})}async function vs(e,n){return window.fetch(e,{referrerPolicy:"strict-origin-when-cross-origin",...n})}const hl=(e,n)=>{const t=new window.Image(e,n);return t.referrerPolicy="strict-origin-when-cross-origin",t};class ji{static async dataUrlToArrayBuffer(n){return vs(n).then(function(t){return t.arrayBuffer()})}static async blobToDataUrl(n){return await new Promise((t,r)=>{if(n){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsDataURL(n)}})}static async blobToText(n){return await new Promise((t,r)=>{if(n){const s=new FileReader;s.onload=()=>t(s.result),s.onerror=o=>r(o),s.onabort=o=>r(o),s.readAsText(n)}})}}function fv(e){let n=0;for(let t=0;t"u"&&(l=p),a>=p||l<=0||a>=l)return-1;o=o.subarray(a,l);let f=-1,S=0,m=0,x="";e:for(;S-1?k+u:w.length-u;x=w.slice(I)}return f>=0&&(f+=a>=0?a:p+a),f}const s=r(n,"IDAT",12);return s>=12?r(n,"acTL",8,s)>=8:!1}const E9=e=>new Uint8Array(e)[3]===44;/*! + */function I9(e){const n=new Uint8Array(e);if(!n||!(typeof Buffer<"u"&&Buffer.isBuffer(n)||n instanceof Uint8Array)||n.length<16||!(n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71&&n[4]===13&&n[5]===10&&n[6]===26&&n[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,h=new TextDecoder,p=o.length;if(typeof l>"u"&&(l=p),a>=p||l<=0||a>=l)return-1;o=o.subarray(a,l);let f=-1,S=0,y=0,x="";e:for(;S-1?k+u:w.length-u;x=w.slice(I)}return f>=0&&(f+=a>=0?a:p+a),f}const s=r(n,"IDAT",12);return s>=12?r(n,"acTL",8,s)>=8:!1}const E9=e=>new Uint8Array(e)[3]===44;/*! * MIT License * Modified code originally from * Copyright (c) 2016 Józef Sokołowski @@ -66,28 +66,28 @@ getFoo() { */const T9=(e,n)=>{let t=~~n^-1;for(let r=0;r>>8;return t^-1},JP=4,eC=4;class as{static isPng(n,t){return n.getUint8(t+0)===137&&n.getUint8(t+1)===80&&n.getUint8(t+2)===78&&n.getUint8(t+3)===71&&n.getUint8(t+4)===13&&n.getUint8(t+5)===10&&n.getUint8(t+6)===26&&n.getUint8(t+7)===10}static getChunkType(n,t){return[String.fromCharCode(n.getUint8(t)),String.fromCharCode(n.getUint8(t+1)),String.fromCharCode(n.getUint8(t+2)),String.fromCharCode(n.getUint8(t+3))].join("")}static readChunks(n,t=0){const r={};if(!as.isPng(n,t))throw new Error("Not a PNG");for(t+=8;t<=n.buffer.byteLength;){const s=t,o=n.getInt32(t);t+=4;const i=as.getChunkType(n,t);if(i==="IDAT"&&r[i]){t+=o+JP+eC;continue}if(i==="IEND")break;r[i]={start:s,dataOffset:t+4,size:o},t+=o+JP+eC}return r}static parsePhys(n,t){return{ppux:n.getUint32(t),ppuy:n.getUint32(t+4),unit:n.getUint8(t+4)}}static findChunk(n,t){return as.readChunks(n)[t]}static setPhysChunk(n,t=1,r){let s=46,o=0;const i=as.findChunk(n,"pHYs");i&&(s=i.start,o=i.size);const a=as.findChunk(n,"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 h=new Uint8Array(l.slice(4,17));c.setInt32(17,T9(h));const p=n.buffer.slice(0,s),f=n.buffer.slice(s+o);return new Blob([p,l,f],r)}}/*! * MIT License: https://github.com/sindresorhus/is-webp/blob/main/license * Copyright (c) Sindre Sorhus (https://sindresorhus.com) - */function M9(e){return!e||e.length<12?!1:e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function A9(e){const n=new Uint8Array(e);return!M9(n)||!n||n.length<21?!1:(n[20]>>1&1)===1}const X2=Object.freeze(["image/svg+xml"]),q2=Object.freeze(["image/jpeg","image/png","image/webp"]),Z2=Object.freeze(["image/gif","image/apng","image/avif"]),$0=Object.freeze([...q2,...X2,...Z2]),Q2=Object.freeze(["video/mp4","video/webm","video/quicktime"]),j9=[...$0,...Q2].join(",");class cs{static loadVideo(n){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=n})}static loadImage(n){return new Promise((t,r)=>{const s=hl();s.onload=()=>t(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.src=n})}static async getVideoSize(n){return cs.usingObjectURL(n,async t=>{const r=await cs.loadVideo(t);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(n){const t=await cs.usingObjectURL(n,cs.loadImage);try{if(n.type==="image/png"){const r=new DataView(await n.arrayBuffer());if(as.isPng(r,0)){const s=as.findChunk(r,"pHYs");if(s){const o=as.parsePhys(r,s.dataOffset);if(o.unit===0&&o.ppux===o.ppuy){const i=Math.max(o.ppux/2834.5,1);return{w:Math.round(t.naturalWidth/i),h:Math.round(t.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:t.naturalWidth,h:t.naturalHeight}}return{w:t.naturalWidth,h:t.naturalHeight}}static async isAnimated(n){return n.type==="image/gif"?k9(await n.arrayBuffer()):n.type==="image/avif"?E9(await n.arrayBuffer()):n.type==="image/webp"?A9(await n.arrayBuffer()):n.type==="image/apng"?I9(await n.arrayBuffer()):!1}static isAnimatedImageType(n){return Z2.includes(n||"")}static isStaticImageType(n){return q2.includes(n||"")}static isVectorImageType(n){return X2.includes(n||"")}static isImageType(n){return $0.includes(n)}static async usingObjectURL(n,t){const r=URL.createObjectURL(n);try{return await t(r)}finally{URL.revokeObjectURL(r)}}}function On(e,n,t){return e+(n-e)*t}function Yr(e=""){let n=0,t=0,r=0,s=0;function o(){const i=n^n<<11;return n=t,t=r,r=s,s^=(s>>>19^i^i>>>8)>>>0,s/4294967296*2}for(let i=0;i="a"&&e<="z")return e.charCodeAt(0)-97+2;if(e>="A"&&e<="Z")return 90-e.charCodeAt(0)+2;throw new Error("Invalid index key head: "+e)}function sT(e){if(e.length!==rT(e.charAt(0)))throw new Error("invalid integer part of index key: "+e)}function nC(e){if(e===void 0)throw Error("n is undefined")}function rC(e){sT(e);const[n,...t]=e.split("");let r=!0;for(let s=t.length-1;r&&s>=0;s--){const o=Jn.indexOf(t[s])+1;o===Jn.length?t[s]="0":(t[s]=Jn.charAt(o),r=!1)}if(r){if(n==="Z")return"a0";if(n==="z")return;const s=String.fromCharCode(n.charCodeAt(0)+1);return s>"a"?t.push("0"):t.pop(),s+t.join("")}else return n+t.join("")}function O9(e){sT(e);const[n,...t]=e.split("");let r=!0;for(let s=t.length-1;r&&s>=0;s--){const o=Jn.indexOf(t[s])-1;o===-1?t[s]=Jn.slice(-1):(t[s]=Jn.charAt(o),r=!1)}if(r){if(n==="a")return"Z"+Jn.slice(-1);if(n==="A")return;const s=String.fromCharCode(n.charCodeAt(0)-1);return s<"Z"?t.push(Jn.slice(-1)):t.pop(),s+t.join("")}else return n+t.join("")}function Fa(e,n){if(n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e.slice(-1)==="0"||n&&n.slice(-1)==="0")throw new Error("trailing zero");if(n){let s=0;for(;(e.charAt(s)||"0")===n.charAt(s);)s++;if(s>0)return n.slice(0,s)+Fa(e.slice(s),n.slice(s))}const t=e?Jn.indexOf(e.charAt(0)):0,r=n!==void 0?Jn.indexOf(n.charAt(0)):Jn.length;if(r-t>1){const s=Math.round(.5*(t+r));return Jn.charAt(s)}else return n&&n.length>1?n.slice(0,1):Jn.charAt(t)+Fa(e.slice(1),void 0)}function wc(e){const n=rT(e.charAt(0));if(n>e.length)throw new Error("invalid index: "+e);return e.slice(0,n)}function mv(e){if(e===nT)throw new Error("invalid index: "+e);const n=wc(e);if(e.slice(n.length).slice(-1)==="0")throw new Error("invalid index: "+e)}function pa(e,n){if(e!==void 0&&mv(e),n!==void 0&&mv(n),e!==void 0&&n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e===void 0&&n===void 0)return tT;if(e===void 0){if(n===void 0)throw Error("b is undefined");const a=wc(n),l=n.slice(a.length);if(a===nT)return a+Fa("",l);if(an.index?1:0}function L9(e,n){return e.id>n.id?1:-1}function N0(e){try{return localStorage.getItem(e)}catch{return null}}function F0(e,n){try{localStorage.setItem(e,n)}catch{}}function $9(){try{localStorage.clear()}catch{}}function iT(e){try{return sessionStorage.getItem(e)}catch{return null}}function z0(e,n){try{sessionStorage.setItem(e,n)}catch{}}function aT(e){try{sessionStorage.removeItem(e)}catch{}}function N9(){try{sessionStorage.clear()}catch{}}const F9=()=>typeof process<"u"&&!1,za=[],z9=60,Lh=Math.ceil(1e3/z9);let Jl,Zm=0,yv=0;const B9=()=>{const e=za.splice(0,za.length);for(const n of e)n()};function lT(){if(Jl)return;const e=Date.now(),n=e-yv;if(Zm+n{Jl=void 0,lT()});return}Jl=requestAnimationFrame(()=>{Jl=void 0,yv=e,Zm=Math.min(Zm+n-Lh,Lh*10),B9()})}let sC=!1;function cT(e){return F9()?(e(),()=>{}):(za.includes(e)||(za.push(e),sC||(sC=!0,yv=Date.now()-Lh-1),lT()),()=>{const n=za.indexOf(e);n>-1&&za.splice(n,1)})}class U9{constructor(){g(this,"timeouts",[]);g(this,"intervals",[]);g(this,"rafs",[])}setTimeout(n,t,...r){const s=window.setTimeout(n,t,r);return this.timeouts.push(s),s}setInterval(n,t,...r){const s=window.setInterval(n,t,r);return this.intervals.push(s),s}requestAnimationFrame(n){const t=window.requestAnimationFrame(n);return this.rafs.push(t),t}dispose(){this.timeouts.forEach(n=>clearTimeout(n)),this.intervals.forEach(n=>clearInterval(n)),this.rafs.forEach(n=>cancelAnimationFrame(n)),this.timeouts.length=0,this.intervals.length=0,this.rafs.length=0}}function H9(e){return e!==null}function K9(){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]:[e=>e&&JSON.parse(JSON.stringify(e)),!1]}const uT=K9(),Be=uT[0];uT[1];const W9=Object.getPrototypeOf(Be({}));var Qm={};const B0={enableLicensing:G9("enableLicensing",{defaults:{all:!0,production:!1}})},dT=kn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),xt={logPreventDefaults:kn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:kn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:kn("logElementRemoves",{defaults:{all:!1}}),debugSvg:kn("debugSvg",{defaults:{all:!1}}),showFps:kn("showFps",{defaults:{all:!1}}),measurePerformance:kn("measurePerformance",{defaults:{all:!1}}),throwToBlob:kn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:kn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:kn("debugCursors",{defaults:{all:!1}}),forceSrgb:kn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:kn("debugGeometry",{defaults:{all:!1}}),hideShapes:kn("hideShapes",{defaults:{all:!1}}),editOnType:kn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const e=Element.prototype.removeChild;oa("element removal logging",()=>{xt.logElementRemoves.get()?Element.prototype.removeChild=function(n){return console.warn("[tldraw] removing child:",n),e.call(this,n)}:Element.prototype.removeChild=e})}function kn(e,{defaults:n,shouldStoreForSession:t=!0}){return hT({name:e,defaults:n,shouldStoreForSession:t})}function G9(e,{defaults:n,shouldStoreForSession:t=!0}){return hT({name:e,defaults:n,shouldStoreForSession:t})}function hT(e){const n=Y9(e),t=e.shouldStoreForSession?V9(e.name):null,r=Mt(`debug:${e.name}`,t??n);return typeof window<"u"&&(e.shouldStoreForSession&&oa(`debug:${e.name}`,()=>{const s=r.get();s===n?aT(`tldraw_debug:${e.name}`):z0(`tldraw_debug:${e.name}`,JSON.stringify(s))}),Object.defineProperty(window,`tldraw${e.name.replace(/^[a-z]/,s=>s.toUpperCase())}`,{get(){return r.get()},set(s){r.set(s)},configurable:!0})),Object.assign(r,e)}function V9(e){try{return JSON.parse(iT(`tldraw_debug:${e}`)??"null")}catch{return null}}function Jm(e){try{return e()}catch{return null}}function Y9(e){switch(Jm(()=>Qm.TLDRAW_ENV)??Jm(()=>Qm.VERCEL_PUBLIC_TLDRAW_ENV)??Jm(()=>Qm.NEXT_PUBLIC_TLDRAW_ENV)??"production"){case"production":return e.defaults.production??e.defaults.all;case"preview":case"staging":return e.defaults.staging??e.defaults.all;default:return e.defaults.development??e.defaults.all}}class $h{constructor(n){g(this,"nextValue");g(this,"diff");this.previousValue=n}get(){var r,s,o,i;const n=((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(!(n===0&&t===0))return{value:this.nextValue,diff:this.diff}}_add(n,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(n),this.diff??(this.diff={}),t?(r=this.diff.removed)==null||r.delete(n):((s=this.diff).added??(s.added=new Set),this.diff.added.add(n))}add(n){var s,o,i;const t=this.previousValue.has(n);if(t)return((o=(s=this.diff)==null?void 0:s.removed)==null?void 0:o.has(n))?this._add(n,t):void 0;(i=this.nextValue)!=null&&i.has(n)||this._add(n,t)}_remove(n,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(n),this.diff??(this.diff={}),t?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(n)):(s=this.diff.added)==null||s.delete(n)}remove(n){var s,o,i,a;const t=this.previousValue.has(n);if(!t)return((o=(s=this.diff)==null?void 0:s.added)==null?void 0:o.has(n))?this._remove(n,t):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(n)||this._remove(n,t)}}let Ku=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((n,t)=>(t&=63,t<36?n+=t.toString(36):t<62?n+=(t-26).toString(36).toUpperCase():t>62?n+="-":n+="_",n),"");class rg{constructor(n,t){g(this,"createDefaultProperties");g(this,"validator");g(this,"ephemeralKeys");g(this,"ephemeralKeySet");g(this,"scope");g(this,"isInstance",n=>(n==null?void 0:n.typeName)===this.typeName);this.typeName=n,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 Hn(t.ephemeralKeys))o&&r.add(s);this.ephemeralKeySet=r}create(n){const t={...this.createDefaultProperties(),id:this.createId()};for(const[r,s]of Object.entries(n))s!==void 0&&(t[r]=s);return t.typeName=this.typeName,t}clone(n){return{...Be(n),id:this.createId()}}createId(n){return this.typeName+":"+(n??Ku())}createCustomId(n){return this.typeName+":"+n}parseId(n){if(!this.isId(n))throw new Error(`ID "${n}" is not a valid ID for type "${this.typeName}"`);return n.slice(this.typeName.length+1)}isId(n){if(!n)return!1;for(let t=0;t({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function qp(){return{added:{},updated:{},removed:{}}}function Sv(e){const n={added:e.removed,removed:e.added,updated:{}};for(const[t,r]of Object.values(e.updated))n.updated[t.id]=[r,t];return n}function pT(e){return Object.keys(e.added).length===0&&Object.keys(e.updated).length===0&&Object.keys(e.removed).length===0}function U0(e){const n={added:{},removed:{},updated:{}};return Gc(n,e),n}function Gc(e,n){for(const t of n){for(const[r,s]of Hn(t.added))if(e.removed[r]){const o=e.removed[r];delete e.removed[r],o!==s&&(e.updated[r]=[o,s])}else e.added[r]=s;for(const[r,[s,o]]of Hn(t.updated)){if(e.added[r]){e.added[r]=o,delete e.updated[r],delete e.removed[r];continue}if(e.updated[r]){e.updated[r]=[e.updated[r][0],o],delete e.removed[r];continue}e.updated[r]=t.updated[r],delete e.removed[r]}for(const[r,s]of Hn(t.removed))e.added[r]?delete e.added[r]:e.updated[r]?(e.removed[r]=e.updated[r][0],delete e.updated[r]):e.removed[r]=s}}var Zp={exports:{}};Zp.exports;(function(e,n){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]",h="[object Date]",p="[object Error]",f="[object Function]",S="[object GeneratorFunction]",m="[object Map]",x="[object Number]",y="[object Null]",v="[object Object]",w="[object Promise]",C="[object Proxy]",E="[object RegExp]",k="[object Set]",I="[object String]",_="[object Symbol]",T="[object Undefined]",M="[object WeakMap]",D="[object ArrayBuffer]",$="[object DataView]",j="[object Float32Array]",O="[object Float64Array]",R="[object Int8Array]",K="[object Int16Array]",B="[object Int32Array]",z="[object Uint8Array]",W="[object Uint8ClampedArray]",Y="[object Uint16Array]",q="[object Uint32Array]",ae=/[\\^$.*+?()[\]{}|]/g,fe=/^\[object .+?Constructor\]$/,we=/^(?:0|[1-9]\d*)$/,J={};J[j]=J[O]=J[R]=J[K]=J[B]=J[z]=J[W]=J[Y]=J[q]=!0,J[a]=J[l]=J[D]=J[u]=J[$]=J[h]=J[p]=J[f]=J[m]=J[x]=J[v]=J[E]=J[k]=J[I]=J[M]=!1;var Ue=typeof ln=="object"&&ln&&ln.Object===Object&&ln,Oe=typeof self=="object"&&self&&self.Object===Object&&self,tt=Ue||Oe||Function("return this")(),Ae=n&&!n.nodeType&&n,ot=Ae&&!0&&e&&!e.nodeType&&e,Ne=ot&&ot.exports===Ae,Vn=Ne&&Ue.process,Nt=function(){try{return Vn&&Vn.binding&&Vn.binding("util")}catch{}}(),_n=Nt&&Nt.isTypedArray;function St(A,L){for(var V=-1,ee=A==null?0:A.length,qe=0,ge=[];++V-1}function HL(A,L){var V=this.__data__,ee=hd(V,A);return ee<0?(++this.size,V.push([A,L])):V[ee][1]=L,this}As.prototype.clear=FL,As.prototype.delete=zL,As.prototype.get=BL,As.prototype.has=UL,As.prototype.set=HL;function mi(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L_t))return!1;var it=ge.get(A);if(it&&ge.get(L))return it==L;var Yn=-1,jr=!0,Qt=V&o?new dd:void 0;for(ge.set(A,L),ge.set(L,A);++Yn<_t;){var pr=A[Yn],fr=L[Yn];if(ee)var So=ft?ee(fr,pr,Yn,L,A,ge):ee(pr,fr,Yn,A,L,ge);if(So!==void 0){if(So)continue;jr=!1;break}if(Qt){if(!Ms(L,function(js,Si){if(!SL(Qt,Si)&&(pr===js||qe(pr,js,V,ee,ge)))return Qt.push(Si)})){jr=!1;break}}else if(!(pr===fr||qe(pr,fr,V,ee,ge))){jr=!1;break}}return ge.delete(A),ge.delete(L),jr}function l3(A,L,V,ee,qe,ge,ft){switch(V){case $:if(A.byteLength!=L.byteLength||A.byteOffset!=L.byteOffset)return!1;A=A.buffer,L=L.buffer;case D:return!(A.byteLength!=L.byteLength||!ge(new T1(A),new T1(L)));case u:case h:case x:return $1(+A,+L);case p:return A.name==L.name&&A.message==L.message;case E:case I:return A==L+"";case m:var _t=xL;case k:var Ft=ee&s;if(_t||(_t=bL),A.size!=L.size&&!Ft)return!1;var it=ft.get(A);if(it)return it==L;ee|=o,ft.set(A,L);var Yn=R1(_t(A),_t(L),ee,qe,ge,ft);return ft.delete(A),Yn;case _:if(Zg)return Zg.call(A)==Zg.call(L)}return!1}function c3(A,L,V,ee,qe,ge){var ft=V&s,_t=L1(A),Ft=_t.length,it=L1(L),Yn=it.length;if(Ft!=Yn&&!ft)return!1;for(var jr=Ft;jr--;){var Qt=_t[jr];if(!(ft?Qt in L:Jr.call(L,Qt)))return!1}var pr=ge.get(A);if(pr&&ge.get(L))return pr==L;var fr=!0;ge.set(A,L),ge.set(L,A);for(var So=ft;++jr-1&&A%1==0&&A-1&&A%1==0&&A<=i}function z1(A){var L=typeof A;return A!=null&&(L=="object"||L=="function")}function Bl(A){return A!=null&&typeof A=="object"}var B1=_n?go(_n):i3;function x3(A){return S3(A)?n3(A):a3(A)}function w3(){return[]}function b3(){return!1}e.exports=v3})(Zp,Zp.exports);var X9=Zp.exports;const q9=ti(X9);function Z9(e){if(e.length===0)return new Set;const n=e[0],t=e.slice(1),r=new Set;for(const s of n)t.every(o=>o.has(s))&&r.add(s);return r}function Q9(e,n){const t={};for(const r of n)e.has(r)||(t.added??(t.added=new Set),t.added.add(r));for(const r of e)n.has(r)||(t.removed??(t.removed=new Set),t.removed.add(r));return t.added||t.removed?t:void 0}function oC(e,n){for(const[t,r]of Object.entries(e)){const s=r,o=n[t];if("eq"in s&&o!==s.eq||"neq"in s&&o===s.neq||"gt"in s&&(typeof o!="number"||o<=s.gt))return!1}return!0}function iC(e,n,t){const r=Object.fromEntries(Object.keys(t).map(s=>[s,new Set]));for(const[s,o]of Object.entries(t))if("eq"in o){const a=e.index(n,s).get().get(o.eq);if(a)for(const l of a)r[s].add(l)}else if("neq"in o){const i=e.index(n,s);for(const[a,l]of i.get())if(a!==o.neq)for(const c of l)r[s].add(c)}else if("gt"in o){const i=e.index(n,s);for(const[a,l]of i.get())if(a>o.gt)for(const c of l)r[s].add(c)}return Z9(Object.values(r))}class J9{constructor(n,t){g(this,"indexCache",new Map);g(this,"historyCache",new Map);this.atoms=n,this.history=t}filterHistory(n){if(this.historyCache.has(n))return this.historyCache.get(n);const t=G("filterHistory:"+n,(r,s)=>{if(Ai(r))return this.history.get();const o=this.history.getDiffSince(s);if(o===nr)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const u of o){for(const h of gt(u.added))if(h.typeName===n)if(i.removed[h.id]){const p=i.removed[h.id];delete i.removed[h.id],l--,p!==h&&(i.updated[h.id]=[p,h],c++)}else i.added[h.id]=h,a++;for(const[h,p]of gt(u.updated))p.typeName===n&&(i.added[p.id]?i.added[p.id]=p:i.updated[p.id]?i.updated[p.id]=[i.updated[p.id][0],p]:(i.updated[p.id]=[h,p],c++));for(const h of gt(u.removed))h.typeName===n&&(i.added[h.id]?(delete i.added[h.id],a--):i.updated[h.id]?(i.removed[h.id]=i.updated[h.id][0],delete i.updated[h.id],c--,l++):(i.removed[h.id]=h,l++))}return a||l||c?vc(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(n,t),t}index(n,t){const r=n+":"+t;if(this.indexCache.has(r))return this.indexCache.get(r);const s=this.__uncached_createIndex(n,t);return this.indexCache.set(r,s),s}__uncached_createIndex(n,t){const r=this.filterHistory(n),s=()=>{r.get();const o=new Map;for(const i of gt(this.atoms.get())){const a=i.get();if(a.typeName===n){const l=a[t];o.has(l)||o.set(l,new Set),o.get(l).add(a.id)}}return o};return G("index:"+n+":"+t,(o,i)=>{if(Ai(o))return s();const a=r.getDiffSince(i);if(a===nr)return s();const l=new Map,c=(f,S)=>{let m=l.get(f);m||(m=new $h(o.get(f)??new Set)),m.add(S),l.set(f,m)},u=(f,S)=>{let m=l.get(f);m||(m=new $h(o.get(f)??new Set)),m.remove(S),l.set(f,m)};for(const f of a){for(const S of gt(f.added))if(S.typeName===n){const m=S[t];c(m,S.id)}for(const[S,m]of gt(f.updated))if(m.typeName===n){const x=S[t],y=m[t];x!==y&&(u(x,m.id),c(y,m.id))}for(const S of gt(f.removed))if(S.typeName===n){const m=S[t];u(m,S.id)}}let h,p;for(const[f,S]of l){const m=S.get();m&&(h||(h=new Map(o)),p||(p=new Map),m.value.size===0?h.delete(f):h.set(f,m.value),p.set(f,m.diff))}return h&&p?vc(h,p):o},{historyLength:100})}record(n,t=()=>({}),r="record:"+n+(t?":"+t.toString():"")){const s=this.ids(n,t,r);return G(r,()=>{var o;for(const i of s.get())return(o=this.atoms.get()[i])==null?void 0:o.get()})}records(n,t=()=>({}),r="records:"+n+(t?":"+t.toString():"")){const s=this.ids(n,t,"ids:"+r);return G(r,()=>[...s.get()].map(o=>{const i=this.atoms.get()[o];if(!i)throw new Error("no atom found for record id: "+o);return i.get()}))}ids(n,t=()=>({}),r="ids:"+n+(t?":"+t.toString():"")){const s=this.filterHistory(n),o=()=>{s.get();const l=t();return Object.keys(l).length===0?new Set(gt(this.atoms.get()).flatMap(c=>{const u=c.get();return u.typeName===n?u.id:[]})):iC(this,n,l)},i=l=>{const c=o(),u=Q9(l,c);return u?vc(c,u):l},a=G("ids_query:"+r,t,{isEqual:q9});return G("query:"+r,(l,c)=>{const u=a.get();if(Ai(l))return o();if(cs[o].get())}}class e7{constructor(n){g(this,"_beforeCreateHandlers",{});g(this,"_afterCreateHandlers",{});g(this,"_beforeChangeHandlers",{});g(this,"_afterChangeHandlers",{});g(this,"_beforeDeleteHandlers",{});g(this,"_afterDeleteHandlers",{});g(this,"_operationCompleteHandlers",[]);g(this,"_isEnabled",!0);this.store=n}isEnabled(){return this._isEnabled}setIsEnabled(n){this._isEnabled=n}handleBeforeCreate(n,t){if(!this._isEnabled)return n;const r=this._beforeCreateHandlers[n.typeName];if(r){let s=n;for(const o of r)s=o(s,t);return s}return n}handleAfterCreate(n,t){if(!this._isEnabled)return;const r=this._afterCreateHandlers[n.typeName];if(r)for(const s of r)s(n,t)}handleBeforeChange(n,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(n,o,r);return o}return t}handleAfterChange(n,t,r){if(!this._isEnabled)return;const s=this._afterChangeHandlers[t.typeName];if(s)for(const o of s)o(n,t,r)}handleBeforeDelete(n,t){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[n.typeName];if(r){for(const s of r)if(s(n,t)===!1)return!1}return!0}handleAfterDelete(n,t){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[n.typeName];if(r)for(const s of r)s(n,t)}handleOperationComplete(n){if(this._isEnabled)for(const t of this._operationCompleteHandlers)t(n)}register(n){const t=[];for(const[r,s]of Object.entries(n))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(n,t){return this._beforeCreateHandlers[n]||(this._beforeCreateHandlers[n]=[]),this._beforeCreateHandlers[n].push(t),()=>vi(this._beforeCreateHandlers[n],t)}registerAfterCreateHandler(n,t){return this._afterCreateHandlers[n]||(this._afterCreateHandlers[n]=[]),this._afterCreateHandlers[n].push(t),()=>vi(this._afterCreateHandlers[n],t)}registerBeforeChangeHandler(n,t){return this._beforeChangeHandlers[n]||(this._beforeChangeHandlers[n]=[]),this._beforeChangeHandlers[n].push(t),()=>vi(this._beforeChangeHandlers[n],t)}registerAfterChangeHandler(n,t){return this._afterChangeHandlers[n]||(this._afterChangeHandlers[n]=[]),this._afterChangeHandlers[n].push(t),()=>vi(this._afterChangeHandlers[n],t)}registerBeforeDeleteHandler(n,t){return this._beforeDeleteHandlers[n]||(this._beforeDeleteHandlers[n]=[]),this._beforeDeleteHandlers[n].push(t),()=>vi(this._beforeDeleteHandlers[n],t)}registerAfterDeleteHandler(n,t){return this._afterDeleteHandlers[n]||(this._afterDeleteHandlers[n]=[]),this._afterDeleteHandlers[n].push(t),()=>vi(this._afterDeleteHandlers[n],t)}registerOperationCompleteHandler(n){return this._operationCompleteHandlers.push(n),()=>vi(this._operationCompleteHandlers,n)}}function vi(e,n){const t=e.indexOf(n);t>=0&&e.splice(t,1)}class H0{constructor(n){g(this,"id");g(this,"atoms",Mt("store_atoms",{}));g(this,"history",Mt("history",0,{historyLength:1e3}));g(this,"query",new J9(this.atoms,this.history));g(this,"listeners",new Set);g(this,"historyAccumulator",new n7);g(this,"historyReactor");g(this,"cancelHistoryReactor",()=>{});g(this,"schema");g(this,"props");g(this,"scopedTypes");g(this,"sideEffects",new e7(this));g(this,"put",(n,t)=>{this.atomic(()=>{const r={},s={},o=this.atoms.__unsafe__getWithoutCapture();let i=null,a,l=!1;const c=this.isMergingRemoteChanges?"remote":"user";for(let u=0,h=n.length;u{this.atomic(()=>{const t=new Set,r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const o of n){const i=this.atoms.__unsafe__getWithoutCapture()[o];i&&this.sideEffects.handleBeforeDelete(i.get(),r)===!1&&t.add(o)}let s;this.atoms.update(o=>{let i;for(const a of n){if(t.has(a)||!(a in o))continue;i||(i={...o}),s||(s={}),delete i[a];const l=o[a].get();s[a]=l,this.addDiffForAfterEvent(l,null)}return i??o}),s&&this.updateHistory({added:{},updated:{},removed:s})})});g(this,"get",n=>{var t;return(t=this.atoms.get()[n])==null?void 0:t.get()});g(this,"unsafeGetWithoutCapture",n=>{var t;return(t=this.atoms.__unsafe__getWithoutCapture()[n])==null?void 0:t.__unsafe__getWithoutCapture()});g(this,"serialize",(n="document")=>{const t={};for(const[r,s]of Hn(this.atoms.get())){const o=s.get();(n==="all"||this.scopedTypes[n].has(o.typeName))&&(t[r]=o)}return t});g(this,"allRecords",()=>gt(this.atoms.get()).map(n=>n.get()));g(this,"clear",()=>{this.remove(tC(this.atoms.get()))});g(this,"update",(n,t)=>{const r=this.atoms.get()[n];if(!r){console.error(`Record ${n} not found. This is probably an error`);return}this.put([t(r.__unsafe__getWithoutCapture())])});g(this,"has",n=>!!this.atoms.get()[n]);g(this,"listen",(n,t)=>{this._flushHistory();const r={onHistory:n,filters:{source:(t==null?void 0:t.source)??"all",scope:(t==null?void 0:t.scope)??"all"}};return this.listeners.add(r),this.historyReactor.scheduler.isActivelyListening||this.historyReactor.start(),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}});g(this,"isMergingRemoteChanges",!1);g(this,"mergeRemoteChanges",n=>{if(this.isMergingRemoteChanges)return n();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.isMergingRemoteChanges=!0,gs(n)}finally{this.isMergingRemoteChanges=!1}});g(this,"createComputedCache",(n,t,r)=>{const s=new eo;return{get:o=>{const i=this.atoms.get()[o];if(i)return s.get(i,()=>{const a=r?G(i.name+":equals",()=>i.get(),{isEqual:r}):i;return G(n+":"+o,()=>t(a.get()))}).get()}}});g(this,"createSelectedComputedCache",(n,t,r)=>{const s=new eo;return{get:o=>{const i=this.atoms.get()[o];if(i)return s.get(i,()=>{const a=G(n+":"+o+":selector",()=>t(i.get()));return G(n+":"+o,()=>r(a.get()))}).get()}}});g(this,"_integrityChecker");g(this,"_isPossiblyCorrupted",!1);g(this,"pendingAfterEvents",null);g(this,"_isInAtomicOp",!1);const{initialData:t,schema:r,id:s}=n;this.id=s??Ku(),this.schema=r,this.props=n.props,t&&this.atoms.set(J2(Hn(t).map(([o,i])=>[o,Mt("atom:"+o,this.schema.validateRecord(this,i,"initialize",null))]))),this.historyReactor=GB("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:o=>this.cancelHistoryReactor=cT(o)}),this.scopedTypes={document:new Set(gt(this.schema.types).filter(o=>o.scope==="document").map(o=>o.typeName)),session:new Set(gt(this.schema.types).filter(o=>o.scope==="session").map(o=>o.typeName)),presence:new Set(gt(this.schema.types).filter(o=>o.scope==="presence").map(o=>o.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){const n=this.historyAccumulator.flush();for(const{changes:t,source:r}of n){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(n,t){const r={added:Wc(n.added,(s,o)=>this.scopedTypes[t].has(o.typeName)),updated:Wc(n.updated,(s,o)=>this.scopedTypes[t].has(o[1].typeName)),removed:Wc(n.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(n){this.historyAccumulator.add({changes:n,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,n)}validate(n){this.allRecords().forEach(t=>this.schema.validateRecord(this,t,n,null))}getStoreSnapshot(n="document"){return{store:this.serialize(n),schema:this.schema.serialize()}}getSnapshot(n="document"){return console.warn("[tldraw] `Store.getSnapshot` is deprecated and will be removed in a future release. Use `getSnapshot` from the `tldraw` package instead."),this.getStoreSnapshot(n)}migrateSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);return{store:t.value,schema:this.schema.serialize()}}loadStoreSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);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)}}loadSnapshot(n){console.warn("[tldraw] `Store.loadSnapshot` is deprecated and will be removed in a future release. Use `loadSnapshot` from the 'tldraw' package instead."),this.loadStoreSnapshot(n)}extractingChanges(n){const t=[],r=this.historyAccumulator.addInterceptor(s=>t.push(s.changes));try{return gs(n),U0(t)}finally{r()}}applyDiff(n,{runCallbacks:t=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const s=gt(n.added);for(const[i,a]of gt(n.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[h,p]of Object.entries(a))l.ephemeralKeySet.has(h)||Object.is(p,$n(c,h))||(u||(u={...c}),u[h]=p);u&&s.push(u)}else s.push(a)}const o=tC(n.removed);s.length&&this.put(s),o.length&&this.remove(o)},t)}ensureStoreIsUsable(){this.atomic(()=>{var n;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(n=this._integrityChecker)==null||n.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(n,t){if(Ye(this.pendingAfterEvents,"must be in event operation"),n===t||(n&&t&&Ye(n.id===t.id),!n&&!t))return;const r=(n||t).id,s=this.pendingAfterEvents.get(r);s?s.after=t:this.pendingAfterEvents.set(r,{before:n,after:t})}flushAtomicCallbacks(){let n=0;const t=this.isMergingRemoteChanges?"remote":"user";for(;this.pendingAfterEvents;){const r=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(n++,n>100)throw new Error("Maximum store update depth exceeded, bailing out");for(const{before:s,after:o}of r.values())s&&o?this.sideEffects.handleAfterChange(s,o,t):s&&!o?this.sideEffects.handleAfterDelete(s,t):!s&&o&&this.sideEffects.handleAfterCreate(o,t);this.pendingAfterEvents||this.sideEffects.handleOperationComplete(t)}}}atomic(n,t=!0){return gs(()=>{if(this._isInAtomicOp)return this.pendingAfterEvents||(this.pendingAfterEvents=new Map),n();this.pendingAfterEvents=new Map;const r=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(t??r),this._isInAtomicOp=!0;try{const s=n();return this.flushAtomicCallbacks(),s}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(r),this._isInAtomicOp=!1}})}addHistoryInterceptor(n){return this.historyAccumulator.addInterceptor(t=>n(t,this.isMergingRemoteChanges?"remote":"user"))}}function t7(e){if(e.length===0)return[];const n=[];let t=[e[0]],r;for(let s=1,o=e.length;s({source:s[0].source,changes:U0(s.map(o=>o.changes))}))}class n7{constructor(){g(this,"_history",[]);g(this,"_interceptors",new Set)}addInterceptor(n){return this._interceptors.add(n),()=>{this._interceptors.delete(n)}}add(n){this._history.push(n);for(const t of this._interceptors)t(n)}flush(){const n=t7(this._history);return this._history=[],n}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function r7(e,n,t){const r=new eo;return{get(s,o){return r.get(s,()=>(s instanceof H0?s:s.store).createComputedCache(e,l=>n(s,l),t)).get(o)}}}function s7(e){const n=[];for(let t=e.length-1;t>=0;t--){const r=e[t];if("id"in r)n.unshift(r);else{const s=r.dependsOn,o=n[0];o&&(n[0]={...o,dependsOn:s.concat(o.dependsOn??[])})}}return n}function Ja({sequence:e,sequenceId:n,retroactive:t=!0}){const r={sequenceId:n,retroactive:t,sequence:s7(e)};return fT(r),r}function Wn(e,n){return Object.fromEntries(Hn(n).map(([t,r])=>[t,`${e}/${r}`]))}function dr(e){const n=e.sequenceId;return Ja({sequenceId:n,retroactive:e.retroactive??!0,sequence:e.sequence.map(t=>"id"in t?{...t,scope:"record",filter:r=>{var s,o;return r.typeName===e.recordType&&(((s=t.filter)==null?void 0:s.call(t,r))??!0)&&(((o=e.filter)==null?void 0:o.call(e,r))??!0)}}:t)})}function o7(e){const n=new Map(e.map(o=>[o.id,o])),t=new Set,r=[];function s(o){Ye(!t.has(o.id),`Circular dependency in migrations: ${o.id}`),t.add(o.id);const{version:i,sequenceId:a}=Qp(o.id),l=n.get(`${a}/${i-1}`);if(l&&s(l),o.dependsOn)for(const c of o.dependsOn){const u=n.get(c);u&&s(u)}n.delete(o.id),r.push(o)}for(const o of n.values())s(o);return r}function Qp(e){const[n,t]=e.split("/");return{sequenceId:n,version:parseInt(t)}}function aC(e,n){n&&Ye(e.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${e}'`),Ye(e.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${e}'`)}function fT(e){if(Ye(!e.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${e.sequenceId}`),Ye(e.sequenceId.length,"sequenceId must be a non-empty string"),e.sequence.length===0)return;aC(e.sequence[0].id,e.sequenceId);let n=Qp(e.sequence[0].id).version;Ye(n===1,`Expected the first migrationId to be '${e.sequenceId}/1' but got '${e.sequence[0].id}'`);for(let t=1;t(e.IncompatibleSubtype="incompatible-subtype",e.UnknownType="unknown-type",e.TargetVersionTooNew="target-version-too-new",e.TargetVersionTooOld="target-version-too-old",e.MigrationError="migration-error",e.UnrecognizedSubtype="unrecognized-subtype",e))(bo||{});function i7(e){if(e.schemaVersion>2||e.schemaVersion<1)return Ho.err("Bad schema version");if(e.schemaVersion===2)return Ho.ok(e);const n={schemaVersion:2,sequences:{}};for(const[t,r]of Object.entries(e.recordVersions))if(n.sequences[`com.tldraw.${t}`]=r.version,"subTypeKey"in r)for(const[s,o]of Object.entries(r.subTypeVersions))n.sequences[`com.tldraw.${t}.${s}`]=o;return Ho.ok(n)}class K0{constructor(n,t){g(this,"migrations",{});g(this,"sortedMigrations");var s;this.types=n,this.options=t;for(const o of t.migrations??[])Ye(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),fT(o),this.migrations[o.sequenceId]=o;const r=Object.values(this.migrations).flatMap(o=>o.sequence);this.sortedMigrations=o7(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);Ye(a,`Migration '${o.id}' depends on missing migration '${i}'`)}}static create(n,t){return new K0(n,t??{})}validateRecord(n,t,r,s){try{const o=$n(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:n,record:t,phase:r,recordBefore:s,error:o});throw o}}getMigrationsSince(n){const t=i7(n);if(!t.ok)return t;const r=t.value,s=new Set(Object.keys(r.sequences).filter(i=>this.migrations[i]));for(const i in this.migrations)r.sequences[i]===void 0&&this.migrations[i].retroactive&&s.add(i);if(s.size===0)return Ho.ok([]);const o=new Set;for(const i of s){const a=r.sequences[i];if(typeof a!="number"&&this.migrations[i].retroactive||a===0){for(const u of this.migrations[i].sequence)o.add(u.id);continue}const l=`${i}/${a}`,c=this.migrations[i].sequence.findIndex(u=>u.id===l);if(c===-1)return Ho.err("Incompatible schema?");for(const u of this.migrations[i].sequence.slice(c+1))o.add(u.id)}return Ho.ok(this.sortedMigrations.filter(({id:i})=>o.has(i)))}migratePersistedRecord(n,t,r="up"){const s=this.getMigrationsSince(t);if(!s.ok)return console.error("Error migrating record",s.error),{type:"error",reason:bo.MigrationError};let o=s.value;if(o.length===0)return{type:"success",value:n};if(o.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?bo.TargetVersionTooOld:bo.TargetVersionTooNew};if(r==="down"){if(!o.every(i=>i.down))return{type:"error",reason:bo.TargetVersionTooOld};o=o.slice().reverse()}n=Be(n);try{for(const i of o){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(n):!0))continue;const l=i[r](n);l&&(n=Be(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:bo.MigrationError}}return{type:"success",value:n}}migrateStoreSnapshot(n){let{store:t}=n;const r=this.getMigrationsSince(n.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:bo.MigrationError};const s=r.value;if(s.length===0)return{type:"success",value:t};t=Be(t);try{for(const o of s)if(o.scope==="record")for(const[i,a]of Object.entries(t)){if(!(o.filter?o.filter(a):!0))continue;const c=o.up(a);c&&(t[i]=Be(c))}else if(o.scope==="store"){const i=o.up(t);i&&(t=Be(i))}else cn(o)}catch(o){return console.error("Error migrating store",o),{type:"error",reason:bo.MigrationError}}return{type:"success",value:t}}createIntegrityChecker(n){var t,r;return((r=(t=this.options).createIntegrityChecker)==null?void 0:r.call(t,n))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n,sequence:t})=>[n,t.length?Qp(t.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n})=>[n,0]))}}getType(n){const t=$n(this.types,n);return Ye(t,"record type does not exists"),t}}function a7(e){if(!e.length)return null;let n="";for(const t of e)typeof t=="number"?n+=`.${t}`:t.startsWith("(")?n.endsWith(")")?n=`${n.slice(0,-1)}, ${t.slice(1)}`:n+=t:n+=`.${t}`;return n=n.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),n.startsWith(".")?n.slice(1):n}class Ee extends Error{constructor(t,r=[]){const s=a7(r),o=t.split(` + */function M9(e){return!e||e.length<12?!1:e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function A9(e){const n=new Uint8Array(e);return!M9(n)||!n||n.length<21?!1:(n[20]>>1&1)===1}const X2=Object.freeze(["image/svg+xml"]),q2=Object.freeze(["image/jpeg","image/png","image/webp"]),Z2=Object.freeze(["image/gif","image/apng","image/avif"]),$0=Object.freeze([...q2,...X2,...Z2]),Q2=Object.freeze(["video/mp4","video/webm","video/quicktime"]),j9=[...$0,...Q2].join(",");class cs{static loadVideo(n){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=n})}static loadImage(n){return new Promise((t,r)=>{const s=hl();s.onload=()=>t(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.src=n})}static async getVideoSize(n){return cs.usingObjectURL(n,async t=>{const r=await cs.loadVideo(t);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(n){const t=await cs.usingObjectURL(n,cs.loadImage);try{if(n.type==="image/png"){const r=new DataView(await n.arrayBuffer());if(as.isPng(r,0)){const s=as.findChunk(r,"pHYs");if(s){const o=as.parsePhys(r,s.dataOffset);if(o.unit===0&&o.ppux===o.ppuy){const i=Math.max(o.ppux/2834.5,1);return{w:Math.round(t.naturalWidth/i),h:Math.round(t.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:t.naturalWidth,h:t.naturalHeight}}return{w:t.naturalWidth,h:t.naturalHeight}}static async isAnimated(n){return n.type==="image/gif"?k9(await n.arrayBuffer()):n.type==="image/avif"?E9(await n.arrayBuffer()):n.type==="image/webp"?A9(await n.arrayBuffer()):n.type==="image/apng"?I9(await n.arrayBuffer()):!1}static isAnimatedImageType(n){return Z2.includes(n||"")}static isStaticImageType(n){return q2.includes(n||"")}static isVectorImageType(n){return X2.includes(n||"")}static isImageType(n){return $0.includes(n)}static async usingObjectURL(n,t){const r=URL.createObjectURL(n);try{return await t(r)}finally{URL.revokeObjectURL(r)}}}function On(e,n,t){return e+(n-e)*t}function Yr(e=""){let n=0,t=0,r=0,s=0;function o(){const i=n^n<<11;return n=t,t=r,r=s,s^=(s>>>19^i^i>>>8)>>>0,s/4294967296*2}for(let i=0;i="a"&&e<="z")return e.charCodeAt(0)-97+2;if(e>="A"&&e<="Z")return 90-e.charCodeAt(0)+2;throw new Error("Invalid index key head: "+e)}function sT(e){if(e.length!==rT(e.charAt(0)))throw new Error("invalid integer part of index key: "+e)}function nC(e){if(e===void 0)throw Error("n is undefined")}function rC(e){sT(e);const[n,...t]=e.split("");let r=!0;for(let s=t.length-1;r&&s>=0;s--){const o=Jn.indexOf(t[s])+1;o===Jn.length?t[s]="0":(t[s]=Jn.charAt(o),r=!1)}if(r){if(n==="Z")return"a0";if(n==="z")return;const s=String.fromCharCode(n.charCodeAt(0)+1);return s>"a"?t.push("0"):t.pop(),s+t.join("")}else return n+t.join("")}function O9(e){sT(e);const[n,...t]=e.split("");let r=!0;for(let s=t.length-1;r&&s>=0;s--){const o=Jn.indexOf(t[s])-1;o===-1?t[s]=Jn.slice(-1):(t[s]=Jn.charAt(o),r=!1)}if(r){if(n==="a")return"Z"+Jn.slice(-1);if(n==="A")return;const s=String.fromCharCode(n.charCodeAt(0)-1);return s<"Z"?t.push(Jn.slice(-1)):t.pop(),s+t.join("")}else return n+t.join("")}function Fa(e,n){if(n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e.slice(-1)==="0"||n&&n.slice(-1)==="0")throw new Error("trailing zero");if(n){let s=0;for(;(e.charAt(s)||"0")===n.charAt(s);)s++;if(s>0)return n.slice(0,s)+Fa(e.slice(s),n.slice(s))}const t=e?Jn.indexOf(e.charAt(0)):0,r=n!==void 0?Jn.indexOf(n.charAt(0)):Jn.length;if(r-t>1){const s=Math.round(.5*(t+r));return Jn.charAt(s)}else return n&&n.length>1?n.slice(0,1):Jn.charAt(t)+Fa(e.slice(1),void 0)}function wc(e){const n=rT(e.charAt(0));if(n>e.length)throw new Error("invalid index: "+e);return e.slice(0,n)}function mv(e){if(e===nT)throw new Error("invalid index: "+e);const n=wc(e);if(e.slice(n.length).slice(-1)==="0")throw new Error("invalid index: "+e)}function pa(e,n){if(e!==void 0&&mv(e),n!==void 0&&mv(n),e!==void 0&&n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e===void 0&&n===void 0)return tT;if(e===void 0){if(n===void 0)throw Error("b is undefined");const a=wc(n),l=n.slice(a.length);if(a===nT)return a+Fa("",l);if(an.index?1:0}function L9(e,n){return e.id>n.id?1:-1}function N0(e){try{return localStorage.getItem(e)}catch{return null}}function F0(e,n){try{localStorage.setItem(e,n)}catch{}}function $9(){try{localStorage.clear()}catch{}}function iT(e){try{return sessionStorage.getItem(e)}catch{return null}}function z0(e,n){try{sessionStorage.setItem(e,n)}catch{}}function aT(e){try{sessionStorage.removeItem(e)}catch{}}function N9(){try{sessionStorage.clear()}catch{}}const F9=()=>typeof process<"u"&&!1,za=[],z9=60,Lh=Math.ceil(1e3/z9);let Jl,Zm=0,yv=0;const B9=()=>{const e=za.splice(0,za.length);for(const n of e)n()};function lT(){if(Jl)return;const e=Date.now(),n=e-yv;if(Zm+n{Jl=void 0,lT()});return}Jl=requestAnimationFrame(()=>{Jl=void 0,yv=e,Zm=Math.min(Zm+n-Lh,Lh*10),B9()})}let sC=!1;function cT(e){return F9()?(e(),()=>{}):(za.includes(e)||(za.push(e),sC||(sC=!0,yv=Date.now()-Lh-1),lT()),()=>{const n=za.indexOf(e);n>-1&&za.splice(n,1)})}class U9{constructor(){g(this,"timeouts",[]);g(this,"intervals",[]);g(this,"rafs",[])}setTimeout(n,t,...r){const s=window.setTimeout(n,t,r);return this.timeouts.push(s),s}setInterval(n,t,...r){const s=window.setInterval(n,t,r);return this.intervals.push(s),s}requestAnimationFrame(n){const t=window.requestAnimationFrame(n);return this.rafs.push(t),t}dispose(){this.timeouts.forEach(n=>clearTimeout(n)),this.intervals.forEach(n=>clearInterval(n)),this.rafs.forEach(n=>cancelAnimationFrame(n)),this.timeouts.length=0,this.intervals.length=0,this.rafs.length=0}}function H9(e){return e!==null}function K9(){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]:[e=>e&&JSON.parse(JSON.stringify(e)),!1]}const uT=K9(),Be=uT[0];uT[1];const W9=Object.getPrototypeOf(Be({}));var Qm={};const B0={enableLicensing:G9("enableLicensing",{defaults:{all:!0,production:!1}})},dT=kn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),xt={logPreventDefaults:kn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:kn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:kn("logElementRemoves",{defaults:{all:!1}}),debugSvg:kn("debugSvg",{defaults:{all:!1}}),showFps:kn("showFps",{defaults:{all:!1}}),measurePerformance:kn("measurePerformance",{defaults:{all:!1}}),throwToBlob:kn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:kn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:kn("debugCursors",{defaults:{all:!1}}),forceSrgb:kn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:kn("debugGeometry",{defaults:{all:!1}}),hideShapes:kn("hideShapes",{defaults:{all:!1}}),editOnType:kn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const e=Element.prototype.removeChild;oa("element removal logging",()=>{xt.logElementRemoves.get()?Element.prototype.removeChild=function(n){return console.warn("[tldraw] removing child:",n),e.call(this,n)}:Element.prototype.removeChild=e})}function kn(e,{defaults:n,shouldStoreForSession:t=!0}){return hT({name:e,defaults:n,shouldStoreForSession:t})}function G9(e,{defaults:n,shouldStoreForSession:t=!0}){return hT({name:e,defaults:n,shouldStoreForSession:t})}function hT(e){const n=Y9(e),t=e.shouldStoreForSession?V9(e.name):null,r=Mt(`debug:${e.name}`,t??n);return typeof window<"u"&&(e.shouldStoreForSession&&oa(`debug:${e.name}`,()=>{const s=r.get();s===n?aT(`tldraw_debug:${e.name}`):z0(`tldraw_debug:${e.name}`,JSON.stringify(s))}),Object.defineProperty(window,`tldraw${e.name.replace(/^[a-z]/,s=>s.toUpperCase())}`,{get(){return r.get()},set(s){r.set(s)},configurable:!0})),Object.assign(r,e)}function V9(e){try{return JSON.parse(iT(`tldraw_debug:${e}`)??"null")}catch{return null}}function Jm(e){try{return e()}catch{return null}}function Y9(e){switch(Jm(()=>Qm.TLDRAW_ENV)??Jm(()=>Qm.VERCEL_PUBLIC_TLDRAW_ENV)??Jm(()=>Qm.NEXT_PUBLIC_TLDRAW_ENV)??"production"){case"production":return e.defaults.production??e.defaults.all;case"preview":case"staging":return e.defaults.staging??e.defaults.all;default:return e.defaults.development??e.defaults.all}}class $h{constructor(n){g(this,"nextValue");g(this,"diff");this.previousValue=n}get(){var r,s,o,i;const n=((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(!(n===0&&t===0))return{value:this.nextValue,diff:this.diff}}_add(n,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(n),this.diff??(this.diff={}),t?(r=this.diff.removed)==null||r.delete(n):((s=this.diff).added??(s.added=new Set),this.diff.added.add(n))}add(n){var s,o,i;const t=this.previousValue.has(n);if(t)return((o=(s=this.diff)==null?void 0:s.removed)==null?void 0:o.has(n))?this._add(n,t):void 0;(i=this.nextValue)!=null&&i.has(n)||this._add(n,t)}_remove(n,t){var r,s;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(n),this.diff??(this.diff={}),t?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(n)):(s=this.diff.added)==null||s.delete(n)}remove(n){var s,o,i,a;const t=this.previousValue.has(n);if(!t)return((o=(s=this.diff)==null?void 0:s.added)==null?void 0:o.has(n))?this._remove(n,t):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(n)||this._remove(n,t)}}let Ku=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((n,t)=>(t&=63,t<36?n+=t.toString(36):t<62?n+=(t-26).toString(36).toUpperCase():t>62?n+="-":n+="_",n),"");class rg{constructor(n,t){g(this,"createDefaultProperties");g(this,"validator");g(this,"ephemeralKeys");g(this,"ephemeralKeySet");g(this,"scope");g(this,"isInstance",n=>(n==null?void 0:n.typeName)===this.typeName);this.typeName=n,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 Hn(t.ephemeralKeys))o&&r.add(s);this.ephemeralKeySet=r}create(n){const t={...this.createDefaultProperties(),id:this.createId()};for(const[r,s]of Object.entries(n))s!==void 0&&(t[r]=s);return t.typeName=this.typeName,t}clone(n){return{...Be(n),id:this.createId()}}createId(n){return this.typeName+":"+(n??Ku())}createCustomId(n){return this.typeName+":"+n}parseId(n){if(!this.isId(n))throw new Error(`ID "${n}" is not a valid ID for type "${this.typeName}"`);return n.slice(this.typeName.length+1)}isId(n){if(!n)return!1;for(let t=0;t({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function qp(){return{added:{},updated:{},removed:{}}}function Sv(e){const n={added:e.removed,removed:e.added,updated:{}};for(const[t,r]of Object.values(e.updated))n.updated[t.id]=[r,t];return n}function pT(e){return Object.keys(e.added).length===0&&Object.keys(e.updated).length===0&&Object.keys(e.removed).length===0}function U0(e){const n={added:{},removed:{},updated:{}};return Gc(n,e),n}function Gc(e,n){for(const t of n){for(const[r,s]of Hn(t.added))if(e.removed[r]){const o=e.removed[r];delete e.removed[r],o!==s&&(e.updated[r]=[o,s])}else e.added[r]=s;for(const[r,[s,o]]of Hn(t.updated)){if(e.added[r]){e.added[r]=o,delete e.updated[r],delete e.removed[r];continue}if(e.updated[r]){e.updated[r]=[e.updated[r][0],o],delete e.removed[r];continue}e.updated[r]=t.updated[r],delete e.removed[r]}for(const[r,s]of Hn(t.removed))e.added[r]?delete e.added[r]:e.updated[r]?(e.removed[r]=e.updated[r][0],delete e.updated[r]):e.removed[r]=s}}var Zp={exports:{}};Zp.exports;(function(e,n){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]",h="[object Date]",p="[object Error]",f="[object Function]",S="[object GeneratorFunction]",y="[object Map]",x="[object Number]",m="[object Null]",v="[object Object]",w="[object Promise]",C="[object Proxy]",E="[object RegExp]",k="[object Set]",I="[object String]",_="[object Symbol]",T="[object Undefined]",M="[object WeakMap]",D="[object ArrayBuffer]",$="[object DataView]",j="[object Float32Array]",O="[object Float64Array]",R="[object Int8Array]",K="[object Int16Array]",B="[object Int32Array]",z="[object Uint8Array]",W="[object Uint8ClampedArray]",Y="[object Uint16Array]",q="[object Uint32Array]",ae=/[\\^$.*+?()[\]{}|]/g,fe=/^\[object .+?Constructor\]$/,we=/^(?:0|[1-9]\d*)$/,J={};J[j]=J[O]=J[R]=J[K]=J[B]=J[z]=J[W]=J[Y]=J[q]=!0,J[a]=J[l]=J[D]=J[u]=J[$]=J[h]=J[p]=J[f]=J[y]=J[x]=J[v]=J[E]=J[k]=J[I]=J[M]=!1;var Ue=typeof ln=="object"&&ln&&ln.Object===Object&&ln,Oe=typeof self=="object"&&self&&self.Object===Object&&self,tt=Ue||Oe||Function("return this")(),Ae=n&&!n.nodeType&&n,ot=Ae&&!0&&e&&!e.nodeType&&e,Ne=ot&&ot.exports===Ae,Vn=Ne&&Ue.process,Nt=function(){try{return Vn&&Vn.binding&&Vn.binding("util")}catch{}}(),_n=Nt&&Nt.isTypedArray;function St(A,L){for(var V=-1,ee=A==null?0:A.length,qe=0,ge=[];++V-1}function HL(A,L){var V=this.__data__,ee=hd(V,A);return ee<0?(++this.size,V.push([A,L])):V[ee][1]=L,this}As.prototype.clear=FL,As.prototype.delete=zL,As.prototype.get=BL,As.prototype.has=UL,As.prototype.set=HL;function mi(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L_t))return!1;var it=ge.get(A);if(it&&ge.get(L))return it==L;var Yn=-1,jr=!0,Qt=V&o?new dd:void 0;for(ge.set(A,L),ge.set(L,A);++Yn<_t;){var pr=A[Yn],fr=L[Yn];if(ee)var So=ft?ee(fr,pr,Yn,L,A,ge):ee(pr,fr,Yn,A,L,ge);if(So!==void 0){if(So)continue;jr=!1;break}if(Qt){if(!Ms(L,function(js,Si){if(!SL(Qt,Si)&&(pr===js||qe(pr,js,V,ee,ge)))return Qt.push(Si)})){jr=!1;break}}else if(!(pr===fr||qe(pr,fr,V,ee,ge))){jr=!1;break}}return ge.delete(A),ge.delete(L),jr}function l3(A,L,V,ee,qe,ge,ft){switch(V){case $:if(A.byteLength!=L.byteLength||A.byteOffset!=L.byteOffset)return!1;A=A.buffer,L=L.buffer;case D:return!(A.byteLength!=L.byteLength||!ge(new T1(A),new T1(L)));case u:case h:case x:return $1(+A,+L);case p:return A.name==L.name&&A.message==L.message;case E:case I:return A==L+"";case y:var _t=xL;case k:var Ft=ee&s;if(_t||(_t=bL),A.size!=L.size&&!Ft)return!1;var it=ft.get(A);if(it)return it==L;ee|=o,ft.set(A,L);var Yn=R1(_t(A),_t(L),ee,qe,ge,ft);return ft.delete(A),Yn;case _:if(Zg)return Zg.call(A)==Zg.call(L)}return!1}function c3(A,L,V,ee,qe,ge){var ft=V&s,_t=L1(A),Ft=_t.length,it=L1(L),Yn=it.length;if(Ft!=Yn&&!ft)return!1;for(var jr=Ft;jr--;){var Qt=_t[jr];if(!(ft?Qt in L:Jr.call(L,Qt)))return!1}var pr=ge.get(A);if(pr&&ge.get(L))return pr==L;var fr=!0;ge.set(A,L),ge.set(L,A);for(var So=ft;++jr-1&&A%1==0&&A-1&&A%1==0&&A<=i}function z1(A){var L=typeof A;return A!=null&&(L=="object"||L=="function")}function Bl(A){return A!=null&&typeof A=="object"}var B1=_n?go(_n):i3;function x3(A){return S3(A)?n3(A):a3(A)}function w3(){return[]}function b3(){return!1}e.exports=v3})(Zp,Zp.exports);var X9=Zp.exports;const q9=ti(X9);function Z9(e){if(e.length===0)return new Set;const n=e[0],t=e.slice(1),r=new Set;for(const s of n)t.every(o=>o.has(s))&&r.add(s);return r}function Q9(e,n){const t={};for(const r of n)e.has(r)||(t.added??(t.added=new Set),t.added.add(r));for(const r of e)n.has(r)||(t.removed??(t.removed=new Set),t.removed.add(r));return t.added||t.removed?t:void 0}function oC(e,n){for(const[t,r]of Object.entries(e)){const s=r,o=n[t];if("eq"in s&&o!==s.eq||"neq"in s&&o===s.neq||"gt"in s&&(typeof o!="number"||o<=s.gt))return!1}return!0}function iC(e,n,t){const r=Object.fromEntries(Object.keys(t).map(s=>[s,new Set]));for(const[s,o]of Object.entries(t))if("eq"in o){const a=e.index(n,s).get().get(o.eq);if(a)for(const l of a)r[s].add(l)}else if("neq"in o){const i=e.index(n,s);for(const[a,l]of i.get())if(a!==o.neq)for(const c of l)r[s].add(c)}else if("gt"in o){const i=e.index(n,s);for(const[a,l]of i.get())if(a>o.gt)for(const c of l)r[s].add(c)}return Z9(Object.values(r))}class J9{constructor(n,t){g(this,"indexCache",new Map);g(this,"historyCache",new Map);this.atoms=n,this.history=t}filterHistory(n){if(this.historyCache.has(n))return this.historyCache.get(n);const t=G("filterHistory:"+n,(r,s)=>{if(Ai(r))return this.history.get();const o=this.history.getDiffSince(s);if(o===nr)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const u of o){for(const h of gt(u.added))if(h.typeName===n)if(i.removed[h.id]){const p=i.removed[h.id];delete i.removed[h.id],l--,p!==h&&(i.updated[h.id]=[p,h],c++)}else i.added[h.id]=h,a++;for(const[h,p]of gt(u.updated))p.typeName===n&&(i.added[p.id]?i.added[p.id]=p:i.updated[p.id]?i.updated[p.id]=[i.updated[p.id][0],p]:(i.updated[p.id]=[h,p],c++));for(const h of gt(u.removed))h.typeName===n&&(i.added[h.id]?(delete i.added[h.id],a--):i.updated[h.id]?(i.removed[h.id]=i.updated[h.id][0],delete i.updated[h.id],c--,l++):(i.removed[h.id]=h,l++))}return a||l||c?vc(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(n,t),t}index(n,t){const r=n+":"+t;if(this.indexCache.has(r))return this.indexCache.get(r);const s=this.__uncached_createIndex(n,t);return this.indexCache.set(r,s),s}__uncached_createIndex(n,t){const r=this.filterHistory(n),s=()=>{r.get();const o=new Map;for(const i of gt(this.atoms.get())){const a=i.get();if(a.typeName===n){const l=a[t];o.has(l)||o.set(l,new Set),o.get(l).add(a.id)}}return o};return G("index:"+n+":"+t,(o,i)=>{if(Ai(o))return s();const a=r.getDiffSince(i);if(a===nr)return s();const l=new Map,c=(f,S)=>{let y=l.get(f);y||(y=new $h(o.get(f)??new Set)),y.add(S),l.set(f,y)},u=(f,S)=>{let y=l.get(f);y||(y=new $h(o.get(f)??new Set)),y.remove(S),l.set(f,y)};for(const f of a){for(const S of gt(f.added))if(S.typeName===n){const y=S[t];c(y,S.id)}for(const[S,y]of gt(f.updated))if(y.typeName===n){const x=S[t],m=y[t];x!==m&&(u(x,y.id),c(m,y.id))}for(const S of gt(f.removed))if(S.typeName===n){const y=S[t];u(y,S.id)}}let h,p;for(const[f,S]of l){const y=S.get();y&&(h||(h=new Map(o)),p||(p=new Map),y.value.size===0?h.delete(f):h.set(f,y.value),p.set(f,y.diff))}return h&&p?vc(h,p):o},{historyLength:100})}record(n,t=()=>({}),r="record:"+n+(t?":"+t.toString():"")){const s=this.ids(n,t,r);return G(r,()=>{var o;for(const i of s.get())return(o=this.atoms.get()[i])==null?void 0:o.get()})}records(n,t=()=>({}),r="records:"+n+(t?":"+t.toString():"")){const s=this.ids(n,t,"ids:"+r);return G(r,()=>[...s.get()].map(o=>{const i=this.atoms.get()[o];if(!i)throw new Error("no atom found for record id: "+o);return i.get()}))}ids(n,t=()=>({}),r="ids:"+n+(t?":"+t.toString():"")){const s=this.filterHistory(n),o=()=>{s.get();const l=t();return Object.keys(l).length===0?new Set(gt(this.atoms.get()).flatMap(c=>{const u=c.get();return u.typeName===n?u.id:[]})):iC(this,n,l)},i=l=>{const c=o(),u=Q9(l,c);return u?vc(c,u):l},a=G("ids_query:"+r,t,{isEqual:q9});return G("query:"+r,(l,c)=>{const u=a.get();if(Ai(l))return o();if(cs[o].get())}}class e7{constructor(n){g(this,"_beforeCreateHandlers",{});g(this,"_afterCreateHandlers",{});g(this,"_beforeChangeHandlers",{});g(this,"_afterChangeHandlers",{});g(this,"_beforeDeleteHandlers",{});g(this,"_afterDeleteHandlers",{});g(this,"_operationCompleteHandlers",[]);g(this,"_isEnabled",!0);this.store=n}isEnabled(){return this._isEnabled}setIsEnabled(n){this._isEnabled=n}handleBeforeCreate(n,t){if(!this._isEnabled)return n;const r=this._beforeCreateHandlers[n.typeName];if(r){let s=n;for(const o of r)s=o(s,t);return s}return n}handleAfterCreate(n,t){if(!this._isEnabled)return;const r=this._afterCreateHandlers[n.typeName];if(r)for(const s of r)s(n,t)}handleBeforeChange(n,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(n,o,r);return o}return t}handleAfterChange(n,t,r){if(!this._isEnabled)return;const s=this._afterChangeHandlers[t.typeName];if(s)for(const o of s)o(n,t,r)}handleBeforeDelete(n,t){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[n.typeName];if(r){for(const s of r)if(s(n,t)===!1)return!1}return!0}handleAfterDelete(n,t){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[n.typeName];if(r)for(const s of r)s(n,t)}handleOperationComplete(n){if(this._isEnabled)for(const t of this._operationCompleteHandlers)t(n)}register(n){const t=[];for(const[r,s]of Object.entries(n))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(n,t){return this._beforeCreateHandlers[n]||(this._beforeCreateHandlers[n]=[]),this._beforeCreateHandlers[n].push(t),()=>vi(this._beforeCreateHandlers[n],t)}registerAfterCreateHandler(n,t){return this._afterCreateHandlers[n]||(this._afterCreateHandlers[n]=[]),this._afterCreateHandlers[n].push(t),()=>vi(this._afterCreateHandlers[n],t)}registerBeforeChangeHandler(n,t){return this._beforeChangeHandlers[n]||(this._beforeChangeHandlers[n]=[]),this._beforeChangeHandlers[n].push(t),()=>vi(this._beforeChangeHandlers[n],t)}registerAfterChangeHandler(n,t){return this._afterChangeHandlers[n]||(this._afterChangeHandlers[n]=[]),this._afterChangeHandlers[n].push(t),()=>vi(this._afterChangeHandlers[n],t)}registerBeforeDeleteHandler(n,t){return this._beforeDeleteHandlers[n]||(this._beforeDeleteHandlers[n]=[]),this._beforeDeleteHandlers[n].push(t),()=>vi(this._beforeDeleteHandlers[n],t)}registerAfterDeleteHandler(n,t){return this._afterDeleteHandlers[n]||(this._afterDeleteHandlers[n]=[]),this._afterDeleteHandlers[n].push(t),()=>vi(this._afterDeleteHandlers[n],t)}registerOperationCompleteHandler(n){return this._operationCompleteHandlers.push(n),()=>vi(this._operationCompleteHandlers,n)}}function vi(e,n){const t=e.indexOf(n);t>=0&&e.splice(t,1)}class H0{constructor(n){g(this,"id");g(this,"atoms",Mt("store_atoms",{}));g(this,"history",Mt("history",0,{historyLength:1e3}));g(this,"query",new J9(this.atoms,this.history));g(this,"listeners",new Set);g(this,"historyAccumulator",new n7);g(this,"historyReactor");g(this,"cancelHistoryReactor",()=>{});g(this,"schema");g(this,"props");g(this,"scopedTypes");g(this,"sideEffects",new e7(this));g(this,"put",(n,t)=>{this.atomic(()=>{const r={},s={},o=this.atoms.__unsafe__getWithoutCapture();let i=null,a,l=!1;const c=this.isMergingRemoteChanges?"remote":"user";for(let u=0,h=n.length;u{this.atomic(()=>{const t=new Set,r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const o of n){const i=this.atoms.__unsafe__getWithoutCapture()[o];i&&this.sideEffects.handleBeforeDelete(i.get(),r)===!1&&t.add(o)}let s;this.atoms.update(o=>{let i;for(const a of n){if(t.has(a)||!(a in o))continue;i||(i={...o}),s||(s={}),delete i[a];const l=o[a].get();s[a]=l,this.addDiffForAfterEvent(l,null)}return i??o}),s&&this.updateHistory({added:{},updated:{},removed:s})})});g(this,"get",n=>{var t;return(t=this.atoms.get()[n])==null?void 0:t.get()});g(this,"unsafeGetWithoutCapture",n=>{var t;return(t=this.atoms.__unsafe__getWithoutCapture()[n])==null?void 0:t.__unsafe__getWithoutCapture()});g(this,"serialize",(n="document")=>{const t={};for(const[r,s]of Hn(this.atoms.get())){const o=s.get();(n==="all"||this.scopedTypes[n].has(o.typeName))&&(t[r]=o)}return t});g(this,"allRecords",()=>gt(this.atoms.get()).map(n=>n.get()));g(this,"clear",()=>{this.remove(tC(this.atoms.get()))});g(this,"update",(n,t)=>{const r=this.atoms.get()[n];if(!r){console.error(`Record ${n} not found. This is probably an error`);return}this.put([t(r.__unsafe__getWithoutCapture())])});g(this,"has",n=>!!this.atoms.get()[n]);g(this,"listen",(n,t)=>{this._flushHistory();const r={onHistory:n,filters:{source:(t==null?void 0:t.source)??"all",scope:(t==null?void 0:t.scope)??"all"}};return this.listeners.add(r),this.historyReactor.scheduler.isActivelyListening||this.historyReactor.start(),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}});g(this,"isMergingRemoteChanges",!1);g(this,"mergeRemoteChanges",n=>{if(this.isMergingRemoteChanges)return n();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.isMergingRemoteChanges=!0,gs(n)}finally{this.isMergingRemoteChanges=!1}});g(this,"createComputedCache",(n,t,r)=>{const s=new eo;return{get:o=>{const i=this.atoms.get()[o];if(i)return s.get(i,()=>{const a=r?G(i.name+":equals",()=>i.get(),{isEqual:r}):i;return G(n+":"+o,()=>t(a.get()))}).get()}}});g(this,"createSelectedComputedCache",(n,t,r)=>{const s=new eo;return{get:o=>{const i=this.atoms.get()[o];if(i)return s.get(i,()=>{const a=G(n+":"+o+":selector",()=>t(i.get()));return G(n+":"+o,()=>r(a.get()))}).get()}}});g(this,"_integrityChecker");g(this,"_isPossiblyCorrupted",!1);g(this,"pendingAfterEvents",null);g(this,"_isInAtomicOp",!1);const{initialData:t,schema:r,id:s}=n;this.id=s??Ku(),this.schema=r,this.props=n.props,t&&this.atoms.set(J2(Hn(t).map(([o,i])=>[o,Mt("atom:"+o,this.schema.validateRecord(this,i,"initialize",null))]))),this.historyReactor=GB("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:o=>this.cancelHistoryReactor=cT(o)}),this.scopedTypes={document:new Set(gt(this.schema.types).filter(o=>o.scope==="document").map(o=>o.typeName)),session:new Set(gt(this.schema.types).filter(o=>o.scope==="session").map(o=>o.typeName)),presence:new Set(gt(this.schema.types).filter(o=>o.scope==="presence").map(o=>o.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){const n=this.historyAccumulator.flush();for(const{changes:t,source:r}of n){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(n,t){const r={added:Wc(n.added,(s,o)=>this.scopedTypes[t].has(o.typeName)),updated:Wc(n.updated,(s,o)=>this.scopedTypes[t].has(o[1].typeName)),removed:Wc(n.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(n){this.historyAccumulator.add({changes:n,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,n)}validate(n){this.allRecords().forEach(t=>this.schema.validateRecord(this,t,n,null))}getStoreSnapshot(n="document"){return{store:this.serialize(n),schema:this.schema.serialize()}}getSnapshot(n="document"){return console.warn("[tldraw] `Store.getSnapshot` is deprecated and will be removed in a future release. Use `getSnapshot` from the `tldraw` package instead."),this.getStoreSnapshot(n)}migrateSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);return{store:t.value,schema:this.schema.serialize()}}loadStoreSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);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)}}loadSnapshot(n){console.warn("[tldraw] `Store.loadSnapshot` is deprecated and will be removed in a future release. Use `loadSnapshot` from the 'tldraw' package instead."),this.loadStoreSnapshot(n)}extractingChanges(n){const t=[],r=this.historyAccumulator.addInterceptor(s=>t.push(s.changes));try{return gs(n),U0(t)}finally{r()}}applyDiff(n,{runCallbacks:t=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const s=gt(n.added);for(const[i,a]of gt(n.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[h,p]of Object.entries(a))l.ephemeralKeySet.has(h)||Object.is(p,$n(c,h))||(u||(u={...c}),u[h]=p);u&&s.push(u)}else s.push(a)}const o=tC(n.removed);s.length&&this.put(s),o.length&&this.remove(o)},t)}ensureStoreIsUsable(){this.atomic(()=>{var n;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(n=this._integrityChecker)==null||n.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(n,t){if(Ye(this.pendingAfterEvents,"must be in event operation"),n===t||(n&&t&&Ye(n.id===t.id),!n&&!t))return;const r=(n||t).id,s=this.pendingAfterEvents.get(r);s?s.after=t:this.pendingAfterEvents.set(r,{before:n,after:t})}flushAtomicCallbacks(){let n=0;const t=this.isMergingRemoteChanges?"remote":"user";for(;this.pendingAfterEvents;){const r=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(n++,n>100)throw new Error("Maximum store update depth exceeded, bailing out");for(const{before:s,after:o}of r.values())s&&o?this.sideEffects.handleAfterChange(s,o,t):s&&!o?this.sideEffects.handleAfterDelete(s,t):!s&&o&&this.sideEffects.handleAfterCreate(o,t);this.pendingAfterEvents||this.sideEffects.handleOperationComplete(t)}}}atomic(n,t=!0){return gs(()=>{if(this._isInAtomicOp)return this.pendingAfterEvents||(this.pendingAfterEvents=new Map),n();this.pendingAfterEvents=new Map;const r=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(t??r),this._isInAtomicOp=!0;try{const s=n();return this.flushAtomicCallbacks(),s}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(r),this._isInAtomicOp=!1}})}addHistoryInterceptor(n){return this.historyAccumulator.addInterceptor(t=>n(t,this.isMergingRemoteChanges?"remote":"user"))}}function t7(e){if(e.length===0)return[];const n=[];let t=[e[0]],r;for(let s=1,o=e.length;s({source:s[0].source,changes:U0(s.map(o=>o.changes))}))}class n7{constructor(){g(this,"_history",[]);g(this,"_interceptors",new Set)}addInterceptor(n){return this._interceptors.add(n),()=>{this._interceptors.delete(n)}}add(n){this._history.push(n);for(const t of this._interceptors)t(n)}flush(){const n=t7(this._history);return this._history=[],n}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function r7(e,n,t){const r=new eo;return{get(s,o){return r.get(s,()=>(s instanceof H0?s:s.store).createComputedCache(e,l=>n(s,l),t)).get(o)}}}function s7(e){const n=[];for(let t=e.length-1;t>=0;t--){const r=e[t];if("id"in r)n.unshift(r);else{const s=r.dependsOn,o=n[0];o&&(n[0]={...o,dependsOn:s.concat(o.dependsOn??[])})}}return n}function Ja({sequence:e,sequenceId:n,retroactive:t=!0}){const r={sequenceId:n,retroactive:t,sequence:s7(e)};return fT(r),r}function Wn(e,n){return Object.fromEntries(Hn(n).map(([t,r])=>[t,`${e}/${r}`]))}function dr(e){const n=e.sequenceId;return Ja({sequenceId:n,retroactive:e.retroactive??!0,sequence:e.sequence.map(t=>"id"in t?{...t,scope:"record",filter:r=>{var s,o;return r.typeName===e.recordType&&(((s=t.filter)==null?void 0:s.call(t,r))??!0)&&(((o=e.filter)==null?void 0:o.call(e,r))??!0)}}:t)})}function o7(e){const n=new Map(e.map(o=>[o.id,o])),t=new Set,r=[];function s(o){Ye(!t.has(o.id),`Circular dependency in migrations: ${o.id}`),t.add(o.id);const{version:i,sequenceId:a}=Qp(o.id),l=n.get(`${a}/${i-1}`);if(l&&s(l),o.dependsOn)for(const c of o.dependsOn){const u=n.get(c);u&&s(u)}n.delete(o.id),r.push(o)}for(const o of n.values())s(o);return r}function Qp(e){const[n,t]=e.split("/");return{sequenceId:n,version:parseInt(t)}}function aC(e,n){n&&Ye(e.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${e}'`),Ye(e.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${e}'`)}function fT(e){if(Ye(!e.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${e.sequenceId}`),Ye(e.sequenceId.length,"sequenceId must be a non-empty string"),e.sequence.length===0)return;aC(e.sequence[0].id,e.sequenceId);let n=Qp(e.sequence[0].id).version;Ye(n===1,`Expected the first migrationId to be '${e.sequenceId}/1' but got '${e.sequence[0].id}'`);for(let t=1;t(e.IncompatibleSubtype="incompatible-subtype",e.UnknownType="unknown-type",e.TargetVersionTooNew="target-version-too-new",e.TargetVersionTooOld="target-version-too-old",e.MigrationError="migration-error",e.UnrecognizedSubtype="unrecognized-subtype",e))(bo||{});function i7(e){if(e.schemaVersion>2||e.schemaVersion<1)return Ho.err("Bad schema version");if(e.schemaVersion===2)return Ho.ok(e);const n={schemaVersion:2,sequences:{}};for(const[t,r]of Object.entries(e.recordVersions))if(n.sequences[`com.tldraw.${t}`]=r.version,"subTypeKey"in r)for(const[s,o]of Object.entries(r.subTypeVersions))n.sequences[`com.tldraw.${t}.${s}`]=o;return Ho.ok(n)}class K0{constructor(n,t){g(this,"migrations",{});g(this,"sortedMigrations");var s;this.types=n,this.options=t;for(const o of t.migrations??[])Ye(!this.migrations[o.sequenceId],`Duplicate migration sequenceId ${o.sequenceId}`),fT(o),this.migrations[o.sequenceId]=o;const r=Object.values(this.migrations).flatMap(o=>o.sequence);this.sortedMigrations=o7(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);Ye(a,`Migration '${o.id}' depends on missing migration '${i}'`)}}static create(n,t){return new K0(n,t??{})}validateRecord(n,t,r,s){try{const o=$n(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:n,record:t,phase:r,recordBefore:s,error:o});throw o}}getMigrationsSince(n){const t=i7(n);if(!t.ok)return t;const r=t.value,s=new Set(Object.keys(r.sequences).filter(i=>this.migrations[i]));for(const i in this.migrations)r.sequences[i]===void 0&&this.migrations[i].retroactive&&s.add(i);if(s.size===0)return Ho.ok([]);const o=new Set;for(const i of s){const a=r.sequences[i];if(typeof a!="number"&&this.migrations[i].retroactive||a===0){for(const u of this.migrations[i].sequence)o.add(u.id);continue}const l=`${i}/${a}`,c=this.migrations[i].sequence.findIndex(u=>u.id===l);if(c===-1)return Ho.err("Incompatible schema?");for(const u of this.migrations[i].sequence.slice(c+1))o.add(u.id)}return Ho.ok(this.sortedMigrations.filter(({id:i})=>o.has(i)))}migratePersistedRecord(n,t,r="up"){const s=this.getMigrationsSince(t);if(!s.ok)return console.error("Error migrating record",s.error),{type:"error",reason:bo.MigrationError};let o=s.value;if(o.length===0)return{type:"success",value:n};if(o.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?bo.TargetVersionTooOld:bo.TargetVersionTooNew};if(r==="down"){if(!o.every(i=>i.down))return{type:"error",reason:bo.TargetVersionTooOld};o=o.slice().reverse()}n=Be(n);try{for(const i of o){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(n):!0))continue;const l=i[r](n);l&&(n=Be(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:bo.MigrationError}}return{type:"success",value:n}}migrateStoreSnapshot(n){let{store:t}=n;const r=this.getMigrationsSince(n.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:bo.MigrationError};const s=r.value;if(s.length===0)return{type:"success",value:t};t=Be(t);try{for(const o of s)if(o.scope==="record")for(const[i,a]of Object.entries(t)){if(!(o.filter?o.filter(a):!0))continue;const c=o.up(a);c&&(t[i]=Be(c))}else if(o.scope==="store"){const i=o.up(t);i&&(t=Be(i))}else cn(o)}catch(o){return console.error("Error migrating store",o),{type:"error",reason:bo.MigrationError}}return{type:"success",value:t}}createIntegrityChecker(n){var t,r;return((r=(t=this.options).createIntegrityChecker)==null?void 0:r.call(t,n))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n,sequence:t})=>[n,t.length?Qp(t.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n})=>[n,0]))}}getType(n){const t=$n(this.types,n);return Ye(t,"record type does not exists"),t}}function a7(e){if(!e.length)return null;let n="";for(const t of e)typeof t=="number"?n+=`.${t}`:t.startsWith("(")?n.endsWith(")")?n=`${n.slice(0,-1)}, ${t.slice(1)}`:n+=t:n+=`.${t}`;return n=n.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),n.startsWith(".")?n.slice(1):n}class Ee extends Error{constructor(t,r=[]){const s=a7(r),o=t.split(` `).map((i,a)=>a===0?i:` ${i}`).join(` `);super(r?`At ${s}: ${o}`:o);g(this,"name","ValidationError");this.rawMessage=t,this.path=r}}function Kn(e,n){try{return n()}catch(t){throw t instanceof Ee?new Ee(t.rawMessage,[e,...t.path]):new Ee(t.toString(),[e])}}function qo(e){if(e===null)return"null";if(Array.isArray(e))return"an array";const n=typeof e;switch(n){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${n}`;case"object":return`an ${n}`;case"undefined":return"undefined";default:cn(n)}}class Pn{constructor(n,t){this.validationFn=n,this.validateUsingKnownGoodVersionFn=t}validate(n){return this.validationFn(n)}validateUsingKnownGoodVersion(n,t){return Object.is(n,t)?n:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(n,t):this.validate(t)}isValid(n){try{return this.validate(n),!0}catch{return!1}}nullable(){return p7(this)}optional(){return mT(this)}refine(n){return new Pn(t=>n(this.validate(t)),(t,r)=>{const s=this.validateUsingKnownGoodVersion(t,r);return Object.is(t,s)?t:n(s)})}check(n,t){return typeof n=="string"?this.refine(r=>(Kn(`(check ${n})`,()=>t(r)),r)):this.refine(r=>(n(r),r))}}class l7 extends Pn{constructor(n){super(t=>{const r=lC.validate(t);for(let s=0;sn.validate(r[s]));return r},(t,r)=>{if(!n.validateUsingKnownGoodVersion)return this.validate(r);const s=lC.validate(r);let o=t.length!==s.length;for(let i=0;i=t.length){o=!0,Kn(i,()=>n.validate(a));continue}if(Object.is(t[i],a))continue;const l=Kn(i,()=>n.validateUsingKnownGoodVersion(t[i],a));Object.is(l,t[i])||(o=!0)}return o?r:t}),this.itemValidator=n}nonEmpty(){return this.check(n=>{if(n.length===0)throw new Ee("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(n=>{if(n.length<=1)throw new Ee("Expected an array with length greater than 1")})}}class Jp extends Pn{constructor(n,t=!1){super(r=>{if(typeof r!="object"||r===null)throw new Ee(`Expected object, got ${qo(r)}`);for(const[s,o]of Object.entries(n))Kn(s,()=>{o.validate($n(r,s))});if(!t){for(const s of Object.keys(r))if(!ms(n,s))throw new Ee("Unexpected property",[s])}return r},(r,s)=>{if(typeof s!="object"||s===null)throw new Ee(`Expected object, got ${qo(s)}`);let o=!1;for(const[i,a]of Object.entries(n)){const l=$n(r,i),c=$n(s,i);if(Object.is(l,c))continue;const u=Kn(i,()=>{const h=a;return h.validateUsingKnownGoodVersion?h.validateUsingKnownGoodVersion(l,c):h.validate(c)});Object.is(u,l)||(o=!0)}if(!t){for(const i of Object.keys(s))if(!ms(n,i))throw new Ee("Unexpected property",[i])}for(const i of Object.keys(r))if(!ms(s,i)){o=!0;break}return o?s:r}),this.config=n,this.shouldAllowUnknownProperties=t}allowUnknownProperties(){return new Jp(this.config,!0)}extend(n){return new Jp({...this.config,...n})}}class sg extends Pn{constructor(n,t,r,s){super(o=>{this.expectObject(o);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(o);return i===void 0?this.unknownValueValidation(o,a):Kn(`(${n} = ${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):$n(o,n)!==$n(i,n)?Kn(`(${n} = ${l})`,()=>a.validate(i)):Kn(`(${n} = ${l})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(o,i):a.validate(i))}),this.key=n,this.config=t,this.unknownValueValidation=r,this.useNumberKeys=s}expectObject(n){if(typeof n!="object"||n===null)throw new Ee(`Expected an object, got ${qo(n)}`,[])}getMatchingSchemaAndVariant(n){const t=$n(n,this.key);if(!this.useNumberKeys&&typeof t!="string")throw new Ee(`Expected a string for key "${this.key}", got ${qo(t)}`);if(this.useNumberKeys&&!Number.isFinite(Number(t)))throw new Ee(`Expected a number for key "${this.key}", got "${t}"`);return{matchingSchema:ms(this.config,t)?this.config[t]:void 0,variant:t}}validateUnknownVariants(n){return new sg(this.key,this.config,n,this.useNumberKeys)}}class c7 extends Pn{constructor(n,t){super(r=>{if(typeof r!="object"||r===null)throw new Ee(`Expected object, got ${qo(r)}`);for(const[s,o]of Object.entries(r))Kn(s,()=>{n.validate(s),t.validate(o)});return r},(r,s)=>{if(typeof s!="object"||s===null)throw new Ee(`Expected object, got ${qo(s)}`);let o=!1;for(const[i,a]of Object.entries(s)){if(!ms(r,i)){o=!0,Kn(i,()=>{n.validate(i),t.validate(a)});continue}const l=$n(r,i),c=a;if(Object.is(l,c))continue;const u=Kn(i,()=>t.validateUsingKnownGoodVersion?t.validateUsingKnownGoodVersion(l,c):t.validate(c));Object.is(u,l)||(o=!0)}for(const i of Object.keys(r))if(!ms(s,i)){o=!0;break}return o?s:r}),this.keyValidator=n,this.valueValidator=t}}function W0(e){return new Pn(n=>{if(typeof n!==e)throw new Ee(`Expected ${e}, got ${qo(n)}`);return n})}const u7=new Pn(e=>e),he=W0("string"),de=W0("number").check(e=>{if(Number.isNaN(e))throw new Ee("Expected a number, got NaN");if(!Number.isFinite(e))throw new Ee(`Expected a finite number, got ${e}`)}),ef=de.check(e=>{if(e<0)throw new Ee(`Expected a positive number, got ${e}`)}),bt=de.check(e=>{if(e<=0)throw new Ee(`Expected a non-zero positive number, got ${e}`)}),gT=de.check(e=>{if(!Number.isInteger(e))throw new Ee(`Expected an integer, got ${e}`)}),Nh=gT.check(e=>{if(e<0)throw new Ee(`Expected a positive integer, got ${e}`)}),d7=gT.check(e=>{if(e<=0)throw new Ee(`Expected a non-zero positive integer, got ${e}`)}),ye=W0("boolean");function dn(e){return new Pn(n=>{if(n!==e)throw new Ee(`Expected ${e}, got ${JSON.stringify(n)}`);return e})}const lC=new Pn(e=>{if(!Array.isArray(e))throw new Ee(`Expected an array, got ${qo(e)}`);return e});function It(e){return new l7(e)}function ve(e){return new Jp(e)}function vv(e){return typeof e=="object"&&e!==null&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===W9)}function xv(e){return e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(xv):vv(e)?Object.values(e).every(xv):!1}const Ht=new Pn(e=>{if(xv(e))return e;throw new Ee(`Expected json serializable value, got ${typeof e}`)},(e,n)=>{if(Array.isArray(e)&&Array.isArray(n)){let t=e.length!==n.length;for(let r=0;r=e.length){t=!0,Ht.validate(n[r]);continue}const s=e[r],o=n[r];if(Object.is(s,o))continue;const i=Ht.validateUsingKnownGoodVersion(s,o);Object.is(i,s)||(t=!0)}return t?n:e}else if(vv(e)&&vv(n)){let t=!1;for(const r of Object.keys(n)){if(!ms(e,r)){t=!0,Ht.validate(n[r]);continue}const s=e[r],o=n[r];if(Object.is(s,o))continue;const i=Ht.validateUsingKnownGoodVersion(s,o);Object.is(i,s)||(t=!0)}for(const r of Object.keys(e))if(!ms(n,r)){t=!0;break}return t?n:e}else return Ht.validate(n)});function tf(e,n){return new c7(e,n)}function G0(e,n){return new sg(e,n,(t,r)=>{throw new Ee(`Expected one of ${Object.keys(n).map(s=>JSON.stringify(s)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!1)}function h7(e,n){return new sg(e,n,(t,r)=>{throw new Ee(`Expected one of ${Object.keys(n).map(s=>JSON.stringify(s)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!0)}function ks(e,n){return new Pn(t=>Kn(e,()=>n.validate(t)),(t,r)=>Kn(e,()=>n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(t,r):n.validate(r)))}function og(e){return new Pn(n=>{if(!e.has(n)){const t=Array.from(e,r=>JSON.stringify(r)).join(" or ");throw new Ee(`Expected ${t}, got ${n}`)}return n})}function mT(e){return new Pn(n=>{if(n!==void 0)return e.validate(n)},(n,t)=>{if(!(n===void 0&&t===void 0)&&t!==void 0)return e.validateUsingKnownGoodVersion&&n!==void 0?e.validateUsingKnownGoodVersion(n,t):e.validate(t)})}function p7(e){return new Pn(n=>n===null?null:e.validate(n),(n,t)=>t===null?null:e.validateUsingKnownGoodVersion&&n!==null?e.validateUsingKnownGoodVersion(n,t):e.validate(t))}function ig(...e){return og(new Set(e))}function V0(e){try{return new URL(e)}catch{if(e.startsWith("/")||e.startsWith("./"))try{return new URL(e,"http://example.com")}catch{throw new Ee(`Expected a valid url, got ${JSON.stringify(e)}`)}throw new Ee(`Expected a valid url, got ${JSON.stringify(e)}`)}}const f7=new Set(["http:","https:","mailto:"]),ar=he.check(e=>{if(e==="")return;const n=V0(e);if(!f7.has(n.protocol.toLowerCase()))throw new Ee(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)}),g7=new Set(["http:","https:","data:","asset:"]),zi=he.check(e=>{if(e==="")return;const n=V0(e);if(!g7.has(n.protocol.toLowerCase()))throw new Ee(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)});he.check(e=>{if(e==="")return;if(!V0(e).protocol.toLowerCase().match(/^https?:$/))throw new Ee(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)});const Y0=he.refine(e=>{try{return D9(e),e}catch{throw new Ee(`Expected an index key, got ${JSON.stringify(e)}`)}});function rr(e){return he.refine(n=>{if(!n.startsWith(`${e}:`))throw new Error(`${e} ID must start with "${e}:"`);return n})}const ag=rr("asset");function X0(e,n){return ve({id:ag,typeName:dn("asset"),type:dn(e),props:n,meta:Ht})}const Bi=ve({x:de,y:de,z:de.optional()}),Vc=ve({x:de,y:de,w:de,h:de}),yT=de.check(e=>{if(e<0||e>1)throw new Ee("Opacity must be between 0 and 1")}),m7=he.refine(e=>{if(!e.startsWith("page:")&&!e.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return e}),mr=rr("shape");function y7(e,n,t){return ve({id:mr,typeName:dn("shape"),x:de,y:de,rotation:de,index:Y0,parentId:m7,type:dn(e),isLocked:ye,opacity:yT,props:n?ve(n):Ht,meta:t?ve(t):Ht})}const S7=rr("binding");function v7(e,n,t){return ve({id:S7,typeName:dn("binding"),type:dn(e),fromId:mr,toId:mr,props:n?ve(n):Ht,meta:t?ve(t):Ht})}Wn("com.tldraw.binding",{});dr({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function Oi(e){return`binding:${Ku()}`}function x7(e){return _s("binding",{scope:"document",validator:ks("binding",G0("type",Hu(e,(n,{props:t,meta:r})=>v7(n,t,r))))}).withDefaultProperties(()=>({meta:{}}))}class Xt{constructor(n,t,r){this.id=n,this.defaultValue=t,this.type=r}static define(n,t){const{defaultValue:r,type:s=u7}=t;return new Xt(n,r,s)}static defineEnum(n,t){const{defaultValue:r,values:s}=t;return new w7(n,r,s)}setDefaultValue(n){this.defaultValue=n}validate(n){return this.type.validate(n)}validateUsingKnownGoodVersion(n,t){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(n,t):this.validate(t)}}class w7 extends Xt{constructor(n,t,r){super(n,t,ig(...r)),this.values=r}}const zd=Wn("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),b7=dr({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:zd.AddIsLocked,up:e=>{e.isLocked=!1},down:e=>{delete e.isLocked}},{id:zd.HoistOpacity,up:e=>{e.opacity=Number(e.props.opacity??"1"),delete e.props.opacity},down:e=>{const n=e.opacity;delete e.opacity,e.props.opacity=n<.175?"0.1":n<.375?"0.25":n<.625?"0.5":n<.875?"0.75":"1"}},{id:zd.AddMeta,up:e=>{e.meta={}}},{id:zd.AddWhite,up:e=>{},down:e=>{e.props.color==="white"&&(e.props.color="black")}}]});function Ba(e){return e?e.typeName==="shape":!1}function An(e){return e?e.startsWith("shape:"):!1}function je(e){return`shape:${e??Ku()}`}function ST(e){const n=new Map;for(const[t,r]of Object.entries(e))if(r instanceof Xt){if(n.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);n.set(r,t)}return n}function Xr(e,n){return Hu(n,(t,r)=>`com.tldraw.shape.${e}/${r}`)}function P7(e){return _s("shape",{scope:"document",validator:ks("shape",G0("type",Hu(e,(n,{props:t,meta:r})=>y7(n,t,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function cC(e,n){const t=[];for(const[r,{migrations:s}]of Object.entries(n)){const o=`com.tldraw.${e}.${r}`;s?"sequenceId"in s?(Ye(o===s.sequenceId,`sequenceId mismatch for ${r} ${rg} migrations. Expected '${o}', got '${s.sequenceId}'`),t.push(s)):"sequence"in s?t.push(Ja({sequenceId:o,retroactive:!1,sequence:s.sequence.map(i=>"id"in i?vT(e,r,i):i)})):t.push(Ja({sequenceId:o,retroactive:!1,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===e&&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(Ja({sequenceId:o,retroactive:!1,sequence:[]}))}return t}function vT(e,n,t){return{id:t.id,dependsOn:t.dependsOn,scope:"record",filter:r=>r.typeName===e&&r.type===n,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 xT=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],nf={lightMode:{id:"light",text:"#000000",background:"rgb(249, 250, 251)",solid:"#fcfffe",black:{solid:"#1d1d1d",fill:"#1d1d1d",note:{fill:"#FCE19C",text:"#000000"},semi:"#e8e8e8",pattern:"#494949",highlight:{srgb:"#fddd00",p3:"color(display-p3 0.972 0.8705 0.05)"}},blue:{solid:"#4465e9",fill:"#4465e9",note:{fill:"#8AA3FF",text:"#000000"},semi:"#dce1f8",pattern:"#6681ee",highlight:{srgb:"#10acff",p3:"color(display-p3 0.308 0.6632 0.9996)"}},green:{solid:"#099268",fill:"#099268",note:{fill:"#6FC896",text:"#000000"},semi:"#d3e9e3",pattern:"#39a785",highlight:{srgb:"#00ffc8",p3:"color(display-p3 0.2536 0.984 0.7981)"}},grey:{solid:"#9fa8b2",fill:"#9fa8b2",note:{fill:"#C0CAD3",text:"#000000"},semi:"#eceef0",pattern:"#bcc3c9",highlight:{srgb:"#cbe7f1",p3:"color(display-p3 0.8163 0.9023 0.9416)"}},"light-blue":{solid:"#4ba1f1",fill:"#4ba1f1",note:{fill:"#9BC4FD",text:"#000000"},semi:"#ddedfa",pattern:"#6fbbf8",highlight:{srgb:"#00f4ff",p3:"color(display-p3 0.1512 0.9414 0.9996)"}},"light-green":{solid:"#4cb05e",fill:"#4cb05e",note:{fill:"#98D08A",text:"#000000"},semi:"#dbf0e0",pattern:"#65cb78",highlight:{srgb:"#65f641",p3:"color(display-p3 0.563 0.9495 0.3857)"}},"light-red":{solid:"#f87777",fill:"#f87777",note:{fill:"#F7A5A1",text:"#000000"},semi:"#f4dadb",pattern:"#fe9e9e",highlight:{srgb:"#ff7fa3",p3:"color(display-p3 0.9988 0.5301 0.6397)"}},"light-violet":{solid:"#e085f4",fill:"#e085f4",note:{fill:"#DFB0F9",text:"#000000"},semi:"#f5eafa",pattern:"#e9acf8",highlight:{srgb:"#ff88ff",p3:"color(display-p3 0.9676 0.5652 0.9999)"}},orange:{solid:"#e16919",fill:"#e16919",note:{fill:"#FAA475",text:"#000000"},semi:"#f8e2d4",pattern:"#f78438",highlight:{srgb:"#ffa500",p3:"color(display-p3 0.9988 0.6905 0.266)"}},red:{solid:"#e03131",fill:"#e03131",note:{fill:"#FC8282",text:"#000000"},semi:"#f4dadb",pattern:"#e55959",highlight:{srgb:"#ff636e",p3:"color(display-p3 0.9992 0.4376 0.45)"}},violet:{solid:"#ae3ec9",fill:"#ae3ec9",note:{fill:"#DB91FD",text:"#000000"},semi:"#ecdcf2",pattern:"#bd63d3",highlight:{srgb:"#c77cff",p3:"color(display-p3 0.7469 0.5089 0.9995)"}},yellow:{solid:"#f1ac4b",fill:"#f1ac4b",note:{fill:"#FED49A",text:"#000000"},semi:"#f9f0e6",pattern:"#fecb92",highlight:{srgb:"#fddd00",p3:"color(display-p3 0.972 0.8705 0.05)"}},white:{solid:"#FFFFFF",fill:"#FFFFFF",semi:"#f5f5f5",pattern:"#f9f9f9",note:{fill:"#FFFFFF",text:"#000000"},highlight:{srgb:"#ffffff",p3:"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",note:{fill:"#2c2c2c",text:"#f2f2f2"},semi:"#2c3036",pattern:"#989898",highlight:{srgb:"#d2b700",p3:"color(display-p3 0.8078 0.7225 0.0312)"}},blue:{solid:"#4f72fc",fill:"#4f72fc",note:{fill:"#2A3F98",text:"#f2f2f2"},semi:"#262d40",pattern:"#3a4b9e",highlight:{srgb:"#0079d2",p3:"color(display-p3 0.0032 0.4655 0.7991)"}},green:{solid:"#099268",fill:"#099268",note:{fill:"#014429",text:"#f2f2f2"},semi:"#253231",pattern:"#366a53",highlight:{srgb:"#009774",p3:"color(display-p3 0.0085 0.582 0.4604)"}},grey:{solid:"#9398b0",fill:"#9398b0",note:{fill:"#56595F",text:"#f2f2f2"},semi:"#33373c",pattern:"#7c8187",highlight:{srgb:"#9cb4cb",p3:"color(display-p3 0.6299 0.7012 0.7856)"}},"light-blue":{solid:"#4dabf7",fill:"#4dabf7",note:{fill:"#1F5495",text:"#f2f2f2"},semi:"#2a3642",pattern:"#4d7aa9",highlight:{srgb:"#00bdc8",p3:"color(display-p3 0.0023 0.7259 0.7735)"}},"light-green":{solid:"#40c057",fill:"#40c057",note:{fill:"#21581D",text:"#f2f2f2"},semi:"#2a3830",pattern:"#4e874e",highlight:{srgb:"#00a000",p3:"color(display-p3 0.2711 0.6172 0.0195)"}},"light-red":{solid:"#ff8787",fill:"#ff8787",note:{fill:"#923632",text:"#f2f2f2"},semi:"#3b3235",pattern:"#a56767",highlight:{srgb:"#db005b",p3:"color(display-p3 0.7849 0.0585 0.3589)"}},"light-violet":{solid:"#e599f7",fill:"#e599f7",note:{fill:"#762F8E",text:"#f2f2f2"},semi:"#383442",pattern:"#9770a9",highlight:{srgb:"#c400c7",p3:"color(display-p3 0.7024 0.0403 0.753)"}},orange:{solid:"#f76707",fill:"#f76707",note:{fill:"#843906",text:"#f2f2f2"},semi:"#3a2e2a",pattern:"#9f552d",highlight:{srgb:"#d07a00",p3:"color(display-p3 0.7699 0.4937 0.0085)"}},red:{solid:"#e03131",fill:"#e03131",note:{fill:"#89231A",text:"#f2f2f2"},semi:"#36292b",pattern:"#8f3734",highlight:{srgb:"#de002c",p3:"color(display-p3 0.7978 0.0509 0.2035)"}},violet:{solid:"#ae3ec9",fill:"#ae3ec9",note:{fill:"#681683",text:"#f2f2f2"},semi:"#31293c",pattern:"#763a8b",highlight:{srgb:"#9e00ee",p3:"color(display-p3 0.5651 0.0079 0.8986)"}},yellow:{solid:"#ffc034",fill:"#ffc034",note:{fill:"#98571B",text:"#f2f2f2"},semi:"#3c3934",pattern:"#fecb92",highlight:{srgb:"#d2b700",p3:"color(display-p3 0.8078 0.7225 0.0312)"}},white:{solid:"#f3f3f3",fill:"#f3f3f3",semi:"#f5f5f5",pattern:"#f9f9f9",note:{fill:"#eaeaea",text:"#1d1d1d"},highlight:{srgb:"#ffffff",p3:"color(display-p3 1 1 1)"}}}};function lo(e){return e.isDarkMode?nf.darkMode:nf.lightMode}const lr=Xt.defineEnum("tldraw:color",{defaultValue:"black",values:xT}),wT=Xt.defineEnum("tldraw:labelColor",{defaultValue:"black",values:xT}),Ui=Xt.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),Hi=Xt.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill"]}),xs=Xt.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),bT={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},ws=Xt.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),PT=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],rf=Xt.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:PT}),sf=Xt.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:PT}),CT={labelColor:wT,color:lr,fill:Hi,dash:Ui,size:ws,arrowheadStart:rf,arrowheadEnd:sf,font:xs,start:Bi,end:Bi,bend:de,text:he,labelPosition:de,scale:bt},ba=Xr("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5});function Bd(e){return vT("shape","arrow",e)}const IT=Ja({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[Bd({id:ba.AddLabelColor,up:e=>{e.labelColor="black"},down:"retired"}),Bd({id:ba.AddIsPrecise,up:({start:e,end:n})=>{e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5)),n.type==="binding"&&(n.isPrecise=!(n.normalizedAnchor.x===.5&&n.normalizedAnchor.y===.5))},down:({start:e,end:n})=>{e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise),n.type==="binding"&&(n.isPrecise||(n.normalizedAnchor={x:.5,y:.5}),delete n.isPrecise)}}),Bd({id:ba.AddLabelPosition,up:e=>{e.labelPosition=.5},down:e=>{delete e.labelPosition}}),{id:ba.ExtractBindings,scope:"store",up:e=>{const n=Object.values(e).filter(t=>t.typeName==="shape"&&t.type==="arrow");for(const t of n){const{start:r,end:s}=t.props;if(r.type==="binding"){const o=Oi(),i={typeName:"binding",id:o,type:"arrow",fromId:t.id,toId:r.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:r.normalizedAnchor,isExact:r.isExact,isPrecise:r.isPrecise}};e[o]=i,t.props.start={x:0,y:0}}else delete t.props.start.type;if(s.type==="binding"){const o=Oi(),i={typeName:"binding",id:o,type:"arrow",fromId:t.id,toId:s.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:s.normalizedAnchor,isExact:s.isExact,isPrecise:s.isPrecise}};e[o]=i,t.props.end={x:0,y:0}}else delete t.props.end.type}}},Bd({id:ba.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}})]}),ET={terminal:ig("start","end"),normalizedAnchor:Bi,isExact:ye,isPrecise:ye},_T={sequence:[{dependsOn:[ba.ExtractBindings]}]},C7=ks("camera",ve({typeName:dn("camera"),id:rr("camera"),x:de,y:de,z:de,meta:Ht})),I7=Wn("com.tldraw.camera",{AddMeta:1}),E7=dr({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:I7.AddMeta,up:e=>{e.meta={}}}]}),us=_s("camera",{validator:C7,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),_7=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"]),kT=og(_7),k7=ve({type:kT,rotation:de}),T7=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),M7=og(T7),A7=new Set(["starting","paused","active","stopping"]),TT=ve({id:he,points:It(Bi),size:ef,color:M7,opacity:de,state:og(A7),delay:de,shrink:de,taper:ye}),wu=rr("page"),j7=ks("page",ve({typeName:dn("page"),id:wu,name:he,index:Y0,meta:Ht})),O7=Wn("com.tldraw.page",{AddMeta:1}),D7=dr({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:O7.AddMeta,up:e=>{e.meta={}}}]}),to=_s("page",{validator:j7,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function Tn(e){return to.isId(e)}const R7={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},MT=e=>e?Wc(e,n=>R7[n]):null;rr("instance");function L7(e){const n={};for(const[r,s]of e)n[r]=mT(s);const t=ks("instance",ve({typeName:dn("instance"),id:rr("instance"),currentPageId:wu,followingUserId:he.nullable(),brush:Vc.nullable(),opacityForNextShape:yT,stylesForNextShape:ve(n),cursor:k7,scribbles:It(TT),isFocusMode:ye,isDebugMode:ye,isToolLocked:ye,exportBackground:ye,screenBounds:Vc,insets:It(ye),zoomBrush:Vc.nullable(),isPenMode:ye,isGridMode:ye,chatMessage:he,isChatting:ye,highlightedUserIds:It(he),isFocused:ye,devicePixelRatio:de,isCoarsePointer:ye,isHoveringCanvas:ye.nullable(),openMenus:It(he),isChangingStyle:ye,isReadonly:ye,meta:Ht,duplicateProps:ve({shapeIds:It(rr("shape")),offset:ve({x:de,y:de})}).nullable()}));return _s("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}}).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}))}const Ze=Wn("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}),$7=dr({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:Ze.AddTransparentExportBgs,up:e=>({...e,exportBackground:!0})},{id:Ze.RemoveDialog,up:({dialog:e,...n})=>n},{id:Ze.AddToolLockMode,up:e=>({...e,isToolLocked:!1})},{id:Ze.RemoveExtraPropsForNextShape,up:({propsForNextShape:e,...n})=>({...n,propsForNextShape:Object.fromEntries(Object.entries(e).filter(([t])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(t)))})},{id:Ze.AddLabelColor,up:({propsForNextShape:e,...n})=>({...n,propsForNextShape:{...e,labelColor:"black"}})},{id:Ze.AddFollowingUserId,up:e=>({...e,followingUserId:null})},{id:Ze.RemoveAlignJustify,up:e=>{let n=e.propsForNextShape.align;return n==="justify"&&(n="start"),{...e,propsForNextShape:{...e.propsForNextShape,align:n}}}},{id:Ze.AddZoom,up:e=>({...e,zoomBrush:null})},{id:Ze.AddVerticalAlign,up:e=>({...e,propsForNextShape:{...e.propsForNextShape,verticalAlign:"middle"}})},{id:Ze.AddScribbleDelay,up:e=>e.scribble!==null?{...e,scribble:{...e.scribble,delay:0}}:{...e}},{id:Ze.RemoveUserId,up:({userId:e,...n})=>n},{id:Ze.AddIsPenModeAndIsGridMode,up:e=>({...e,isPenMode:!1,isGridMode:!1})},{id:Ze.HoistOpacity,up:({propsForNextShape:{opacity:e,...n},...t})=>({...t,opacityForNextShape:Number(e??"1"),propsForNextShape:n})},{id:Ze.AddChat,up:e=>({...e,chatMessage:"",isChatting:!1})},{id:Ze.AddHighlightedUserIds,up:e=>({...e,highlightedUserIds:[]})},{id:Ze.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:e,...n})=>({...n,stylesForNextShape:{}})},{id:Ze.AddMeta,up:e=>({...e,meta:{}})},{id:Ze.RemoveCursorColor,up:e=>{const{color:n,...t}=e.cursor;return{...e,cursor:t}}},{id:Ze.AddLonelyProperties,up:e=>({...e,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:Ze.ReadOnlyReadonly,up:({isReadOnly:e,...n})=>({...n,isReadonly:e})},{id:Ze.AddHoveringCanvas,up:e=>({...e,isHoveringCanvas:null})},{id:Ze.AddScribbles,up:({scribble:e,...n})=>({...n,scribbles:[]})},{id:Ze.AddInset,up:e=>({...e,insets:[!1,!1,!1,!1]}),down:({insets:e,...n})=>({...n})},{id:Ze.AddDuplicateProps,up:e=>({...e,duplicateProps:null}),down:({duplicateProps:e,...n})=>({...n})},{id:Ze.RemoveCanMoveCamera,up:({canMoveCamera:e,...n})=>({...n}),down:e=>({...e,canMoveCamera:!0})}]}),mn="instance:instance",N7=ks("instance_page_state",ve({typeName:dn("instance_page_state"),id:rr("instance_page_state"),pageId:wu,selectedShapeIds:It(mr),hintingShapeIds:It(mr),erasingShapeIds:It(mr),hoveredShapeId:mr.nullable(),editingShapeId:mr.nullable(),croppingShapeId:mr.nullable(),focusedGroupId:mr.nullable(),meta:Ht})),ec=Wn("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),F7=dr({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:ec.AddCroppingId,up(e){e.croppingShapeId=null}},{id:ec.RemoveInstanceIdAndCameraId,up(e){delete e.instanceId,delete e.cameraId}},{id:ec.AddMeta,up:e=>{e.meta={}}},{id:ec.RenameProperties,up:e=>{},down:e=>{}},{id:ec.RenamePropertiesAgain,up:e=>{e.selectedShapeIds=e.selectedIds,delete e.selectedIds,e.hintingShapeIds=e.hintingIds,delete e.hintingIds,e.erasingShapeIds=e.erasingIds,delete e.erasingIds,e.hoveredShapeId=e.hoveredId,delete e.hoveredId,e.editingShapeId=e.editingId,delete e.editingId,e.croppingShapeId=e.croppingShapeId??e.croppingId??null,delete e.croppingId,e.focusedGroupId=e.focusLayerId,delete e.focusLayerId},down:e=>{e.selectedIds=e.selectedShapeIds,delete e.selectedShapeIds,e.hintingIds=e.hintingShapeIds,delete e.hintingShapeIds,e.erasingIds=e.erasingShapeIds,delete e.erasingShapeIds,e.hoveredId=e.hoveredShapeId,delete e.hoveredShapeId,e.editingId=e.editingShapeId,delete e.editingShapeId,e.croppingId=e.croppingShapeId,delete e.croppingShapeId,e.focusLayerId=e.focusedGroupId,delete e.focusedGroupId}}]}),zr=_s("instance_page_state",{validator:N7,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:{}})),z7=ks("pointer",ve({typeName:dn("pointer"),id:rr("pointer"),x:de,y:de,lastActivityTimestamp:de,meta:Ht})),B7=Wn("com.tldraw.pointer",{AddMeta:1}),U7=dr({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:B7.AddMeta,up:e=>{e.meta={}}}]}),q0=_s("pointer",{validator:z7,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),of=q0.createId("pointer"),H7=ks("instance_presence",ve({typeName:dn("instance_presence"),id:rr("instance_presence"),userId:he,userName:he,lastActivityTimestamp:de,followingUserId:he.nullable(),cursor:ve({x:de,y:de,type:kT,rotation:de}),color:he,camera:ve({x:de,y:de,z:de}),screenBounds:Vc,selectedShapeIds:It(rr("shape")),currentPageId:rr("page"),brush:Vc.nullable(),scribbles:It(TT),chatMessage:he,meta:Ht})),tc=Wn("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5}),K7=dr({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:tc.AddScribbleDelay,up:e=>{e.scribble!==null&&(e.scribble.delay=0)}},{id:tc.RemoveInstanceId,up:e=>{delete e.instanceId}},{id:tc.AddChatMessage,up:e=>{e.chatMessage=""}},{id:tc.AddMeta,up:e=>{e.meta={}}},{id:tc.RenameSelectedShapeIds,up:e=>{}}]}),W7=_s("instance_presence",{validator:H7,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:0,followingUserId:null,color:"#FF0000",camera:{x:0,y:0,z:1},cursor:{x:0,y:0,type:"default",rotation:0},screenBounds:{x:0,y:0,w:1,h:1},selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}})),G7=ks("document",ve({typeName:dn("document"),id:dn("document:document"),gridSize:de,name:he,meta:Ht})),uC=Wn("com.tldraw.document",{AddName:1,AddMeta:2}),V7=dr({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:uC.AddName,up:e=>{e.name=""},down:e=>{delete e.name}},{id:uC.AddMeta,up:e=>{e.meta={}}}]}),Z0=_s("document",{validator:G7,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),wv=Z0.createId("document");function Y7(e,n){return e.indexn.index?1:0}function dC(e){e.typeName==="asset"&&("src"in e&&(e.src=""),"src"in e.props&&(e.props.src=""))}const X7=({error:e,phase:n,record:t,recordBefore:r})=>{throw L0(e,{tags:{origin:"store.validateRecord",storePhase:n,isExistingValidationIssue:n==="initialize"},extras:{recordBefore:r?dC(Be(r)):void 0,recordAfter:dC(Be(t))}}),e};function q7(){return[to.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function Z7(e){const n=e.query.ids("page"),t=()=>{if(!e.has(wv))return e.put([Z0.create({id:wv,name:e.props.defaultName})]),t();if(!e.has(of))return e.put([q0.create({id:of})]),t();const r=n.get();if(r.size===0)return e.put(q7()),t();const s=()=>[...r].map(l=>e.get(l)).sort(Y7)[0].id,o=e.get(mn);if(o){if(!r.has(o.currentPageId))return e.put([{...o,currentPageId:s()}]),t()}else return e.put([e.schema.types.instance.create({id:mn,currentPageId:s(),exportBackground:!0})]),t();const i=new Set,a=new Set;for(const l of r){const c=zr.createId(l);e.has(c)||i.add(c);const u=us.createId(l);e.has(u)||a.add(u)}i.size>0&&e.put([...i].map(l=>zr.create({id:l,pageId:zr.parseId(l)}))),a.size>0&&e.put([...a].map(l=>us.create({id:l})))};return t}const Q7=X0("bookmark",ve({title:he,description:he,image:he,favicon:he,src:zi.nullable()})),hC=Wn("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),J7=dr({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:e=>e.type==="bookmark",sequence:[{id:hC.MakeUrlsValid,up:e=>{zi.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:hC.AddFavicon,up:e=>{zi.isValid(e.props.favicon)||(e.props.favicon="")},down:e=>{delete e.props.favicon}}]}),eH=X0("image",ve({w:de,h:de,name:he,isAnimated:ye,mimeType:he.nullable(),src:zi.nullable(),fileSize:bt.optional()})),nc=Wn("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),tH=dr({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:e=>e.type==="image",sequence:[{id:nc.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:nc.RenameWidthHeight,up:e=>{e.props.w=e.props.width,e.props.h=e.props.height,delete e.props.width,delete e.props.height},down:e=>{e.props.width=e.props.w,e.props.height=e.props.h,delete e.props.w,delete e.props.h}},{id:nc.MakeUrlsValid,up:e=>{zi.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:nc.AddFileSize,up:e=>{e.props.fileSize=-1},down:e=>{delete e.props.fileSize}},{id:nc.MakeFileSizeOptional,up:e=>{e.props.fileSize===-1&&(e.props.fileSize=void 0)},down:e=>{e.props.fileSize===void 0&&(e.props.fileSize=-1)}}]}),nH=X0("video",ve({w:de,h:de,name:he,isAnimated:ye,mimeType:he.nullable(),src:zi.nullable(),fileSize:de.optional()})),rc=Wn("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),rH=dr({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:e=>e.type==="video",sequence:[{id:rc.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:rc.RenameWidthHeight,up:e=>{e.props.w=e.props.width,e.props.h=e.props.height,delete e.props.width,delete e.props.height},down:e=>{e.props.width=e.props.w,e.props.height=e.props.h,delete e.props.w,delete e.props.h}},{id:rc.MakeUrlsValid,up:e=>{zi.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:rc.AddFileSize,up:e=>{e.props.fileSize=-1},down:e=>{delete e.props.fileSize}},{id:rc.MakeFileSizeOptional,up:e=>{e.props.fileSize===-1&&(e.props.fileSize=void 0)},down:e=>{e.props.fileSize===void 0&&(e.props.fileSize=-1)}}]}),sH=ks("asset",G0("type",{image:eH,video:nH,bookmark:Q7})),oH=Wn("com.tldraw.asset",{AddMeta:1}),iH=dr({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:oH.AddMeta,up:e=>{e.meta={}}}]}),_i=_s("asset",{validator:sH,scope:"document"}).withDefaultProperties(()=>({meta:{}})),AT={w:bt,h:bt,assetId:ag.nullable(),url:ar},pC=Xr("bookmark",{NullAssetId:1,MakeUrlsValid:2}),jT={sequence:[{id:pC.NullAssetId,up:e=>{e.assetId===void 0&&(e.assetId=null)},down:"retired"},{id:pC.MakeUrlsValid,up:e=>{ar.isValid(e.url)||(e.url="")},down:e=>{}}]},OT=ve({type:ig("free","straight"),points:It(Bi)}),DT={color:lr,fill:Hi,dash:Ui,size:ws,segments:It(OT),isComplete:ye,isClosed:ye,isPen:ye,scale:bt},fC=Xr("draw",{AddInPen:1,AddScale:2}),RT={sequence:[{id:fC.AddInPen,up:e=>{const{points:n}=e.segments[0];if(n.length===0){e.isPen=!1;return}let t=!(n[0].z===0||n[0].z===.5);n[1]&&(t=t&&!(n[1].z===0||n[1].z===.5)),e.isPen=t},down:"retired"},{id:fC.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]};var aH={};const gC=/(^\/r\/[^/]+\/?$)/,De=e=>{try{return new URL(e)}catch{return}},Wu=[{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:e=>{const n=De(e);if(n&&n.pathname.match(gC))return e},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(gC))return e}},{type:"figma",title:"Figma",hostnames:["figma.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{if(e.match(/https:\/\/([\w\.-]+\.)?figma.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/)&&!e.includes("figma.com/embed"))return`https://www.figma.com/embed?embed_host=share&url=${e}`},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/embed\/?$/)){const t=n.searchParams.get("url");if(t)return t}}},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,overridePermissions:{"allow-presentation":!0},toEmbedUrl:e=>{if(e.includes("/maps/")){const n=e.match(/@(.*),(.*),(.*)z/);let t;if(n){const[,r,s,o]=n;t=`https://${new URL(e).host.replace("www.","")}/maps/embed/v1/view?key=${aH.NEXT_PUBLIC_GC_API_KEY}¢er=${r},${s}&zoom=${o}`}else t="";return t}},fromEmbedUrl:e=>{const n=De(e);if(!n)return;if(n.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&n.searchParams.has("center")&&n.searchParams.get("zoom")){const r=n.searchParams.get("zoom"),[s,o]=n.searchParams.get("center").split(",");return`https://www.google.com/maps/@${s},${o},${r}z`}}},{type:"val_town",title:"Val Town",hostnames:["val.town"],minWidth:260,minHeight:100,width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=De(e),t=n&&n.pathname.match(/\/v\/(.+)\/?/);if(t)return`https://www.val.town/embed/${t[1]}`},fromEmbedUrl:e=>{const n=De(e),t=n&&n.pathname.match(/\/embed\/(.+)\/?/);if(t)return`https://www.val.town/v/${t[1]}`}},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=De(e),t=n&&n.pathname.match(/\/s\/([^/]+)\/?/);if(t)return`https://codesandbox.io/embed/${t[1]}`},fromEmbedUrl:e=>{const n=De(e),t=n&&n.pathname.match(/\/embed\/([^/]+)\/?/);if(t)return`https://codesandbox.io/s/${t[1]}`}},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:e=>{const n=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,t=e.match(n);if(t){const[r,s,o]=t;return`https://codepen.io/${s}/embed/${o}`}},fromEmbedUrl:e=>{const n=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,t=e.match(n);if(t){const[r,s,o]=t;return`https://codepen.io/${s}/pen/${o}`}}},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,toEmbedUrl:e=>{const n=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,t=e.match(n);if(t){const[r,s]=t;return`https://scratch.mit.edu/projects/embed/${s}`}},fromEmbedUrl:e=>{const n=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,t=e.match(n);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,toEmbedUrl:e=>{const n=De(e);if(!n)return;const t=n.hostname.replace(/^www./,"");if(t==="youtu.be")return`https://www.youtube.com/embed/${n.pathname.split("/").filter(Boolean)[0]}`;if((t==="youtube.com"||t==="m.youtube.com")&&n.pathname.match(/^\/watch/))return`https://www.youtube.com/embed/${n.searchParams.get("v")}`},fromEmbedUrl:e=>{const n=De(e);if(!n)return;if(n.hostname.replace(/^www./,"")==="youtube.com"){const r=n.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{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},toEmbedUrl:e=>{const n=De(e),t=n==null?void 0:n.searchParams.get("cid");if(n!=null&&n.pathname.match(/\/calendar\/u\/0/)&&t){n.pathname="/calendar/embed";const r=Array.from(n.searchParams.keys());for(const s of r)n.searchParams.delete(s);return n.searchParams.set("src",t),n.href}},fromEmbedUrl:e=>{const n=De(e),t=n==null?void 0:n.searchParams.get("src");if(n!=null&&n.pathname.match(/\/calendar\/embed/)&&t){n.pathname="/calendar/u/0";const r=Array.from(n.searchParams.keys());for(const s of r)n.searchParams.delete(s);return n.searchParams.set("cid",t),n.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},toEmbedUrl:e=>{const n=De(e);if(n!=null&&n.pathname.match(/^\/presentation/)&&(n!=null&&n.pathname.match(/\/pub\/?$/))){n.pathname=n.pathname.replace(/\/pub$/,"/embed");const t=Array.from(n.searchParams.keys());for(const r of t)n.searchParams.delete(r);return n.href}},fromEmbedUrl:e=>{const n=De(e);if(n!=null&&n.pathname.match(/^\/presentation/)&&(n!=null&&n.pathname.match(/\/embed\/?$/))){n.pathname=n.pathname.replace(/\/embed$/,"/pub");const t=Array.from(n.searchParams.keys());for(const r of t)n.searchParams.delete(r);return n.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/))return e.split("/").pop()?e:void 0},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/))return e.split("/").pop()?e:void 0}},{type:"replit",title:"Replit",hostnames:["replit.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/))return`${e}?embed=true`},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/)&&n.searchParams.has("embed"))return n.searchParams.delete("embed"),n.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/map\//))return n.origin+"/embed"+n.pathname},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/embed\/map\//))return n.pathname=n.pathname.replace(/^\/embed/,""),n.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/(artist|album)\//))return n.origin+"/embed"+n.pathname},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/embed\/(artist|album)\//))return n.origin+n.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.hostname==="vimeo.com"&&n.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+n.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:e=>{const n=De(e);if(n&&n.hostname==="player.vimeo.com"){const t=n.pathname.match(/^\/video\/([^/]+)\/?$/);if(t)return"https://vimeo.com/"+t[1]}}},{type:"excalidraw",title:"Excalidraw",hostnames:["excalidraw.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.hash.match(/#room=/))return e},fromEmbedUrl:e=>{const n=De(e);if(n&&n.hash.match(/#room=/))return e}},{type:"observable",title:"Observable",hostnames:["observablehq.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!1,backgroundColor:"#fff",toEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}/embed${n.pathname}?cell=*`;if(n&&n.pathname.match(/^\/d\/([^/]+)\/?$/)){const t=n.pathname.replace(/^\/d/,"");return`${n.origin}/embed${t}?cell=*`}},fromEmbedUrl:e=>{const n=De(e);if(n&&n.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","")}#cell-*`;if(n&&n.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","/d")}#cell-*`}},{type:"desmos",title:"Desmos",hostnames:["desmos.com"],width:700,height:450,doesResize:!0,toEmbedUrl:e=>{const n=De(e);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search===""&&n.hash==="")return`${e}?embed`},fromEmbedUrl:e=>{const n=De(e);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search==="?embed"&&n.hash==="")return e.replace("?embed","")}}],lH={"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},LT={w:bt,h:bt,url:he},Ud=Xr("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),$T={sequence:[{id:Ud.GenOriginalUrlInEmbed,up:e=>{try{const n=e.url,t=new URL(n).host.replace("www.","");let r;for(const s of Wu)if(s.hostnames.includes(t))try{r=s.fromEmbedUrl(n)}catch(o){console.warn(o)}e.tmpOldUrl=e.url,e.url=r??""}catch{e.url="",e.tmpOldUrl=e.url}},down:"retired"},{id:Ud.RemoveDoesResize,up:e=>{delete e.doesResize},down:"retired"},{id:Ud.RemoveTmpOldUrl,up:e=>{delete e.tmpOldUrl},down:"retired"},{id:Ud.RemovePermissionOverrides,up:e=>{delete e.overridePermissions},down:"retired"}]},NT={w:bt,h:bt,name:he},FT={sequence:[]},af=Xt.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),lf=Xt.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),Br=Xt.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"]}),zT={geo:Br,labelColor:wT,color:lr,fill:Hi,dash:Ui,size:ws,font:xs,align:af,verticalAlign:lf,url:ar,w:bt,h:bt,growY:ef,text:he,scale:bt},Os=Xr("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9}),BT={sequence:[{id:Os.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:Os.AddLabelColor,up:e=>{e.labelColor="black"},down:"retired"},{id:Os.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:Os.AddCheckBox,up:e=>{},down:"retired"},{id:Os.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:"retired"},{id:Os.MigrateLegacyAlign,up:e=>{let n;switch(e.align){case"start":n="start-legacy";break;case"end":n="end-legacy";break;default:n="middle-legacy";break}e.align=n},down:"retired"},{id:Os.AddCloud,up:e=>{},down:"retired"},{id:Os.MakeUrlsValid,up:e=>{ar.isValid(e.url)||(e.url="")},down:e=>{}},{id:Os.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},UT={},HT={sequence:[]},KT={color:lr,size:ws,segments:It(OT),isComplete:ye,isPen:ye,scale:bt},cH=Xr("highlight",{AddScale:1}),WT={sequence:[{id:cH.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},uH=ve({topLeft:Bi,bottomRight:Bi}),GT={w:bt,h:bt,playing:ye,url:ar,assetId:ag.nullable(),crop:uH.nullable(),flipX:ye,flipY:ye},Hd=Xr("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4}),VT={sequence:[{id:Hd.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:Hd.AddCropProp,up:e=>{e.crop=null},down:e=>{delete e.crop}},{id:Hd.MakeUrlsValid,up:e=>{ar.isValid(e.url)||(e.url="")},down:e=>{}},{id:Hd.AddFlipProps,up:e=>{e.flipX=!1,e.flipY=!1},down:e=>{delete e.flipX,delete e.flipY}}]},cf=Xt.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),dH=ve({id:he,index:Y0,x:de,y:de}),YT={color:lr,dash:Ui,size:ws,spline:cf,points:tf(he,dH),scale:bt},sc=Xr("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),XT={sequence:[{id:sc.AddSnapHandles,up:e=>{for(const n of Object.values(e.handles))n.canSnap=!0},down:"retired"},{id:sc.RemoveExtraHandleProps,up:e=>{e.handles=J2(Object.values(e.handles).map(n=>[n.index,{x:n.x,y:n.y}]))},down:e=>{const n=Object.entries(e.handles).map(([t,r])=>({index:t,...r})).sort(an);e.handles=Object.fromEntries(n.map((t,r)=>{const s=r===0?"start":r===n.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:sc.HandlesToPoints,up:e=>{const n=Object.entries(e.handles).map(([t,{x:r,y:s}])=>({x:r,y:s,index:t})).sort(an);e.points=n.map(({x:t,y:r})=>({x:t,y:r})),delete e.handles},down:e=>{const n=xu(e.points.length);e.handles=Object.fromEntries(e.points.map((t,r)=>[n[r],{x:t.x,y:t.y}])),delete e.points}},{id:sc.PointIndexIds,up:e=>{const n=xu(e.points.length);e.points=Object.fromEntries(e.points.map((t,r)=>{const s=n[r];return[s,{id:s,index:s,x:t.x,y:t.y}]}))},down:e=>{const n=Object.values(e.points).sort(an);e.points=n.map(({x:t,y:r})=>({x:t,y:r}))}},{id:sc.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},qT={color:lr,size:ws,font:xs,fontSizeAdjustment:ef,align:af,verticalAlign:lf,growY:ef,url:ar,text:he,scale:bt},xi=Xr("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7}),ZT={sequence:[{id:xi.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:xi.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:xi.MigrateLegacyAlign,up:e=>{switch(e.align){case"start":e.align="start-legacy";return;case"end":e.align="end-legacy";return;default:e.align="middle-legacy";return}},down:"retired"},{id:xi.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:"retired"},{id:xi.MakeUrlsValid,up:e=>{ar.isValid(e.url)||(e.url="")},down:e=>{}},{id:xi.AddFontSizeAdjustment,up:e=>{e.fontSizeAdjustment=0},down:e=>{delete e.fontSizeAdjustment}},{id:xi.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},bv=Xt.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]}),QT={color:lr,size:ws,font:xs,textAlign:bv,w:bt,text:he,scale:bt,autoSize:ye},mC=Xr("text",{RemoveJustify:1,AddTextAlign:2}),JT={sequence:[{id:mC.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:mC.AddTextAlign,up:e=>{e.textAlign=e.align,delete e.align},down:e=>{e.align=e.textAlign,delete e.textAlign}}]},eM={w:bt,h:bt,time:de,playing:ye,url:ar,assetId:ag.nullable()},yC=Xr("video",{AddUrlProp:1,MakeUrlsValid:2}),tM={sequence:[{id:yC.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:yC.MakeUrlsValid,up:e=>{ar.isValid(e.url)||(e.url="")},down:e=>{}}]},Kd=Wn("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4}),hH=Ja({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:Kd.RemoveCodeAndIconShapeTypes,scope:"store",up:e=>{for(const[n,t]of Hn(e))t.typeName==="shape"&&(t.type==="icon"||t.type==="code")&&delete e[n]}},{id:Kd.AddInstancePresenceType,scope:"store",up(e){}},{id:Kd.RemoveTLUserAndPresenceAndAddPointer,scope:"store",up:e=>{for(const[n,t]of Hn(e))t.typeName.match(/^(user|user_presence)$/)&&delete e[n]}},{id:Kd.RemoveUserDocument,scope:"store",up:e=>{for(const[n,t]of Hn(e))t.typeName.match("user_document")&&delete e[n]}}]}),pH={arrow:{migrations:IT,props:CT},bookmark:{migrations:jT,props:AT},draw:{migrations:RT,props:DT},embed:{migrations:$T,props:LT},frame:{migrations:FT,props:NT},geo:{migrations:BT,props:zT},group:{migrations:HT,props:UT},highlight:{migrations:WT,props:KT},image:{migrations:VT,props:GT},line:{migrations:XT,props:YT},note:{migrations:ZT,props:qT},text:{migrations:JT,props:QT},video:{migrations:tM,props:eM}},fH={arrow:{migrations:_T,props:ET}};function gH({shapes:e=pH,bindings:n=fH,migrations:t}={}){const r=new Map;for(const a of gt(e))for(const l of ST(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=P7(e),o=x7(n),i=L7(r);return K0.create({asset:_i,binding:o,camera:us,document:Z0,instance:i,instance_page_state:zr,page:to,instance_presence:W7,pointer:q0,shape:s},{migrations:[hH,iH,E7,V7,$7,F7,D7,K7,U7,b7,J7,tH,rH,...cC("shape",e),...cC("binding",n),...t??[]],onValidationFailure:X7,createIntegrityChecker:Z7})}const bu=[{locale:"id",label:"Bahasa Indonesia"},{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:"fr",label:"Français"},{locale:"gl",label:"Galego"},{locale:"hr",label:"Hrvatski"},{locale:"it",label:"Italiano"},{locale:"hu",label:"Magyar"},{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:"ru",label:"Russian"},{locale:"sl",label:"Slovenščina"},{locale:"fi",label:"Suomi"},{locale:"sv",label:"Svenska"},{locale:"vi",label:"Tiếng Việt"},{locale:"tr",label:"Türkçe"},{locale:"uk",label:"Ukrainian"},{locale:"he",label:"עברית"},{locale:"ar",label:"عربي"},{locale:"fa",label:"فارسی"},{locale:"ku",label:"کوردی"},{locale:"ne",label:"नेपाली"},{locale:"hi-in",label:"हिन्दी"},{locale:"te",label:"తెలుగు"},{locale:"th",label:"ภาษาไทย"},{locale:"my",label:"မြန်မာစာ"},{locale:"ko-kr",label:"한국어"},{locale:"ja",label:"日本語"},{locale:"zh-cn",label:"简体中文"},{locale:"zh-tw",label:"繁體中文 (台灣)"}];function mH(){const e=typeof window<"u"?window.navigator.languages??["en"]:["en"];return yH(e)}function yH(e){for(const n of e){const t=SH(n);if(t)return t}return"en"}const SC={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function SH(e){const n=bu.find(s=>s.locale===e.toLowerCase());if(n)return n.locale;const[t,r]=e.split(/[-_]/).map(s=>s.toLowerCase());if(r){const s=bu.find(o=>o.locale===t);if(s)return s.locale}return t in SC?SC[t]:null}function lg(e,n){const t=Ce.useRef(n);t.current=n;const[r,s,o]=Ce.useMemo(()=>{let i=null;const a=u=>(i=u,()=>{i=null}),l=new Tl(`useStateTracking(${e})`,()=>{var u;return(u=t.current)==null?void 0:u.call(t)},{scheduleEffect(){i==null||i()}});return[l,a,()=>l.scheduleCount]},[e]);return Ce.useSyncExternalStore(s,o,o),Ce.useEffect(()=>(r.attach(),r.maybeScheduleEffect(),()=>{r.detach()}),[r]),r.execute()}const vC={apply(e,n,t){return lg(e.displayName??e.name??"tracked(???)",()=>e.apply(n,t))}},vH=Symbol.for("react.memo"),xH=Symbol.for("react.forward_ref");function Lt(e){let n=null;const t=e.$$typeof;return t===vH&&(e=e.type,n=e.compare),t===xH?P.memo(P.forwardRef(new Proxy(e.render,vC))):P.memo(new Proxy(e,vC),n)}function wH(){const e=arguments[0],n=arguments[1],t=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return P.useMemo(()=>G(`useComputed(${e})`,n,t),r)}function Ko(e,n,t=Gs){P.useEffect(()=>{const r=new Tl(e,n);return r.attach(),r.execute(),()=>{r.detach()}},t)}function H(){const e=arguments,n=e.length===3?e[2]:[e[0]],t=e.length===3?e[0]:`useValue(${e[0].name})`,r=P.useRef(!0);r.current=!0;const s=P.useMemo(()=>e.length===1?e[0]:G(t,()=>{if(r.current)return e[1]();try{return e[1]()}catch{return{}}}),n);try{const{subscribe:o,getSnapshot:i}=P.useMemo(()=>({subscribe:a=>oa(`useValue(${t})`,()=>{s.get(),a()}),getSnapshot:()=>s.get()}),[s]);return P.useSyncExternalStore(o,i,i)}finally{r.current=!1}}var nM={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames -*/(function(e){(function(){var n={}.hasOwnProperty;function t(){for(var o="",i=0;i or components");return e}function CH(){return d.jsx("div",{className:"tl-background"})}function jl(e,n,t,r,s,o){P.useLayoutEffect(()=>{const i=e.current;if(!i||n===void 0)return;let a=`translate(${n}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 At={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:-1+(4-2*e)*e,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,easeInQuart:e=>e*e*e*e,easeOutQuart:e=>1- --e*e*e*e,easeInOutQuart:e=>e<.5?8*e*e*e*e:1-8*--e*e*e*e,easeInQuint:e=>e*e*e*e*e,easeOutQuint:e=>1+--e*e*e*e*e,easeInOutQuint:e=>e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e,easeInSine:e=>1-Math.cos(e*Math.PI/2),easeOutSine:e=>Math.sin(e*Math.PI/2),easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,easeInExpo:e=>e<=0?0:Math.pow(2,10*e-10),easeOutExpo:e=>e>=1?1:1-Math.pow(2,-10*e),easeInOutExpo:e=>e<=0?0:e>=1?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2};class b{constructor(n=0,t=0,r=1){this.x=n,this.y=t,this.z=r}get pressure(){return this.z}set(n=this.x,t=this.y,r=this.z){return this.x=n,this.y=t,this.z=r,this}setTo({x:n=0,y:t=0,z:r=1}){return this.x=n,this.y=t,this.z=r,this}rot(n){if(n===0)return this;const{x:t,y:r}=this,s=Math.sin(n),o=Math.cos(n);return this.x=t*o-r*s,this.y=t*s+r*o,this}rotWith(n,t){if(t===0)return this;const r=this.x-n.x,s=this.y-n.y,o=Math.sin(t),i=Math.cos(t);return this.x=n.x+(r*i-s*o),this.y=n.y+(r*o+s*i),this}clone(){const{x:n,y:t,z:r}=this;return new b(n,t,r)}sub(n){return this.x-=n.x,this.y-=n.y,this}subXY(n,t){return this.x-=n,this.y-=t,this}subScalar(n){return this.x-=n,this.y-=n,this}add(n){return this.x+=n.x,this.y+=n.y,this}addXY(n,t){return this.x+=n,this.y+=t,this}addScalar(n){return this.x+=n,this.y+=n,this}clamp(n,t){return this.x=Math.max(this.x,n),this.y=Math.max(this.y,n),t!==void 0&&(this.x=Math.min(this.x,t),this.y=Math.min(this.y,t)),this}div(n){return this.x/=n,this.y/=n,this}divV(n){return this.x/=n.x,this.y/=n.y,this}mul(n){return this.x*=n,this.y*=n,this}mulV(n){return this.x*=n.x,this.y*=n.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(n,t){const r=b.Tan(n,this);return this.add(r.mul(t))}neg(){return this.x*=-1,this.y*=-1,this}cross(n){return this.x=this.y*n.z-this.z*n.y,this.y=this.z*n.x-this.x*n.z,this}dpr(n){return b.Dpr(this,n)}cpr(n){return b.Cpr(this,n)}len2(){return b.Len2(this)}len(){return b.Len(this)}pry(n){return b.Pry(this,n)}per(){const{x:n,y:t}=this;return this.x=t,this.y=-n,this}uni(){return b.Uni(this)}tan(n){return b.Tan(this,n)}dist(n){return b.Dist(this,n)}distanceToLineSegment(n,t){return b.DistanceToLineSegment(n,t,this)}slope(n){return b.Slope(this,n)}snapToGrid(n){return this.x=Math.round(this.x/n)*n,this.y=Math.round(this.y/n)*n,this}angle(n){return b.Angle(this,n)}toAngle(){return b.ToAngle(this)}lrp(n,t){return this.x=this.x+(n.x-this.x)*t,this.y=this.y+(n.y-this.y)*t,this}equals(n){return b.Equals(this,n)}equalsXY(n,t){return b.EqualsXY(this,n,t)}norm(){const n=this.len();return this.x=n===0?0:this.x/n,this.y=n===0?0:this.y/n,this}toFixed(){return b.ToFixed(this)}toString(){return b.ToString(b.ToFixed(this))}toJson(){return b.ToJson(this)}toArray(){return b.ToArray(this)}static Add(n,t){return new b(n.x+t.x,n.y+t.y)}static AddXY(n,t,r){return new b(n.x+t,n.y+r)}static Sub(n,t){return new b(n.x-t.x,n.y-t.y)}static SubXY(n,t,r){return new b(n.x-t,n.y-r)}static AddScalar(n,t){return new b(n.x+t,n.y+t)}static SubScalar(n,t){return new b(n.x-t,n.y-t)}static Div(n,t){return new b(n.x/t,n.y/t)}static Mul(n,t){return new b(n.x*t,n.y*t)}static DivV(n,t){return new b(n.x/t.x,n.y/t.y)}static MulV(n,t){return new b(n.x*t.x,n.y*t.y)}static Neg(n){return new b(-n.x,-n.y)}static Per(n){return new b(n.y,-n.x)}static Abs(n){return new b(Math.abs(n.x),Math.abs(n.y))}static Dist(n,t){return((n.y-t.y)**2+(n.x-t.x)**2)**.5}static DistMin(n,t,r){return(n.x-t.x)*(n.x-t.x)+(n.y-t.y)*(n.y-t.y)Math.max(n.x,t.x))return b.Cast(n.x>t.x?n:t);if(i.yMath.max(n.y,t.y))return b.Cast(n.y>t.y?n:t)}return i}static DistanceToLineThroughPoint(n,t,r){return b.Dist(r,b.NearestPointOnLineThroughPoint(n,t,r))}static DistanceToLineSegment(n,t,r,s=!0){return b.Dist(r,b.NearestPointOnLineSegment(n,t,r,s))}static Snap(n,t=1){return new b(Math.round(n.x/t)*t,Math.round(n.y/t)*t)}static Cast(n){return n instanceof b?n:b.From(n)}static Slope(n,t){return n.x===t.y?NaN:(n.y-t.y)/(n.x-t.x)}static IsNaN(n){return isNaN(n.x)||isNaN(n.y)}static Angle(n,t){return Math.atan2(t.y-n.y,t.x-n.x)}static Lrp(n,t,r){return b.Sub(t,n).mul(r).add(n)}static Med(n,t){return new b((n.x+t.x)/2,(n.y+t.y)/2)}static Equals(n,t){return Math.abs(n.x-t.x)<1e-4&&Math.abs(n.y-t.y)<1e-4}static EqualsXY(n,t,r){return n.x===t&&n.y===r}static Clockwise(n,t,r){return(r.x-n.x)*(t.y-n.y)-(t.x-n.x)*(r.y-n.y)<0}static Rescale(n,t){const r=b.Len(n);return new b(t*n.x/r,t*n.y/r)}static ScaleWithOrigin(n,t,r){return b.Sub(n,r).mul(t).add(r)}static ToFixed(n){return new b(zs(n.x),zs(n.y))}static ToInt(n){return new b(parseInt(n.x.toFixed(0)),parseInt(n.y.toFixed(0)),parseInt((n.z??0).toFixed(0)))}static ToCss(n){return`${n.x},${n.y}`}static Nudge(n,t,r){return b.Add(n,b.Tan(t,n).mul(r))}static ToString(n){return`${n.x}, ${n.y}`}static ToAngle(n){let t=Math.atan2(n.y,n.x);return t<0&&(t+=Math.PI*2),t}static FromAngle(n,t=1){return new b(Math.cos(n)*t,Math.sin(n)*t)}static ToArray(n){return[n.x,n.y,n.z]}static ToJson(n){const{x:t,y:r,z:s}=n;return{x:t,y:r,z:s}}static Average(n){const t=n.length,r=new b(0,0);if(t===0)return r;for(let s=0;se<.5?2*e*e:-1+(4-2*e)*e;function ke(e){return`${N(e.x)},${N(e.y)} `}function Dn(e,n){return`${N((e.x+n.x)/2)},${N((e.y+n.y)/2)} `}const Me=Math.PI,Ve=Me/2,Le=Me*2,EH=Math.sin;function kt(e,n,t){return Math.max(n,typeof t<"u"?Math.min(e,t):e)}function Wd(e,n=1e10){return e?Math.round(e*n)/n:0}function Wo(e,n,t=1e-6){return Math.abs(e-n)<=t}function oM(e,n){const t=Math.pow(e-n,2)/Math.pow(e+n,2);return Me*(e+n)*(1+3*t/(10+Math.sqrt(4-3*t)))}function Go(e){return e=e%Le,e<0?e=e+Le:e===0&&(e=0),e}function Gu(e,n){return e=Go(e),n=Go(n),e>n&&(n+=Le),n-e}function iM(e,n){return Le-Gu(e,n)}function Fh(e,n){const t=(n-e)%Le;return 2*t%Le-t}function Pv(e){return(Le+e)%Le}function uf(e,n){const t=Le/n;let r=Math.floor((Pv(e)+t/2)/t)*t%Le;return rMe&&(r-=Le),r}function aM(e,n){return e===n||Wo(e%(Math.PI/2)-n%(Math.PI/2),0)}function _H(e){return e*Me/180}function kH(e){return e*180/Me}function Ki(e,n,t){return new b(e.x,e.y).add(b.FromAngle(t,n))}function ey(e,n,t){const r=e/2,s=n/2,o=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let S=0;Sa&&(a=y),v>c&&(c=v),o.push(new b(y,v))}const u=a-i,h=c-l,p=e-u,f=n-h;if(p!==0||f!==0)for(let S=0;Se.y&&wC(r,s,e)>0&&(t+=1):s.y<=e.y&&wC(r,s,e)<0&&(t-=1)}return t!==0}function N(e){return Math.round(e*1e4)/1e4}function zs(e){return Math.round(e*100)/100}const bC=e=>Math.abs(e)Me){s=Fh(n,r);const o=Fh(r,t);return Math.abs(s).5?1:0:o}}function TH(e,n,t,r){const s=2*((n-e)%Le)%Le-(n-e)%Le;return r?(Le-Math.abs(s))*(t?1:-1):s}function Q0(e,n,t){const r=-2*(e.x*(n.y-t.y)-e.y*(n.x-t.x)+n.x*t.y-t.x*n.y);return new b(((e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y)+(t.x*t.x+t.y*t.y)*(n.y-e.y))/r,((e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x)+(t.x*t.x+t.y*t.y)*(e.x-n.x))/r)}function MH(e,n,t,r,s){if(t===null)return[b.From(e),b.From(n)];const o=[],i=b.Angle(t,e),a=b.Angle(t,n),l=Gu(i,a);for(let c=0;c{const s=P.useRef(null);jl(s,e.x,e.y);const o=N(Math.max(1,e.w)),i=N(Math.max(1,e.h));return d.jsx("svg",{className:"tl-overlays__item",ref:s,children:n?d.jsxs("g",{className:"tl-brush",opacity:t,children:[d.jsx("rect",{width:o,height:i,fill:n,opacity:.75}),d.jsx("rect",{width:o,height:i,fill:"none",stroke:n,opacity:.1})]}):d.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:o,height:i})})},PC={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.1,.25,.5,1,2,4,8]},ny={duration:0,easing:At.easeInOutCubic},CC={CAMERA_MOVE:-10},AH=["top","right","bottom","left"],IC=0,J0=2,Gd=1,EC=5,jH=128;function df(e){if(e instanceof HTMLElement)return e;if(e.parentElement)return df(e.parentElement);throw Error("Could not find a parent element of an HTML type!")}function Ie(e){e.preventDefault(),xt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",e)}function Vu(e,n){if(e.setPointerCapture(n.pointerId),xt.logPointerCaptures.get()){const t=dT.get();t.set(e,(t.get(e)??0)+1),console.warn("setPointerCapture called on element:",e,n)}}function Yu(e,n){if(e.hasPointerCapture(n.pointerId)&&(e.releasePointerCapture(n.pointerId),xt.logPointerCaptures.get())){const t=dT.get();t.get(e)===1?t.delete(e):t.has(e)?t.set(e,t.get(e)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",e,n)}}const Dt=e=>e.stopPropagation(),tn=(e,n,t)=>{e&&e.style.setProperty(n,t)};function Nn(e){return e.isKilled=!0,{point:{x:e.clientX,y:e.clientY,z:e.pressure},shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.metaKey||e.ctrlKey,pointerId:e.pointerId,button:e.button,isPen:e.pointerType==="pen"}}function lM(){const e=F();return P.useMemo(function(){let r,s;function o(m){if(!m.isKilled){if(m.button===J0){e.dispatch({type:"pointer",target:"canvas",name:"right_click",...Nn(m)});return}m.button!==0&&m.button!==1&&m.button!==5||(Vu(m.currentTarget,m),e.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...Nn(m)}))}}function i(m){m.isKilled||m.clientX===r&&m.clientY===s||(r=m.clientX,s=m.clientY,e.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...Nn(m)}))}function a(m){m.isKilled||m.button!==0&&m.button!==1&&m.button!==2&&m.button!==5||(r=m.clientX,s=m.clientY,Yu(m.currentTarget,m),e.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...Nn(m)}))}function l(m){if(m.isKilled||e.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const x=m.pointerType==="mouse"||m.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!0:null})}function c(m){if(m.isKilled||e.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const x=m.pointerType==="mouse"||m.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!1:null})}function u(m){m.isKilled=!0,Ie(m)}function h(m){m.isKilled=!0,m.target instanceof HTMLElement&&m.target.tagName!=="A"&&m.target.tagName!=="TEXTAREA"&&!(e.getEditingShape()&&m.target.className.includes("tl-text-content"))&&Ie(m)}function p(m){Ie(m)}async function f(m){var y,v;if(Ie(m),!((v=(y=m.dataTransfer)==null?void 0:y.files)!=null&&v.length))return;const x=Array.from(m.dataTransfer.files);await e.putExternalContent({type:"files",files:x,point:e.screenToPage({x:m.clientX,y:m.clientY}),ignoreParent:!1})}function S(m){Dt(m)}return{onPointerDown:o,onPointerMove:i,onPointerUp:a,onPointerEnter:l,onPointerLeave:c,onDragOver:p,onDrop:f,onTouchStart:u,onTouchEnd:h,onClick:S}},[e])}function OH(){const e=F();P.useEffect(()=>{let n=e.getInstanceState().isCoarsePointer;const t=i=>{const a=i.pointerType!=="mouse";n!==a&&(n=a,e.updateInstanceState({isCoarsePointer:a}))};window.addEventListener("pointerdown",t,{capture:!0});const r=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),s=e.environment.isFirefox&&!e.environment.isAndroid&&!e.environment.isIos,o=()=>{const i=s?!1:r.matches;n===i&&(n=i,e.updateInstanceState({isCoarsePointer:i}))};return r&&(r.addEventListener("change",o),o()),()=>{window.removeEventListener("pointerdown",t,{capture:!0}),r&&r.removeEventListener("change",o)}},[e])}const cM=P.createContext(null);function DH({container:e,children:n}){return d.jsx(cM.Provider,{value:e,children:n})}function $t(){return xr(P.useContext(cM),"useContainer used outside of ")}function RH(){const e=F(),n=$t(),t=H("isFocused",()=>e.getIsFocused(),[e]);P.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;let r=null;const s=()=>{r!=null&&r();const o=`(resolution: ${window.devicePixelRatio}dppx)`,i=matchMedia(o),a=l=>{l.type==="change"&&s()};i.addEventListener?i.addEventListener("change",s):i.addListener&&i.addListener(a),r=()=>{i.removeEventListener?i.removeEventListener("change",s):i.removeListener&&i.removeListener(a)},e.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return s(),()=>{r==null||r()}},[e]),P.useEffect(()=>{if(!t)return;const r=a=>{if(a.altKey&&(e.isIn("zoom")||!e.getPath().endsWith(".idle"))&&!Vd()&&Ie(a),a.isKilled)return;switch(a.isKilled=!0,a.key){case"=":case"-":case"0":{if(a.metaKey||a.ctrlKey){Ie(a);return}break}case"Tab":{if(Vd()||e.getIsMenuOpen())return;break}case",":return;case"Escape":{if((e.getEditingShape()||e.getSelectedShapeIds().length>0)&&a.preventDefault(),e.getOpenMenus().length>0)return;e.inputs.keys.has("Escape")||(e.inputs.keys.add("Escape"),e.cancel(),e.focus());return}default:if(Vd()||e.getIsMenuOpen())return}const l={type:"keyboard",name:a.repeat?"key_repeat":"key_down",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)},s=a=>{if(a.isKilled||(a.isKilled=!0,Vd()||e.getIsMenuOpen())||a.key===",")return;const l={type:"keyboard",name:"key_up",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)};function o(a){var l,c;if(n.contains(a.target)){const u=a.touches[0].pageX,h=a.touches[0].radiusX||0;(u-h<10||u+h>e.getViewportScreenBounds().width-10)&&(((l=a.target)==null?void 0:l.tagName)==="BUTTON"&&((c=a.target)==null||c.click()),Ie(a))}}const i=a=>{n.contains(a.target)&&(a.ctrlKey||a.metaKey)&&Ie(a)};return n.addEventListener("touchstart",o,{passive:!1}),n.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",Ie),document.addEventListener("gesturechange",Ie),document.addEventListener("gestureend",Ie),n.addEventListener("keydown",r),n.addEventListener("keyup",s),()=>{n.removeEventListener("touchstart",o),n.removeEventListener("wheel",i),document.removeEventListener("gesturestart",Ie),document.removeEventListener("gesturechange",Ie),document.removeEventListener("gestureend",Ie),n.removeEventListener("keydown",r),n.removeEventListener("keyup",s)}},[e,n,t])}const LH=["input","select","button","textarea"];function Vd(){const{activeElement:e}=document;return!!(e&&(e.getAttribute("contenteditable")||LH.indexOf(e.tagName.toLowerCase())>-1))}const $H=["textarea","input"];function NH(e){const n=F();P.useEffect(()=>{const t=e.current;if(!t)return;const r=s=>{var o;if(s instanceof PointerEvent&&s.pointerType==="pen"){s.isKilled=!0;const{target:i}=s;if($H.includes((o=i.tagName)==null?void 0:o.toLocaleLowerCase())||n.isIn("select.editing_shape"))return;Ie(s)}};return t.addEventListener("touchstart",r),t.addEventListener("touchend",r),()=>{t.removeEventListener("touchstart",r),t.removeEventListener("touchend",r)}},[n,e])}function FH(e,n,t){return Math.max(n,Math.min(e,t))}const Kt={toVector(e,n){return e===void 0&&(e=n),Array.isArray(e)?e:[e,e]},add(e,n){return[e[0]+n[0],e[1]+n[1]]},sub(e,n){return[e[0]-n[0],e[1]-n[1]]},addTo(e,n){e[0]+=n[0],e[1]+=n[1]},subTo(e,n){e[0]-=n[0],e[1]-=n[1]}};function _C(e,n,t){return n===0||Math.abs(n)===1/0?Math.pow(e,t*5):e*n*t/(n+t*e)}function kC(e,n,t,r=.15){return r===0?FH(e,n,t):et?+_C(e-t,t-n,r)+t:e}function zH(e,[n,t],[r,s]){const[[o,i],[a,l]]=e;return[kC(n,o,i,r),kC(t,a,l,s)]}function BH(e,n){if(typeof e!="object"||e===null)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var r=t.call(e,n||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function UH(e){var n=BH(e,"string");return typeof n=="symbol"?n:String(n)}function rn(e,n,t){return n=UH(n),n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function TC(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),t.push.apply(t,r)}return t}function ut(e){for(var n=1;n{var t,r;return n.target===e.currentTarget||((t=e.currentTarget)===null||t===void 0||(r=t.contains)===null||r===void 0?void 0:r.call(t,n.target))})}function Iv(e,n){try{const t=n.clientX-e.clientX,r=n.clientY-e.clientY,s=(n.clientX+e.clientX)/2,o=(n.clientY+e.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 ZH(e){return qH(e).map(n=>n.identifier)}function AC(e,n){const[t,r]=Array.from(e.touches).filter(s=>n.includes(s.identifier));return Iv(t,r)}const jC=40,OC=800;function hM(e){let{deltaX:n,deltaY:t,deltaMode:r}=e;return r===1?(n*=jC,t*=jC):r===2&&(n*=OC,t*=OC),[n,t]}function QH(e){const n={};if("buttons"in e&&(n.buttons=e.buttons),"shiftKey"in e){const{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o}=e;Object.assign(n,{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o})}return n}function hf(e,...n){return typeof e=="function"?e(...n):e}function JH(){}function eK(...e){return e.length===0?JH:e.length===1?e[0]:function(){let n;for(const t of e)n=t.apply(this,arguments)||n;return n}}function DC(e,n){return Object.assign({},n,e||{})}const tK=32;class pM{constructor(n,t,r){this.ctrl=n,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(n){this.ctrl.state[this.key]=n}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:n,shared:t,ingKey:r,args:s}=this;t[r]=n._active=n.active=n._blocked=n._force=!1,n._step=[!1,!1],n.intentional=!1,n._movement=[0,0],n._distance=[0,0],n._direction=[0,0],n._delta=[0,0],n._bounds=[[-1/0,1/0],[-1/0,1/0]],n.args=s,n.axis=void 0,n.memo=void 0,n.elapsedTime=n.timeDelta=0,n.direction=[0,0],n.distance=[0,0],n.overflow=[0,0],n._movementBound=[!1,!1],n.velocity=[0,0],n.movement=[0,0],n.delta=[0,0],n.timeStamp=0}start(n){const t=this.state,r=this.config;t._active||(this.reset(),this.computeInitial(),t._active=!0,t.target=n.target,t.currentTarget=n.currentTarget,t.lastOffset=r.from?hf(r.from,t):t.offset,t.offset=t.lastOffset,t.startTime=t.timeStamp=n.timeStamp)}computeValues(n){const t=this.state;t._values=n,t.values=this.config.transform(n)}computeInitial(){const n=this.state;n._initial=n._values,n.initial=n.values}compute(n){const{state:t,config:r,shared:s}=this;t.args=this.args;let o=0;if(n&&(t.event=n,r.preventDefault&&n.cancelable&&t.event.preventDefault(),t.type=n.type,s.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,s.locked=!!document.pointerLockElement,Object.assign(s,QH(n)),s.down=s.pressed=s.buttons%2===1||s.touches>0,o=n.timeStamp-t.timeStamp,t.timeStamp=n.timeStamp,t.elapsedTime=t.timeStamp-t.startTime),t._active){const k=t._delta.map(Math.abs);Kt.addTo(t._distance,k)}this.axisIntent&&this.axisIntent(n);const[i,a]=t._movement,[l,c]=r.threshold,{_step:u,values:h}=t;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=l&&h[0]),u[1]===!1&&(u[1]=Math.abs(a)>=c&&h[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 p=[0,0];if(r.hasCustomTransform){const[k,I]=h;p[0]=u[0]!==!1?k-u[0]:0,p[1]=u[1]!==!1?I-u[1]:0}else p[0]=u[0]!==!1?i-u[0]:0,p[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!t._blocked&&this.restrictToAxis(p);const f=t.offset,S=t._active&&!t._blocked||t.active;S&&(t.first=t._active&&!t.active,t.last=!t._active&&t.active,t.active=s[this.ingKey]=t._active,n&&(t.first&&("bounds"in r&&(t._bounds=hf(r.bounds,t)),this.setup&&this.setup()),t.movement=p,this.computeOffset()));const[m,x]=t.offset,[[y,v],[w,C]]=t._bounds;t.overflow=[mv?1:0,xC?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 E=t._active?r.rubberband||[0,0]:[0,0];if(t.offset=zH(t._bounds,t.offset,E),t.delta=Kt.sub(t.offset,f),this.computeMovement(),S&&(!t.last||o>tK)){t.delta=Kt.sub(t.offset,f);const k=t.delta.map(Math.abs);Kt.addTo(t.distance,k),t.direction=t.delta.map(Math.sign),t._direction=t._delta.map(Math.sign),!t.first&&o>0&&(t.velocity=[k[0]/o,k[1]/o],t.timeDelta=o)}}emit(){const n=this.state,t=this.shared,r=this.config;if(n._active||this.clean(),(n._blocked||!n.intentional)&&!n._force&&!r.triggerAllEvents)return;const s=this.handler(ut(ut(ut({},t),n),{},{[this.aliasKey]:n.values}));s!==void 0&&(n.memo=s)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function nK([e,n],t){const r=Math.abs(e),s=Math.abs(n);if(r>s&&r>t)return"x";if(s>r&&s>t)return"y"}class rK extends pM{constructor(...n){super(...n),rn(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=Kt.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Kt.sub(this.state.offset,this.state.lastOffset)}axisIntent(n){const t=this.state,r=this.config;if(!t.axis&&n){const s=typeof r.axisThreshold=="object"?r.axisThreshold[XH(n)]:r.axisThreshold;t.axis=nK(t._movement,s)}t._blocked=(r.lockDirection||!!r.axis)&&!t.axis||!!r.axis&&r.axis!==t.axis}restrictToAxis(n){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":n[1]=0;break;case"y":n[0]=0;break}}}const sK=e=>e,RC=.15,fM={enabled(e=!0){return e},eventOptions(e,n,t){return ut(ut({},t.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[RC,RC];case!1:return[0,0];default:return Kt.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return Kt.toVector(e)},transform(e,n,t){const r=e||t.shared.transform;return this.hasCustomTransform=!!r,r||sK},threshold(e){return Kt.toVector(e,0)}},oK=0,Xu=ut(ut({},fM),{},{axis(e,n,{axis:t}){if(this.lockDirection=t==="lock",!this.lockDirection)return t},axisThreshold(e=oK){return e},bounds(e={}){if(typeof e=="function")return o=>Xu.bounds(e(o));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:n=-1/0,right:t=1/0,top:r=-1/0,bottom:s=1/0}=e;return[[n,t],[r,s]]}}),qu=typeof window<"u"&&window.document&&window.document.createElement;function gM(){return qu&&"ontouchstart"in window}function iK(){return gM()||qu&&window.navigator.maxTouchPoints>1}function aK(){return qu&&"onpointerdown"in window}function lK(){return qu&&"exitPointerLock"in window.document}function cK(){try{return"constructor"in GestureEvent}catch{return!1}}const wr={isBrowser:qu,gesture:cK(),touch:gM(),touchscreen:iK(),pointer:aK(),pointerLock:lK()},uK=250,dK=180,hK=.5,pK=50,fK=250,gK=10,LC={mouse:0,touch:0,pen:8};ut(ut({},Xu),{},{device(e,n,{pointer:{touch:t=!1,lock:r=!1,mouse:s=!1}={}}){return this.pointerLock=r&&wr.pointerLock,wr.touch&&t?"touch":this.pointerLock?"mouse":wr.pointer&&!s?"pointer":wr.touch?"touch":"mouse"},preventScrollAxis(e,n,{preventScroll:t}){if(this.preventScrollDelay=typeof t=="number"?t:t||t===void 0&&e?uK:void 0,!(!wr.touchscreen||t===!1))return e||(t!==void 0?"y":void 0)},pointerCapture(e,n,{pointer:{capture:t=!0,buttons:r=1,keys:s=!0}={}}){return this.pointerButtons=r,this.keys=s,!this.pointerLock&&this.device==="pointer"&&t},threshold(e,n,{filterTaps:t=!1,tapsThreshold:r=3,axis:s=void 0}){const o=Kt.toVector(e,t?r:s?1:0);return this.filterTaps=t,this.tapsThreshold=r,o},swipe({velocity:e=hK,distance:n=pK,duration:t=fK}={}){return{velocity:this.transform(Kt.toVector(e)),distance:this.transform(Kt.toVector(n)),duration:t}},delay(e=0){switch(e){case!0:return dK;case!1:return 0;default:return e}},axisThreshold(e){return e?ut(ut({},LC),e):LC},keyboardDisplacement(e=gK){return e}});function mM(e){const[n,t]=e.overflow,[r,s]=e._delta,[o,i]=e._direction;(n<0&&r>0&&o<0||n>0&&r<0&&o>0)&&(e._movement[0]=e._movementBound[0]),(t<0&&s>0&&i<0||t>0&&s<0&&i>0)&&(e._movement[1]=e._movementBound[1])}const mK=30,yK=100;class SK extends pM{constructor(...n){super(...n),rn(this,"ingKey","pinching"),rn(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const n=this.state;n._touchIds=[],n.canceled=!1,n.cancel=this.cancel.bind(this),n.turns=0}computeOffset(){const{type:n,movement:t,lastOffset:r}=this.state;n==="wheel"?this.state.offset=Kt.add(t,r):this.state.offset=[(1+t[0])*r[0],t[1]+r[1]]}computeMovement(){const{offset:n,lastOffset:t}=this.state;this.state.movement=[n[0]/t[0],n[1]-t[1]]}axisIntent(){const n=this.state,[t,r]=n._movement;if(!n.axis){const s=Math.abs(t)*mK-Math.abs(r);s<0?n.axis="angle":s>0&&(n.axis="scale")}}restrictToAxis(n){this.config.lockDirection&&(this.state.axis==="scale"?n[1]=0:this.state.axis==="angle"&&(n[0]=0))}cancel(){const n=this.state;n.canceled||setTimeout(()=>{n.canceled=!0,n._active=!1,this.compute(),this.emit()},0)}touchStart(n){this.ctrl.setEventIds(n);const t=this.state,r=this.ctrl.touchIds;if(t._active&&t._touchIds.every(o=>r.has(o))||r.size<2)return;this.start(n),t._touchIds=Array.from(r).slice(0,2);const s=AC(n,t._touchIds);s&&this.pinchStart(n,s)}pointerStart(n){if(n.buttons!=null&&n.buttons%2!==1)return;this.ctrl.setEventIds(n),n.target.setPointerCapture(n.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(n.pointerId,n),t._pointerEvents.size<2))return;this.start(n);const o=Iv(...Array.from(r.values()));o&&this.pinchStart(n,o)}pinchStart(n,t){const r=this.state;r.origin=t.origin,this.computeValues([t.distance,t.angle]),this.computeInitial(),this.compute(n),this.emit()}touchMove(n){if(!this.state._active)return;const t=AC(n,this.state._touchIds);t&&this.pinchMove(n,t)}pointerMove(n){const t=this.state._pointerEvents;if(t.has(n.pointerId)&&t.set(n.pointerId,n),!this.state._active)return;const r=Iv(...Array.from(t.values()));r&&this.pinchMove(n,r)}pinchMove(n,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(n),this.emit()}touchEnd(n){this.ctrl.setEventIds(n),this.state._active&&this.state._touchIds.some(t=>!this.ctrl.touchIds.has(t))&&(this.state._active=!1,this.compute(n),this.emit())}pointerEnd(n){const t=this.state;this.ctrl.setEventIds(n);try{n.target.releasePointerCapture(n.pointerId)}catch{}t._pointerEvents.has(n.pointerId)&&t._pointerEvents.delete(n.pointerId),t._active&&t._pointerEvents.size<2&&(t._active=!1,this.compute(n),this.emit())}gestureStart(n){n.cancelable&&n.preventDefault();const t=this.state;t._active||(this.start(n),this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY],this.compute(n),this.emit())}gestureMove(n){if(n.cancelable&&n.preventDefault(),!this.state._active)return;const t=this.state;this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY];const r=t._movement;t._movement=[n.scale-1,n.rotation],t._delta=Kt.sub(t._movement,r),this.compute(n),this.emit()}gestureEnd(n){this.state._active&&(this.state._active=!1,this.compute(n),this.emit())}wheel(n){const t=this.config.modifierKey;t&&(Array.isArray(t)?!t.find(r=>n[r]):!n[t])||(this.state._active?this.wheelChange(n):this.wheelStart(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(n){this.start(n),this.wheelChange(n)}wheelChange(n){"uv"in n||n.cancelable&&n.preventDefault();const r=this.state;r._delta=[-hM(n)[1]/yK*r.offset[0],0],Kt.addTo(r._movement,r._delta),mM(r),this.state.origin=[n.clientX,n.clientY],this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){const t=this.config.device;t&&(n(t,"start",this[t+"Start"].bind(this)),n(t,"change",this[t+"Move"].bind(this)),n(t,"end",this[t+"End"].bind(this)),n(t,"cancel",this[t+"End"].bind(this)),n("lostPointerCapture","",this[t+"End"].bind(this))),this.config.pinchOnWheel&&n("wheel","",this.wheel.bind(this),{passive:!1})}}const vK=ut(ut({},fM),{},{device(e,n,{shared:t,pointer:{touch:r=!1}={}}){if(t.target&&!wr.touch&&wr.gesture)return"gesture";if(wr.touch&&r)return"touch";if(wr.touchscreen){if(wr.pointer)return"pointer";if(wr.touch)return"touch"}},bounds(e,n,{scaleBounds:t={},angleBounds:r={}}){const s=i=>{const a=DC(hf(t,i),{min:-1/0,max:1/0});return[a.min,a.max]},o=i=>{const a=DC(hf(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(e,n,t){return this.lockDirection=t.axis==="lock",Kt.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});ut(ut({},Xu),{},{mouseOnly:(e=!0)=>e});class xK extends rK{constructor(...n){super(...n),rn(this,"ingKey","wheeling")}wheel(n){this.state._active||this.start(n),this.wheelChange(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(n){const t=this.state;t._delta=hM(n),Kt.addTo(t._movement,t._delta),mM(t),this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){n("wheel","",this.wheel.bind(this))}}const wK=Xu;ut(ut({},Xu),{},{mouseOnly:(e=!0)=>e});const ew=new Map,Ev=new Map;function bK(e){ew.set(e.key,e.engine),Ev.set(e.key,e.resolver)}const PK={key:"pinch",engine:SK,resolver:vK},CK={key:"wheel",engine:xK,resolver:wK};function IK(e,n){if(e==null)return{};var t={},r=Object.keys(e),s,o;for(o=0;o=0)&&(t[s]=e[s]);return t}function EK(e,n){if(e==null)return{};var t=IK(e,n),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(t[r]=e[r])}return t}const _K={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=wr.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:n=!1}={}){return{passive:e,capture:n}},transform(e){return e}},kK=["target","eventOptions","window","enabled","transform"];function zh(e={},n){const t={};for(const[r,s]of Object.entries(n))switch(typeof s){case"function":t[r]=s.call(t,e[r],r,e);break;case"object":t[r]=zh(e[r],s);break;case"boolean":s&&(t[r]=e[r]);break}return t}function TK(e,n,t={}){const r=e,{target:s,eventOptions:o,window:i,enabled:a,transform:l}=r,c=EK(r,kK);if(t.shared=zh({target:s,eventOptions:o,window:i,enabled:a,transform:l},_K),n){const u=Ev.get(n);t[n]=zh(ut({shared:t.shared},c),u)}else for(const u in c){const h=Ev.get(u);h&&(t[u]=zh(ut({shared:t.shared},c[u]),h))}return t}class yM{constructor(n,t){rn(this,"_listeners",new Set),this._ctrl=n,this._gestureKey=t}add(n,t,r,s,o){const i=this._listeners,a=YH(t,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=ut(ut({},l),o);n.addEventListener(a,s,c);const u=()=>{n.removeEventListener(a,s,c),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(n=>n()),this._listeners.clear()}}class MK{constructor(){rn(this,"_timeouts",new Map)}add(n,t,r=140,...s){this.remove(n),this._timeouts.set(n,window.setTimeout(t,r,...s))}remove(n){const t=this._timeouts.get(n);t&&window.clearTimeout(t)}clean(){this._timeouts.forEach(n=>void window.clearTimeout(n)),this._timeouts.clear()}}class AK{constructor(n){rn(this,"gestures",new Set),rn(this,"_targetEventStore",new yM(this)),rn(this,"gestureEventStores",{}),rn(this,"gestureTimeoutStores",{}),rn(this,"handlers",{}),rn(this,"config",{}),rn(this,"pointerIds",new Set),rn(this,"touchIds",new Set),rn(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),jK(this,n)}setEventIds(n){if(dM(n))return this.touchIds=new Set(ZH(n)),this.touchIds;if("pointerId"in n)return n.type==="pointerup"||n.type==="pointercancel"?this.pointerIds.delete(n.pointerId):n.type==="pointerdown"&&this.pointerIds.add(n.pointerId),this.pointerIds}applyHandlers(n,t){this.handlers=n,this.nativeHandlers=t}applyConfig(n,t){this.config=TK(n,t,this.config)}clean(){this._targetEventStore.clean();for(const n of this.gestures)this.gestureEventStores[n].clean(),this.gestureTimeoutStores[n].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...n){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=$C(r,a.eventOptions,!!s);if(a.enabled){const c=ew.get(i);new c(this,n,i).bind(l)}}const o=$C(r,t.eventOptions,!!s);for(const i in this.nativeHandlers)o(i,"",a=>this.nativeHandlers[i](ut(ut({},this.state.shared),{},{event:a,args:n})),void 0,!0)}for(const o in r)r[o]=eK(...r[o]);if(!s)return r;for(const o in r){const{device:i,capture:a,passive:l}=VH(o);this._targetEventStore.add(s,i,"",r[o],{capture:a,passive:l})}}}}function fa(e,n){e.gestures.add(n),e.gestureEventStores[n]=new yM(e,n),e.gestureTimeoutStores[n]=new MK}function jK(e,n){n.drag&&fa(e,"drag"),n.wheel&&fa(e,"wheel"),n.scroll&&fa(e,"scroll"),n.move&&fa(e,"move"),n.pinch&&fa(e,"pinch"),n.hover&&fa(e,"hover")}const $C=(e,n,t)=>(r,s,o,i={},a=!1)=>{var l,c;const u=(l=i.capture)!==null&&l!==void 0?l:n.capture,h=(c=i.passive)!==null&&c!==void 0?c:n.passive;let p=a?r:WH(r,s,u);t&&h&&(p+="Passive"),e[p]=e[p]||[],e[p].push(o)},OK=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function DK(e){const n={},t={},r=new Set;for(let s in e)OK.test(s)?(r.add(RegExp.lastMatch),t[s]=e[s]):n[s]=e[s];return[t,n,r]}function ga(e,n,t,r,s,o){if(!e.has(t)||!ew.has(r))return;const i=t+"Start",a=t+"End",l=c=>{let u;return c.first&&i in n&&n[i](c),t in n&&(u=n[t](c)),c.last&&a in n&&n[a](c),u};s[r]=l,o[r]=o[r]||{}}function RK(e,n){const[t,r,s]=DK(e),o={};return ga(s,t,"onDrag","drag",o,n),ga(s,t,"onWheel","wheel",o,n),ga(s,t,"onScroll","scroll",o,n),ga(s,t,"onPinch","pinch",o,n),ga(s,t,"onMove","move",o,n),ga(s,t,"onHover","hover",o,n),{handlers:o,config:n,nativeHandlers:r}}function LK(e,n={},t,r){const s=Ce.useMemo(()=>new AK(e),[]);if(s.applyHandlers(e,r),s.applyConfig(n,t),Ce.useEffect(s.effect.bind(s)),Ce.useEffect(()=>s.clean.bind(s),[]),n.target===void 0)return s.bind.bind(s)}function $K(e){return e.forEach(bK),function(t,r){const{handlers:s,nativeHandlers:o,config:i}=RK(t,r||{});return LK(s,i,void 0,o)}}const NC=10,NK=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function SM(e){let{deltaY:n,deltaX:t}=e,r=0;return e.ctrlKey||e.altKey||e.metaKey?r=(Math.abs(n)>NC?NC*Math.sign(n):n)/100:e.shiftKey&&!NK&&(t=n,n=0),{x:-t,y:-n,z:-r}}const FK=$K([CK,PK]);let ma;const zK=e=>ma===void 0?(ma=e,!1):e-ma>120&&e-ma<160?(ma=e,!0):(ma=e,!1);function BK(e){const n=F(),t=P.useMemo(()=>{let r="not sure";const s=({event:m})=>{if(!n.getInstanceState().isFocused||(r="not sure",zK(Date.now())))return;const x=n.getEditingShapeId();if(x){const w=n.getShape(x);if(w&&n.getShapeUtil(w).canScroll(w)){const E=n.getShapePageBounds(x);if(E!=null&&E.containsPoint(n.inputs.currentPagePoint))return}}Ie(m),Dt(m);const y=SM(m);if(y.x===0&&y.y===0)return;const v={type:"wheel",name:"wheel",delta:y,point:new b(m.clientX,m.clientY),shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey};n.dispatch(v)};let o=1,i=1,a=1,l=0;const c=new b,u=new b,h=m=>{const x=e.current;r="not sure";const{event:y,origin:v,da:w}=m;y instanceof WheelEvent||(y.target===x||x!=null&&x.contains(y.target))&&(u.x=v[0],u.y=v[1],c.x=v[0],c.y=v[1],o=w[0],i=n.getZoomLevel(),n.dispatch({type:"pinch",name:"pinch_start",point:{x:v[0],y:v[1],z:n.getZoomLevel()},delta:{x:0,y:0},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey}))},p=m=>{if(m&&(r="zooming"),r==="zooming")return;const x=Math.abs(l-o),y=b.Dist(c,u);switch(r){case"not sure":{x>24?r="zooming":y>16&&(r="panning");break}case"panning":{x>64&&(r="zooming");break}}};return{onWheel:s,onPinchStart:h,onPinchEnd:m=>{const x=e.current,{event:y,origin:v,offset:w}=m;if(y instanceof WheelEvent||!(y.target===x||x!=null&&x.contains(y.target)))return;const C=w[0];r="not sure",n.timers.requestAnimationFrame(()=>{n.dispatch({type:"pinch",name:"pinch_end",point:{x:v[0],y:v[1],z:C},delta:{x:v[0],y:v[1]},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey})})},onPinch:m=>{const x=e.current,{event:y,origin:v,offset:w,da:C}=m;if(y instanceof WheelEvent||!(y.target===x||x!=null&&x.contains(y.target)))return;const E=m.type==="gesturechange"||m.type==="gestureend";l=C[0];const k=v[0]-u.x,I=v[1]-u.y;switch(u.x=v[0],u.y=v[1],p(E),r){case"zooming":{a=w[0],n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:a},delta:{x:k,y:I},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey});break}case"panning":{n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:i},delta:{x:k,y:I},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey});break}}}}},[n,e]);FK(t,{target:e,eventOptions:{passive:!1},pinch:{from:()=>[n.getZoomLevel(),0],scaleBounds:()=>({from:n.getZoomLevel(),max:8,min:.05})}})}function ry(e,n,t){const r=e.getShape(n),s=e.getShapeHandles(r);return{shape:r,handle:s.find(o=>o.id===t)}}function UK(e,n){const t=F();return P.useMemo(()=>{const r=l=>{if(l.isKilled)return;const c=df(l.currentTarget);Vu(c,l);const{shape:u,handle:h}=ry(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_down",...Nn(l)})};let s,o;return{onPointerDown:r,onPointerMove:l=>{if(l.isKilled||l.clientX===s&&l.clientY===o)return;s=l.clientX,o=l.clientY;const{shape:c,handle:u}=ry(t,e,n);u&&t.dispatch({type:"pointer",target:"handle",handle:u,shape:c,name:"pointer_move",...Nn(l)})},onPointerUp:l=>{if(l.isKilled)return;const c=df(l.currentTarget);Yu(c,l);const{shape:u,handle:h}=ry(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_up",...Nn(l)})}}},[t,e,n])}const Je=class Je{constructor(n=0,t=0,r=0,s=0){g(this,"x",0);g(this,"y",0);g(this,"w",0);g(this,"h",0);this.x=n,this.y=t,this.w=r,this.h=s}get point(){return new b(this.x,this.y)}set point(n){this.x=n.x,this.y=n.y}get minX(){return this.x}set minX(n){this.x=n}get midX(){return this.x+this.w/2}get maxX(){return this.x+this.w}get minY(){return this.y}set minY(n){this.y=n}get midY(){return this.y+this.h/2}get maxY(){return this.y+this.h}get width(){return this.w}set width(n){this.w=n}get height(){return this.h}set height(n){this.h=n}get aspectRatio(){return this.width/this.height}get center(){return new b(this.midX,this.midY)}set center(n){this.minX=n.x-this.width/2,this.minY=n.y-this.height/2}get corners(){return[new b(this.minX,this.minY),new b(this.maxX,this.minY),new b(this.maxX,this.maxY),new b(this.minX,this.maxY)]}get cornersAndCenter(){return[new b(this.minX,this.minY),new b(this.maxX,this.minY),new b(this.maxX,this.maxY),new b(this.minX,this.maxY),this.center]}get sides(){const{corners:n}=this;return[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]]}get size(){return new b(this.w,this.h)}toFixed(){return this.x=Wd(this.x),this.y=Wd(this.y),this.w=Wd(this.w),this.h=Wd(this.h),this}setTo(n){return this.x=n.x,this.y=n.y,this.w=n.w,this.h=n.h,this}set(n=0,t=0,r=0,s=0){return this.x=n,this.y=t,this.w=r,this.h=s,this}expand(n){const t=Math.min(this.minX,n.minX),r=Math.min(this.minY,n.minY),s=Math.max(this.maxX,n.maxX),o=Math.max(this.maxY,n.maxY);return this.x=t,this.y=r,this.w=s-t,this.h=o-r,this}expandBy(n){return this.x-=n,this.y-=n,this.w+=n*2,this.h+=n*2,this}scale(n){return this.x/=n,this.y/=n,this.w/=n,this.h/=n,this}clone(){const{x:n,y:t,w:r,h:s}=this;return new Je(n,t,r,s)}translate(n){return this.x+=n.x,this.y+=n.y,this}snapToGrid(n){const t=Math.round(this.minX/n)*n,r=Math.round(this.minY/n)*n,s=Math.round(this.maxX/n)*n,o=Math.round(this.maxY/n)*n;this.minX=t,this.minY=r,this.width=Math.max(1,s-t),this.height=Math.max(1,o-r)}collides(n){return Je.Collides(this,n)}contains(n){return Je.Contains(this,n)}includes(n){return Je.Includes(this,n)}containsPoint(n,t=0){return Je.ContainsPoint(this,n,t)}getHandlePoint(n){switch(n){case"top_left":return new b(this.minX,this.minY);case"top_right":return new b(this.maxX,this.minY);case"bottom_left":return new b(this.minX,this.maxY);case"bottom_right":return new b(this.maxX,this.maxY);case"top":return new b(this.midX,this.minY);case"right":return new b(this.maxX,this.midY);case"bottom":return new b(this.midX,this.maxY);case"left":return new b(this.minX,this.midY)}}toJson(){return{x:this.minX,y:this.minY,w:this.w,h:this.h}}resize(n,t,r){const{minX:s,minY:o,maxX:i,maxY:a}=this;let{minX:l,minY:c,maxX:u,maxY:h}=this;switch(n){case"left":case"top_left":case"bottom_left":{l+=t;break}case"right":case"top_right":case"bottom_right":{u+=t;break}}switch(n){case"top":case"top_left":case"top_right":{c+=r;break}case"bottom":case"bottom_left":case"bottom_right":{h+=r;break}}const p=(u-l)/(i-s),f=(h-c)/(a-o),S=p<0,m=f<0;if(S){const x=u;u=l,l=x}if(m){const x=h;h=c,c=x}this.minX=l,this.minY=c,this.width=Math.abs(u-l),this.height=Math.abs(h-c)}union(n){const t=Math.min(this.minX,n.x),r=Math.min(this.minY,n.y),s=Math.max(this.maxX,n.w+n.x),o=Math.max(this.maxY,n.h+n.y);return this.x=t,this.y=r,this.width=s-t,this.height=o-r,this}static From(n){return new Je(n.x,n.y,n.w,n.h)}static FromCenter(n,t){return new Je(n.x-t.x/2,n.y-t.y/2,t.x,t.y)}static FromPoints(n){if(n.length===0)return new Je;let t=1/0,r=1/0,s=-1/0,o=-1/0,i;for(let a=0,l=n.length;a0?1:-1)).toFixed(5),scaleY:+(v.height/n.height*(m>0?1:-1)).toFixed(5)}}equals(n){return Je.Equals(this,n)}static Equals(n,t){return t.x===n.x&&t.y===n.y&&t.w===n.w&&t.h===n.h}zeroFix(){return this.w=Math.max(1,this.w),this.h=Math.max(1,this.h),this}static ZeroFix(n){return new Je(n.x,n.y,Math.max(1,n.w),Math.max(1,n.h))}};g(Je,"Collides",(n,t)=>!(n.maxXt.maxX||n.maxYt.maxY)),g(Je,"Contains",(n,t)=>n.minXt.maxY&&n.maxX>t.maxX),g(Je,"Includes",(n,t)=>Je.Collides(n,t)||Je.Contains(n,t)),g(Je,"ContainsPoint",(n,t,r=0)=>!(t.xn.maxX+r||t.y>n.maxY+r)),g(Je,"Common",n=>{let t=1/0,r=1/0,s=-1/0,o=-1/0;for(let i=0;i{const{corners:r}=n;return[[r[0],r[1]],[r[1],r[2]],[r[2],r[3]],[r[3],r[0]]]});let Q=Je;function HK(e){switch(e){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 e}}function KK(e){switch(e){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 e}}function WK(e){return e==="top_left"||e==="top_right"||e==="bottom_right"||e==="bottom_left"}function GK(e){const n=F();P.useLayoutEffect(()=>{let t=new Q;function r(){const c=e.current;if(!c)return null;const u=c.getBoundingClientRect(),h=new Q(u.left||u.x,u.top||u.y,Math.max(u.width,1),Math.max(u.height,1));t.equals(h)||(n.updateViewportScreenBounds(h),t=h)}r();const s=B2(r,200,{trailing:!0}),o=n.timers.setInterval(s,1e3);window.addEventListener("resize",s);const i=new ResizeObserver(c=>{c[0].contentRect&&s()}),a=e.current;let l=null;return a&&(i.observe(a),l=VK(a),l.addEventListener("scroll",s)),()=>{clearInterval(o),window.removeEventListener("resize",s),i.disconnect(),l==null||l.removeEventListener("scroll",s),s.cancel()}},[n,e])}/*! +*/(function(e){(function(){var n={}.hasOwnProperty;function t(){for(var o="",i=0;i or components");return e}function CH(){return d.jsx("div",{className:"tl-background"})}function jl(e,n,t,r,s,o){P.useLayoutEffect(()=>{const i=e.current;if(!i||n===void 0)return;let a=`translate(${n}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 At={linear:e=>e,easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),easeInOutQuad:e=>e<.5?2*e*e:-1+(4-2*e)*e,easeInCubic:e=>e*e*e,easeOutCubic:e=>--e*e*e+1,easeInOutCubic:e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,easeInQuart:e=>e*e*e*e,easeOutQuart:e=>1- --e*e*e*e,easeInOutQuart:e=>e<.5?8*e*e*e*e:1-8*--e*e*e*e,easeInQuint:e=>e*e*e*e*e,easeOutQuint:e=>1+--e*e*e*e*e,easeInOutQuint:e=>e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e,easeInSine:e=>1-Math.cos(e*Math.PI/2),easeOutSine:e=>Math.sin(e*Math.PI/2),easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,easeInExpo:e=>e<=0?0:Math.pow(2,10*e-10),easeOutExpo:e=>e>=1?1:1-Math.pow(2,-10*e),easeInOutExpo:e=>e<=0?0:e>=1?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2};class b{constructor(n=0,t=0,r=1){this.x=n,this.y=t,this.z=r}get pressure(){return this.z}set(n=this.x,t=this.y,r=this.z){return this.x=n,this.y=t,this.z=r,this}setTo({x:n=0,y:t=0,z:r=1}){return this.x=n,this.y=t,this.z=r,this}rot(n){if(n===0)return this;const{x:t,y:r}=this,s=Math.sin(n),o=Math.cos(n);return this.x=t*o-r*s,this.y=t*s+r*o,this}rotWith(n,t){if(t===0)return this;const r=this.x-n.x,s=this.y-n.y,o=Math.sin(t),i=Math.cos(t);return this.x=n.x+(r*i-s*o),this.y=n.y+(r*o+s*i),this}clone(){const{x:n,y:t,z:r}=this;return new b(n,t,r)}sub(n){return this.x-=n.x,this.y-=n.y,this}subXY(n,t){return this.x-=n,this.y-=t,this}subScalar(n){return this.x-=n,this.y-=n,this}add(n){return this.x+=n.x,this.y+=n.y,this}addXY(n,t){return this.x+=n,this.y+=t,this}addScalar(n){return this.x+=n,this.y+=n,this}clamp(n,t){return this.x=Math.max(this.x,n),this.y=Math.max(this.y,n),t!==void 0&&(this.x=Math.min(this.x,t),this.y=Math.min(this.y,t)),this}div(n){return this.x/=n,this.y/=n,this}divV(n){return this.x/=n.x,this.y/=n.y,this}mul(n){return this.x*=n,this.y*=n,this}mulV(n){return this.x*=n.x,this.y*=n.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(n,t){const r=b.Tan(n,this);return this.add(r.mul(t))}neg(){return this.x*=-1,this.y*=-1,this}cross(n){return this.x=this.y*n.z-this.z*n.y,this.y=this.z*n.x-this.x*n.z,this}dpr(n){return b.Dpr(this,n)}cpr(n){return b.Cpr(this,n)}len2(){return b.Len2(this)}len(){return b.Len(this)}pry(n){return b.Pry(this,n)}per(){const{x:n,y:t}=this;return this.x=t,this.y=-n,this}uni(){return b.Uni(this)}tan(n){return b.Tan(this,n)}dist(n){return b.Dist(this,n)}distanceToLineSegment(n,t){return b.DistanceToLineSegment(n,t,this)}slope(n){return b.Slope(this,n)}snapToGrid(n){return this.x=Math.round(this.x/n)*n,this.y=Math.round(this.y/n)*n,this}angle(n){return b.Angle(this,n)}toAngle(){return b.ToAngle(this)}lrp(n,t){return this.x=this.x+(n.x-this.x)*t,this.y=this.y+(n.y-this.y)*t,this}equals(n){return b.Equals(this,n)}equalsXY(n,t){return b.EqualsXY(this,n,t)}norm(){const n=this.len();return this.x=n===0?0:this.x/n,this.y=n===0?0:this.y/n,this}toFixed(){return b.ToFixed(this)}toString(){return b.ToString(b.ToFixed(this))}toJson(){return b.ToJson(this)}toArray(){return b.ToArray(this)}static Add(n,t){return new b(n.x+t.x,n.y+t.y)}static AddXY(n,t,r){return new b(n.x+t,n.y+r)}static Sub(n,t){return new b(n.x-t.x,n.y-t.y)}static SubXY(n,t,r){return new b(n.x-t,n.y-r)}static AddScalar(n,t){return new b(n.x+t,n.y+t)}static SubScalar(n,t){return new b(n.x-t,n.y-t)}static Div(n,t){return new b(n.x/t,n.y/t)}static Mul(n,t){return new b(n.x*t,n.y*t)}static DivV(n,t){return new b(n.x/t.x,n.y/t.y)}static MulV(n,t){return new b(n.x*t.x,n.y*t.y)}static Neg(n){return new b(-n.x,-n.y)}static Per(n){return new b(n.y,-n.x)}static Abs(n){return new b(Math.abs(n.x),Math.abs(n.y))}static Dist(n,t){return((n.y-t.y)**2+(n.x-t.x)**2)**.5}static DistMin(n,t,r){return(n.x-t.x)*(n.x-t.x)+(n.y-t.y)*(n.y-t.y)Math.max(n.x,t.x))return b.Cast(n.x>t.x?n:t);if(i.yMath.max(n.y,t.y))return b.Cast(n.y>t.y?n:t)}return i}static DistanceToLineThroughPoint(n,t,r){return b.Dist(r,b.NearestPointOnLineThroughPoint(n,t,r))}static DistanceToLineSegment(n,t,r,s=!0){return b.Dist(r,b.NearestPointOnLineSegment(n,t,r,s))}static Snap(n,t=1){return new b(Math.round(n.x/t)*t,Math.round(n.y/t)*t)}static Cast(n){return n instanceof b?n:b.From(n)}static Slope(n,t){return n.x===t.y?NaN:(n.y-t.y)/(n.x-t.x)}static IsNaN(n){return isNaN(n.x)||isNaN(n.y)}static Angle(n,t){return Math.atan2(t.y-n.y,t.x-n.x)}static Lrp(n,t,r){return b.Sub(t,n).mul(r).add(n)}static Med(n,t){return new b((n.x+t.x)/2,(n.y+t.y)/2)}static Equals(n,t){return Math.abs(n.x-t.x)<1e-4&&Math.abs(n.y-t.y)<1e-4}static EqualsXY(n,t,r){return n.x===t&&n.y===r}static Clockwise(n,t,r){return(r.x-n.x)*(t.y-n.y)-(t.x-n.x)*(r.y-n.y)<0}static Rescale(n,t){const r=b.Len(n);return new b(t*n.x/r,t*n.y/r)}static ScaleWithOrigin(n,t,r){return b.Sub(n,r).mul(t).add(r)}static ToFixed(n){return new b(zs(n.x),zs(n.y))}static ToInt(n){return new b(parseInt(n.x.toFixed(0)),parseInt(n.y.toFixed(0)),parseInt((n.z??0).toFixed(0)))}static ToCss(n){return`${n.x},${n.y}`}static Nudge(n,t,r){return b.Add(n,b.Tan(t,n).mul(r))}static ToString(n){return`${n.x}, ${n.y}`}static ToAngle(n){let t=Math.atan2(n.y,n.x);return t<0&&(t+=Math.PI*2),t}static FromAngle(n,t=1){return new b(Math.cos(n)*t,Math.sin(n)*t)}static ToArray(n){return[n.x,n.y,n.z]}static ToJson(n){const{x:t,y:r,z:s}=n;return{x:t,y:r,z:s}}static Average(n){const t=n.length,r=new b(0,0);if(t===0)return r;for(let s=0;se<.5?2*e*e:-1+(4-2*e)*e;function ke(e){return`${N(e.x)},${N(e.y)} `}function Dn(e,n){return`${N((e.x+n.x)/2)},${N((e.y+n.y)/2)} `}const Me=Math.PI,Ve=Me/2,Le=Me*2,EH=Math.sin;function kt(e,n,t){return Math.max(n,typeof t<"u"?Math.min(e,t):e)}function Wd(e,n=1e10){return e?Math.round(e*n)/n:0}function Wo(e,n,t=1e-6){return Math.abs(e-n)<=t}function oM(e,n){const t=Math.pow(e-n,2)/Math.pow(e+n,2);return Me*(e+n)*(1+3*t/(10+Math.sqrt(4-3*t)))}function Go(e){return e=e%Le,e<0?e=e+Le:e===0&&(e=0),e}function Gu(e,n){return e=Go(e),n=Go(n),e>n&&(n+=Le),n-e}function iM(e,n){return Le-Gu(e,n)}function Fh(e,n){const t=(n-e)%Le;return 2*t%Le-t}function Pv(e){return(Le+e)%Le}function uf(e,n){const t=Le/n;let r=Math.floor((Pv(e)+t/2)/t)*t%Le;return rMe&&(r-=Le),r}function aM(e,n){return e===n||Wo(e%(Math.PI/2)-n%(Math.PI/2),0)}function _H(e){return e*Me/180}function kH(e){return e*180/Me}function Ki(e,n,t){return new b(e.x,e.y).add(b.FromAngle(t,n))}function ey(e,n,t){const r=e/2,s=n/2,o=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let S=0;Sa&&(a=m),v>c&&(c=v),o.push(new b(m,v))}const u=a-i,h=c-l,p=e-u,f=n-h;if(p!==0||f!==0)for(let S=0;Se.y&&wC(r,s,e)>0&&(t+=1):s.y<=e.y&&wC(r,s,e)<0&&(t-=1)}return t!==0}function N(e){return Math.round(e*1e4)/1e4}function zs(e){return Math.round(e*100)/100}const bC=e=>Math.abs(e)Me){s=Fh(n,r);const o=Fh(r,t);return Math.abs(s).5?1:0:o}}function TH(e,n,t,r){const s=2*((n-e)%Le)%Le-(n-e)%Le;return r?(Le-Math.abs(s))*(t?1:-1):s}function Q0(e,n,t){const r=-2*(e.x*(n.y-t.y)-e.y*(n.x-t.x)+n.x*t.y-t.x*n.y);return new b(((e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y)+(t.x*t.x+t.y*t.y)*(n.y-e.y))/r,((e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x)+(t.x*t.x+t.y*t.y)*(e.x-n.x))/r)}function MH(e,n,t,r,s){if(t===null)return[b.From(e),b.From(n)];const o=[],i=b.Angle(t,e),a=b.Angle(t,n),l=Gu(i,a);for(let c=0;c{const s=P.useRef(null);jl(s,e.x,e.y);const o=N(Math.max(1,e.w)),i=N(Math.max(1,e.h));return d.jsx("svg",{className:"tl-overlays__item",ref:s,children:n?d.jsxs("g",{className:"tl-brush",opacity:t,children:[d.jsx("rect",{width:o,height:i,fill:n,opacity:.75}),d.jsx("rect",{width:o,height:i,fill:"none",stroke:n,opacity:.1})]}):d.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:o,height:i})})},PC={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.1,.25,.5,1,2,4,8]},ny={duration:0,easing:At.easeInOutCubic},CC={CAMERA_MOVE:-10},AH=["top","right","bottom","left"],IC=0,J0=2,Gd=1,EC=5,jH=128;function df(e){if(e instanceof HTMLElement)return e;if(e.parentElement)return df(e.parentElement);throw Error("Could not find a parent element of an HTML type!")}function Ie(e){e.preventDefault(),xt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",e)}function Vu(e,n){if(e.setPointerCapture(n.pointerId),xt.logPointerCaptures.get()){const t=dT.get();t.set(e,(t.get(e)??0)+1),console.warn("setPointerCapture called on element:",e,n)}}function Yu(e,n){if(e.hasPointerCapture(n.pointerId)&&(e.releasePointerCapture(n.pointerId),xt.logPointerCaptures.get())){const t=dT.get();t.get(e)===1?t.delete(e):t.has(e)?t.set(e,t.get(e)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",e,n)}}const Dt=e=>e.stopPropagation(),tn=(e,n,t)=>{e&&e.style.setProperty(n,t)};function Nn(e){return e.isKilled=!0,{point:{x:e.clientX,y:e.clientY,z:e.pressure},shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.metaKey||e.ctrlKey,pointerId:e.pointerId,button:e.button,isPen:e.pointerType==="pen"}}function lM(){const e=F();return P.useMemo(function(){let r,s;function o(y){if(!y.isKilled){if(y.button===J0){e.dispatch({type:"pointer",target:"canvas",name:"right_click",...Nn(y)});return}y.button!==0&&y.button!==1&&y.button!==5||(Vu(y.currentTarget,y),e.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...Nn(y)}))}}function i(y){y.isKilled||y.clientX===r&&y.clientY===s||(r=y.clientX,s=y.clientY,e.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...Nn(y)}))}function a(y){y.isKilled||y.button!==0&&y.button!==1&&y.button!==2&&y.button!==5||(r=y.clientX,s=y.clientY,Yu(y.currentTarget,y),e.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...Nn(y)}))}function l(y){if(y.isKilled||e.getInstanceState().isPenMode&&y.pointerType!=="pen")return;const x=y.pointerType==="mouse"||y.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!0:null})}function c(y){if(y.isKilled||e.getInstanceState().isPenMode&&y.pointerType!=="pen")return;const x=y.pointerType==="mouse"||y.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!1:null})}function u(y){y.isKilled=!0,Ie(y)}function h(y){y.isKilled=!0,y.target instanceof HTMLElement&&y.target.tagName!=="A"&&y.target.tagName!=="TEXTAREA"&&!(e.getEditingShape()&&y.target.className.includes("tl-text-content"))&&Ie(y)}function p(y){Ie(y)}async function f(y){var m,v;if(Ie(y),!((v=(m=y.dataTransfer)==null?void 0:m.files)!=null&&v.length))return;const x=Array.from(y.dataTransfer.files);await e.putExternalContent({type:"files",files:x,point:e.screenToPage({x:y.clientX,y:y.clientY}),ignoreParent:!1})}function S(y){Dt(y)}return{onPointerDown:o,onPointerMove:i,onPointerUp:a,onPointerEnter:l,onPointerLeave:c,onDragOver:p,onDrop:f,onTouchStart:u,onTouchEnd:h,onClick:S}},[e])}function OH(){const e=F();P.useEffect(()=>{let n=e.getInstanceState().isCoarsePointer;const t=i=>{const a=i.pointerType!=="mouse";n!==a&&(n=a,e.updateInstanceState({isCoarsePointer:a}))};window.addEventListener("pointerdown",t,{capture:!0});const r=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),s=e.environment.isFirefox&&!e.environment.isAndroid&&!e.environment.isIos,o=()=>{const i=s?!1:r.matches;n===i&&(n=i,e.updateInstanceState({isCoarsePointer:i}))};return r&&(r.addEventListener("change",o),o()),()=>{window.removeEventListener("pointerdown",t,{capture:!0}),r&&r.removeEventListener("change",o)}},[e])}const cM=P.createContext(null);function DH({container:e,children:n}){return d.jsx(cM.Provider,{value:e,children:n})}function $t(){return xr(P.useContext(cM),"useContainer used outside of ")}function RH(){const e=F(),n=$t(),t=H("isFocused",()=>e.getIsFocused(),[e]);P.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;let r=null;const s=()=>{r!=null&&r();const o=`(resolution: ${window.devicePixelRatio}dppx)`,i=matchMedia(o),a=l=>{l.type==="change"&&s()};i.addEventListener?i.addEventListener("change",s):i.addListener&&i.addListener(a),r=()=>{i.removeEventListener?i.removeEventListener("change",s):i.removeListener&&i.removeListener(a)},e.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return s(),()=>{r==null||r()}},[e]),P.useEffect(()=>{if(!t)return;const r=a=>{if(a.altKey&&(e.isIn("zoom")||!e.getPath().endsWith(".idle"))&&!Vd()&&Ie(a),a.isKilled)return;switch(a.isKilled=!0,a.key){case"=":case"-":case"0":{if(a.metaKey||a.ctrlKey){Ie(a);return}break}case"Tab":{if(Vd()||e.getIsMenuOpen())return;break}case",":return;case"Escape":{if((e.getEditingShape()||e.getSelectedShapeIds().length>0)&&a.preventDefault(),e.getOpenMenus().length>0)return;e.inputs.keys.has("Escape")||(e.inputs.keys.add("Escape"),e.cancel(),e.focus());return}default:if(Vd()||e.getIsMenuOpen())return}const l={type:"keyboard",name:a.repeat?"key_repeat":"key_down",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)},s=a=>{if(a.isKilled||(a.isKilled=!0,Vd()||e.getIsMenuOpen())||a.key===",")return;const l={type:"keyboard",name:"key_up",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)};function o(a){var l,c;if(n.contains(a.target)){const u=a.touches[0].pageX,h=a.touches[0].radiusX||0;(u-h<10||u+h>e.getViewportScreenBounds().width-10)&&(((l=a.target)==null?void 0:l.tagName)==="BUTTON"&&((c=a.target)==null||c.click()),Ie(a))}}const i=a=>{n.contains(a.target)&&(a.ctrlKey||a.metaKey)&&Ie(a)};return n.addEventListener("touchstart",o,{passive:!1}),n.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",Ie),document.addEventListener("gesturechange",Ie),document.addEventListener("gestureend",Ie),n.addEventListener("keydown",r),n.addEventListener("keyup",s),()=>{n.removeEventListener("touchstart",o),n.removeEventListener("wheel",i),document.removeEventListener("gesturestart",Ie),document.removeEventListener("gesturechange",Ie),document.removeEventListener("gestureend",Ie),n.removeEventListener("keydown",r),n.removeEventListener("keyup",s)}},[e,n,t])}const LH=["input","select","button","textarea"];function Vd(){const{activeElement:e}=document;return!!(e&&(e.getAttribute("contenteditable")||LH.indexOf(e.tagName.toLowerCase())>-1))}const $H=["textarea","input"];function NH(e){const n=F();P.useEffect(()=>{const t=e.current;if(!t)return;const r=s=>{var o;if(s instanceof PointerEvent&&s.pointerType==="pen"){s.isKilled=!0;const{target:i}=s;if($H.includes((o=i.tagName)==null?void 0:o.toLocaleLowerCase())||n.isIn("select.editing_shape"))return;Ie(s)}};return t.addEventListener("touchstart",r),t.addEventListener("touchend",r),()=>{t.removeEventListener("touchstart",r),t.removeEventListener("touchend",r)}},[n,e])}function FH(e,n,t){return Math.max(n,Math.min(e,t))}const Kt={toVector(e,n){return e===void 0&&(e=n),Array.isArray(e)?e:[e,e]},add(e,n){return[e[0]+n[0],e[1]+n[1]]},sub(e,n){return[e[0]-n[0],e[1]-n[1]]},addTo(e,n){e[0]+=n[0],e[1]+=n[1]},subTo(e,n){e[0]-=n[0],e[1]-=n[1]}};function _C(e,n,t){return n===0||Math.abs(n)===1/0?Math.pow(e,t*5):e*n*t/(n+t*e)}function kC(e,n,t,r=.15){return r===0?FH(e,n,t):et?+_C(e-t,t-n,r)+t:e}function zH(e,[n,t],[r,s]){const[[o,i],[a,l]]=e;return[kC(n,o,i,r),kC(t,a,l,s)]}function BH(e,n){if(typeof e!="object"||e===null)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var r=t.call(e,n||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function UH(e){var n=BH(e,"string");return typeof n=="symbol"?n:String(n)}function rn(e,n,t){return n=UH(n),n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function TC(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),t.push.apply(t,r)}return t}function ut(e){for(var n=1;n{var t,r;return n.target===e.currentTarget||((t=e.currentTarget)===null||t===void 0||(r=t.contains)===null||r===void 0?void 0:r.call(t,n.target))})}function Iv(e,n){try{const t=n.clientX-e.clientX,r=n.clientY-e.clientY,s=(n.clientX+e.clientX)/2,o=(n.clientY+e.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 ZH(e){return qH(e).map(n=>n.identifier)}function AC(e,n){const[t,r]=Array.from(e.touches).filter(s=>n.includes(s.identifier));return Iv(t,r)}const jC=40,OC=800;function hM(e){let{deltaX:n,deltaY:t,deltaMode:r}=e;return r===1?(n*=jC,t*=jC):r===2&&(n*=OC,t*=OC),[n,t]}function QH(e){const n={};if("buttons"in e&&(n.buttons=e.buttons),"shiftKey"in e){const{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o}=e;Object.assign(n,{shiftKey:t,altKey:r,metaKey:s,ctrlKey:o})}return n}function hf(e,...n){return typeof e=="function"?e(...n):e}function JH(){}function eK(...e){return e.length===0?JH:e.length===1?e[0]:function(){let n;for(const t of e)n=t.apply(this,arguments)||n;return n}}function DC(e,n){return Object.assign({},n,e||{})}const tK=32;class pM{constructor(n,t,r){this.ctrl=n,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(n){this.ctrl.state[this.key]=n}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:n,shared:t,ingKey:r,args:s}=this;t[r]=n._active=n.active=n._blocked=n._force=!1,n._step=[!1,!1],n.intentional=!1,n._movement=[0,0],n._distance=[0,0],n._direction=[0,0],n._delta=[0,0],n._bounds=[[-1/0,1/0],[-1/0,1/0]],n.args=s,n.axis=void 0,n.memo=void 0,n.elapsedTime=n.timeDelta=0,n.direction=[0,0],n.distance=[0,0],n.overflow=[0,0],n._movementBound=[!1,!1],n.velocity=[0,0],n.movement=[0,0],n.delta=[0,0],n.timeStamp=0}start(n){const t=this.state,r=this.config;t._active||(this.reset(),this.computeInitial(),t._active=!0,t.target=n.target,t.currentTarget=n.currentTarget,t.lastOffset=r.from?hf(r.from,t):t.offset,t.offset=t.lastOffset,t.startTime=t.timeStamp=n.timeStamp)}computeValues(n){const t=this.state;t._values=n,t.values=this.config.transform(n)}computeInitial(){const n=this.state;n._initial=n._values,n.initial=n.values}compute(n){const{state:t,config:r,shared:s}=this;t.args=this.args;let o=0;if(n&&(t.event=n,r.preventDefault&&n.cancelable&&t.event.preventDefault(),t.type=n.type,s.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,s.locked=!!document.pointerLockElement,Object.assign(s,QH(n)),s.down=s.pressed=s.buttons%2===1||s.touches>0,o=n.timeStamp-t.timeStamp,t.timeStamp=n.timeStamp,t.elapsedTime=t.timeStamp-t.startTime),t._active){const k=t._delta.map(Math.abs);Kt.addTo(t._distance,k)}this.axisIntent&&this.axisIntent(n);const[i,a]=t._movement,[l,c]=r.threshold,{_step:u,values:h}=t;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=l&&h[0]),u[1]===!1&&(u[1]=Math.abs(a)>=c&&h[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 p=[0,0];if(r.hasCustomTransform){const[k,I]=h;p[0]=u[0]!==!1?k-u[0]:0,p[1]=u[1]!==!1?I-u[1]:0}else p[0]=u[0]!==!1?i-u[0]:0,p[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!t._blocked&&this.restrictToAxis(p);const f=t.offset,S=t._active&&!t._blocked||t.active;S&&(t.first=t._active&&!t.active,t.last=!t._active&&t.active,t.active=s[this.ingKey]=t._active,n&&(t.first&&("bounds"in r&&(t._bounds=hf(r.bounds,t)),this.setup&&this.setup()),t.movement=p,this.computeOffset()));const[y,x]=t.offset,[[m,v],[w,C]]=t._bounds;t.overflow=[yv?1:0,xC?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 E=t._active?r.rubberband||[0,0]:[0,0];if(t.offset=zH(t._bounds,t.offset,E),t.delta=Kt.sub(t.offset,f),this.computeMovement(),S&&(!t.last||o>tK)){t.delta=Kt.sub(t.offset,f);const k=t.delta.map(Math.abs);Kt.addTo(t.distance,k),t.direction=t.delta.map(Math.sign),t._direction=t._delta.map(Math.sign),!t.first&&o>0&&(t.velocity=[k[0]/o,k[1]/o],t.timeDelta=o)}}emit(){const n=this.state,t=this.shared,r=this.config;if(n._active||this.clean(),(n._blocked||!n.intentional)&&!n._force&&!r.triggerAllEvents)return;const s=this.handler(ut(ut(ut({},t),n),{},{[this.aliasKey]:n.values}));s!==void 0&&(n.memo=s)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function nK([e,n],t){const r=Math.abs(e),s=Math.abs(n);if(r>s&&r>t)return"x";if(s>r&&s>t)return"y"}class rK extends pM{constructor(...n){super(...n),rn(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=Kt.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Kt.sub(this.state.offset,this.state.lastOffset)}axisIntent(n){const t=this.state,r=this.config;if(!t.axis&&n){const s=typeof r.axisThreshold=="object"?r.axisThreshold[XH(n)]:r.axisThreshold;t.axis=nK(t._movement,s)}t._blocked=(r.lockDirection||!!r.axis)&&!t.axis||!!r.axis&&r.axis!==t.axis}restrictToAxis(n){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":n[1]=0;break;case"y":n[0]=0;break}}}const sK=e=>e,RC=.15,fM={enabled(e=!0){return e},eventOptions(e,n,t){return ut(ut({},t.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[RC,RC];case!1:return[0,0];default:return Kt.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return Kt.toVector(e)},transform(e,n,t){const r=e||t.shared.transform;return this.hasCustomTransform=!!r,r||sK},threshold(e){return Kt.toVector(e,0)}},oK=0,Xu=ut(ut({},fM),{},{axis(e,n,{axis:t}){if(this.lockDirection=t==="lock",!this.lockDirection)return t},axisThreshold(e=oK){return e},bounds(e={}){if(typeof e=="function")return o=>Xu.bounds(e(o));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:n=-1/0,right:t=1/0,top:r=-1/0,bottom:s=1/0}=e;return[[n,t],[r,s]]}}),qu=typeof window<"u"&&window.document&&window.document.createElement;function gM(){return qu&&"ontouchstart"in window}function iK(){return gM()||qu&&window.navigator.maxTouchPoints>1}function aK(){return qu&&"onpointerdown"in window}function lK(){return qu&&"exitPointerLock"in window.document}function cK(){try{return"constructor"in GestureEvent}catch{return!1}}const wr={isBrowser:qu,gesture:cK(),touch:gM(),touchscreen:iK(),pointer:aK(),pointerLock:lK()},uK=250,dK=180,hK=.5,pK=50,fK=250,gK=10,LC={mouse:0,touch:0,pen:8};ut(ut({},Xu),{},{device(e,n,{pointer:{touch:t=!1,lock:r=!1,mouse:s=!1}={}}){return this.pointerLock=r&&wr.pointerLock,wr.touch&&t?"touch":this.pointerLock?"mouse":wr.pointer&&!s?"pointer":wr.touch?"touch":"mouse"},preventScrollAxis(e,n,{preventScroll:t}){if(this.preventScrollDelay=typeof t=="number"?t:t||t===void 0&&e?uK:void 0,!(!wr.touchscreen||t===!1))return e||(t!==void 0?"y":void 0)},pointerCapture(e,n,{pointer:{capture:t=!0,buttons:r=1,keys:s=!0}={}}){return this.pointerButtons=r,this.keys=s,!this.pointerLock&&this.device==="pointer"&&t},threshold(e,n,{filterTaps:t=!1,tapsThreshold:r=3,axis:s=void 0}){const o=Kt.toVector(e,t?r:s?1:0);return this.filterTaps=t,this.tapsThreshold=r,o},swipe({velocity:e=hK,distance:n=pK,duration:t=fK}={}){return{velocity:this.transform(Kt.toVector(e)),distance:this.transform(Kt.toVector(n)),duration:t}},delay(e=0){switch(e){case!0:return dK;case!1:return 0;default:return e}},axisThreshold(e){return e?ut(ut({},LC),e):LC},keyboardDisplacement(e=gK){return e}});function mM(e){const[n,t]=e.overflow,[r,s]=e._delta,[o,i]=e._direction;(n<0&&r>0&&o<0||n>0&&r<0&&o>0)&&(e._movement[0]=e._movementBound[0]),(t<0&&s>0&&i<0||t>0&&s<0&&i>0)&&(e._movement[1]=e._movementBound[1])}const mK=30,yK=100;class SK extends pM{constructor(...n){super(...n),rn(this,"ingKey","pinching"),rn(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const n=this.state;n._touchIds=[],n.canceled=!1,n.cancel=this.cancel.bind(this),n.turns=0}computeOffset(){const{type:n,movement:t,lastOffset:r}=this.state;n==="wheel"?this.state.offset=Kt.add(t,r):this.state.offset=[(1+t[0])*r[0],t[1]+r[1]]}computeMovement(){const{offset:n,lastOffset:t}=this.state;this.state.movement=[n[0]/t[0],n[1]-t[1]]}axisIntent(){const n=this.state,[t,r]=n._movement;if(!n.axis){const s=Math.abs(t)*mK-Math.abs(r);s<0?n.axis="angle":s>0&&(n.axis="scale")}}restrictToAxis(n){this.config.lockDirection&&(this.state.axis==="scale"?n[1]=0:this.state.axis==="angle"&&(n[0]=0))}cancel(){const n=this.state;n.canceled||setTimeout(()=>{n.canceled=!0,n._active=!1,this.compute(),this.emit()},0)}touchStart(n){this.ctrl.setEventIds(n);const t=this.state,r=this.ctrl.touchIds;if(t._active&&t._touchIds.every(o=>r.has(o))||r.size<2)return;this.start(n),t._touchIds=Array.from(r).slice(0,2);const s=AC(n,t._touchIds);s&&this.pinchStart(n,s)}pointerStart(n){if(n.buttons!=null&&n.buttons%2!==1)return;this.ctrl.setEventIds(n),n.target.setPointerCapture(n.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(n.pointerId,n),t._pointerEvents.size<2))return;this.start(n);const o=Iv(...Array.from(r.values()));o&&this.pinchStart(n,o)}pinchStart(n,t){const r=this.state;r.origin=t.origin,this.computeValues([t.distance,t.angle]),this.computeInitial(),this.compute(n),this.emit()}touchMove(n){if(!this.state._active)return;const t=AC(n,this.state._touchIds);t&&this.pinchMove(n,t)}pointerMove(n){const t=this.state._pointerEvents;if(t.has(n.pointerId)&&t.set(n.pointerId,n),!this.state._active)return;const r=Iv(...Array.from(t.values()));r&&this.pinchMove(n,r)}pinchMove(n,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(n),this.emit()}touchEnd(n){this.ctrl.setEventIds(n),this.state._active&&this.state._touchIds.some(t=>!this.ctrl.touchIds.has(t))&&(this.state._active=!1,this.compute(n),this.emit())}pointerEnd(n){const t=this.state;this.ctrl.setEventIds(n);try{n.target.releasePointerCapture(n.pointerId)}catch{}t._pointerEvents.has(n.pointerId)&&t._pointerEvents.delete(n.pointerId),t._active&&t._pointerEvents.size<2&&(t._active=!1,this.compute(n),this.emit())}gestureStart(n){n.cancelable&&n.preventDefault();const t=this.state;t._active||(this.start(n),this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY],this.compute(n),this.emit())}gestureMove(n){if(n.cancelable&&n.preventDefault(),!this.state._active)return;const t=this.state;this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY];const r=t._movement;t._movement=[n.scale-1,n.rotation],t._delta=Kt.sub(t._movement,r),this.compute(n),this.emit()}gestureEnd(n){this.state._active&&(this.state._active=!1,this.compute(n),this.emit())}wheel(n){const t=this.config.modifierKey;t&&(Array.isArray(t)?!t.find(r=>n[r]):!n[t])||(this.state._active?this.wheelChange(n):this.wheelStart(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(n){this.start(n),this.wheelChange(n)}wheelChange(n){"uv"in n||n.cancelable&&n.preventDefault();const r=this.state;r._delta=[-hM(n)[1]/yK*r.offset[0],0],Kt.addTo(r._movement,r._delta),mM(r),this.state.origin=[n.clientX,n.clientY],this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){const t=this.config.device;t&&(n(t,"start",this[t+"Start"].bind(this)),n(t,"change",this[t+"Move"].bind(this)),n(t,"end",this[t+"End"].bind(this)),n(t,"cancel",this[t+"End"].bind(this)),n("lostPointerCapture","",this[t+"End"].bind(this))),this.config.pinchOnWheel&&n("wheel","",this.wheel.bind(this),{passive:!1})}}const vK=ut(ut({},fM),{},{device(e,n,{shared:t,pointer:{touch:r=!1}={}}){if(t.target&&!wr.touch&&wr.gesture)return"gesture";if(wr.touch&&r)return"touch";if(wr.touchscreen){if(wr.pointer)return"pointer";if(wr.touch)return"touch"}},bounds(e,n,{scaleBounds:t={},angleBounds:r={}}){const s=i=>{const a=DC(hf(t,i),{min:-1/0,max:1/0});return[a.min,a.max]},o=i=>{const a=DC(hf(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(e,n,t){return this.lockDirection=t.axis==="lock",Kt.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});ut(ut({},Xu),{},{mouseOnly:(e=!0)=>e});class xK extends rK{constructor(...n){super(...n),rn(this,"ingKey","wheeling")}wheel(n){this.state._active||this.start(n),this.wheelChange(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(n){const t=this.state;t._delta=hM(n),Kt.addTo(t._movement,t._delta),mM(t),this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){n("wheel","",this.wheel.bind(this))}}const wK=Xu;ut(ut({},Xu),{},{mouseOnly:(e=!0)=>e});const ew=new Map,Ev=new Map;function bK(e){ew.set(e.key,e.engine),Ev.set(e.key,e.resolver)}const PK={key:"pinch",engine:SK,resolver:vK},CK={key:"wheel",engine:xK,resolver:wK};function IK(e,n){if(e==null)return{};var t={},r=Object.keys(e),s,o;for(o=0;o=0)&&(t[s]=e[s]);return t}function EK(e,n){if(e==null)return{};var t=IK(e,n),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(t[r]=e[r])}return t}const _K={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=wr.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:n=!1}={}){return{passive:e,capture:n}},transform(e){return e}},kK=["target","eventOptions","window","enabled","transform"];function zh(e={},n){const t={};for(const[r,s]of Object.entries(n))switch(typeof s){case"function":t[r]=s.call(t,e[r],r,e);break;case"object":t[r]=zh(e[r],s);break;case"boolean":s&&(t[r]=e[r]);break}return t}function TK(e,n,t={}){const r=e,{target:s,eventOptions:o,window:i,enabled:a,transform:l}=r,c=EK(r,kK);if(t.shared=zh({target:s,eventOptions:o,window:i,enabled:a,transform:l},_K),n){const u=Ev.get(n);t[n]=zh(ut({shared:t.shared},c),u)}else for(const u in c){const h=Ev.get(u);h&&(t[u]=zh(ut({shared:t.shared},c[u]),h))}return t}class yM{constructor(n,t){rn(this,"_listeners",new Set),this._ctrl=n,this._gestureKey=t}add(n,t,r,s,o){const i=this._listeners,a=YH(t,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=ut(ut({},l),o);n.addEventListener(a,s,c);const u=()=>{n.removeEventListener(a,s,c),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(n=>n()),this._listeners.clear()}}class MK{constructor(){rn(this,"_timeouts",new Map)}add(n,t,r=140,...s){this.remove(n),this._timeouts.set(n,window.setTimeout(t,r,...s))}remove(n){const t=this._timeouts.get(n);t&&window.clearTimeout(t)}clean(){this._timeouts.forEach(n=>void window.clearTimeout(n)),this._timeouts.clear()}}class AK{constructor(n){rn(this,"gestures",new Set),rn(this,"_targetEventStore",new yM(this)),rn(this,"gestureEventStores",{}),rn(this,"gestureTimeoutStores",{}),rn(this,"handlers",{}),rn(this,"config",{}),rn(this,"pointerIds",new Set),rn(this,"touchIds",new Set),rn(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),jK(this,n)}setEventIds(n){if(dM(n))return this.touchIds=new Set(ZH(n)),this.touchIds;if("pointerId"in n)return n.type==="pointerup"||n.type==="pointercancel"?this.pointerIds.delete(n.pointerId):n.type==="pointerdown"&&this.pointerIds.add(n.pointerId),this.pointerIds}applyHandlers(n,t){this.handlers=n,this.nativeHandlers=t}applyConfig(n,t){this.config=TK(n,t,this.config)}clean(){this._targetEventStore.clean();for(const n of this.gestures)this.gestureEventStores[n].clean(),this.gestureTimeoutStores[n].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...n){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=$C(r,a.eventOptions,!!s);if(a.enabled){const c=ew.get(i);new c(this,n,i).bind(l)}}const o=$C(r,t.eventOptions,!!s);for(const i in this.nativeHandlers)o(i,"",a=>this.nativeHandlers[i](ut(ut({},this.state.shared),{},{event:a,args:n})),void 0,!0)}for(const o in r)r[o]=eK(...r[o]);if(!s)return r;for(const o in r){const{device:i,capture:a,passive:l}=VH(o);this._targetEventStore.add(s,i,"",r[o],{capture:a,passive:l})}}}}function fa(e,n){e.gestures.add(n),e.gestureEventStores[n]=new yM(e,n),e.gestureTimeoutStores[n]=new MK}function jK(e,n){n.drag&&fa(e,"drag"),n.wheel&&fa(e,"wheel"),n.scroll&&fa(e,"scroll"),n.move&&fa(e,"move"),n.pinch&&fa(e,"pinch"),n.hover&&fa(e,"hover")}const $C=(e,n,t)=>(r,s,o,i={},a=!1)=>{var l,c;const u=(l=i.capture)!==null&&l!==void 0?l:n.capture,h=(c=i.passive)!==null&&c!==void 0?c:n.passive;let p=a?r:WH(r,s,u);t&&h&&(p+="Passive"),e[p]=e[p]||[],e[p].push(o)},OK=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function DK(e){const n={},t={},r=new Set;for(let s in e)OK.test(s)?(r.add(RegExp.lastMatch),t[s]=e[s]):n[s]=e[s];return[t,n,r]}function ga(e,n,t,r,s,o){if(!e.has(t)||!ew.has(r))return;const i=t+"Start",a=t+"End",l=c=>{let u;return c.first&&i in n&&n[i](c),t in n&&(u=n[t](c)),c.last&&a in n&&n[a](c),u};s[r]=l,o[r]=o[r]||{}}function RK(e,n){const[t,r,s]=DK(e),o={};return ga(s,t,"onDrag","drag",o,n),ga(s,t,"onWheel","wheel",o,n),ga(s,t,"onScroll","scroll",o,n),ga(s,t,"onPinch","pinch",o,n),ga(s,t,"onMove","move",o,n),ga(s,t,"onHover","hover",o,n),{handlers:o,config:n,nativeHandlers:r}}function LK(e,n={},t,r){const s=Ce.useMemo(()=>new AK(e),[]);if(s.applyHandlers(e,r),s.applyConfig(n,t),Ce.useEffect(s.effect.bind(s)),Ce.useEffect(()=>s.clean.bind(s),[]),n.target===void 0)return s.bind.bind(s)}function $K(e){return e.forEach(bK),function(t,r){const{handlers:s,nativeHandlers:o,config:i}=RK(t,r||{});return LK(s,i,void 0,o)}}const NC=10,NK=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function SM(e){let{deltaY:n,deltaX:t}=e,r=0;return e.ctrlKey||e.altKey||e.metaKey?r=(Math.abs(n)>NC?NC*Math.sign(n):n)/100:e.shiftKey&&!NK&&(t=n,n=0),{x:-t,y:-n,z:-r}}const FK=$K([CK,PK]);let ma;const zK=e=>ma===void 0?(ma=e,!1):e-ma>120&&e-ma<160?(ma=e,!0):(ma=e,!1);function BK(e){const n=F(),t=P.useMemo(()=>{let r="not sure";const s=({event:y})=>{if(!n.getInstanceState().isFocused||(r="not sure",zK(Date.now())))return;const x=n.getEditingShapeId();if(x){const w=n.getShape(x);if(w&&n.getShapeUtil(w).canScroll(w)){const E=n.getShapePageBounds(x);if(E!=null&&E.containsPoint(n.inputs.currentPagePoint))return}}Ie(y),Dt(y);const m=SM(y);if(m.x===0&&m.y===0)return;const v={type:"wheel",name:"wheel",delta:m,point:new b(y.clientX,y.clientY),shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey};n.dispatch(v)};let o=1,i=1,a=1,l=0;const c=new b,u=new b,h=y=>{const x=e.current;r="not sure";const{event:m,origin:v,da:w}=y;m instanceof WheelEvent||(m.target===x||x!=null&&x.contains(m.target))&&(u.x=v[0],u.y=v[1],c.x=v[0],c.y=v[1],o=w[0],i=n.getZoomLevel(),n.dispatch({type:"pinch",name:"pinch_start",point:{x:v[0],y:v[1],z:n.getZoomLevel()},delta:{x:0,y:0},shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey}))},p=y=>{if(y&&(r="zooming"),r==="zooming")return;const x=Math.abs(l-o),m=b.Dist(c,u);switch(r){case"not sure":{x>24?r="zooming":m>16&&(r="panning");break}case"panning":{x>64&&(r="zooming");break}}};return{onWheel:s,onPinchStart:h,onPinchEnd:y=>{const x=e.current,{event:m,origin:v,offset:w}=y;if(m instanceof WheelEvent||!(m.target===x||x!=null&&x.contains(m.target)))return;const C=w[0];r="not sure",n.timers.requestAnimationFrame(()=>{n.dispatch({type:"pinch",name:"pinch_end",point:{x:v[0],y:v[1],z:C},delta:{x:v[0],y:v[1]},shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey})})},onPinch:y=>{const x=e.current,{event:m,origin:v,offset:w,da:C}=y;if(m instanceof WheelEvent||!(m.target===x||x!=null&&x.contains(m.target)))return;const E=y.type==="gesturechange"||y.type==="gestureend";l=C[0];const k=v[0]-u.x,I=v[1]-u.y;switch(u.x=v[0],u.y=v[1],p(E),r){case"zooming":{a=w[0],n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:a},delta:{x:k,y:I},shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey});break}case"panning":{n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:i},delta:{x:k,y:I},shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey});break}}}}},[n,e]);FK(t,{target:e,eventOptions:{passive:!1},pinch:{from:()=>[n.getZoomLevel(),0],scaleBounds:()=>({from:n.getZoomLevel(),max:8,min:.05})}})}function ry(e,n,t){const r=e.getShape(n),s=e.getShapeHandles(r);return{shape:r,handle:s.find(o=>o.id===t)}}function UK(e,n){const t=F();return P.useMemo(()=>{const r=l=>{if(l.isKilled)return;const c=df(l.currentTarget);Vu(c,l);const{shape:u,handle:h}=ry(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_down",...Nn(l)})};let s,o;return{onPointerDown:r,onPointerMove:l=>{if(l.isKilled||l.clientX===s&&l.clientY===o)return;s=l.clientX,o=l.clientY;const{shape:c,handle:u}=ry(t,e,n);u&&t.dispatch({type:"pointer",target:"handle",handle:u,shape:c,name:"pointer_move",...Nn(l)})},onPointerUp:l=>{if(l.isKilled)return;const c=df(l.currentTarget);Yu(c,l);const{shape:u,handle:h}=ry(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_up",...Nn(l)})}}},[t,e,n])}const Je=class Je{constructor(n=0,t=0,r=0,s=0){g(this,"x",0);g(this,"y",0);g(this,"w",0);g(this,"h",0);this.x=n,this.y=t,this.w=r,this.h=s}get point(){return new b(this.x,this.y)}set point(n){this.x=n.x,this.y=n.y}get minX(){return this.x}set minX(n){this.x=n}get midX(){return this.x+this.w/2}get maxX(){return this.x+this.w}get minY(){return this.y}set minY(n){this.y=n}get midY(){return this.y+this.h/2}get maxY(){return this.y+this.h}get width(){return this.w}set width(n){this.w=n}get height(){return this.h}set height(n){this.h=n}get aspectRatio(){return this.width/this.height}get center(){return new b(this.midX,this.midY)}set center(n){this.minX=n.x-this.width/2,this.minY=n.y-this.height/2}get corners(){return[new b(this.minX,this.minY),new b(this.maxX,this.minY),new b(this.maxX,this.maxY),new b(this.minX,this.maxY)]}get cornersAndCenter(){return[new b(this.minX,this.minY),new b(this.maxX,this.minY),new b(this.maxX,this.maxY),new b(this.minX,this.maxY),this.center]}get sides(){const{corners:n}=this;return[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]]}get size(){return new b(this.w,this.h)}toFixed(){return this.x=Wd(this.x),this.y=Wd(this.y),this.w=Wd(this.w),this.h=Wd(this.h),this}setTo(n){return this.x=n.x,this.y=n.y,this.w=n.w,this.h=n.h,this}set(n=0,t=0,r=0,s=0){return this.x=n,this.y=t,this.w=r,this.h=s,this}expand(n){const t=Math.min(this.minX,n.minX),r=Math.min(this.minY,n.minY),s=Math.max(this.maxX,n.maxX),o=Math.max(this.maxY,n.maxY);return this.x=t,this.y=r,this.w=s-t,this.h=o-r,this}expandBy(n){return this.x-=n,this.y-=n,this.w+=n*2,this.h+=n*2,this}scale(n){return this.x/=n,this.y/=n,this.w/=n,this.h/=n,this}clone(){const{x:n,y:t,w:r,h:s}=this;return new Je(n,t,r,s)}translate(n){return this.x+=n.x,this.y+=n.y,this}snapToGrid(n){const t=Math.round(this.minX/n)*n,r=Math.round(this.minY/n)*n,s=Math.round(this.maxX/n)*n,o=Math.round(this.maxY/n)*n;this.minX=t,this.minY=r,this.width=Math.max(1,s-t),this.height=Math.max(1,o-r)}collides(n){return Je.Collides(this,n)}contains(n){return Je.Contains(this,n)}includes(n){return Je.Includes(this,n)}containsPoint(n,t=0){return Je.ContainsPoint(this,n,t)}getHandlePoint(n){switch(n){case"top_left":return new b(this.minX,this.minY);case"top_right":return new b(this.maxX,this.minY);case"bottom_left":return new b(this.minX,this.maxY);case"bottom_right":return new b(this.maxX,this.maxY);case"top":return new b(this.midX,this.minY);case"right":return new b(this.maxX,this.midY);case"bottom":return new b(this.midX,this.maxY);case"left":return new b(this.minX,this.midY)}}toJson(){return{x:this.minX,y:this.minY,w:this.w,h:this.h}}resize(n,t,r){const{minX:s,minY:o,maxX:i,maxY:a}=this;let{minX:l,minY:c,maxX:u,maxY:h}=this;switch(n){case"left":case"top_left":case"bottom_left":{l+=t;break}case"right":case"top_right":case"bottom_right":{u+=t;break}}switch(n){case"top":case"top_left":case"top_right":{c+=r;break}case"bottom":case"bottom_left":case"bottom_right":{h+=r;break}}const p=(u-l)/(i-s),f=(h-c)/(a-o),S=p<0,y=f<0;if(S){const x=u;u=l,l=x}if(y){const x=h;h=c,c=x}this.minX=l,this.minY=c,this.width=Math.abs(u-l),this.height=Math.abs(h-c)}union(n){const t=Math.min(this.minX,n.x),r=Math.min(this.minY,n.y),s=Math.max(this.maxX,n.w+n.x),o=Math.max(this.maxY,n.h+n.y);return this.x=t,this.y=r,this.width=s-t,this.height=o-r,this}static From(n){return new Je(n.x,n.y,n.w,n.h)}static FromCenter(n,t){return new Je(n.x-t.x/2,n.y-t.y/2,t.x,t.y)}static FromPoints(n){if(n.length===0)return new Je;let t=1/0,r=1/0,s=-1/0,o=-1/0,i;for(let a=0,l=n.length;a0?1:-1)).toFixed(5),scaleY:+(v.height/n.height*(y>0?1:-1)).toFixed(5)}}equals(n){return Je.Equals(this,n)}static Equals(n,t){return t.x===n.x&&t.y===n.y&&t.w===n.w&&t.h===n.h}zeroFix(){return this.w=Math.max(1,this.w),this.h=Math.max(1,this.h),this}static ZeroFix(n){return new Je(n.x,n.y,Math.max(1,n.w),Math.max(1,n.h))}};g(Je,"Collides",(n,t)=>!(n.maxXt.maxX||n.maxYt.maxY)),g(Je,"Contains",(n,t)=>n.minXt.maxY&&n.maxX>t.maxX),g(Je,"Includes",(n,t)=>Je.Collides(n,t)||Je.Contains(n,t)),g(Je,"ContainsPoint",(n,t,r=0)=>!(t.xn.maxX+r||t.y>n.maxY+r)),g(Je,"Common",n=>{let t=1/0,r=1/0,s=-1/0,o=-1/0;for(let i=0;i{const{corners:r}=n;return[[r[0],r[1]],[r[1],r[2]],[r[2],r[3]],[r[3],r[0]]]});let Q=Je;function HK(e){switch(e){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 e}}function KK(e){switch(e){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 e}}function WK(e){return e==="top_left"||e==="top_right"||e==="bottom_right"||e==="bottom_left"}function GK(e){const n=F();P.useLayoutEffect(()=>{let t=new Q;function r(){const c=e.current;if(!c)return null;const u=c.getBoundingClientRect(),h=new Q(u.left||u.x,u.top||u.y,Math.max(u.width,1),Math.max(u.height,1));t.equals(h)||(n.updateViewportScreenBounds(h),t=h)}r();const s=B2(r,200,{trailing:!0}),o=n.timers.setInterval(s,1e3);window.addEventListener("resize",s);const i=new ResizeObserver(c=>{c[0].contentRect&&s()}),a=e.current;let l=null;return a&&(i.observe(a),l=VK(a),l.addEventListener("scroll",s)),()=>{clearInterval(o),window.removeEventListener("resize",s),i.disconnect(),l==null||l.removeEventListener("scroll",s),s.cancel()}},[n,e])}/*! * Author: excalidraw * MIT License: https://github.com/excalidraw/excalidraw/blob/master/LICENSE * https://github.com/excalidraw/excalidraw/blob/48c3465b19f10ec755b3eb84e21a01a468e96e43/packages/excalidraw/utils.ts#L600 - */const VK=e=>{let n=e.parentElement;for(;n;){if(n===document.body)return document;const{overflowY:t}=window.getComputedStyle(n);if(n.scrollHeight>n.clientHeight&&(t==="auto"||t==="scroll"||t==="overlay"))return n;n=n.parentElement}return document},Re=class Re{constructor(n,t,r,s,o,i){g(this,"a",1);g(this,"b",0);g(this,"c",0);g(this,"d",1);g(this,"e",0);g(this,"f",0);this.a=n,this.b=t,this.c=r,this.d=s,this.e=o,this.f=i}equals(n){return this===n||this.a===n.a&&this.b===n.b&&this.c===n.c&&this.d===n.d&&this.e===n.e&&this.f===n.f}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this}multiply(n){const t=n,{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(n,t,r){return n===0?this:t===void 0?this.multiply(Re.Rotate(n)):this.translate(t,r).multiply(Re.Rotate(n)).translate(-t,-r)}translate(n,t){return this.multiply(Re.Translate(n,t))}scale(n,t){return this.multiply(Re.Scale(n,t))}invert(){const{a:n,b:t,c:r,d:s,e:o,f:i}=this,a=n*s-t*r;return this.a=s/a,this.b=t/-a,this.c=r/-a,this.d=n/a,this.e=(s*o-r*i)/-a,this.f=(t*o-n*i)/a,this}applyToPoint(n){return Re.applyToPoint(this,n)}applyToPoints(n){return Re.applyToPoints(this,n)}rotation(){return Re.Rotation(this)}point(){return Re.Point(this)}decomposed(){return Re.Decompose(this)}toCssString(){return Re.toCssString(this)}setTo(n){return Object.assign(this,n),this}decompose(){return Re.Decompose(this)}clone(){return new Re(this.a,this.b,this.c,this.d,this.e,this.f)}static Identity(){return new Re(1,0,0,1,0,0)}static Translate(n,t){return new Re(1,0,0,1,n,t)}static Rotate(n,t,r){if(n===0)return Re.Identity();const s=Math.cos(n),o=Math.sin(n),i=new Re(s,o,-o,s,0,0);return t===void 0?i:Re.Compose(Re.Translate(t,r),i,Re.Translate(-t,-r))}static Multiply(n,t){return{a:n.a*t.a+n.c*t.b,c:n.a*t.c+n.c*t.d,e:n.a*t.e+n.c*t.f+n.e,b:n.b*t.a+n.d*t.b,d:n.b*t.c+n.d*t.d,f:n.b*t.e+n.d*t.f+n.f}}static Inverse(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/-t,f:(n.b*n.e-n.a*n.f)/t}}static Absolute(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/t,f:(n.b*n.e-n.a*n.f)/-t}}static Compose(...n){const t=Re.Identity();for(let r=0,s=n.length;r0?-1:1)}else if(n.b!==0||n.d!==0){const r=(n.b*n.b+n.d*n.d)**.5;t=Ve+Math.acos(n.b/r)*(n.d>0?-1:1)}else t=0;return Pv(t)}static Decompose(n){let t,r,s;if(n.a!==0||n.c!==0){const o=(n.a*n.a+n.c*n.c)**.5;t=o,r=(n.a*n.d-n.b*n.c)/o,s=Math.acos(n.a/o)*(n.c>0?-1:1)}else if(n.b!==0||n.d!==0){const o=(n.b*n.b+n.d*n.d)**.5;t=(n.a*n.d-n.b*n.c)/o,r=o,s=Ve+Math.acos(n.b/o)*(n.d>0?-1:1)}else t=0,r=0,s=0;return{x:n.e,y:n.f,scaleX:t,scaleY:r,rotation:Pv(s)}}static Smooth(n,t=1e10){return n.a=Math.round(n.a*t)/t,n.b=Math.round(n.b*t)/t,n.c=Math.round(n.c*t)/t,n.d=Math.round(n.d*t)/t,n.e=Math.round(n.e*t)/t,n.f=Math.round(n.f*t)/t,n}static toCssString(n){return`matrix(${N(n.a)}, ${N(n.b)}, ${N(n.c)}, ${N(n.d)}, ${N(n.e)}, ${N(n.f)})`}static applyToPoint(n,t){return new b(n.a*t.x+n.c*t.y+n.e,n.b*t.x+n.d*t.y+n.f,t.z)}static applyToXY(n,t,r){return[n.a*t+n.c*r+n.e,n.b*t+n.d*r+n.f]}static applyToPoints(n,t){return t.map(r=>new b(n.a*r.x+n.c*r.y+n.e,n.b*r.x+n.d*r.y+n.f,r.z))}static applyToBounds(n,t){return new Q(n.e+t.minX,n.f+t.minY,t.width,t.height)}static From(n){return new Re(n.a,n.b,n.c,n.d,n.e,n.f)}static Cast(n){return n instanceof Re?n:Re.From(n)}};g(Re,"Scale",(n,t,r,s)=>{const o=new Re(n,0,0,t,0,0);return r===void 0?o:Re.Compose(Re.Translate(r,s),o,Re.Translate(-r,-s))});let oe=Re;function vM(e,n){return n===0?e:vM(n,e%n)}function xM(e){const n=e.toString().split(".")[1];if(!n)return 1;const t=Math.pow(10,n.length),r=parseInt(n,10);return t/vM(r,t)}class li{constructor(n){g(this,"isFilled",!1);g(this,"isClosed",!0);g(this,"isLabel",!1);g(this,"debugColor");g(this,"ignore");g(this,"_vertices");g(this,"_bounds");g(this,"_area");g(this,"_length");this.isFilled=n.isFilled,this.isClosed=n.isClosed,this.isLabel=n.isLabel??!1,this.debugColor=n.debugColor,this.ignore=n.ignore}hitTestPoint(n,t=0,r=!1){return this.isClosed&&(this.isFilled||r)&&sr(n,this.vertices)?!0:b.Dist2(n,this.nearestPoint(n))<=t*t}distanceToPoint(n,t=!1){return n.dist(this.nearestPoint(n))*(this.isClosed&&(this.isFilled||t)&&sr(n,this.vertices)?-1:1)}distanceToLineSegment(n,t){if(n.equals(t))return this.distanceToPoint(n);const{vertices:r}=this;let s,o=1/0,i,a,l;for(let c=0;cr.maxX+t||n.y>r.maxY+t)}get vertices(){return this._vertices||(this._vertices=this.getVertices()),this._vertices}getBounds(){return Q.FromPoints(this.vertices)}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:n}=this;let t=0;for(let r=0,s=n.length;r!t.isLabel).flatMap(t=>t.vertices)}nearestPoint(t){let r=1/0,s;const{children:o}=this;if(o.length===0)throw Error("no children");let i,a;for(const l of o)i=l.nearestPoint(t),a=b.Dist2(i,t),as.distanceToPoint(t,r||o>0)))}hitTestPoint(t,r,s){return!!this.children.filter(o=>!o.isLabel).find(o=>o.hitTestPoint(t,r,s))}hitTestLineSegment(t,r,s){return!!this.children.filter(o=>!o.isLabel).find(o=>o.hitTestLineSegment(t,r,s))}getArea(){return this.children[0].area}toSimpleSvgPath(){let t="";for(const s of this.children)t+=s.toSimpleSvgPath();const r=Q.FromPoints(this.vertices).corners;for(let s=0,o=r.length;sr.isLabel?t:t+r.length,0)}getSvgPathData(){return this.children.map((t,r)=>t.isLabel?"":t.getSvgPathData(r===0)).join(" ")}}function YK(e=!0){const[n,t]=P.useState(0),r=F();P.useEffect(()=>{if(!e)return;const s=()=>t(o=>o+1);return r.on("tick",s),()=>{r.off("tick",s)}},[r,e])}const XK=Lt(function({showStroke:n=!0,showVertices:t=!0,showClosestPointOnOutline:r=!0}){const s=F();YK(r);const o=s.getZoomLevel(),i=s.getRenderingShapes(),{inputs:{currentPagePoint:a}}=s;return d.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),h=s.getShapePageTransform(c),p=s.getPointInShapeSpace(c,a),f=u.nearestPoint(p),S=u.distanceToPoint(p,!0),m=Math.abs(S)*o,x=S<0,{vertices:y}=u;return d.jsxs("g",{transform:h.toCssString(),strokeLinecap:"round",strokeLinejoin:"round",children:[n&&d.jsx("g",{stroke:u.debugColor??"red",opacity:"1",strokeWidth:2/o,fill:"none",children:d.jsx(wM,{geometry:u})}),t&&y.map((v,w)=>d.jsx("circle",{cx:v.x,cy:v.y,r:2/o,fill:`hsl(${pl(w,[0,y.length-1],[120,200])}, 100%, 50%)`,stroke:"black",strokeWidth:1/o},`v${w}`)),r&&m<150&&d.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,opacity:1-m/150,stroke:x?"goldenrod":"dodgerblue",strokeWidth:2/o})]},l.id+"_outline")})})});function wM({geometry:e}){return e instanceof Wr?d.jsx(d.Fragment,{children:[...e.children,...e.ignoredChildren].map((n,t)=>d.jsx(wM,{geometry:n},t))}):d.jsx("path",{d:e.toSimpleSvgPath()})}function bM(e){return x9(e)}function PM(){const e=F(),n=wH("userIds",()=>bM(e.getCollaborators().map(t=>t.userId)).sort(),{isEqual:(t,r)=>{var s;return t.join(",")===((s=r.join)==null?void 0:s.call(r,","))}},[e]);return H(n)}function ug(e){const n=F();return H(`latestPresence:${e}`,()=>n.getCollaborators().find(r=>r.userId===e),[n,e])??null}const qK=Lt(function(){return PM().map(t=>d.jsx(ZK,{collaboratorId:t},t))}),ZK=Lt(function({collaboratorId:n}){const t=F(),r=ug(n),s=JK(t,r);if(!(r&&r.currentPageId===t.getCurrentPageId()))return null;switch(s){case"inactive":{const{followingUserId:o,highlightedUserIds:i}=t.getInstanceState();if(!(o===r.userId||i.includes(r.userId)))return null;break}case"idle":{const{highlightedUserIds:o}=t.getInstanceState();if(r.followingUserId===t.user.getId()&&!(r.chatMessage||o.includes(r.userId)))return null;break}}return d.jsx(QK,{latestPresence:r})}),QK=Lt(function({latestPresence:n}){const t=F(),{CollaboratorBrush:r,CollaboratorScribble:s,CollaboratorCursor:o,CollaboratorHint:i,CollaboratorShapeIndicator:a}=st(),l=t.getZoomLevel(),c=t.getViewportPageBounds(),{userId:u,chatMessage:h,brush:p,scribbles:f,selectedShapeIds:S,userName:m,cursor:x,color:y}=n,v=!(x.xc.maxX-12/l||x.y>c.maxY-16/l);return d.jsxs(d.Fragment,{children:[p&&r?d.jsx(r,{className:"tl-collaborator__brush",brush:p,color:y,opacity:.1},u+"_brush"):null,v&&o?d.jsx(o,{className:"tl-collaborator__cursor",point:x,color:y,zoom:l,name:m!=="New User"?m:null,chatMessage:h},u+"_cursor"):i?d.jsx(i,{className:"tl-collaborator__cursor-hint",point:x,color:y,zoom:l,viewport:c},u+"_cursor_hint"):null,s&&f.length?d.jsx(d.Fragment,{children:f.map(w=>d.jsx(s,{className:"tl-collaborator__scribble",scribble:w,color:y,zoom:l,opacity:w.color==="laser"?.5:.1},u+"_scribble_"+w.id))}):null,a&&S.map(w=>d.jsx(a,{className:"tl-collaborator__shape-indicator",shapeId:w,color:y,opacity:.5},u+"_"+w))]})});function FC(e,n){return n>e.options.collaboratorInactiveTimeoutMs?"inactive":n>e.options.collaboratorIdleTimeoutMs?"idle":"active"}function JK(e,n){const t=P.useRef((n==null?void 0:n.lastActivityTimestamp)??-1),[r,s]=P.useState(()=>FC(e,Date.now()-t.current));return P.useEffect(()=>{const o=e.timers.setInterval(()=>{s(FC(e,Date.now()-t.current))},e.options.collaboratorCheckIntervalMs);return()=>clearInterval(o)},[e]),n&&(t.current=n.lastActivityTimestamp),r}const CM=P.memo(function({id:n,shape:t,util:r,index:s,backgroundIndex:o,opacity:i,dprMultiple:a}){const l=F(),{ShapeErrorFallback:c}=st(),u=P.useRef(null),h=P.useRef(null),p=P.useRef({transform:"",clipPath:"none",width:0,height:0,x:0,y:0,isCulled:!1});Ko("set shape stuff",()=>{const m=l.getShape(n);if(!m)return;const x=p.current,y=l.getShapeClipPath(n)??"none";y!==x.clipPath&&(tn(u.current,"clip-path",y),tn(h.current,"clip-path",y),x.clipPath=y);const v=l.getShapePageTransform(n),w=oe.toCssString(v),C=l.getShapeGeometry(m).bounds;w!==x.transform&&(tn(u.current,"transform",w),tn(h.current,"transform",w),x.transform=w);const E=C.w%a,k=C.h%a,I=E===0?C.w:C.w+(a-E),_=k===0?C.h:C.h+(a-k);(I!==x.width||_!==x.height)&&(tn(u.current,"width",Math.max(I,a)+"px"),tn(u.current,"height",Math.max(_,a)+"px"),tn(h.current,"width",Math.max(I,a)+"px"),tn(h.current,"height",Math.max(_,a)+"px"),x.width=I,x.height=_)},[l]),Ko("set opacity and z-index",()=>{const m=u.current,x=h.current;tn(m,"opacity",i),tn(x,"opacity",i),tn(m,"z-index",s),tn(x,"z-index",o)},[i,s,o]),Ko("set display",()=>{if(!l.getShape(n))return;const y=l.getCulledShapes().has(n);y!==p.current.isCulled&&(tn(u.current,"display",y?"none":"block"),tn(h.current,"display",y?"none":"block"),p.current.isCulled=y)},[l]);const f=P.useCallback(m=>l.annotateError(m,{origin:"shape",willCrashApp:!1}),[l]);if(!t)return null;const S="fill"in t.props&&t.props.fill!=="none";return d.jsxs(d.Fragment,{children:[r.backgroundComponent&&d.jsx("div",{ref:h,className:"tl-shape tl-shape-background","data-shape-type":t.type,draggable:!1,children:d.jsx(Pu,{fallback:c,onError:f,children:d.jsx(tW,{shape:t,util:r})})}),d.jsx("div",{ref:u,className:"tl-shape","data-shape-type":t.type,"data-shape-is-filled":S,draggable:!1,children:d.jsx(Pu,{fallback:c,onError:f,children:d.jsx(eW,{shape:t,util:r})})})]})}),eW=P.memo(function({shape:n,util:t}){return lg("InnerShape:"+n.type,()=>t.component(t.editor.store.unsafeGetWithoutCapture(n.id)))},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta),tW=P.memo(function({shape:n,util:t}){return lg("InnerShape:"+n.type,()=>{var r;return(r=t.backgroundComponent)==null?void 0:r.call(t,t.editor.store.unsafeGetWithoutCapture(n.id))})},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta);function nW({className:e}){const n=F(),{Background:t,SvgDefs:r,ShapeIndicators:s}=st(),o=P.useRef(null),i=P.useRef(null),a=P.useRef(null),l=$t();GK(o),RH(),OH(),BK(o),NH(o);const c=P.useRef({lodDisableTextOutline:!1,allowTextOutline:!0});Ko("position layers",function(){const{x:v,y:w,z:C}=n.getCamera();if(c.current.allowTextOutline&&n.environment.isSafari&&(l.style.setProperty("--tl-text-outline","none"),c.current.allowTextOutline=!1),c.current.allowTextOutline&&C=1?pl(C,[1,8],[.125,.5],!0):pl(C,[.1,1],[-2,.125],!0),k=`scale(${N(C)}) translate(${N(v+E)}px,${N(w+E)}px)`;tn(i.current,"transform",k),tn(a.current,"transform",k)},[n,l]);const u=lM(),h=H("shapeSvgDefs",()=>{const y=new Map;for(const v of gt(n.shapeUtils)){if(!v)return;const w=v.getCanvasSvgDefs();for(const{key:C,component:E}of w)y.has(C)||y.set(C,d.jsx(E,{},C))}return[...y.values()]},[n]),p=H("debug_shapes",()=>xt.hideShapes.get(),[xt]),f=H("debug_svg",()=>xt.debugSvg.get(),[xt]),S=H("debug_geometry",()=>xt.debugGeometry.get(),[xt]),m=H("isEditingAnything",()=>n.getEditingShapeId()!==null,[n]),x=H("isSelectingAnything",()=>!!n.getSelectedShapeIds().length,[n]);return d.jsxs(d.Fragment,{children:[d.jsxs("div",{ref:o,draggable:!1,"data-iseditinganything":m,"data-isselectinganything":x,className:le("tl-canvas",e),"data-testid":"canvas",...u,children:[d.jsx("svg",{className:"tl-svg-context",children:d.jsxs("defs",{children:[h,d.jsx(mW,{}),d.jsx(yW,{}),r&&d.jsx(r,{})]})}),t&&d.jsx("div",{className:"tl-background__wrapper",children:d.jsx(t,{})}),d.jsx(sW,{}),d.jsxs("div",{ref:i,className:"tl-html-layer tl-shapes",draggable:!1,children:[d.jsx(wW,{}),d.jsx(xW,{}),p?null:f?d.jsx(hW,{}):d.jsx(fW,{})]}),d.jsx("div",{className:"tl-overlays",children:d.jsxs("div",{ref:a,className:"tl-html-layer",children:[S?d.jsx(XK,{}):null,d.jsx(cW,{}),d.jsx(iW,{}),d.jsx(oW,{}),d.jsx(aW,{}),s&&d.jsx(s,{}),d.jsx(gW,{}),d.jsx(lW,{}),d.jsx(vW,{}),d.jsx(qK,{})]})}),d.jsx(bW,{})]}),d.jsx(rW,{})]})}function rW(){const{InFrontOfTheCanvas:e}=st();return e?d.jsx(e,{}):null}function sW(){const e=F(),n=H("gridSize",()=>e.getDocumentSettings().gridSize,[e]),{x:t,y:r,z:s}=H("camera",()=>e.getCamera(),[e]),o=H("isGridMode",()=>e.getInstanceState().isGridMode,[e]),{Grid:i}=st();return i&&o?d.jsx(i,{x:t,y:r,z:s,size:n}):null}function oW(){const e=F(),n=H("scribbles",()=>e.getInstanceState().scribbles,[e]),t=H("zoomLevel",()=>e.getZoomLevel(),[e]),{Scribble:r}=st();return r&&n.length?n.map(s=>d.jsx(r,{className:"tl-user-scribble",scribble:s,zoom:t},s.id)):null}function iW(){const e=F(),n=H("brush",()=>e.getInstanceState().brush,[e]),{Brush:t}=st();return t&&n?d.jsx(t,{className:"tl-user-brush",brush:n}):null}function aW(){const e=F(),n=H("zoomBrush",()=>e.getInstanceState().zoomBrush,[e]),{ZoomBrush:t}=st();return t&&n?d.jsx(t,{className:"tl-user-brush tl-zoom-brush",brush:n}):null}function lW(){const e=F(),n=H("snapLines",()=>e.snaps.getIndicators(),[e]),t=H("zoomLevel",()=>e.getZoomLevel(),[e]),{SnapIndicator:r}=st();return r&&n.length>0?n.map(s=>d.jsx(r,{className:"tl-user-snapline",line:s,zoom:t},s.id)):null}function cW(){const e=F(),n=H("handles shapeIdWithHandles",()=>{const{isReadonly:t,isChangingStyle:r}=e.getInstanceState();if(t||r)return!1;const s=e.getOnlySelectedShape();return!s||!e.getShapeHandles(s)?!1:s.id},[e]);return n?d.jsx(uW,{shapeId:n}):null}function uW({shapeId:e}){const n=F(),{Handles:t}=st(),r=H("zoomLevel",()=>n.getZoomLevel(),[n]),s=H("coarse pointer",()=>n.getInstanceState().isCoarsePointer,[n]),o=H("handles transform",()=>n.getShapePageTransform(e),[n,e]),i=H("handles",()=>{const a=n.getShapeHandles(e);if(!a)return null;const l=(s?n.options.coarseHandleRadius:n.options.handleRadius)/r*2;return a.filter(c=>c.type!=="virtual"||!a.some(u=>u!==c&&u.type==="vertex"&&b.Dist(c,u)c.type==="vertex"?1:-1)},[n,r,s,e]);return!t||!i||!o?null:d.jsx(t,{children:d.jsx("g",{transform:oe.toCssString(o),children:i.map(a=>d.jsx(dW,{shapeId:e,handle:a,zoom:r,isCoarse:s},a.id))})})}function dW({shapeId:e,handle:n,zoom:t,isCoarse:r}){const s=UK(e,n.id),{Handle:o}=st();return o?d.jsx("g",{"aria-label":"handle",transform:`translate(${n.x}, ${n.y})`,...s,children:d.jsx(o,{shapeId:e,handle:n,zoom:t,isCoarse:r})}):null}function hW(){const e=F(),n=H("rendering shapes",()=>e.getRenderingShapes(),[e]),t=H("dpr multiple",()=>xM(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return n.map(r=>d.jsxs(P.Fragment,{children:[d.jsx(CM,{...r,dprMultiple:t}),d.jsx(SW,{id:r.id})]},r.id+"_fragment"))}function pW(){const e=F(),n=P.useRef(new Set);return Ko("reflow for culled shapes",()=>{const t=e.getCulledShapes();if(n.current.size===t.size&&[...t].every(s=>n.current.has(s)))return;n.current=t;const r=document.getElementsByClassName("tl-canvas");r.length!==0&&r[0].offsetHeight},[e]),null}function fW(){const e=F(),n=H("rendering shapes",()=>e.getRenderingShapes(),[e]),t=H("dpr multiple",()=>xM(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return d.jsxs(d.Fragment,{children:[n.map(r=>d.jsx(CM,{...r,dprMultiple:t},r.id+"_shape")),e.environment.isSafari&&d.jsx(pW,{})]})}function gW(){const e=F(),{ShapeIndicator:n}=st(),t=H("hinting shape ids",()=>R0(e.getHintingShapeIds()),[e]);return!t.length||!n?null:t.map(r=>d.jsx(n,{className:"tl-user-indicator__hint",shapeId:r},r+"_hinting"))}function mW(){return d.jsxs("g",{id:"cursor",children:[d.jsxs("g",{fill:"rgba(0,0,0,.2)",transform:"translate(-11,-11)",children:[d.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),d.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),d.jsxs("g",{fill:"white",transform:"translate(-12,-12)",children:[d.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),d.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),d.jsxs("g",{fill:"currentColor",transform:"translate(-12,-12)",children:[d.jsx("path",{d:"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z"}),d.jsx("path",{d:"m13 10.814v11.188l2.969-2.866.428-.139h4.768z"})]})]})}function yW(){return d.jsx("path",{id:"cursor_hint",fill:"currentColor",d:"M -2,-5 2,0 -2,5 Z"})}function SW({id:e}){const n=F(),[t,r]=P.useState(null),s=H("is in root",()=>{const o=n.getShape(e);return(o==null?void 0:o.parentId)===n.getCurrentPageId()},[n,e]);return P.useEffect(()=>{if(!s)return;let o=null;const i=oa("shape to svg",async()=>{const a=Math.random();o=a;const c=n.isShapeOfType(e,"frame")?0:10;let u=n.getShapePageBounds(e);if(!u)return;u=u.clone().expandBy(c);const h=await n.getSvgString([e],{padding:c,background:n.getInstanceState().exportBackground});if(o!==a||!h)return;const p=`data:image/svg+xml;utf8,${encodeURIComponent(h.svg)}`;r({src:p,bounds:u})});return()=>{o=null,i()}},[n,e,s]),!s||!t?null:d.jsx("img",{src:t.src,width:t.bounds.width,height:t.bounds.height,referrerPolicy:"no-referrer",style:{position:"absolute",top:0,left:0,transform:`translate(${t.bounds.x}px, ${t.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}})}function vW(){const e=F(),n=H("selection rotation",()=>e.getSelectionRotation(),[e]),t=H("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionForeground:r}=st();return!t||!r?null:d.jsx(r,{bounds:t,rotation:n})}function xW(){const e=F(),n=H("selection rotation",()=>e.getSelectionRotation(),[e]),t=H("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionBackground:r}=st();return!t||!r?null:d.jsx(r,{bounds:t,rotation:n})}function wW(){const{OnTheCanvas:e}=st();return e?d.jsx(e,{}):null}function bW(){const e=F(),n=H("camera state",()=>e.getCameraState(),[e]);return d.jsx("div",{className:le("tl-hit-test-blocker",{"tl-hit-test-blocker__hidden":n==="idle"})})}function PW({className:e,zoom:n,point:t,color:r,viewport:s,opacity:o=1}){const i=P.useRef(null);return jl(i,kt(t.x,s.minX+5/n,s.maxX-5/n),kt(t.y,s.minY+5/n,s.maxY-5/n),1/n,b.Angle(s.center,t)),d.jsxs("svg",{ref:i,className:le("tl-overlays__item",e),children:[d.jsx("use",{href:"#cursor_hint",color:r,strokeWidth:3,stroke:"var(--color-background)"}),d.jsx("use",{href:"#cursor_hint",color:r,opacity:o})]})}const zC=P.memo(function({className:n,zoom:t,point:r,color:s,name:o,chatMessage:i}){const a=P.useRef(null);return jl(a,r==null?void 0:r.x,r==null?void 0:r.y,1/t),r?d.jsxs("div",{ref:a,className:le("tl-overlays__item",n),children:[d.jsx("svg",{className:"tl-cursor",children:d.jsx("use",{href:"#cursor",color:s})}),i?d.jsxs(d.Fragment,{children:[o&&d.jsx("div",{className:"tl-nametag-title",style:{color:s},children:o}),d.jsx("div",{className:"tl-nametag-chat",style:{backgroundColor:s},children:i})]}):o&&d.jsx("div",{className:"tl-nametag",style:{backgroundColor:s},children:o})]}):null});function IM(){return P.useId().replace(/:/g,"_")}function CW({x:e,y:n,z:t,size:r}){const s=`grid_${IM()}`,o=F(),{gridSteps:i}=o.options;return d.jsxs("svg",{className:"tl-grid",version:"1.1",xmlns:"http://www.w3.org/2000/svg",children:[d.jsx("defs",{children:i.map(({min:a,mid:l,step:c},u)=>{const h=c*r*t,p=.5+e*t,f=.5+n*t,S=p>0?p%h:h+p%h,m=f>0?f%h:h+f%h,x=td.jsx("rect",{width:"100%",height:"100%",fill:`url(#${s}_${a})`},l))]})}function IW({handle:e,isCoarse:n,className:t,zoom:r}){const s=F(),o=(n?s.options.coarseHandleRadius:s.options.handleRadius)/r;if(e.type==="clone"){const a=3/r,l=`M0,${-a} A${a},${a} 0 0,1 0,${a}`,c=AH.indexOf(e.id);return d.jsxs("g",{className:le(`tl-handle tl-handle__${e.type}`,t),children:[d.jsx("circle",{className:"tl-handle__bg",r:o}),d.jsx("path",{className:"tl-handle__fg",d:l,transform:`rotate(${-90+90*c})`})]})}const i=(e.type==="create"&&n?3:4)/Math.max(r,.25);return d.jsxs("g",{className:le(`tl-handle tl-handle__${e.type}`,t),children:[d.jsx("circle",{className:"tl-handle__bg",r:o}),d.jsx("circle",{className:"tl-handle__fg",r:i})]})}const EW=({children:e})=>d.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}),_W=()=>{const{Spinner:e}=st();return d.jsx(pw,{children:e?d.jsx(e,{}):null})};function tw(e,n=!0){const t=e.length;if(t<2)return"";let r=e[0],s=e[1];if(t===2)return`M${ke(r)}L${ke(s)}`;let o="";for(let i=2,a=t-1;i3?"T":""}${o}L${ke(e[t-1])}`}function BC({scribble:e,zoom:n,color:t,opacity:r,className:s}){return e.points.length?d.jsx("svg",{className:s&&le("tl-overlays__item",s),children:d.jsx("path",{className:"tl-scribble",d:tw(e.points,!1),stroke:t??`var(--color-${e.color})`,fill:"none",strokeWidth:8/n,opacity:r??e.opacity})}):null}function EM({bounds:e,rotation:n}){const t=P.useRef(null);return jl(t,e.x,e.y,1,n),P.useLayoutEffect(()=>{const r=t.current;r&&(r.style.width=N(Math.max(1,e.width))+"px",r.style.height=N(Math.max(1,e.height))+"px")},[e.width,e.height]),d.jsx("div",{ref:t,className:"tl-selection__bg",draggable:!1})}function kW({bounds:e,rotation:n}){const t=F(),r=P.useRef(null),s=H("only selected shape",()=>t.getOnlySelectedShape(),[t]),o=s?t.getShapeUtil(s).expandSelectionOutlinePx(s):0;return jl(r,e==null?void 0:e.x,e==null?void 0:e.y,1,n,{x:-o,y:-o}),e=e.clone().expandBy(o).zeroFix(),d.jsx("svg",{ref:r,className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:d.jsx("rect",{className:le("tl-selection__fg__outline"),width:N(e.width),height:N(e.height)})})}const TW=()=>d.jsx("div",{className:"tl-shape-error-boundary"}),MW=({shape:e,util:n})=>lg("Indicator: "+e.type,()=>n.indicator(n.editor.store.unsafeGetWithoutCapture(e.id))),AW=({editor:e,id:n})=>{const t=H("shape for indicator",()=>e.store.get(n),[e,n]),{ShapeIndicatorErrorFallback:r}=st();return!t||t.isLocked?null:d.jsx(Pu,{fallback:r,onError:s=>e.annotateError(s,{origin:"react.shapeIndicator",willCrashApp:!1}),children:d.jsx(MW,{shape:t,util:e.getShapeUtil(t)},t.id)})},UC=P.memo(function({shapeId:n,className:t,color:r,hidden:s,opacity:o}){const i=F(),a=P.useRef(null);return Ko("indicator transform",()=>{const l=a.current;if(!l)return;const c=i.getShapePageTransform(n);c&&l.style.setProperty("transform",c.toCssString())},[i,n]),P.useLayoutEffect(()=>{const l=a.current;l&&l.style.setProperty("display",s?"none":"block")},[s]),d.jsx("svg",{ref:a,className:le("tl-overlays__item",t),children:d.jsx("g",{className:"tl-shape-indicator",stroke:r??"var(--color-selected)",opacity:o,children:d.jsx(AW,{editor:i,id:n})})})}),jW=()=>d.jsx("circle",{cx:4,cy:4,r:8,strokeWidth:"1",stroke:"red"}),_M=P.memo(function(){const n=F(),t=P.useRef(new Set),r=H("should display selected ids",()=>{const i=t.current,a=new Set;if(n.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle")&&!n.getInstanceState().isChangingStyle){const l=n.getSelectedShapeIds();for(const c of l)a.add(c);if(n.isInAny("select.idle","select.editing_shape")){const c=n.getInstanceState();if(c.isHoveringCanvas&&!c.isCoarsePointer){const u=n.getHoveredShapeId();u&&a.add(u)}}}if(i.size!==a.size)return t.current=a,a;for(const l of a)if(!i.has(l))return t.current=a,a;return i},[n]),s=H("rendering shapes",()=>n.getRenderingShapes(),[n]),{ShapeIndicator:o}=st();return o?s.map(({id:i})=>d.jsx(o,{shapeId:i,hidden:!r.has(i)},i+"_indicator")):null});function OW({points:e,zoom:n}){const t=2.5/n,r=e.reduce((p,f)=>Math.min(p,f.x),1/0),s=e.reduce((p,f)=>Math.max(p,f.x),-1/0),o=e.reduce((p,f)=>Math.min(p,f.y),1/0),i=e.reduce((p,f)=>Math.max(p,f.y),-1/0),a=e.some(p=>p.x===r&&p.y===o);let l,c,u,h;return a?(l=r,c=o,u=s,h=i):(l=r,c=i,u=s,h=o),d.jsxs("g",{className:"tl-snap-indicator",stroke:"lime",children:[d.jsx("line",{x1:l,y1:c,x2:u,y2:h}),e.map((p,f)=>d.jsx("g",{transform:`translate(${p.x},${p.y})`,children:d.jsx("path",{className:"tl-snap-point",d:`M ${-t},${-t} L ${t},${t} M ${-t},${t} L ${t},${-t}`})},f))]})}function DW({gaps:e,direction:n,zoom:t}){const r=3.5/t;let s=[-1/0,1/0],o=null;const i=n==="horizontal";for(const l of e){if(o=Lr(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=Lr(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 d.jsx("g",{className:"tl-snap-indicator",stroke:"cyan",children:e.map(({startEdge:l,endEdge:c},u)=>d.jsx(P.Fragment,{children:i?d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:l[0].x,y1:a-2*r,x2:l[1].x,y2:a+2*r}),d.jsx("line",{x1:c[0].x,y1:a-2*r,x2:c[1].x,y2:a+2*r}),d.jsx("line",{x1:l[0].x,y1:a,x2:c[0].x,y2:a}),d.jsx("line",{x1:(l[0].x+c[0].x)/2,y1:a-r,x2:(l[0].x+c[0].x)/2,y2:a+r})]}):d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:a-2*r,y1:l[0].y,x2:a+2*r,y2:l[1].y}),d.jsx("line",{x1:a-2*r,y1:c[0].y,x2:a+2*r,y2:c[1].y}),d.jsx("line",{x1:a,y1:l[0].y,x2:a,y2:c[0].y}),d.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 RW({className:e,line:n,zoom:t}){return d.jsx("svg",{className:le("tl-overlays__item",e),children:n.type==="points"?d.jsx(OW,{...n,zoom:t}):n.type==="gaps"?d.jsx(DW,{...n,zoom:t}):null})}function nw(){return d.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",children:d.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[d.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),d.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor",children:d.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}const LW=()=>null;function kM(e,n){const t=P.useRef(e);return n(e,t.current)?t.current:(t.current=e,e)}function Yc(e){return kM(e,P9)}const $W=(e,n)=>(e??(e=null),n??(n=null),e===n?!0:!e||!n?!1:eT(e,n));function dg(e){return kM(e,$W)}const TM=P.createContext(null);function NW({overrides:e={},children:n}){const t=dg(e),r=P.useMemo(()=>({Background:CH,SvgDefs:LW,Brush:ty,ZoomBrush:ty,CollaboratorBrush:ty,Cursor:zC,CollaboratorCursor:zC,CollaboratorHint:PW,CollaboratorShapeIndicator:UC,Grid:CW,Scribble:BC,SnapIndicator:RW,Handles:EW,Handle:IW,CollaboratorScribble:BC,ErrorFallback:AM,ShapeErrorFallback:TW,ShapeIndicatorErrorFallback:jW,Spinner:nw,SelectionBackground:EM,SelectionForeground:kW,ShapeIndicators:_M,ShapeIndicator:UC,OnTheCanvas:null,InFrontOfTheCanvas:null,Canvas:nW,LoadingScreen:_W,...t}),[t]);return d.jsx(TM.Provider,{value:r,children:n})}function st(){const e=P.useContext(TM);if(!e)throw new Error("useEditorComponents must be used inside of ");return e}const rw={openWindow:(e,n)=>window.open(e,n,"noopener noreferrer"),refreshPage:()=>window.location.reload(),hardReset:async()=>{var e;return await((e=window.__tldraw__hardReset)==null?void 0:e.call(window))}};function MM(){rw.hardReset()}function FW(){rw.refreshPage()}const zW="https://github.com/tldraw/tldraw/issues/new",AM=({error:e,editor:n})=>{const t=P.useRef(null),[r,s]=P.useState(!1),[o,i]=P.useState(!1),[a,l]=P.useState(!1);let c=null;try{c=st().Canvas??null}catch{}const u=e instanceof Error?e.message:String(e),h=e instanceof Error?e.stack:null,p=H("isDarkMode",()=>{try{if(n)return n.user.getIsDarkMode()}catch{}return null},[n]),[f,S]=P.useState(null);P.useLayoutEffect(()=>{var E;p!==null&&S(p);let w=(E=t.current)==null?void 0:E.parentElement,C=!1;for(;w;){if(w.classList.contains("tl-theme__dark")||w.classList.contains("tl-theme__light")){C=!0;break}w=w.parentElement}if(C){S(null);return}typeof window<"u"&&"matchMedia"in window&&S(window.matchMedia("(prefers-color-scheme: dark)").matches)},[p]),P.useEffect(()=>{if(o){const w=n==null?void 0:n.timers.setTimeout(()=>{i(!1)},2e3);return()=>clearTimeout(w)}},[o,n]);const m=()=>{const w=document.createElement("textarea");w.value=h??u,document.body.appendChild(w),w.select(),document.execCommand("copy"),w.remove(),i(!0)},x=()=>{FW()},y=async()=>{MM()},v=new URL(zW);return v.searchParams.set("title",u),v.searchParams.set("labels","bug"),v.searchParams.set("body",`Hey, I ran into an error while using tldraw: + */const VK=e=>{let n=e.parentElement;for(;n;){if(n===document.body)return document;const{overflowY:t}=window.getComputedStyle(n);if(n.scrollHeight>n.clientHeight&&(t==="auto"||t==="scroll"||t==="overlay"))return n;n=n.parentElement}return document},Re=class Re{constructor(n,t,r,s,o,i){g(this,"a",1);g(this,"b",0);g(this,"c",0);g(this,"d",1);g(this,"e",0);g(this,"f",0);this.a=n,this.b=t,this.c=r,this.d=s,this.e=o,this.f=i}equals(n){return this===n||this.a===n.a&&this.b===n.b&&this.c===n.c&&this.d===n.d&&this.e===n.e&&this.f===n.f}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this}multiply(n){const t=n,{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(n,t,r){return n===0?this:t===void 0?this.multiply(Re.Rotate(n)):this.translate(t,r).multiply(Re.Rotate(n)).translate(-t,-r)}translate(n,t){return this.multiply(Re.Translate(n,t))}scale(n,t){return this.multiply(Re.Scale(n,t))}invert(){const{a:n,b:t,c:r,d:s,e:o,f:i}=this,a=n*s-t*r;return this.a=s/a,this.b=t/-a,this.c=r/-a,this.d=n/a,this.e=(s*o-r*i)/-a,this.f=(t*o-n*i)/a,this}applyToPoint(n){return Re.applyToPoint(this,n)}applyToPoints(n){return Re.applyToPoints(this,n)}rotation(){return Re.Rotation(this)}point(){return Re.Point(this)}decomposed(){return Re.Decompose(this)}toCssString(){return Re.toCssString(this)}setTo(n){return Object.assign(this,n),this}decompose(){return Re.Decompose(this)}clone(){return new Re(this.a,this.b,this.c,this.d,this.e,this.f)}static Identity(){return new Re(1,0,0,1,0,0)}static Translate(n,t){return new Re(1,0,0,1,n,t)}static Rotate(n,t,r){if(n===0)return Re.Identity();const s=Math.cos(n),o=Math.sin(n),i=new Re(s,o,-o,s,0,0);return t===void 0?i:Re.Compose(Re.Translate(t,r),i,Re.Translate(-t,-r))}static Multiply(n,t){return{a:n.a*t.a+n.c*t.b,c:n.a*t.c+n.c*t.d,e:n.a*t.e+n.c*t.f+n.e,b:n.b*t.a+n.d*t.b,d:n.b*t.c+n.d*t.d,f:n.b*t.e+n.d*t.f+n.f}}static Inverse(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/-t,f:(n.b*n.e-n.a*n.f)/t}}static Absolute(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/t,f:(n.b*n.e-n.a*n.f)/-t}}static Compose(...n){const t=Re.Identity();for(let r=0,s=n.length;r0?-1:1)}else if(n.b!==0||n.d!==0){const r=(n.b*n.b+n.d*n.d)**.5;t=Ve+Math.acos(n.b/r)*(n.d>0?-1:1)}else t=0;return Pv(t)}static Decompose(n){let t,r,s;if(n.a!==0||n.c!==0){const o=(n.a*n.a+n.c*n.c)**.5;t=o,r=(n.a*n.d-n.b*n.c)/o,s=Math.acos(n.a/o)*(n.c>0?-1:1)}else if(n.b!==0||n.d!==0){const o=(n.b*n.b+n.d*n.d)**.5;t=(n.a*n.d-n.b*n.c)/o,r=o,s=Ve+Math.acos(n.b/o)*(n.d>0?-1:1)}else t=0,r=0,s=0;return{x:n.e,y:n.f,scaleX:t,scaleY:r,rotation:Pv(s)}}static Smooth(n,t=1e10){return n.a=Math.round(n.a*t)/t,n.b=Math.round(n.b*t)/t,n.c=Math.round(n.c*t)/t,n.d=Math.round(n.d*t)/t,n.e=Math.round(n.e*t)/t,n.f=Math.round(n.f*t)/t,n}static toCssString(n){return`matrix(${N(n.a)}, ${N(n.b)}, ${N(n.c)}, ${N(n.d)}, ${N(n.e)}, ${N(n.f)})`}static applyToPoint(n,t){return new b(n.a*t.x+n.c*t.y+n.e,n.b*t.x+n.d*t.y+n.f,t.z)}static applyToXY(n,t,r){return[n.a*t+n.c*r+n.e,n.b*t+n.d*r+n.f]}static applyToPoints(n,t){return t.map(r=>new b(n.a*r.x+n.c*r.y+n.e,n.b*r.x+n.d*r.y+n.f,r.z))}static applyToBounds(n,t){return new Q(n.e+t.minX,n.f+t.minY,t.width,t.height)}static From(n){return new Re(n.a,n.b,n.c,n.d,n.e,n.f)}static Cast(n){return n instanceof Re?n:Re.From(n)}};g(Re,"Scale",(n,t,r,s)=>{const o=new Re(n,0,0,t,0,0);return r===void 0?o:Re.Compose(Re.Translate(r,s),o,Re.Translate(-r,-s))});let oe=Re;function vM(e,n){return n===0?e:vM(n,e%n)}function xM(e){const n=e.toString().split(".")[1];if(!n)return 1;const t=Math.pow(10,n.length),r=parseInt(n,10);return t/vM(r,t)}class li{constructor(n){g(this,"isFilled",!1);g(this,"isClosed",!0);g(this,"isLabel",!1);g(this,"debugColor");g(this,"ignore");g(this,"_vertices");g(this,"_bounds");g(this,"_area");g(this,"_length");this.isFilled=n.isFilled,this.isClosed=n.isClosed,this.isLabel=n.isLabel??!1,this.debugColor=n.debugColor,this.ignore=n.ignore}hitTestPoint(n,t=0,r=!1){return this.isClosed&&(this.isFilled||r)&&sr(n,this.vertices)?!0:b.Dist2(n,this.nearestPoint(n))<=t*t}distanceToPoint(n,t=!1){return n.dist(this.nearestPoint(n))*(this.isClosed&&(this.isFilled||t)&&sr(n,this.vertices)?-1:1)}distanceToLineSegment(n,t){if(n.equals(t))return this.distanceToPoint(n);const{vertices:r}=this;let s,o=1/0,i,a,l;for(let c=0;cr.maxX+t||n.y>r.maxY+t)}get vertices(){return this._vertices||(this._vertices=this.getVertices()),this._vertices}getBounds(){return Q.FromPoints(this.vertices)}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:n}=this;let t=0;for(let r=0,s=n.length;r!t.isLabel).flatMap(t=>t.vertices)}nearestPoint(t){let r=1/0,s;const{children:o}=this;if(o.length===0)throw Error("no children");let i,a;for(const l of o)i=l.nearestPoint(t),a=b.Dist2(i,t),as.distanceToPoint(t,r||o>0)))}hitTestPoint(t,r,s){return!!this.children.filter(o=>!o.isLabel).find(o=>o.hitTestPoint(t,r,s))}hitTestLineSegment(t,r,s){return!!this.children.filter(o=>!o.isLabel).find(o=>o.hitTestLineSegment(t,r,s))}getArea(){return this.children[0].area}toSimpleSvgPath(){let t="";for(const s of this.children)t+=s.toSimpleSvgPath();const r=Q.FromPoints(this.vertices).corners;for(let s=0,o=r.length;sr.isLabel?t:t+r.length,0)}getSvgPathData(){return this.children.map((t,r)=>t.isLabel?"":t.getSvgPathData(r===0)).join(" ")}}function YK(e=!0){const[n,t]=P.useState(0),r=F();P.useEffect(()=>{if(!e)return;const s=()=>t(o=>o+1);return r.on("tick",s),()=>{r.off("tick",s)}},[r,e])}const XK=Lt(function({showStroke:n=!0,showVertices:t=!0,showClosestPointOnOutline:r=!0}){const s=F();YK(r);const o=s.getZoomLevel(),i=s.getRenderingShapes(),{inputs:{currentPagePoint:a}}=s;return d.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),h=s.getShapePageTransform(c),p=s.getPointInShapeSpace(c,a),f=u.nearestPoint(p),S=u.distanceToPoint(p,!0),y=Math.abs(S)*o,x=S<0,{vertices:m}=u;return d.jsxs("g",{transform:h.toCssString(),strokeLinecap:"round",strokeLinejoin:"round",children:[n&&d.jsx("g",{stroke:u.debugColor??"red",opacity:"1",strokeWidth:2/o,fill:"none",children:d.jsx(wM,{geometry:u})}),t&&m.map((v,w)=>d.jsx("circle",{cx:v.x,cy:v.y,r:2/o,fill:`hsl(${pl(w,[0,m.length-1],[120,200])}, 100%, 50%)`,stroke:"black",strokeWidth:1/o},`v${w}`)),r&&y<150&&d.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,opacity:1-y/150,stroke:x?"goldenrod":"dodgerblue",strokeWidth:2/o})]},l.id+"_outline")})})});function wM({geometry:e}){return e instanceof Wr?d.jsx(d.Fragment,{children:[...e.children,...e.ignoredChildren].map((n,t)=>d.jsx(wM,{geometry:n},t))}):d.jsx("path",{d:e.toSimpleSvgPath()})}function bM(e){return x9(e)}function PM(){const e=F(),n=wH("userIds",()=>bM(e.getCollaborators().map(t=>t.userId)).sort(),{isEqual:(t,r)=>{var s;return t.join(",")===((s=r.join)==null?void 0:s.call(r,","))}},[e]);return H(n)}function ug(e){const n=F();return H(`latestPresence:${e}`,()=>n.getCollaborators().find(r=>r.userId===e),[n,e])??null}const qK=Lt(function(){return PM().map(t=>d.jsx(ZK,{collaboratorId:t},t))}),ZK=Lt(function({collaboratorId:n}){const t=F(),r=ug(n),s=JK(t,r);if(!(r&&r.currentPageId===t.getCurrentPageId()))return null;switch(s){case"inactive":{const{followingUserId:o,highlightedUserIds:i}=t.getInstanceState();if(!(o===r.userId||i.includes(r.userId)))return null;break}case"idle":{const{highlightedUserIds:o}=t.getInstanceState();if(r.followingUserId===t.user.getId()&&!(r.chatMessage||o.includes(r.userId)))return null;break}}return d.jsx(QK,{latestPresence:r})}),QK=Lt(function({latestPresence:n}){const t=F(),{CollaboratorBrush:r,CollaboratorScribble:s,CollaboratorCursor:o,CollaboratorHint:i,CollaboratorShapeIndicator:a}=st(),l=t.getZoomLevel(),c=t.getViewportPageBounds(),{userId:u,chatMessage:h,brush:p,scribbles:f,selectedShapeIds:S,userName:y,cursor:x,color:m}=n,v=!(x.xc.maxX-12/l||x.y>c.maxY-16/l);return d.jsxs(d.Fragment,{children:[p&&r?d.jsx(r,{className:"tl-collaborator__brush",brush:p,color:m,opacity:.1},u+"_brush"):null,v&&o?d.jsx(o,{className:"tl-collaborator__cursor",point:x,color:m,zoom:l,name:y!=="New User"?y:null,chatMessage:h},u+"_cursor"):i?d.jsx(i,{className:"tl-collaborator__cursor-hint",point:x,color:m,zoom:l,viewport:c},u+"_cursor_hint"):null,s&&f.length?d.jsx(d.Fragment,{children:f.map(w=>d.jsx(s,{className:"tl-collaborator__scribble",scribble:w,color:m,zoom:l,opacity:w.color==="laser"?.5:.1},u+"_scribble_"+w.id))}):null,a&&S.map(w=>d.jsx(a,{className:"tl-collaborator__shape-indicator",shapeId:w,color:m,opacity:.5},u+"_"+w))]})});function FC(e,n){return n>e.options.collaboratorInactiveTimeoutMs?"inactive":n>e.options.collaboratorIdleTimeoutMs?"idle":"active"}function JK(e,n){const t=P.useRef((n==null?void 0:n.lastActivityTimestamp)??-1),[r,s]=P.useState(()=>FC(e,Date.now()-t.current));return P.useEffect(()=>{const o=e.timers.setInterval(()=>{s(FC(e,Date.now()-t.current))},e.options.collaboratorCheckIntervalMs);return()=>clearInterval(o)},[e]),n&&(t.current=n.lastActivityTimestamp),r}const CM=P.memo(function({id:n,shape:t,util:r,index:s,backgroundIndex:o,opacity:i,dprMultiple:a}){const l=F(),{ShapeErrorFallback:c}=st(),u=P.useRef(null),h=P.useRef(null),p=P.useRef({transform:"",clipPath:"none",width:0,height:0,x:0,y:0,isCulled:!1});Ko("set shape stuff",()=>{const y=l.getShape(n);if(!y)return;const x=p.current,m=l.getShapeClipPath(n)??"none";m!==x.clipPath&&(tn(u.current,"clip-path",m),tn(h.current,"clip-path",m),x.clipPath=m);const v=l.getShapePageTransform(n),w=oe.toCssString(v),C=l.getShapeGeometry(y).bounds;w!==x.transform&&(tn(u.current,"transform",w),tn(h.current,"transform",w),x.transform=w);const E=C.w%a,k=C.h%a,I=E===0?C.w:C.w+(a-E),_=k===0?C.h:C.h+(a-k);(I!==x.width||_!==x.height)&&(tn(u.current,"width",Math.max(I,a)+"px"),tn(u.current,"height",Math.max(_,a)+"px"),tn(h.current,"width",Math.max(I,a)+"px"),tn(h.current,"height",Math.max(_,a)+"px"),x.width=I,x.height=_)},[l]),Ko("set opacity and z-index",()=>{const y=u.current,x=h.current;tn(y,"opacity",i),tn(x,"opacity",i),tn(y,"z-index",s),tn(x,"z-index",o)},[i,s,o]),Ko("set display",()=>{if(!l.getShape(n))return;const m=l.getCulledShapes().has(n);m!==p.current.isCulled&&(tn(u.current,"display",m?"none":"block"),tn(h.current,"display",m?"none":"block"),p.current.isCulled=m)},[l]);const f=P.useCallback(y=>l.annotateError(y,{origin:"shape",willCrashApp:!1}),[l]);if(!t)return null;const S="fill"in t.props&&t.props.fill!=="none";return d.jsxs(d.Fragment,{children:[r.backgroundComponent&&d.jsx("div",{ref:h,className:"tl-shape tl-shape-background","data-shape-type":t.type,draggable:!1,children:d.jsx(Pu,{fallback:c,onError:f,children:d.jsx(tW,{shape:t,util:r})})}),d.jsx("div",{ref:u,className:"tl-shape","data-shape-type":t.type,"data-shape-is-filled":S,draggable:!1,children:d.jsx(Pu,{fallback:c,onError:f,children:d.jsx(eW,{shape:t,util:r})})})]})}),eW=P.memo(function({shape:n,util:t}){return lg("InnerShape:"+n.type,()=>t.component(t.editor.store.unsafeGetWithoutCapture(n.id)))},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta),tW=P.memo(function({shape:n,util:t}){return lg("InnerShape:"+n.type,()=>{var r;return(r=t.backgroundComponent)==null?void 0:r.call(t,t.editor.store.unsafeGetWithoutCapture(n.id))})},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta);function nW({className:e}){const n=F(),{Background:t,SvgDefs:r,ShapeIndicators:s}=st(),o=P.useRef(null),i=P.useRef(null),a=P.useRef(null),l=$t();GK(o),RH(),OH(),BK(o),NH(o);const c=P.useRef({lodDisableTextOutline:!1,allowTextOutline:!0});Ko("position layers",function(){const{x:v,y:w,z:C}=n.getCamera();if(c.current.allowTextOutline&&n.environment.isSafari&&(l.style.setProperty("--tl-text-outline","none"),c.current.allowTextOutline=!1),c.current.allowTextOutline&&C=1?pl(C,[1,8],[.125,.5],!0):pl(C,[.1,1],[-2,.125],!0),k=`scale(${N(C)}) translate(${N(v+E)}px,${N(w+E)}px)`;tn(i.current,"transform",k),tn(a.current,"transform",k)},[n,l]);const u=lM(),h=H("shapeSvgDefs",()=>{const m=new Map;for(const v of gt(n.shapeUtils)){if(!v)return;const w=v.getCanvasSvgDefs();for(const{key:C,component:E}of w)m.has(C)||m.set(C,d.jsx(E,{},C))}return[...m.values()]},[n]),p=H("debug_shapes",()=>xt.hideShapes.get(),[xt]),f=H("debug_svg",()=>xt.debugSvg.get(),[xt]),S=H("debug_geometry",()=>xt.debugGeometry.get(),[xt]),y=H("isEditingAnything",()=>n.getEditingShapeId()!==null,[n]),x=H("isSelectingAnything",()=>!!n.getSelectedShapeIds().length,[n]);return d.jsxs(d.Fragment,{children:[d.jsxs("div",{ref:o,draggable:!1,"data-iseditinganything":y,"data-isselectinganything":x,className:le("tl-canvas",e),"data-testid":"canvas",...u,children:[d.jsx("svg",{className:"tl-svg-context",children:d.jsxs("defs",{children:[h,d.jsx(mW,{}),d.jsx(yW,{}),r&&d.jsx(r,{})]})}),t&&d.jsx("div",{className:"tl-background__wrapper",children:d.jsx(t,{})}),d.jsx(sW,{}),d.jsxs("div",{ref:i,className:"tl-html-layer tl-shapes",draggable:!1,children:[d.jsx(wW,{}),d.jsx(xW,{}),p?null:f?d.jsx(hW,{}):d.jsx(fW,{})]}),d.jsx("div",{className:"tl-overlays",children:d.jsxs("div",{ref:a,className:"tl-html-layer",children:[S?d.jsx(XK,{}):null,d.jsx(cW,{}),d.jsx(iW,{}),d.jsx(oW,{}),d.jsx(aW,{}),s&&d.jsx(s,{}),d.jsx(gW,{}),d.jsx(lW,{}),d.jsx(vW,{}),d.jsx(qK,{})]})}),d.jsx(bW,{})]}),d.jsx(rW,{})]})}function rW(){const{InFrontOfTheCanvas:e}=st();return e?d.jsx(e,{}):null}function sW(){const e=F(),n=H("gridSize",()=>e.getDocumentSettings().gridSize,[e]),{x:t,y:r,z:s}=H("camera",()=>e.getCamera(),[e]),o=H("isGridMode",()=>e.getInstanceState().isGridMode,[e]),{Grid:i}=st();return i&&o?d.jsx(i,{x:t,y:r,z:s,size:n}):null}function oW(){const e=F(),n=H("scribbles",()=>e.getInstanceState().scribbles,[e]),t=H("zoomLevel",()=>e.getZoomLevel(),[e]),{Scribble:r}=st();return r&&n.length?n.map(s=>d.jsx(r,{className:"tl-user-scribble",scribble:s,zoom:t},s.id)):null}function iW(){const e=F(),n=H("brush",()=>e.getInstanceState().brush,[e]),{Brush:t}=st();return t&&n?d.jsx(t,{className:"tl-user-brush",brush:n}):null}function aW(){const e=F(),n=H("zoomBrush",()=>e.getInstanceState().zoomBrush,[e]),{ZoomBrush:t}=st();return t&&n?d.jsx(t,{className:"tl-user-brush tl-zoom-brush",brush:n}):null}function lW(){const e=F(),n=H("snapLines",()=>e.snaps.getIndicators(),[e]),t=H("zoomLevel",()=>e.getZoomLevel(),[e]),{SnapIndicator:r}=st();return r&&n.length>0?n.map(s=>d.jsx(r,{className:"tl-user-snapline",line:s,zoom:t},s.id)):null}function cW(){const e=F(),n=H("handles shapeIdWithHandles",()=>{const{isReadonly:t,isChangingStyle:r}=e.getInstanceState();if(t||r)return!1;const s=e.getOnlySelectedShape();return!s||!e.getShapeHandles(s)?!1:s.id},[e]);return n?d.jsx(uW,{shapeId:n}):null}function uW({shapeId:e}){const n=F(),{Handles:t}=st(),r=H("zoomLevel",()=>n.getZoomLevel(),[n]),s=H("coarse pointer",()=>n.getInstanceState().isCoarsePointer,[n]),o=H("handles transform",()=>n.getShapePageTransform(e),[n,e]),i=H("handles",()=>{const a=n.getShapeHandles(e);if(!a)return null;const l=(s?n.options.coarseHandleRadius:n.options.handleRadius)/r*2;return a.filter(c=>c.type!=="virtual"||!a.some(u=>u!==c&&u.type==="vertex"&&b.Dist(c,u)c.type==="vertex"?1:-1)},[n,r,s,e]);return!t||!i||!o?null:d.jsx(t,{children:d.jsx("g",{transform:oe.toCssString(o),children:i.map(a=>d.jsx(dW,{shapeId:e,handle:a,zoom:r,isCoarse:s},a.id))})})}function dW({shapeId:e,handle:n,zoom:t,isCoarse:r}){const s=UK(e,n.id),{Handle:o}=st();return o?d.jsx("g",{"aria-label":"handle",transform:`translate(${n.x}, ${n.y})`,...s,children:d.jsx(o,{shapeId:e,handle:n,zoom:t,isCoarse:r})}):null}function hW(){const e=F(),n=H("rendering shapes",()=>e.getRenderingShapes(),[e]),t=H("dpr multiple",()=>xM(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return n.map(r=>d.jsxs(P.Fragment,{children:[d.jsx(CM,{...r,dprMultiple:t}),d.jsx(SW,{id:r.id})]},r.id+"_fragment"))}function pW(){const e=F(),n=P.useRef(new Set);return Ko("reflow for culled shapes",()=>{const t=e.getCulledShapes();if(n.current.size===t.size&&[...t].every(s=>n.current.has(s)))return;n.current=t;const r=document.getElementsByClassName("tl-canvas");r.length!==0&&r[0].offsetHeight},[e]),null}function fW(){const e=F(),n=H("rendering shapes",()=>e.getRenderingShapes(),[e]),t=H("dpr multiple",()=>xM(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return d.jsxs(d.Fragment,{children:[n.map(r=>d.jsx(CM,{...r,dprMultiple:t},r.id+"_shape")),e.environment.isSafari&&d.jsx(pW,{})]})}function gW(){const e=F(),{ShapeIndicator:n}=st(),t=H("hinting shape ids",()=>R0(e.getHintingShapeIds()),[e]);return!t.length||!n?null:t.map(r=>d.jsx(n,{className:"tl-user-indicator__hint",shapeId:r},r+"_hinting"))}function mW(){return d.jsxs("g",{id:"cursor",children:[d.jsxs("g",{fill:"rgba(0,0,0,.2)",transform:"translate(-11,-11)",children:[d.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),d.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),d.jsxs("g",{fill:"white",transform:"translate(-12,-12)",children:[d.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),d.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),d.jsxs("g",{fill:"currentColor",transform:"translate(-12,-12)",children:[d.jsx("path",{d:"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z"}),d.jsx("path",{d:"m13 10.814v11.188l2.969-2.866.428-.139h4.768z"})]})]})}function yW(){return d.jsx("path",{id:"cursor_hint",fill:"currentColor",d:"M -2,-5 2,0 -2,5 Z"})}function SW({id:e}){const n=F(),[t,r]=P.useState(null),s=H("is in root",()=>{const o=n.getShape(e);return(o==null?void 0:o.parentId)===n.getCurrentPageId()},[n,e]);return P.useEffect(()=>{if(!s)return;let o=null;const i=oa("shape to svg",async()=>{const a=Math.random();o=a;const c=n.isShapeOfType(e,"frame")?0:10;let u=n.getShapePageBounds(e);if(!u)return;u=u.clone().expandBy(c);const h=await n.getSvgString([e],{padding:c,background:n.getInstanceState().exportBackground});if(o!==a||!h)return;const p=`data:image/svg+xml;utf8,${encodeURIComponent(h.svg)}`;r({src:p,bounds:u})});return()=>{o=null,i()}},[n,e,s]),!s||!t?null:d.jsx("img",{src:t.src,width:t.bounds.width,height:t.bounds.height,referrerPolicy:"no-referrer",style:{position:"absolute",top:0,left:0,transform:`translate(${t.bounds.x}px, ${t.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}})}function vW(){const e=F(),n=H("selection rotation",()=>e.getSelectionRotation(),[e]),t=H("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionForeground:r}=st();return!t||!r?null:d.jsx(r,{bounds:t,rotation:n})}function xW(){const e=F(),n=H("selection rotation",()=>e.getSelectionRotation(),[e]),t=H("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionBackground:r}=st();return!t||!r?null:d.jsx(r,{bounds:t,rotation:n})}function wW(){const{OnTheCanvas:e}=st();return e?d.jsx(e,{}):null}function bW(){const e=F(),n=H("camera state",()=>e.getCameraState(),[e]);return d.jsx("div",{className:le("tl-hit-test-blocker",{"tl-hit-test-blocker__hidden":n==="idle"})})}function PW({className:e,zoom:n,point:t,color:r,viewport:s,opacity:o=1}){const i=P.useRef(null);return jl(i,kt(t.x,s.minX+5/n,s.maxX-5/n),kt(t.y,s.minY+5/n,s.maxY-5/n),1/n,b.Angle(s.center,t)),d.jsxs("svg",{ref:i,className:le("tl-overlays__item",e),children:[d.jsx("use",{href:"#cursor_hint",color:r,strokeWidth:3,stroke:"var(--color-background)"}),d.jsx("use",{href:"#cursor_hint",color:r,opacity:o})]})}const zC=P.memo(function({className:n,zoom:t,point:r,color:s,name:o,chatMessage:i}){const a=P.useRef(null);return jl(a,r==null?void 0:r.x,r==null?void 0:r.y,1/t),r?d.jsxs("div",{ref:a,className:le("tl-overlays__item",n),children:[d.jsx("svg",{className:"tl-cursor",children:d.jsx("use",{href:"#cursor",color:s})}),i?d.jsxs(d.Fragment,{children:[o&&d.jsx("div",{className:"tl-nametag-title",style:{color:s},children:o}),d.jsx("div",{className:"tl-nametag-chat",style:{backgroundColor:s},children:i})]}):o&&d.jsx("div",{className:"tl-nametag",style:{backgroundColor:s},children:o})]}):null});function IM(){return P.useId().replace(/:/g,"_")}function CW({x:e,y:n,z:t,size:r}){const s=`grid_${IM()}`,o=F(),{gridSteps:i}=o.options;return d.jsxs("svg",{className:"tl-grid",version:"1.1",xmlns:"http://www.w3.org/2000/svg",children:[d.jsx("defs",{children:i.map(({min:a,mid:l,step:c},u)=>{const h=c*r*t,p=.5+e*t,f=.5+n*t,S=p>0?p%h:h+p%h,y=f>0?f%h:h+f%h,x=td.jsx("rect",{width:"100%",height:"100%",fill:`url(#${s}_${a})`},l))]})}function IW({handle:e,isCoarse:n,className:t,zoom:r}){const s=F(),o=(n?s.options.coarseHandleRadius:s.options.handleRadius)/r;if(e.type==="clone"){const a=3/r,l=`M0,${-a} A${a},${a} 0 0,1 0,${a}`,c=AH.indexOf(e.id);return d.jsxs("g",{className:le(`tl-handle tl-handle__${e.type}`,t),children:[d.jsx("circle",{className:"tl-handle__bg",r:o}),d.jsx("path",{className:"tl-handle__fg",d:l,transform:`rotate(${-90+90*c})`})]})}const i=(e.type==="create"&&n?3:4)/Math.max(r,.25);return d.jsxs("g",{className:le(`tl-handle tl-handle__${e.type}`,t),children:[d.jsx("circle",{className:"tl-handle__bg",r:o}),d.jsx("circle",{className:"tl-handle__fg",r:i})]})}const EW=({children:e})=>d.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}),_W=()=>{const{Spinner:e}=st();return d.jsx(pw,{children:e?d.jsx(e,{}):null})};function tw(e,n=!0){const t=e.length;if(t<2)return"";let r=e[0],s=e[1];if(t===2)return`M${ke(r)}L${ke(s)}`;let o="";for(let i=2,a=t-1;i3?"T":""}${o}L${ke(e[t-1])}`}function BC({scribble:e,zoom:n,color:t,opacity:r,className:s}){return e.points.length?d.jsx("svg",{className:s&&le("tl-overlays__item",s),children:d.jsx("path",{className:"tl-scribble",d:tw(e.points,!1),stroke:t??`var(--color-${e.color})`,fill:"none",strokeWidth:8/n,opacity:r??e.opacity})}):null}function EM({bounds:e,rotation:n}){const t=P.useRef(null);return jl(t,e.x,e.y,1,n),P.useLayoutEffect(()=>{const r=t.current;r&&(r.style.width=N(Math.max(1,e.width))+"px",r.style.height=N(Math.max(1,e.height))+"px")},[e.width,e.height]),d.jsx("div",{ref:t,className:"tl-selection__bg",draggable:!1})}function kW({bounds:e,rotation:n}){const t=F(),r=P.useRef(null),s=H("only selected shape",()=>t.getOnlySelectedShape(),[t]),o=s?t.getShapeUtil(s).expandSelectionOutlinePx(s):0;return jl(r,e==null?void 0:e.x,e==null?void 0:e.y,1,n,{x:-o,y:-o}),e=e.clone().expandBy(o).zeroFix(),d.jsx("svg",{ref:r,className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:d.jsx("rect",{className:le("tl-selection__fg__outline"),width:N(e.width),height:N(e.height)})})}const TW=()=>d.jsx("div",{className:"tl-shape-error-boundary"}),MW=({shape:e,util:n})=>lg("Indicator: "+e.type,()=>n.indicator(n.editor.store.unsafeGetWithoutCapture(e.id))),AW=({editor:e,id:n})=>{const t=H("shape for indicator",()=>e.store.get(n),[e,n]),{ShapeIndicatorErrorFallback:r}=st();return!t||t.isLocked?null:d.jsx(Pu,{fallback:r,onError:s=>e.annotateError(s,{origin:"react.shapeIndicator",willCrashApp:!1}),children:d.jsx(MW,{shape:t,util:e.getShapeUtil(t)},t.id)})},UC=P.memo(function({shapeId:n,className:t,color:r,hidden:s,opacity:o}){const i=F(),a=P.useRef(null);return Ko("indicator transform",()=>{const l=a.current;if(!l)return;const c=i.getShapePageTransform(n);c&&l.style.setProperty("transform",c.toCssString())},[i,n]),P.useLayoutEffect(()=>{const l=a.current;l&&l.style.setProperty("display",s?"none":"block")},[s]),d.jsx("svg",{ref:a,className:le("tl-overlays__item",t),children:d.jsx("g",{className:"tl-shape-indicator",stroke:r??"var(--color-selected)",opacity:o,children:d.jsx(AW,{editor:i,id:n})})})}),jW=()=>d.jsx("circle",{cx:4,cy:4,r:8,strokeWidth:"1",stroke:"red"}),_M=P.memo(function(){const n=F(),t=P.useRef(new Set),r=H("should display selected ids",()=>{const i=t.current,a=new Set;if(n.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle")&&!n.getInstanceState().isChangingStyle){const l=n.getSelectedShapeIds();for(const c of l)a.add(c);if(n.isInAny("select.idle","select.editing_shape")){const c=n.getInstanceState();if(c.isHoveringCanvas&&!c.isCoarsePointer){const u=n.getHoveredShapeId();u&&a.add(u)}}}if(i.size!==a.size)return t.current=a,a;for(const l of a)if(!i.has(l))return t.current=a,a;return i},[n]),s=H("rendering shapes",()=>n.getRenderingShapes(),[n]),{ShapeIndicator:o}=st();return o?s.map(({id:i})=>d.jsx(o,{shapeId:i,hidden:!r.has(i)},i+"_indicator")):null});function OW({points:e,zoom:n}){const t=2.5/n,r=e.reduce((p,f)=>Math.min(p,f.x),1/0),s=e.reduce((p,f)=>Math.max(p,f.x),-1/0),o=e.reduce((p,f)=>Math.min(p,f.y),1/0),i=e.reduce((p,f)=>Math.max(p,f.y),-1/0),a=e.some(p=>p.x===r&&p.y===o);let l,c,u,h;return a?(l=r,c=o,u=s,h=i):(l=r,c=i,u=s,h=o),d.jsxs("g",{className:"tl-snap-indicator",stroke:"lime",children:[d.jsx("line",{x1:l,y1:c,x2:u,y2:h}),e.map((p,f)=>d.jsx("g",{transform:`translate(${p.x},${p.y})`,children:d.jsx("path",{className:"tl-snap-point",d:`M ${-t},${-t} L ${t},${t} M ${-t},${t} L ${t},${-t}`})},f))]})}function DW({gaps:e,direction:n,zoom:t}){const r=3.5/t;let s=[-1/0,1/0],o=null;const i=n==="horizontal";for(const l of e){if(o=Lr(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=Lr(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 d.jsx("g",{className:"tl-snap-indicator",stroke:"cyan",children:e.map(({startEdge:l,endEdge:c},u)=>d.jsx(P.Fragment,{children:i?d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:l[0].x,y1:a-2*r,x2:l[1].x,y2:a+2*r}),d.jsx("line",{x1:c[0].x,y1:a-2*r,x2:c[1].x,y2:a+2*r}),d.jsx("line",{x1:l[0].x,y1:a,x2:c[0].x,y2:a}),d.jsx("line",{x1:(l[0].x+c[0].x)/2,y1:a-r,x2:(l[0].x+c[0].x)/2,y2:a+r})]}):d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:a-2*r,y1:l[0].y,x2:a+2*r,y2:l[1].y}),d.jsx("line",{x1:a-2*r,y1:c[0].y,x2:a+2*r,y2:c[1].y}),d.jsx("line",{x1:a,y1:l[0].y,x2:a,y2:c[0].y}),d.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 RW({className:e,line:n,zoom:t}){return d.jsx("svg",{className:le("tl-overlays__item",e),children:n.type==="points"?d.jsx(OW,{...n,zoom:t}):n.type==="gaps"?d.jsx(DW,{...n,zoom:t}):null})}function nw(){return d.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",children:d.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[d.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),d.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor",children:d.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}const LW=()=>null;function kM(e,n){const t=P.useRef(e);return n(e,t.current)?t.current:(t.current=e,e)}function Yc(e){return kM(e,P9)}const $W=(e,n)=>(e??(e=null),n??(n=null),e===n?!0:!e||!n?!1:eT(e,n));function dg(e){return kM(e,$W)}const TM=P.createContext(null);function NW({overrides:e={},children:n}){const t=dg(e),r=P.useMemo(()=>({Background:CH,SvgDefs:LW,Brush:ty,ZoomBrush:ty,CollaboratorBrush:ty,Cursor:zC,CollaboratorCursor:zC,CollaboratorHint:PW,CollaboratorShapeIndicator:UC,Grid:CW,Scribble:BC,SnapIndicator:RW,Handles:EW,Handle:IW,CollaboratorScribble:BC,ErrorFallback:AM,ShapeErrorFallback:TW,ShapeIndicatorErrorFallback:jW,Spinner:nw,SelectionBackground:EM,SelectionForeground:kW,ShapeIndicators:_M,ShapeIndicator:UC,OnTheCanvas:null,InFrontOfTheCanvas:null,Canvas:nW,LoadingScreen:_W,...t}),[t]);return d.jsx(TM.Provider,{value:r,children:n})}function st(){const e=P.useContext(TM);if(!e)throw new Error("useEditorComponents must be used inside of ");return e}const rw={openWindow:(e,n)=>window.open(e,n,"noopener noreferrer"),refreshPage:()=>window.location.reload(),hardReset:async()=>{var e;return await((e=window.__tldraw__hardReset)==null?void 0:e.call(window))}};function MM(){rw.hardReset()}function FW(){rw.refreshPage()}const zW="https://github.com/tldraw/tldraw/issues/new",AM=({error:e,editor:n})=>{const t=P.useRef(null),[r,s]=P.useState(!1),[o,i]=P.useState(!1),[a,l]=P.useState(!1);let c=null;try{c=st().Canvas??null}catch{}const u=e instanceof Error?e.message:String(e),h=e instanceof Error?e.stack:null,p=H("isDarkMode",()=>{try{if(n)return n.user.getIsDarkMode()}catch{}return null},[n]),[f,S]=P.useState(null);P.useLayoutEffect(()=>{var E;p!==null&&S(p);let w=(E=t.current)==null?void 0:E.parentElement,C=!1;for(;w;){if(w.classList.contains("tl-theme__dark")||w.classList.contains("tl-theme__light")){C=!0;break}w=w.parentElement}if(C){S(null);return}typeof window<"u"&&"matchMedia"in window&&S(window.matchMedia("(prefers-color-scheme: dark)").matches)},[p]),P.useEffect(()=>{if(o){const w=n==null?void 0:n.timers.setTimeout(()=>{i(!1)},2e3);return()=>clearTimeout(w)}},[o,n]);const y=()=>{const w=document.createElement("textarea");w.value=h??u,document.body.appendChild(w),w.select(),document.execCommand("copy"),w.remove(),i(!0)},x=()=>{FW()},m=async()=>{MM()},v=new URL(zW);return v.searchParams.set("title",u),v.searchParams.set("labels","bug"),v.searchParams.set("body",`Hey, I ran into an error while using tldraw: \`\`\`js ${h??u} \`\`\` -My browser: ${navigator.userAgent}`),d.jsxs("div",{ref:t,className:le("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[d.jsx("div",{className:"tl-error-boundary__overlay"}),n&&d.jsx(sM,{onError:Su,fallback:()=>null,children:d.jsx(cg.Provider,{value:n,children:d.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:c?d.jsx(c,{}):null})})}),d.jsx("div",{className:le("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Are you sure?"}),d.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>l(!1),children:"Cancel"}),d.jsx("button",{className:"tl-error-boundary__reset",onClick:y,children:"Reset data"})]})]}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Something's gone wrong."}),d.jsxs("p",{children:["Sorry, we encountered an error. Please refresh the page to continue. If you keep seeing this error, you can ",d.jsx("a",{href:v.toString(),children:"create a GitHub issue"})," or"," ",d.jsx("a",{href:"https://discord.gg/Cq6cPsTfNy",children:"ask for help on Discord"}),"."]}),r&&d.jsxs(d.Fragment,{children:["Message:",d.jsx("h4",{children:d.jsx("code",{children:u})}),"Stack trace:",d.jsxs("div",{className:"tl-error-boundary__content__error",children:[d.jsx("pre",{children:d.jsx("code",{children:h??u})}),d.jsx("button",{onClick:m,children:o?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>s(!r),children:r?"Hide details":"Show details"}),d.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[d.jsx("button",{className:"tl-error-boundary__reset",onClick:()=>l(!0),children:"Reset data"}),d.jsx("button",{className:"tl-error-boundary__refresh",onClick:x,children:"Refresh Page"})]})]})]})})]})};function ct(){return Ku()}const jM="TLDRAW_USER_DATA_v3",OM=ve({id:he,name:he.nullable().optional(),locale:he.nullable().optional(),color:he.nullable().optional(),colorScheme:ig("light","dark","system").optional(),animationSpeed:de.nullable().optional(),edgeScrollSpeed:de.nullable().optional(),isSnapMode:ye.nullable().optional(),isWrapMode:ye.nullable().optional(),isDynamicSizeMode:ye.nullable().optional(),isPasteAtCursorMode:ye.nullable().optional()}),Rs={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5,AddDynamicSizeMode:6,AllowSystemColorScheme:7,AddPasteAtCursor:8},sw=Math.max(...Object.values(Rs));function BW(e){e.version{const n=e.data;(n==null?void 0:n.type)===NM&&(n==null?void 0:n.origin)!==$M()&&hg.set(RM(n.data))});let oy=null;function $M(){return oy===null&&(oy=ct()),oy}const NM="tldraw-user-preferences-change";function GW(){el==null||el.postMessage({type:NM,origin:$M(),data:{user:FM(),version:sw}})}function FM(){let e=hg.get();return e||(e=HW(),LM(e)),e}const VW=G("defaultLocalStorageUserPrefs",()=>FM());function zM(e={}){return{userPreferences:e.userPreferences??VW,setUserPreferences:e.setUserPreferences??LM}}var BM={exports:{}};(function(e){var n=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,h,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,h||l,p),S=t?t+c:c;return l._events[S]?l._events[S].fn?l._events[S]=[l._events[S],f]:l._events[S].push(f):(l._events[S]=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,h;if(this._eventsCount===0)return c;for(h in u=this._events)n.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,S=new Array(f);p";ys&&(ys[tl]=pf,qW()?z0(tl,pf):aT(tl));ys==null||ys.addEventListener("beforeunload",()=>{z0(tl,pf)});const UM={Initial:0},pg=Math.max(...Object.values(UM));function ZW(e){e.version{const t=e.get(mn);if(!t)return null;const r=[...n.get()];return{version:pg,currentPageId:t.currentPageId,exportBackground:t.exportBackground,isFocusMode:t.isFocusMode,isDebugMode:t.isDebugMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,pageStates:r.map(s=>{const o=e.get(zr.createId(s)),i=e.get(us.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}})}})}function WM(e,n){const t=QW(n);if(!t)return;const r=e.schema.types.instance.create({id:mn,...MT(e.get(mn)),currentPageId:t.currentPageId,isDebugMode:t.isDebugMode,isFocusMode:t.isFocusMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,exportBackground:t.exportBackground}),s=e.allRecords().filter(o=>o.typeName==="instance_page_state"||o.typeName==="camera");e.atomic(()=>{e.remove(s.map(o=>o.id));for(const o of t.pageStates)e.put([us.create({id:us.createId(o.pageId),x:o.camera.x,y:o.camera.y,z:o.camera.z}),zr.create({id:zr.createId(o.pageId),pageId:o.pageId,selectedShapeIds:o.selectedShapeIds,focusedGroupId:o.focusedGroupId})]);e.put([r]),e.ensureStoreIsUsable()})}function JW(e){var s;const n=[];for(const o of Object.values(e))(s=o.typeName)!=null&&s.match(/^(instance.*|pointer|camera)$/)&&n.push(o);const t=n.filter(o=>o.typeName==="instance"&&o.id!==mn)[0];if(!t)return null;const r={version:pg,currentPageId:t.currentPageId,exportBackground:!!t.exportBackground,isFocusMode:!!t.isFocusMode,isDebugMode:!!t.isDebugMode,isToolLocked:!!t.isToolLocked,isGridMode:!1,pageStates:n.filter(o=>o.typeName==="instance_page_state"&&o.instanceId===t.id).map(o=>{const i=e[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 HM.validate(r),r}catch{return null}}function GM(e,n){let t={};if("store"in n){const s=e.schema.migrateStoreSnapshot(n);if(s.type!=="success")throw new Error("Failed to migrate store snapshot: "+s.reason);t.document={schema:e.schema.serialize(),store:Wc(s.value,(o,{typeName:i})=>e.scopedTypes.document.has(i))}}else t=n;const r=MT(e.get(mn));e.atomic(()=>{t.document&&e.loadStoreSnapshot(t.document),r&&e.update(mn,s=>({...s,...r})),t.session&&WM(e,t.session)})}const eG=new eo;function tG(e){const t=eG.get(e,KM).get();if(!t)throw new Error("Session state is not ready yet");return{document:e.getStoreSnapshot(),session:t}}function VM(e){const n=[],t=new Set;for(const r of e){if(t.has(r.type))throw new Error(`Binding type "${r.type}" is defined more than once`);n.push(r),t.add(r.type)}return n}function bs({children:e,className:n="",...t}){return d.jsx("svg",{...t,className:le("tl-svg-container",n),children:e})}function ow(e,n,t,r){const s=e.x-t.x,o=e.y-t.y,i=r.x-t.x,a=r.y-t.y,l=n.x-e.x,c=n.y-e.y,u=i*o-a*s,h=l*o-c*s,p=a*l-i*c;if(u===0||h===0||p===0)return null;if(p!==0){const f=u/p,S=h/p;if(0<=f&&f<=1&&0<=S&&S<=1)return b.AddXY(e,f*l,f*c)}return null}function Zu(e,n,t,r){const s=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),o=2*((n.x-e.x)*(e.x-t.x)+(n.y-e.y)*(e.y-t.y)),i=t.x*t.x+t.y*t.y+e.x*e.x+e.y*e.y-2*(t.x*e.x+t.y*e.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 h=[];return 0<=c&&c<=1&&h.push(b.Lrp(e,n,c)),0<=u&&u<=1&&h.push(b.Lrp(e,n,u)),h.length===0?null:h}function nG(e,n,t){const r=[];let s;for(let o=0,i=t.length-1;o(n.y-e.y)*(t.x-e.x)}function aw(e,n,t,r){return Yd(e,t,r)!==Yd(n,t,r)&&Yd(e,n,t)!==Yd(e,n,r)}function KC(e,n){const t=new Map;let r,s,o,i;for(let a=0,l=e.length;ab.Angle(n,t)-b.Angle(n,r))}function YM(e,n){let t,r,s,o;for(let i=0,a=e.length;iMath.max(r.x,s.x))return r.x>s.x?r:s;const c=r.y+o.y*a;return cMath.max(r.y,s.y)?r.y>s.y?r:s:new b(l,c)}hitTestLineSegment(t,r,s=0){return aw(t,r,this.start,this.end)||this.distanceToLineSegment(t,r)<=s}getSvgPathData(t=!0){const{start:r,end:s}=this;return`${t?`M${r.toFixed()}`:""} L${s.toFixed()}`}}class ia extends li{constructor(t){super({isClosed:!1,isFilled:!1,...t});g(this,"points");g(this,"_segments");const{points:r}=t;this.points=r}get segments(){if(!this._segments){this._segments=[];const{vertices:t}=this;for(let r=0,s=t.length-1;rt+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;lo===0?`M ${s.x} ${s.y}`:`${r} L ${s.x} ${s.y}`,"")}}class at extends ia{constructor(n){super({...n}),this.isClosed=!0}}class no extends at{constructor(t){const{x:r=0,y:s=0,width:o,height:i}=t;super({...t,points:[new b(r,s),new b(r+o,s),new b(r+o,s+i),new b(r,s+i)]});g(this,"x");g(this,"y");g(this,"w");g(this,"h");this.x=r,this.y=s,this.w=o,this.h=i}getBounds(){return new Q(this.x,this.y,this.w,this.h)}getSvgPathData(){const{x:t,y:r,w:s,h:o}=this;return`M${t},${r} h${s} v${o} h-${s}z`}}class Ir{constructor(n){g(this,"canSnap",()=>!0);g(this,"canScroll",()=>!1);g(this,"canEdit",()=>!1);g(this,"canResize",()=>!0);g(this,"canEditInReadOnly",()=>!1);g(this,"canCrop",()=>!1);g(this,"canBeLaidOut",()=>!0);g(this,"hideResizeHandles",()=>!1);g(this,"hideRotateHandle",()=>!1);g(this,"hideSelectionBoundsBg",()=>!1);g(this,"hideSelectionBoundsFg",()=>!1);g(this,"isAspectRatioLocked",()=>!1);g(this,"onBeforeCreate");g(this,"onBeforeUpdate");g(this,"onDragShapesOver");g(this,"onDragShapesOut");g(this,"onDropShapesOver");g(this,"onResizeStart");g(this,"onResize");g(this,"onResizeEnd");g(this,"onTranslateStart");g(this,"onTranslate");g(this,"onTranslateEnd");g(this,"onHandleDrag");g(this,"onRotateStart");g(this,"onRotate");g(this,"onRotateEnd");g(this,"onBindingChange");g(this,"onChildrenChange");g(this,"onDoubleClickHandle");g(this,"onDoubleClickEdge");g(this,"onDoubleClick");g(this,"onClick");g(this,"onEditEnd");this.editor=n}canBind(n){return!0}providesBackgroundForChildren(n){return!1}canReceiveNewChildrenOfType(n,t){return!1}canDropShapes(n,t){return!1}expandSelectionOutlinePx(n){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(n){return{}}getHandleSnapGeometry(n){return{}}}g(Ir,"props"),g(Ir,"migrations"),g(Ir,"type");function iG(e,n,t={}){const{closed:r=!1,snap:s=1,start:o="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,u=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(o==="outset"?(e+=c/2,f+=c/2):o==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),u=Math.floor(e/c/(2*h)),u-=u%s,u<3&&l==="dashed"?e/n<5?(c=e,u=1,p=0):(c=e*.333,p=e*.333):(u=Math.max(u,3),c=e/u/(2*h),r?(f=c/2,p=(e-u*c)/u):p=(e-u*c)/Math.max(1,u-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}function WC({bounds:e,className:n}){const t=F(),r=H("zoom level",()=>t.getZoomLevel(),[t]);return d.jsx("g",{className:n,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:e.sides.map((s,o)=>{const{strokeDasharray:i,strokeDashoffset:a}=iG(s[0].dist(s[1]),1/r,{style:"dashed",lengthRatio:4});return d.jsx("line",{x1:s[0].x,y1:s[0].y,x2:s[1].x,y2:s[1].y,strokeDasharray:i,strokeDashoffset:a},o)})})}class Bh extends Ir{constructor(){super(...arguments);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"canBind",()=>!1);g(this,"onChildrenChange",t=>{const r=this.editor.getSortedChildIdsForParent(t.id);if(r.length===0){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([t.id]);return}else if(r.length===1){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(r,t.parentId),this.editor.deleteShapes([t.id]);return}})}getDefaultProps(){return{}}getGeometry(t){const r=this.editor.getSortedChildIdsForParent(t.id);return r.length===0?new no({width:1,height:1,isFilled:!1}):new Wr({children:r.map(s=>{const o=this.editor.getShape(s),i=this.editor.getShapeGeometry(s),a=this.editor.getShapeLocalTransform(o).applyToPoints(i.vertices);return i.isClosed?new at({points:a,isFilled:!0}):new ia({points:a})})})}component(t){const r=this.editor.getErasingShapeIds().includes(t.id),{hintingShapeIds:s}=this.editor.getCurrentPageState(),o=s.length>0&&s.some(l=>l!==t.id&&this.editor.isShapeOfType(this.editor.getShape(l),"group")),i=this.editor.getCurrentPageState().focusedGroupId!==t.id;if(!r&&(i||o))return null;const a=this.editor.getShapeGeometry(t).bounds;return d.jsx(bs,{id:t.id,children:d.jsx(WC,{className:"tl-group",bounds:a})})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds;return d.jsx(WC,{className:"",bounds:r})}}g(Bh,"type","group"),g(Bh,"props",UT),g(Bh,"migrations",HT);const XM=[Bh],aG=new Set(XM.map(e=>e.type));function qM(e){const n=[...XM],t=new Set;for(const r of e){if(aG.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`);n.push(r),t.add(r.type)}return n}const lG={maxShapesPerPage:4e3,maxPages:40,animationMediumMs:320,followChaseViewportSnap:2,doubleClickDurationMs:450,multiClickDurationMs:200,coarseDragDistanceSquared:36,dragDistanceSquared:16,defaultSvgPadding:32,cameraSlideFriction:.09,maxPointsPerDrawShape:500,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};function GC(e,n){if(!n)return!1;switch(e.type){case"mixed":return n.type==="mixed";case"shared":return n.type==="shared"&&e.value===n.value;default:throw cn(e)}}class cG{constructor(n){g(this,"map");this.map=new Map(n)}get(n){return this.map.get(n)}getAsKnownValue(n){const t=this.get(n);if(t&&t.type!=="mixed")return t.value}get size(){return this.map.size}equals(n){if(this.size!==n.size)return!1;const t=new Set;for(const[r,s]of this){if(!GC(s,n.get(r)))return!1;t.add(r)}for(const[r,s]of n)if(!t.has(r)&&!GC(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 Tv extends cG{set(n,t){this.map.set(n,t)}applyValue(n,t){const r=this.get(n);if(!r){this.set(n,{type:"shared",value:t});return}switch(r.type){case"mixed":return;case"shared":r.value!==t&&this.set(n,{type:"mixed"});return;default:cn(r,"type")}}}function uG(e,n,t){return vs(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],n,{type:t})})}const dG="https://cdn.tldraw.com";function jo(){return`${dG}/${rM}`}function hG(e,n){var s;let t=e;const r=new Set(n);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 Xd(e,n,t){if(t.length===0)return[];const r=new Map;for(const o of me(t.map(i=>e.getShape(i)))){const{parentId:i}=o;r.has(i)||r.set(i,{children:me(e.getSortedChildIdsForParent(i).map(a=>e.getShape(a))),moving:new Set}),r.get(i).moving.add(o)}const s=[];switch(n){case"toBack":{r.forEach(({moving:o,children:i})=>pG(o,i,s));break}case"toFront":{r.forEach(({moving:o,children:i})=>fG(o,i,s));break}case"forward":{r.forEach(({moving:o,children:i})=>gG(o,i,s));break}case"backward":{r.forEach(({moving:o,children:i})=>mG(o,i,s));break}}return s}function pG(e,n,t){const r=n.length;if(e.size===r)return;let s,o;for(let i=0;i({...a,index:i[l]})))}}function fG(e,n,t){const r=n.length;if(e.size===r)return;let s,o;for(let i=r-1;i>-1;i--){const a=n[i];if(e.has(a))o=a.index,e.delete(a);else{s=a.index;break}}if(e.size!==0){const i=fl(s,o,e.size);t.push(...Array.from(e.values()).sort(an).map((a,l)=>({...a,index:i[l]})))}}function gG(e,n,t){var o;const r=n.length;if(e.size===r)return;let s={name:"skipping"};for(let i=0;it.push({...n[l+u],index:c})),s={name:"skipping"};break}}}}function mG(e,n,t){var o;const r=n.length;if(e.size===r)return;let s={name:"skipping"};for(let i=r-1;i>-1;i--){const a=e.has(n[i]);switch(s.name){case"skipping":{if(!a)continue;s={name:"selecting",selectIndex:i};break}case"selecting":{if(a)continue;fl((o=n[i-1])==null?void 0:o.index,n[i].index,s.selectIndex-i).forEach((l,c)=>{t.push({...n[i+c+1],index:l})}),s={name:"skipping"};break}}}}function ZM({editor:e}){const n=e.getSelectedShapes(),t=e.getSelectionRotation(),r=e.getSelectionRotatedPageBounds(),{inputs:{originPagePoint:s}}=e;if(!r)return null;const o=r.center.clone().rotWith(r.point,t);return{selectionPageCenter:o,initialCursorAngle:o.angle(s),initialSelectionRotation:t,shapeSnapshots:n.map(i=>({shape:Be(i),initialPagePoint:e.getShapePageTransform(i.id).point()}))}}function Uh({delta:e,editor:n,snapshot:t,stage:r}){const{selectionPageCenter:s,shapeSnapshots:o}=t;n.updateShapes(o.map(({shape:a,initialPagePoint:l})=>{const c=An(a.parentId)?n.getShapePageTransform(a.parentId):oe.Identity(),u=b.RotWith(l,s,e),h=oe.applyToPoint(oe.Inverse(c),u),p=Go(a.rotation+e);return{id:a.id,type:a.type,x:h.x,y:h.y,rotation:p}}));const i=[];o.forEach(({shape:a})=>{var h,p,f;const l=n.getShape(a.id);if(!l)return;const c=n.getShapeUtil(a);if(r==="start"||r==="one-off"){const S=(h=c.onRotateStart)==null?void 0:h.call(c,a);S&&i.push(S)}const u=(p=c.onRotate)==null?void 0:p.call(c,a,l);if(u&&i.push(u),r==="end"||r==="one-off"){const S=(f=c.onRotateEnd)==null?void 0:f.call(c,a,l);S&&i.push(S)}}),i.length>0&&n.updateShapes(i)}const yG=e=>{const{store:n}=e,t=n.query.filterHistory("binding"),r=n.query.records("binding");function s(){const o=r.get(),i=new Map;for(const a of o){const{fromId:l,toId:c}=a,u=i.get(l);u?u.push(a):i.set(l,[a]);const h=i.get(c);h?h.push(a):i.set(c,[a])}return i}return G("arrowBindingsIndex",(o,i)=>{if(Ai(o))return s();const a=o,l=t.getDiffSince(i);if(l===nr)return s();let c;function u(f){c??(c=new Map(a));const S=c.get(f.fromId),m=S==null?void 0:S.filter(v=>v.id!==f.id);m!=null&&m.length?c.set(f.fromId,m):c.delete(f.fromId);const x=c.get(f.toId),y=x==null?void 0:x.filter(v=>v.id!==f.id);y!=null&&y.length?c.set(f.toId,y):c.delete(f.toId)}function h(f){c??(c=new Map(a));let S=c.get(f);return S?S===a.get(f)&&(S=S.slice(0),c.set(f,S)):(S=[],c.set(f,S)),S}function p(f){h(f.fromId).push(f),h(f.toId).push(f)}for(const f of l){for(const S of gt(f.added))p(S);for(const[S,m]of gt(f.updated))u(S),p(m);for(const S of gt(f.removed))u(S)}return c??a})};function SG(e,n,t){const r=e.getShapeMaskedPageBounds(n);return r===void 0?!0:!t.includes(r)}const vG=e=>{function n(t){const r=t.getCurrentPageShapeIds(),s=t.getViewportPageBounds(),o=new Set;return r.forEach(i=>{SG(t,i,s)&&o.add(i)}),o}return G("getCulledShapes",t=>{if(Ai(t))return n(e);const r=n(e);if(t.size!==r.size)return r;for(const s of t)if(!r.has(s))return r;return t})},xG=e=>{const n=e.query.ids("shape"),t=e.query.filterHistory("shape");function r(){const s={},o=n.get(),i=Array(o.size);return o.forEach(a=>i.push(e.get(a))),i.sort(an),i.forEach(a=>{s[a.parentId]||(s[a.parentId]=[]),s[a.parentId].push(a.id)}),s}return G("parentsToChildrenWithIndexes",(s,o)=>{if(Ai(s))return r();const i=t.getDiffSince(o);if(i===nr)return r();if(i.length===0)return s;let a=null;const l=h=>{a||(a={...s}),a[h]?a[h]===s[h]&&(a[h]=[...a[h]]):a[h]=[]},c=new Set;let u;for(let h=0,p=i.length;he.get(f)));p.sort(an),h.splice(0,h.length,...p.map(f=>f.id))}return a??s})},ay=(e,n,t)=>{for(;!Tn(t.parentId);){const r=e.get(t.parentId);if(!r)return!1;t=r}return t.parentId===n},wG=(e,n)=>{const t=e.query.ids("shape");let r=null;function s(){const o=n();return r=o,new Set([...t.get()].filter(i=>ay(e,o,e.get(i))))}return G("_shapeIdsInCurrentPage",(o,i)=>{if(Ai(o))return s();const a=n();if(a!==r)return s();const l=e.history.getDiffSince(i);if(l===nr)return s();const c=new $h(o);for(const h of l){for(const p of Object.values(h.added))Ba(p)&&ay(e,a,p)&&c.add(p.id);for(const[p,f]of Object.values(h.updated))Ba(f)&&(ay(e,a,f)?c.add(f.id):c.remove(f.id));for(const p of Object.keys(h.removed))An(p)&&c.remove(p)}const u=c.get();return u?vc(u.value,u.diff):o})},QM=P.createContext(null);function bG({context:e,editor:n,children:t}){return d.jsx(cg.Provider,{value:n,children:d.jsx(QM.Provider,{value:e,children:t})})}function JM(){const e=P.useContext(QM);return e?{isDarkMode:e.isDarkMode}:null}async function PG(e,n,t={}){var E,k;const r=typeof n[0]=="string"?n:n.map(I=>I.id);if(r.length===0)return;if(!window.document)throw Error("No document");const{scale:s=1,background:o=!1,padding:i=e.options.defaultSvgPadding,preserveAspectRatio:a=!1}=t,l=t.darkMode??e.user.getIsDarkMode(),c=lo({isDarkMode:l}),u=e.getShapeAndDescendantIds(r),h=e.getUnorderedRenderingShapes(!1).filter(({id:I})=>u.has(I));let p=null;if(t.bounds)p=t.bounds;else for(const{id:I}of h){const _=e.getShapeMaskedPageBounds(I);_&&(p?p.union(_):p=_.clone())}if(!p)return;const f=r.length===1&&e.isShapeOfType(e.getShape(r[0]),"frame")?r[0]:null;f||p.expandBy(i);const S=p.width*s,m=p.height*s;try{(k=(E=document.body).focus)==null||k.call(E)}catch{}const x=[],y=new Map,v={isDarkMode:l,addExportDef:I=>{if(y.has(I.key))return;const _=(async()=>{const T=await I.getElement();T&&x.push(d.jsx(P.Fragment,{children:T},x.length))})();y.set(I.key,_)}},w=(await Promise.all(h.map(async({id:I,opacity:_,index:T,backgroundIndex:M})=>{var z,W;if(I===f)return[];const D=e.getShape(I);if(e.isShapeOfType(D,"group"))return[];const $=e.getShapeUtil(D);let j=await((z=$.toSvg)==null?void 0:z.call($,D,v)),O=await((W=$.toBackgroundSvg)==null?void 0:W.call($,D,v));if(!j&&!O){const Y=e.getShapePageBounds(D);j=d.jsx("rect",{width:Y.w,height:Y.h,fill:c.solid,stroke:c.grey.pattern,strokeWidth:1})}let R=e.getShapePageTransform(D).toCssString();"scale"in D.props&&D.props.scale!==1&&(R=`${R} scale(${D.props.scale}, ${D.props.scale})`),j&&(j=d.jsx("g",{transform:R,opacity:_,children:j},D.id)),O&&(O=d.jsx("g",{transform:R,opacity:_,children:O},`bg_${D.id}`));const K=e.getShapeMask(D.id);if(K){const Y=`mask_${D.id.replace(":","_")}`;x.push(d.jsx("clipPath",{id:Y,children:d.jsx("path",{d:`M${K.map(({x:q,y:ae})=>`${q},${ae}`).join("L")}Z`})},x.length)),j&&(j=d.jsx("g",{clipPath:`url(#${Y})`,children:j},D.id)),O&&(O=d.jsx("g",{clipPath:`url(#${Y})`,children:O},`bg_${D.id}`))}const B=[];return j&&B.push({zIndex:T,element:j}),O&&B.push({zIndex:M,element:O}),B}))).flat();return await Promise.all(y.values()),{jsx:d.jsx(bG,{editor:e,context:v,children:d.jsxs("svg",{preserveAspectRatio:a||void 0,direction:"ltr",width:S,height:m,viewBox:`${p.minX} ${p.minY} ${p.width} ${p.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:o?f?c.solid:c.background:"transparent"},children:[d.jsx("defs",{children:x}),w.sort((I,_)=>I.zIndex-_.zIndex).map(({element:I})=>I)]})}),width:S,height:m}}const CG=40;class IG{constructor(n){g(this,"_clickId","");g(this,"_clickTimeout");g(this,"_clickScreenPoint");g(this,"_previousScreenPoint");g(this,"_getClickTimeout",(n,t=ct())=>{this._clickId=t,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===n&&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"}},n==="idle"||n==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)});g(this,"_clickState","idle");g(this,"lastPointerInfo",{});g(this,"handlePointerEvent",n=>{switch(n.name){case"pointer_down":{if(!this._clickState)return n;switch(this._clickScreenPoint=b.From(n.point),this._previousScreenPoint&&b.Dist2(this._previousScreenPoint,this._clickScreenPoint)>CG**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=n,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,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),n}case"pointer_up":{if(!this._clickState)return n;switch(this._clickScreenPoint=b.From(n.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 n}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&b.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),n}return n});g(this,"cancelDoubleClickTimeout",()=>{this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"});this.editor=n}get clickState(){return this._clickState}}class EG{constructor(n){g(this,"_isEdgeScrolling",!1);g(this,"_edgeScrollDuration",-1);this.editor=n}updateEdgeScrolling(n){const{editor:t}=this,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+=n,this._edgeScrollDuration>t.options.edgeScrollDelay){const s=t.options.edgeScrollEaseDuration>0?At.easeInCubic(Math.min(1,this._edgeScrollDuration/(t.options.edgeScrollDelay+t.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*s,y:r.y*s})}}getEdgeProximityFactors(n,t,r,s,o){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=n-l,u=n+l,h=s?0:a,p=o?t:t-a;return cp?-Math.min(1,(u-p)/a):0}getEdgeScroll(){const{editor:n}=this,{inputs:{currentScreenPoint:{x:t,y:r}}}=n,s=n.getViewportScreenBounds(),{isCoarsePointer:o,insets:[i,a,l,c]}=n.getInstanceState(),u=this.getEdgeProximityFactors(t,s.w,o,c,a),h=this.getEdgeProximityFactors(r,s.h,o,i,l);return{x:u,y:h}}moveCameraWhenCloseToEdge(n){const{editor:t}=this;if(!t.inputs.isDragging||t.inputs.isPanning||t.getCameraOptions().isLocked||n.x===0&&n.y===0)return;const 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*n.x*s/i,c=a*n.y*o/i,{x:u,y:h,z:p}=t.getCamera();t.setCamera(new b(u+l,h+c,p))}}class _G{constructor(n){g(this,"isSafari");g(this,"isIos");g(this,"isChromeForIos");g(this,"isFirefox");g(this,"isAndroid");this.editor=n,typeof window<"u"&&"navigator"in window?(this.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),this.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),this.isFirefox=/firefox/i.test(navigator.userAgent),this.isAndroid=/android/i.test(navigator.userAgent)):(this.isSafari=!1,this.isIos=!1,this.isChromeForIos=!1,this.isFirefox=!1,this.isAndroid=!1)}}class kG{constructor(n,t){g(this,"disposeSideEffectListener");this.editor=n,this.disposeSideEffectListener=n.sideEffects.registerAfterChangeHandler("instance",(s,o)=>{s.isFocused!==o.isFocused&&(o.isFocused?this.focus():this.blur(),this.updateContainerClass())});const r=n.getInstanceState().isFocused;t!==r&&n.updateInstanceState({isFocused:!!t}),this.updateContainerClass()}updateContainerClass(){const n=this.editor.getContainer();this.editor.getInstanceState().isFocused?n.classList.add("tl-container__focused"):n.classList.remove("tl-container__focused")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var n;(n=this.disposeSideEffectListener)==null||n.call(this)}}function ic(e){return MG}class TG{constructor(){g(this,"length",0);g(this,"head",null);g(this,"tail",this)}push(n){return new lw(n,this)}toArray(){return Gs}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const MG=new TG;class lw{constructor(n,t){g(this,"length");this.head=n,this.tail=t,this.length=t.length+1}push(n){return new lw(n,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let n=this;return{next(){if(n.length){const t=n.head;return n=n.tail,{value:t,done:!1}}else return{value:void 0,done:!0}}}}}class AG{constructor(n){g(this,"store");g(this,"dispose");g(this,"state","recording");g(this,"pendingDiff",new OG);g(this,"stacks",Mt("HistoryManager.stacks",{undos:ic(),redos:ic()},{isEqual:(n,t)=>n.undos===t.undos&&n.redos===t.redos}));g(this,"annotateError");g(this,"_isInBatch",!1);g(this,"batch",(n,t)=>{const r=this.state;r!=="paused"&&(t!=null&&t.history)&&(this.state=jG[t.history]);try{if(this._isInBatch)return gs(n),this;this._isInBatch=!0;try{gs(n)}catch(s){throw this.annotateError(s),s}finally{this._isInBatch=!1}return this}finally{this.state=r}});g(this,"_undo",({pushToRedoStack:n,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=pT(a),c=Sv(a);n&&!l&&(i=i.push({type:"diff",diff:a}));let u=!1;if(l)for(;((s=o.head)==null?void 0:s.type)==="stop";){const h=o.head;if(o=o.tail,n&&(i=i.push(h)),h.id===t){u=!0;break}}if(!u)e:for(;o.head;){const h=o.head;switch(o=o.tail,n&&(i=i.push(h)),h.type){case"diff":Gc(c,[Sv(h.diff)]);break;case"stop":if(!t||h.id===t)break e;break;default:cn(h)}}this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:o,redos:i})}finally{this.state=r}return this});g(this,"undo",()=>(this._undo({pushToRedoStack:!0}),this));g(this,"redo",()=>{var t;const n=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=qp();for(;s.head;){const i=s.head;if(r=r.push(i),s=s.tail,i.type==="diff")Gc(o,[i.diff]);else break}this.store.applyDiff(o,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:s})}finally{this.state=n}return this});g(this,"bail",()=>(this._undo({pushToRedoStack:!1}),this));g(this,"bailToMark",n=>(this._undo({pushToRedoStack:!1,toMark:n}),this));g(this,"squashToMark",n=>{var o;let t=this.stacks.get().undos;const r=[];for(;t.head&&!(t.head.type==="stop"&&t.head.id===n);)t.head.type==="diff"&&r.push(t.head.diff),t=t.tail;if(!t.head||((o=t.head)==null?void 0:o.id)!==n)return console.error("Could not find mark to squash to: ",n),this;if(r.length===0)return this;const s=qp();return Gc(s,r.reverse()),this.stacks.update(({redos:i})=>({undos:t.push({type:"diff",diff:s}),redos:i})),this});g(this,"mark",(n=ct())=>(gs(()=>{this.flushPendingDiff(),this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"stop",id:n}),redos:r}))}),n));this.store=n.store,this.annotateError=n.annotateError??Su,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:ic()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(t.changes);break;case"paused":break;default:cn(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const n=this.pendingDiff.clear();this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"diff",diff:n}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}clear(){this.stacks.set({undos:ic(),redos:ic()}),this.pendingDiff.clear()}debug(){const{undos:n,redos:t}=this.stacks.get();return{undos:n.toArray(),redos:t.toArray(),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const jG={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class OG{constructor(){g(this,"diff",qp());g(this,"isEmptyAtom",Mt("PendingDiff.isEmpty",!0))}clear(){const n=this.diff;return this.diff=qp(),this.isEmptyAtom.set(!0),n}isEmpty(){return this.isEmptyAtom.get()}apply(n){Gc(this.diff,[n]),this.isEmptyAtom.set(pT(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}class DG{constructor(n){g(this,"scribbleItems",new Map);g(this,"state","paused");g(this,"addScribble",(n,t=ct())=>{const r={id:t,scribble:{id:t,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...n,state:"starting"},timeoutMs:0,delayRemaining:n.delay??0,prev:null,next:null};return this.scribbleItems.set(t,r),r});g(this,"stop",n=>{const t=this.scribbleItems.get(n);if(!t)throw Error(`Scribble with id ${n} not found`);return t.delayRemaining=Math.min(t.delayRemaining,200),t.scribble.state="stopping",t});g(this,"addPoint",(n,t,r)=>{const s=this.scribbleItems.get(n);if(!s)throw Error(`Scribble with id ${n} not found`);const{prev:o}=s,i={x:t,y:r,z:.5};return(!o||b.Dist(o,i)>=1)&&(s.next=i),s});g(this,"tick",n=>{this.scribbleItems.size!==0&&this.editor.run(()=>{this.scribbleItems.forEach(t=>{if(t.scribble.state==="starting"){const{next:l,prev:c}=t;l&&l!==c&&(t.prev=l,t.scribble.points.push(l)),t.scribble.points.length>8&&(t.scribble.state="active");return}t.delayRemaining>0&&(t.delayRemaining=Math.max(0,t.delayRemaining-n)),t.timeoutMs+=n,t.timeoutMs>=16&&(t.timeoutMs=0);const{delayRemaining:r,timeoutMs:s,prev:o,next:i,scribble:a}=t;switch(a.state){case"active":{i&&i!==o?(t.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):s===0&&(a.points.length>1?a.points.shift():t.delayRemaining=a.delay);break}case"stopping":{if(t.delayRemaining===0&&s===0){if(a.points.length===1){this.scribbleItems.delete(t.id);return}a.shrink&&(a.size=Math.max(1,a.size*(1-a.shrink))),a.points.shift()}break}}}),this.editor.updateInstanceState({scribbles:Array.from(this.scribbleItems.values()).map(({scribble:t})=>({...t,points:[...t.points]})).slice(-5)})})});this.editor=n}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}}var RG=Object.defineProperty,LG=Object.getOwnPropertyDescriptor,fg=(e,n,t,r)=>{for(var s=LG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&RG(n,t,s),s};const ue=e=>Math.round(e*10**8)/10**8;function Ls(e,n,t,r,s){const o=e.filter(a=>(r==="forward"?a.startNode.id===n:a.endNode.id===n)&&ue(a.length)===ue(t)&&Lr(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=Ls(e,l,t,r,Lr(a.breadthIntersection[0],a.breadthIntersection[1],s[0],s[1]));o.push(...c)}}),o}function $G(e){e.sort((n,t)=>t.gaps.length-n.gaps.length);for(let n=e.length-1;n>0;n--){const t=e[n];for(let r=n-1;r>=0;r--){const s=e[r];if(s.direction===t.direction&&t.gaps.every(o=>s.gaps.some(i=>ue(o.startEdge[0].x)===ue(i.startEdge[0].x)&&ue(o.startEdge[0].y)===ue(i.startEdge[0].y)&&ue(o.startEdge[1].x)===ue(i.startEdge[1].x)&&ue(o.startEdge[1].y)===ue(i.startEdge[1].y))&&s.gaps.some(i=>ue(o.endEdge[0].x)===ue(i.endEdge[0].x)&&ue(o.endEdge[0].y)===ue(i.endEdge[0].y)&&ue(o.endEdge[1].x)===ue(i.endEdge[1].x)&&ue(o.endEdge[1].y)===ue(i.endEdge[1].y)))){e.splice(n,1);break}}}}class Qu{constructor(n){g(this,"editor");this.manager=n,this.editor=n.editor}getSnapPointsCache(){const{editor:n}=this;return n.store.createComputedCache("snapPoints",t=>{const r=n.getShapePageTransform(t.id);if(!r)return;const o=n.getShapeUtil(t).getBoundsSnapGeometry(t).points??n.getShapeGeometry(t).bounds.cornersAndCenter;if(!(!r||!o))return o.map((i,a)=>{const{x:l,y:c}=oe.applyToPoint(r,i);return{x:l,y:c,id:`${t.id}:${a}`}})})}getSnapPoints(n){return this.getSnapPointsCache().get(n)??[]}getSnappablePoints(){const n=this.getSnapPointsCache(),t=this.manager.getSnappableShapes(),r=[];for(const s of t){const o=n.get(s);o&&r.push(...o)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),n=>({id:n,pageBounds:xr(this.editor.getShapePageBounds(n))}))}getVisibleGaps(){const n=[],t=[];let r,s;const o=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;aa.pageBounds.minY-l.pageBounds.minY);for(let a=0;a({id:"selection:"+C,x:v+s.x,y:w+s.y})),c=i,u=[],h=[],p=new b(o,o);this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const f=new b(n==="x"?0:((x=u[0])==null?void 0:x.nudge)??0,n==="y"?0:((y=h[0])==null?void 0:y.nudge)??0);p.x=0,p.y=0,u.length=0,h.length=0,l.forEach(v=>{v.x+=f.x,v.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const S=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:h}),m=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h});return this.manager.setIndicators([...m,...S]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:n,dragDelta:t,handle:r,isAspectRatioLocked:s,isResizingFromCenter:o}){var I,_;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=Q.Resize(n,r,o?t.x*2:t.x,o?t.y*2:t.y,s);let u=r;l<0&&(u=KK(u)),c<0&&(u=HK(u)),o&&(a.center=n.center);const h=u==="top"||u==="bottom",p=u==="left"||u==="right",f=VC(u,a),S=this.getSnappablePoints(),m=[],x=[],y=new b(i,i);this.collectPointSnaps({minOffset:y,nearestSnapsX:m,nearestSnapsY:x,otherNodeSnapPoints:S,selectionSnapPoints:f});const v=new b(h?0:((I=m[0])==null?void 0:I.nudge)??0,p?0:((_=x[0])==null?void 0:_.nudge)??0);if(s&&WK(u)&&v.len()!==0){const T=m.length&&x.length?Math.abs(v.x)n.width&&ue(Math.abs(c))<=ue(t.x)){ue(Math.abs(c))C==="gap_center"),w=v&&Lr(a.breadthIntersection[0],a.breadthIntersection[1],v.gap.breadthIntersection[0],v.gap.breadthIntersection[1]);v&&v.gap.length>a.length&&w?r[r.indexOf(v)]=y:(!v||!w)&&r.push(y)}const h=a.startNode.pageBounds.minX-a.length,p=n.maxX,f=h-p;ue(Math.abs(f))<=ue(t.x)&&(ue(Math.abs(f))n.height&&ue(Math.abs(c))<=ue(t.y)){ue(Math.abs(c))C==="gap_center"),w=v&&oc(v.gap.breadthIntersection[0],v.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);v&&v.gap.length>a.length&&w?s[s.indexOf(v)]=y:(!v||!w)&&s.push(y);continue}const h=a.startNode.pageBounds.minY-a.length,p=n.maxY,f=h-p;ue(Math.abs(f))<=ue(t.y)&&(ue(Math.abs(f))0){for(const o of n)if(o.type==="points"){const i=ue(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=ue(o.points.otherPoint.y);s[i]||(s[i]=[]),s[i].push(o.points)}}return Object.values(r).concat(Object.values(s)).map(o=>({id:ct(),type:"points",points:R0(o.map(i=>b.From(i.otherPoint)).concat(o.map(i=>b.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:n,nearestSnapsX:t,nearestSnapsY:r}){const{vertical:s,horizontal:o}=this.getVisibleGaps(),i={top:n.sides[0],right:n.sides[1],bottom:[n.corners[3],n.corners[2]],left:[n.corners[0],n.corners[3]]},a=[];if(t.length>0)for(const l of t){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const m=(f-n.width)/2,x=Lr(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ct(),gaps:[...Ls(o,h.id,m,"backward",x),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:S},...Ls(o,p.id,m,"forward",x)]});break}case"gap_duplicate":{const m=Lr(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ct(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(x=>x.clone().addXY(-h.pageBounds.width,0))},{startEdge:u,endEdge:S},...Ls(o,p.id,f,"forward",m)]:[...Ls(o,h.id,f,"backward",m),{startEdge:u,endEdge:S},{startEdge:S.map(x=>x.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:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const m=(f-n.height)/2,x=Lr(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ct(),gaps:[...Ls(s,h.id,m,"backward",x),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:S},...Ls(s,l.gap.endNode.id,m,"forward",x)]});break}case"gap_duplicate":{const m=Lr(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ct(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(x=>x.clone().addXY(0,-h.pageBounds.height))},{startEdge:u,endEdge:S},...Ls(s,p.id,f,"forward",m)]:[...Ls(s,h.id,f,"backward",m),{startEdge:u,endEdge:S},{startEdge:S.map(x=>x.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return $G(a),a}}fg([G],Qu.prototype,"getSnapPointsCache");fg([G],Qu.prototype,"getSnappablePoints");fg([G],Qu.prototype,"getSnappableGapNodes");fg([G],Qu.prototype,"getVisibleGaps");function VC(e,n){const{minX:t,maxX:r,minY:s,maxY:o}=n,i=[];switch(e){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:t,y:s})}switch(e){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:s})}switch(e){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:o})}switch(e){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:t,y:o})}return i}var NG=Object.defineProperty,FG=Object.getOwnPropertyDescriptor,zG=(e,n,t,r)=>{for(var s=FG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&NG(n,t,s),s};const BG=()=>null,UG=()=>[];class eA{constructor(n){g(this,"editor");this.manager=n,this.editor=n.editor}getSnapGeometryCache(){const{editor:n}=this;return n.store.createComputedCache("handle snap geometry",t=>{const r=n.getShapeUtil(t).getHandleSnapGeometry(t);return{outline:r.outline===void 0?n.getShapeGeometry(t):r.outline,points:r.points??[],getSelfSnapOutline:r.getSelfSnapOutline??BG,getSelfSnapPoints:r.getSelfSnapPoints??UG}})}*iterateSnapPointsInPageSpace(n,t){var s,o;const r=(s=this.getSnapGeometryCache().get(n))==null?void 0:s.getSelfSnapPoints(t);if(r&&r.length){const i=xr(this.editor.getShapePageTransform(n));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.points;if(!a||!a.length)continue;const l=xr(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(n,t){var s,o;const r=(s=this.getSnapGeometryCache().get(n))==null?void 0:s.getSelfSnapOutline(t);r&&(yield{shapeId:n,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:r}){const s=this.manager.getSnapThreshold();let o=s,i=null;for(const c of this.iterateSnapPointsInPageSpace(n,t))b.DistMin(r,c,o)&&(o=b.Dist(r,c),i=c);if(i)return i;let a=s,l=null;for(const{shapeId:c,outline:u}of this.iterateSnapOutlines(n,t)){const h=xr(this.editor.getShapePageTransform(c)),p=this.editor.getPointInShapeSpace(c,r),f=u.nearestPoint(p),S=h.applyToPoint(f);b.DistMin(r,S,a)&&(a=b.Dist(r,S),l=S)}return l||null}snapHandle({currentShapeId:n,handle:t}){const s=xr(this.editor.getShapePageTransform(n)).applyToPoint(t),o=this.getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:s});return o?(this.manager.setIndicators([{id:ct(),type:"points",points:[o]}]),{nudge:b.Sub(o,s)}):null}}zG([G],eA.prototype,"getSnapGeometryCache");var HG=Object.defineProperty,KG=Object.getOwnPropertyDescriptor,cw=(e,n,t,r)=>{for(var s=KG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&HG(n,t,s),s};let gg=class{constructor(n){g(this,"shapeBounds");g(this,"handles");g(this,"_snapIndicators",Mt("snapLines",void 0));this.editor=n,this.shapeBounds=new Qu(this),this.handles=new eA(this)}getIndicators(){return this._snapIndicators.get()??Gs}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(n){this._snapIndicators.set(n)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:n}=this,t=n.getViewportPageBounds(),r=n.getSelectedShapeIds(),s=new Set,o=i=>{if(An(i)){const l=n.getShape(i);l&&n.isShapeOfType(l,"frame")&&s.add(i)}const a=n.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=n.getShape(l);if(!c||!n.getShapeUtil(c).canSnap(c))continue;const h=n.getShapePageBounds(l);if(h&&t.includes(h)){if(n.isShapeOfType(c,"group")){o(l);continue}s.add(l)}}};return o(this.getCurrentCommonAncestor()??n.getCurrentPageId()),s}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}};cw([G],gg.prototype,"getSnapThreshold");cw([G],gg.prototype,"getSnappableShapes");cw([G],gg.prototype,"getCurrentCommonAncestor");const WG=/\r?\n|\r/g;function YC(e){return e.replace(WG,` +My browser: ${navigator.userAgent}`),d.jsxs("div",{ref:t,className:le("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[d.jsx("div",{className:"tl-error-boundary__overlay"}),n&&d.jsx(sM,{onError:Su,fallback:()=>null,children:d.jsx(cg.Provider,{value:n,children:d.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:c?d.jsx(c,{}):null})})}),d.jsx("div",{className:le("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Are you sure?"}),d.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>l(!1),children:"Cancel"}),d.jsx("button",{className:"tl-error-boundary__reset",onClick:m,children:"Reset data"})]})]}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Something's gone wrong."}),d.jsxs("p",{children:["Sorry, we encountered an error. Please refresh the page to continue. If you keep seeing this error, you can ",d.jsx("a",{href:v.toString(),children:"create a GitHub issue"})," or"," ",d.jsx("a",{href:"https://discord.gg/Cq6cPsTfNy",children:"ask for help on Discord"}),"."]}),r&&d.jsxs(d.Fragment,{children:["Message:",d.jsx("h4",{children:d.jsx("code",{children:u})}),"Stack trace:",d.jsxs("div",{className:"tl-error-boundary__content__error",children:[d.jsx("pre",{children:d.jsx("code",{children:h??u})}),d.jsx("button",{onClick:y,children:o?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>s(!r),children:r?"Hide details":"Show details"}),d.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[d.jsx("button",{className:"tl-error-boundary__reset",onClick:()=>l(!0),children:"Reset data"}),d.jsx("button",{className:"tl-error-boundary__refresh",onClick:x,children:"Refresh Page"})]})]})]})})]})};function ct(){return Ku()}const jM="TLDRAW_USER_DATA_v3",OM=ve({id:he,name:he.nullable().optional(),locale:he.nullable().optional(),color:he.nullable().optional(),colorScheme:ig("light","dark","system").optional(),animationSpeed:de.nullable().optional(),edgeScrollSpeed:de.nullable().optional(),isSnapMode:ye.nullable().optional(),isWrapMode:ye.nullable().optional(),isDynamicSizeMode:ye.nullable().optional(),isPasteAtCursorMode:ye.nullable().optional()}),Rs={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5,AddDynamicSizeMode:6,AllowSystemColorScheme:7,AddPasteAtCursor:8},sw=Math.max(...Object.values(Rs));function BW(e){e.version{const n=e.data;(n==null?void 0:n.type)===NM&&(n==null?void 0:n.origin)!==$M()&&hg.set(RM(n.data))});let oy=null;function $M(){return oy===null&&(oy=ct()),oy}const NM="tldraw-user-preferences-change";function GW(){el==null||el.postMessage({type:NM,origin:$M(),data:{user:FM(),version:sw}})}function FM(){let e=hg.get();return e||(e=HW(),LM(e)),e}const VW=G("defaultLocalStorageUserPrefs",()=>FM());function zM(e={}){return{userPreferences:e.userPreferences??VW,setUserPreferences:e.setUserPreferences??LM}}var BM={exports:{}};(function(e){var n=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,h,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new s(u,h||l,p),S=t?t+c:c;return l._events[S]?l._events[S].fn?l._events[S]=[l._events[S],f]:l._events[S].push(f):(l._events[S]=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,h;if(this._eventsCount===0)return c;for(h in u=this._events)n.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,S=new Array(f);p";ys&&(ys[tl]=pf,qW()?z0(tl,pf):aT(tl));ys==null||ys.addEventListener("beforeunload",()=>{z0(tl,pf)});const UM={Initial:0},pg=Math.max(...Object.values(UM));function ZW(e){e.version{const t=e.get(mn);if(!t)return null;const r=[...n.get()];return{version:pg,currentPageId:t.currentPageId,exportBackground:t.exportBackground,isFocusMode:t.isFocusMode,isDebugMode:t.isDebugMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,pageStates:r.map(s=>{const o=e.get(zr.createId(s)),i=e.get(us.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}})}})}function WM(e,n){const t=QW(n);if(!t)return;const r=e.schema.types.instance.create({id:mn,...MT(e.get(mn)),currentPageId:t.currentPageId,isDebugMode:t.isDebugMode,isFocusMode:t.isFocusMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,exportBackground:t.exportBackground}),s=e.allRecords().filter(o=>o.typeName==="instance_page_state"||o.typeName==="camera");e.atomic(()=>{e.remove(s.map(o=>o.id));for(const o of t.pageStates)e.put([us.create({id:us.createId(o.pageId),x:o.camera.x,y:o.camera.y,z:o.camera.z}),zr.create({id:zr.createId(o.pageId),pageId:o.pageId,selectedShapeIds:o.selectedShapeIds,focusedGroupId:o.focusedGroupId})]);e.put([r]),e.ensureStoreIsUsable()})}function JW(e){var s;const n=[];for(const o of Object.values(e))(s=o.typeName)!=null&&s.match(/^(instance.*|pointer|camera)$/)&&n.push(o);const t=n.filter(o=>o.typeName==="instance"&&o.id!==mn)[0];if(!t)return null;const r={version:pg,currentPageId:t.currentPageId,exportBackground:!!t.exportBackground,isFocusMode:!!t.isFocusMode,isDebugMode:!!t.isDebugMode,isToolLocked:!!t.isToolLocked,isGridMode:!1,pageStates:n.filter(o=>o.typeName==="instance_page_state"&&o.instanceId===t.id).map(o=>{const i=e[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 HM.validate(r),r}catch{return null}}function GM(e,n){let t={};if("store"in n){const s=e.schema.migrateStoreSnapshot(n);if(s.type!=="success")throw new Error("Failed to migrate store snapshot: "+s.reason);t.document={schema:e.schema.serialize(),store:Wc(s.value,(o,{typeName:i})=>e.scopedTypes.document.has(i))}}else t=n;const r=MT(e.get(mn));e.atomic(()=>{t.document&&e.loadStoreSnapshot(t.document),r&&e.update(mn,s=>({...s,...r})),t.session&&WM(e,t.session)})}const eG=new eo;function tG(e){const t=eG.get(e,KM).get();if(!t)throw new Error("Session state is not ready yet");return{document:e.getStoreSnapshot(),session:t}}function VM(e){const n=[],t=new Set;for(const r of e){if(t.has(r.type))throw new Error(`Binding type "${r.type}" is defined more than once`);n.push(r),t.add(r.type)}return n}function bs({children:e,className:n="",...t}){return d.jsx("svg",{...t,className:le("tl-svg-container",n),children:e})}function ow(e,n,t,r){const s=e.x-t.x,o=e.y-t.y,i=r.x-t.x,a=r.y-t.y,l=n.x-e.x,c=n.y-e.y,u=i*o-a*s,h=l*o-c*s,p=a*l-i*c;if(u===0||h===0||p===0)return null;if(p!==0){const f=u/p,S=h/p;if(0<=f&&f<=1&&0<=S&&S<=1)return b.AddXY(e,f*l,f*c)}return null}function Zu(e,n,t,r){const s=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),o=2*((n.x-e.x)*(e.x-t.x)+(n.y-e.y)*(e.y-t.y)),i=t.x*t.x+t.y*t.y+e.x*e.x+e.y*e.y-2*(t.x*e.x+t.y*e.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 h=[];return 0<=c&&c<=1&&h.push(b.Lrp(e,n,c)),0<=u&&u<=1&&h.push(b.Lrp(e,n,u)),h.length===0?null:h}function nG(e,n,t){const r=[];let s;for(let o=0,i=t.length-1;o(n.y-e.y)*(t.x-e.x)}function aw(e,n,t,r){return Yd(e,t,r)!==Yd(n,t,r)&&Yd(e,n,t)!==Yd(e,n,r)}function KC(e,n){const t=new Map;let r,s,o,i;for(let a=0,l=e.length;ab.Angle(n,t)-b.Angle(n,r))}function YM(e,n){let t,r,s,o;for(let i=0,a=e.length;iMath.max(r.x,s.x))return r.x>s.x?r:s;const c=r.y+o.y*a;return cMath.max(r.y,s.y)?r.y>s.y?r:s:new b(l,c)}hitTestLineSegment(t,r,s=0){return aw(t,r,this.start,this.end)||this.distanceToLineSegment(t,r)<=s}getSvgPathData(t=!0){const{start:r,end:s}=this;return`${t?`M${r.toFixed()}`:""} L${s.toFixed()}`}}class ia extends li{constructor(t){super({isClosed:!1,isFilled:!1,...t});g(this,"points");g(this,"_segments");const{points:r}=t;this.points=r}get segments(){if(!this._segments){this._segments=[];const{vertices:t}=this;for(let r=0,s=t.length-1;rt+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;lo===0?`M ${s.x} ${s.y}`:`${r} L ${s.x} ${s.y}`,"")}}class at extends ia{constructor(n){super({...n}),this.isClosed=!0}}class no extends at{constructor(t){const{x:r=0,y:s=0,width:o,height:i}=t;super({...t,points:[new b(r,s),new b(r+o,s),new b(r+o,s+i),new b(r,s+i)]});g(this,"x");g(this,"y");g(this,"w");g(this,"h");this.x=r,this.y=s,this.w=o,this.h=i}getBounds(){return new Q(this.x,this.y,this.w,this.h)}getSvgPathData(){const{x:t,y:r,w:s,h:o}=this;return`M${t},${r} h${s} v${o} h-${s}z`}}class Ir{constructor(n){g(this,"canSnap",()=>!0);g(this,"canScroll",()=>!1);g(this,"canEdit",()=>!1);g(this,"canResize",()=>!0);g(this,"canEditInReadOnly",()=>!1);g(this,"canCrop",()=>!1);g(this,"canBeLaidOut",()=>!0);g(this,"hideResizeHandles",()=>!1);g(this,"hideRotateHandle",()=>!1);g(this,"hideSelectionBoundsBg",()=>!1);g(this,"hideSelectionBoundsFg",()=>!1);g(this,"isAspectRatioLocked",()=>!1);g(this,"onBeforeCreate");g(this,"onBeforeUpdate");g(this,"onDragShapesOver");g(this,"onDragShapesOut");g(this,"onDropShapesOver");g(this,"onResizeStart");g(this,"onResize");g(this,"onResizeEnd");g(this,"onTranslateStart");g(this,"onTranslate");g(this,"onTranslateEnd");g(this,"onHandleDrag");g(this,"onRotateStart");g(this,"onRotate");g(this,"onRotateEnd");g(this,"onBindingChange");g(this,"onChildrenChange");g(this,"onDoubleClickHandle");g(this,"onDoubleClickEdge");g(this,"onDoubleClick");g(this,"onClick");g(this,"onEditEnd");this.editor=n}canBind(n){return!0}providesBackgroundForChildren(n){return!1}canReceiveNewChildrenOfType(n,t){return!1}canDropShapes(n,t){return!1}expandSelectionOutlinePx(n){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(n){return{}}getHandleSnapGeometry(n){return{}}}g(Ir,"props"),g(Ir,"migrations"),g(Ir,"type");function iG(e,n,t={}){const{closed:r=!1,snap:s=1,start:o="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,u=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(o==="outset"?(e+=c/2,f+=c/2):o==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),u=Math.floor(e/c/(2*h)),u-=u%s,u<3&&l==="dashed"?e/n<5?(c=e,u=1,p=0):(c=e*.333,p=e*.333):(u=Math.max(u,3),c=e/u/(2*h),r?(f=c/2,p=(e-u*c)/u):p=(e-u*c)/Math.max(1,u-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}function WC({bounds:e,className:n}){const t=F(),r=H("zoom level",()=>t.getZoomLevel(),[t]);return d.jsx("g",{className:n,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:e.sides.map((s,o)=>{const{strokeDasharray:i,strokeDashoffset:a}=iG(s[0].dist(s[1]),1/r,{style:"dashed",lengthRatio:4});return d.jsx("line",{x1:s[0].x,y1:s[0].y,x2:s[1].x,y2:s[1].y,strokeDasharray:i,strokeDashoffset:a},o)})})}class Bh extends Ir{constructor(){super(...arguments);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"canBind",()=>!1);g(this,"onChildrenChange",t=>{const r=this.editor.getSortedChildIdsForParent(t.id);if(r.length===0){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([t.id]);return}else if(r.length===1){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(r,t.parentId),this.editor.deleteShapes([t.id]);return}})}getDefaultProps(){return{}}getGeometry(t){const r=this.editor.getSortedChildIdsForParent(t.id);return r.length===0?new no({width:1,height:1,isFilled:!1}):new Wr({children:r.map(s=>{const o=this.editor.getShape(s),i=this.editor.getShapeGeometry(s),a=this.editor.getShapeLocalTransform(o).applyToPoints(i.vertices);return i.isClosed?new at({points:a,isFilled:!0}):new ia({points:a})})})}component(t){const r=this.editor.getErasingShapeIds().includes(t.id),{hintingShapeIds:s}=this.editor.getCurrentPageState(),o=s.length>0&&s.some(l=>l!==t.id&&this.editor.isShapeOfType(this.editor.getShape(l),"group")),i=this.editor.getCurrentPageState().focusedGroupId!==t.id;if(!r&&(i||o))return null;const a=this.editor.getShapeGeometry(t).bounds;return d.jsx(bs,{id:t.id,children:d.jsx(WC,{className:"tl-group",bounds:a})})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds;return d.jsx(WC,{className:"",bounds:r})}}g(Bh,"type","group"),g(Bh,"props",UT),g(Bh,"migrations",HT);const XM=[Bh],aG=new Set(XM.map(e=>e.type));function qM(e){const n=[...XM],t=new Set;for(const r of e){if(aG.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`);n.push(r),t.add(r.type)}return n}const lG={maxShapesPerPage:4e3,maxPages:40,animationMediumMs:320,followChaseViewportSnap:2,doubleClickDurationMs:450,multiClickDurationMs:200,coarseDragDistanceSquared:36,dragDistanceSquared:16,defaultSvgPadding:32,cameraSlideFriction:.09,maxPointsPerDrawShape:500,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};function GC(e,n){if(!n)return!1;switch(e.type){case"mixed":return n.type==="mixed";case"shared":return n.type==="shared"&&e.value===n.value;default:throw cn(e)}}class cG{constructor(n){g(this,"map");this.map=new Map(n)}get(n){return this.map.get(n)}getAsKnownValue(n){const t=this.get(n);if(t&&t.type!=="mixed")return t.value}get size(){return this.map.size}equals(n){if(this.size!==n.size)return!1;const t=new Set;for(const[r,s]of this){if(!GC(s,n.get(r)))return!1;t.add(r)}for(const[r,s]of n)if(!t.has(r)&&!GC(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 Tv extends cG{set(n,t){this.map.set(n,t)}applyValue(n,t){const r=this.get(n);if(!r){this.set(n,{type:"shared",value:t});return}switch(r.type){case"mixed":return;case"shared":r.value!==t&&this.set(n,{type:"mixed"});return;default:cn(r,"type")}}}function uG(e,n,t){return vs(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],n,{type:t})})}const dG="https://cdn.tldraw.com";function jo(){return`${dG}/${rM}`}function hG(e,n){var s;let t=e;const r=new Set(n);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 Xd(e,n,t){if(t.length===0)return[];const r=new Map;for(const o of me(t.map(i=>e.getShape(i)))){const{parentId:i}=o;r.has(i)||r.set(i,{children:me(e.getSortedChildIdsForParent(i).map(a=>e.getShape(a))),moving:new Set}),r.get(i).moving.add(o)}const s=[];switch(n){case"toBack":{r.forEach(({moving:o,children:i})=>pG(o,i,s));break}case"toFront":{r.forEach(({moving:o,children:i})=>fG(o,i,s));break}case"forward":{r.forEach(({moving:o,children:i})=>gG(o,i,s));break}case"backward":{r.forEach(({moving:o,children:i})=>mG(o,i,s));break}}return s}function pG(e,n,t){const r=n.length;if(e.size===r)return;let s,o;for(let i=0;i({...a,index:i[l]})))}}function fG(e,n,t){const r=n.length;if(e.size===r)return;let s,o;for(let i=r-1;i>-1;i--){const a=n[i];if(e.has(a))o=a.index,e.delete(a);else{s=a.index;break}}if(e.size!==0){const i=fl(s,o,e.size);t.push(...Array.from(e.values()).sort(an).map((a,l)=>({...a,index:i[l]})))}}function gG(e,n,t){var o;const r=n.length;if(e.size===r)return;let s={name:"skipping"};for(let i=0;it.push({...n[l+u],index:c})),s={name:"skipping"};break}}}}function mG(e,n,t){var o;const r=n.length;if(e.size===r)return;let s={name:"skipping"};for(let i=r-1;i>-1;i--){const a=e.has(n[i]);switch(s.name){case"skipping":{if(!a)continue;s={name:"selecting",selectIndex:i};break}case"selecting":{if(a)continue;fl((o=n[i-1])==null?void 0:o.index,n[i].index,s.selectIndex-i).forEach((l,c)=>{t.push({...n[i+c+1],index:l})}),s={name:"skipping"};break}}}}function ZM({editor:e}){const n=e.getSelectedShapes(),t=e.getSelectionRotation(),r=e.getSelectionRotatedPageBounds(),{inputs:{originPagePoint:s}}=e;if(!r)return null;const o=r.center.clone().rotWith(r.point,t);return{selectionPageCenter:o,initialCursorAngle:o.angle(s),initialSelectionRotation:t,shapeSnapshots:n.map(i=>({shape:Be(i),initialPagePoint:e.getShapePageTransform(i.id).point()}))}}function Uh({delta:e,editor:n,snapshot:t,stage:r}){const{selectionPageCenter:s,shapeSnapshots:o}=t;n.updateShapes(o.map(({shape:a,initialPagePoint:l})=>{const c=An(a.parentId)?n.getShapePageTransform(a.parentId):oe.Identity(),u=b.RotWith(l,s,e),h=oe.applyToPoint(oe.Inverse(c),u),p=Go(a.rotation+e);return{id:a.id,type:a.type,x:h.x,y:h.y,rotation:p}}));const i=[];o.forEach(({shape:a})=>{var h,p,f;const l=n.getShape(a.id);if(!l)return;const c=n.getShapeUtil(a);if(r==="start"||r==="one-off"){const S=(h=c.onRotateStart)==null?void 0:h.call(c,a);S&&i.push(S)}const u=(p=c.onRotate)==null?void 0:p.call(c,a,l);if(u&&i.push(u),r==="end"||r==="one-off"){const S=(f=c.onRotateEnd)==null?void 0:f.call(c,a,l);S&&i.push(S)}}),i.length>0&&n.updateShapes(i)}const yG=e=>{const{store:n}=e,t=n.query.filterHistory("binding"),r=n.query.records("binding");function s(){const o=r.get(),i=new Map;for(const a of o){const{fromId:l,toId:c}=a,u=i.get(l);u?u.push(a):i.set(l,[a]);const h=i.get(c);h?h.push(a):i.set(c,[a])}return i}return G("arrowBindingsIndex",(o,i)=>{if(Ai(o))return s();const a=o,l=t.getDiffSince(i);if(l===nr)return s();let c;function u(f){c??(c=new Map(a));const S=c.get(f.fromId),y=S==null?void 0:S.filter(v=>v.id!==f.id);y!=null&&y.length?c.set(f.fromId,y):c.delete(f.fromId);const x=c.get(f.toId),m=x==null?void 0:x.filter(v=>v.id!==f.id);m!=null&&m.length?c.set(f.toId,m):c.delete(f.toId)}function h(f){c??(c=new Map(a));let S=c.get(f);return S?S===a.get(f)&&(S=S.slice(0),c.set(f,S)):(S=[],c.set(f,S)),S}function p(f){h(f.fromId).push(f),h(f.toId).push(f)}for(const f of l){for(const S of gt(f.added))p(S);for(const[S,y]of gt(f.updated))u(S),p(y);for(const S of gt(f.removed))u(S)}return c??a})};function SG(e,n,t){const r=e.getShapeMaskedPageBounds(n);return r===void 0?!0:!t.includes(r)}const vG=e=>{function n(t){const r=t.getCurrentPageShapeIds(),s=t.getViewportPageBounds(),o=new Set;return r.forEach(i=>{SG(t,i,s)&&o.add(i)}),o}return G("getCulledShapes",t=>{if(Ai(t))return n(e);const r=n(e);if(t.size!==r.size)return r;for(const s of t)if(!r.has(s))return r;return t})},xG=e=>{const n=e.query.ids("shape"),t=e.query.filterHistory("shape");function r(){const s={},o=n.get(),i=Array(o.size);return o.forEach(a=>i.push(e.get(a))),i.sort(an),i.forEach(a=>{s[a.parentId]||(s[a.parentId]=[]),s[a.parentId].push(a.id)}),s}return G("parentsToChildrenWithIndexes",(s,o)=>{if(Ai(s))return r();const i=t.getDiffSince(o);if(i===nr)return r();if(i.length===0)return s;let a=null;const l=h=>{a||(a={...s}),a[h]?a[h]===s[h]&&(a[h]=[...a[h]]):a[h]=[]},c=new Set;let u;for(let h=0,p=i.length;he.get(f)));p.sort(an),h.splice(0,h.length,...p.map(f=>f.id))}return a??s})},ay=(e,n,t)=>{for(;!Tn(t.parentId);){const r=e.get(t.parentId);if(!r)return!1;t=r}return t.parentId===n},wG=(e,n)=>{const t=e.query.ids("shape");let r=null;function s(){const o=n();return r=o,new Set([...t.get()].filter(i=>ay(e,o,e.get(i))))}return G("_shapeIdsInCurrentPage",(o,i)=>{if(Ai(o))return s();const a=n();if(a!==r)return s();const l=e.history.getDiffSince(i);if(l===nr)return s();const c=new $h(o);for(const h of l){for(const p of Object.values(h.added))Ba(p)&&ay(e,a,p)&&c.add(p.id);for(const[p,f]of Object.values(h.updated))Ba(f)&&(ay(e,a,f)?c.add(f.id):c.remove(f.id));for(const p of Object.keys(h.removed))An(p)&&c.remove(p)}const u=c.get();return u?vc(u.value,u.diff):o})},QM=P.createContext(null);function bG({context:e,editor:n,children:t}){return d.jsx(cg.Provider,{value:n,children:d.jsx(QM.Provider,{value:e,children:t})})}function JM(){const e=P.useContext(QM);return e?{isDarkMode:e.isDarkMode}:null}async function PG(e,n,t={}){var E,k;const r=typeof n[0]=="string"?n:n.map(I=>I.id);if(r.length===0)return;if(!window.document)throw Error("No document");const{scale:s=1,background:o=!1,padding:i=e.options.defaultSvgPadding,preserveAspectRatio:a=!1}=t,l=t.darkMode??e.user.getIsDarkMode(),c=lo({isDarkMode:l}),u=e.getShapeAndDescendantIds(r),h=e.getUnorderedRenderingShapes(!1).filter(({id:I})=>u.has(I));let p=null;if(t.bounds)p=t.bounds;else for(const{id:I}of h){const _=e.getShapeMaskedPageBounds(I);_&&(p?p.union(_):p=_.clone())}if(!p)return;const f=r.length===1&&e.isShapeOfType(e.getShape(r[0]),"frame")?r[0]:null;f||p.expandBy(i);const S=p.width*s,y=p.height*s;try{(k=(E=document.body).focus)==null||k.call(E)}catch{}const x=[],m=new Map,v={isDarkMode:l,addExportDef:I=>{if(m.has(I.key))return;const _=(async()=>{const T=await I.getElement();T&&x.push(d.jsx(P.Fragment,{children:T},x.length))})();m.set(I.key,_)}},w=(await Promise.all(h.map(async({id:I,opacity:_,index:T,backgroundIndex:M})=>{var z,W;if(I===f)return[];const D=e.getShape(I);if(e.isShapeOfType(D,"group"))return[];const $=e.getShapeUtil(D);let j=await((z=$.toSvg)==null?void 0:z.call($,D,v)),O=await((W=$.toBackgroundSvg)==null?void 0:W.call($,D,v));if(!j&&!O){const Y=e.getShapePageBounds(D);j=d.jsx("rect",{width:Y.w,height:Y.h,fill:c.solid,stroke:c.grey.pattern,strokeWidth:1})}let R=e.getShapePageTransform(D).toCssString();"scale"in D.props&&D.props.scale!==1&&(R=`${R} scale(${D.props.scale}, ${D.props.scale})`),j&&(j=d.jsx("g",{transform:R,opacity:_,children:j},D.id)),O&&(O=d.jsx("g",{transform:R,opacity:_,children:O},`bg_${D.id}`));const K=e.getShapeMask(D.id);if(K){const Y=`mask_${D.id.replace(":","_")}`;x.push(d.jsx("clipPath",{id:Y,children:d.jsx("path",{d:`M${K.map(({x:q,y:ae})=>`${q},${ae}`).join("L")}Z`})},x.length)),j&&(j=d.jsx("g",{clipPath:`url(#${Y})`,children:j},D.id)),O&&(O=d.jsx("g",{clipPath:`url(#${Y})`,children:O},`bg_${D.id}`))}const B=[];return j&&B.push({zIndex:T,element:j}),O&&B.push({zIndex:M,element:O}),B}))).flat();return await Promise.all(m.values()),{jsx:d.jsx(bG,{editor:e,context:v,children:d.jsxs("svg",{preserveAspectRatio:a||void 0,direction:"ltr",width:S,height:y,viewBox:`${p.minX} ${p.minY} ${p.width} ${p.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:o?f?c.solid:c.background:"transparent"},children:[d.jsx("defs",{children:x}),w.sort((I,_)=>I.zIndex-_.zIndex).map(({element:I})=>I)]})}),width:S,height:y}}const CG=40;class IG{constructor(n){g(this,"_clickId","");g(this,"_clickTimeout");g(this,"_clickScreenPoint");g(this,"_previousScreenPoint");g(this,"_getClickTimeout",(n,t=ct())=>{this._clickId=t,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===n&&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"}},n==="idle"||n==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)});g(this,"_clickState","idle");g(this,"lastPointerInfo",{});g(this,"handlePointerEvent",n=>{switch(n.name){case"pointer_down":{if(!this._clickState)return n;switch(this._clickScreenPoint=b.From(n.point),this._previousScreenPoint&&b.Dist2(this._previousScreenPoint,this._clickScreenPoint)>CG**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=n,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,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),n}case"pointer_up":{if(!this._clickState)return n;switch(this._clickScreenPoint=b.From(n.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 n}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&b.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),n}return n});g(this,"cancelDoubleClickTimeout",()=>{this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"});this.editor=n}get clickState(){return this._clickState}}class EG{constructor(n){g(this,"_isEdgeScrolling",!1);g(this,"_edgeScrollDuration",-1);this.editor=n}updateEdgeScrolling(n){const{editor:t}=this,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+=n,this._edgeScrollDuration>t.options.edgeScrollDelay){const s=t.options.edgeScrollEaseDuration>0?At.easeInCubic(Math.min(1,this._edgeScrollDuration/(t.options.edgeScrollDelay+t.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*s,y:r.y*s})}}getEdgeProximityFactors(n,t,r,s,o){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=n-l,u=n+l,h=s?0:a,p=o?t:t-a;return cp?-Math.min(1,(u-p)/a):0}getEdgeScroll(){const{editor:n}=this,{inputs:{currentScreenPoint:{x:t,y:r}}}=n,s=n.getViewportScreenBounds(),{isCoarsePointer:o,insets:[i,a,l,c]}=n.getInstanceState(),u=this.getEdgeProximityFactors(t,s.w,o,c,a),h=this.getEdgeProximityFactors(r,s.h,o,i,l);return{x:u,y:h}}moveCameraWhenCloseToEdge(n){const{editor:t}=this;if(!t.inputs.isDragging||t.inputs.isPanning||t.getCameraOptions().isLocked||n.x===0&&n.y===0)return;const 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*n.x*s/i,c=a*n.y*o/i,{x:u,y:h,z:p}=t.getCamera();t.setCamera(new b(u+l,h+c,p))}}class _G{constructor(n){g(this,"isSafari");g(this,"isIos");g(this,"isChromeForIos");g(this,"isFirefox");g(this,"isAndroid");this.editor=n,typeof window<"u"&&"navigator"in window?(this.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),this.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),this.isFirefox=/firefox/i.test(navigator.userAgent),this.isAndroid=/android/i.test(navigator.userAgent)):(this.isSafari=!1,this.isIos=!1,this.isChromeForIos=!1,this.isFirefox=!1,this.isAndroid=!1)}}class kG{constructor(n,t){g(this,"disposeSideEffectListener");this.editor=n,this.disposeSideEffectListener=n.sideEffects.registerAfterChangeHandler("instance",(s,o)=>{s.isFocused!==o.isFocused&&(o.isFocused?this.focus():this.blur(),this.updateContainerClass())});const r=n.getInstanceState().isFocused;t!==r&&n.updateInstanceState({isFocused:!!t}),this.updateContainerClass()}updateContainerClass(){const n=this.editor.getContainer();this.editor.getInstanceState().isFocused?n.classList.add("tl-container__focused"):n.classList.remove("tl-container__focused")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var n;(n=this.disposeSideEffectListener)==null||n.call(this)}}function ic(e){return MG}class TG{constructor(){g(this,"length",0);g(this,"head",null);g(this,"tail",this)}push(n){return new lw(n,this)}toArray(){return Gs}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const MG=new TG;class lw{constructor(n,t){g(this,"length");this.head=n,this.tail=t,this.length=t.length+1}push(n){return new lw(n,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let n=this;return{next(){if(n.length){const t=n.head;return n=n.tail,{value:t,done:!1}}else return{value:void 0,done:!0}}}}}class AG{constructor(n){g(this,"store");g(this,"dispose");g(this,"state","recording");g(this,"pendingDiff",new OG);g(this,"stacks",Mt("HistoryManager.stacks",{undos:ic(),redos:ic()},{isEqual:(n,t)=>n.undos===t.undos&&n.redos===t.redos}));g(this,"annotateError");g(this,"_isInBatch",!1);g(this,"batch",(n,t)=>{const r=this.state;r!=="paused"&&(t!=null&&t.history)&&(this.state=jG[t.history]);try{if(this._isInBatch)return gs(n),this;this._isInBatch=!0;try{gs(n)}catch(s){throw this.annotateError(s),s}finally{this._isInBatch=!1}return this}finally{this.state=r}});g(this,"_undo",({pushToRedoStack:n,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=pT(a),c=Sv(a);n&&!l&&(i=i.push({type:"diff",diff:a}));let u=!1;if(l)for(;((s=o.head)==null?void 0:s.type)==="stop";){const h=o.head;if(o=o.tail,n&&(i=i.push(h)),h.id===t){u=!0;break}}if(!u)e:for(;o.head;){const h=o.head;switch(o=o.tail,n&&(i=i.push(h)),h.type){case"diff":Gc(c,[Sv(h.diff)]);break;case"stop":if(!t||h.id===t)break e;break;default:cn(h)}}this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:o,redos:i})}finally{this.state=r}return this});g(this,"undo",()=>(this._undo({pushToRedoStack:!0}),this));g(this,"redo",()=>{var t;const n=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=qp();for(;s.head;){const i=s.head;if(r=r.push(i),s=s.tail,i.type==="diff")Gc(o,[i.diff]);else break}this.store.applyDiff(o,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:s})}finally{this.state=n}return this});g(this,"bail",()=>(this._undo({pushToRedoStack:!1}),this));g(this,"bailToMark",n=>(this._undo({pushToRedoStack:!1,toMark:n}),this));g(this,"squashToMark",n=>{var o;let t=this.stacks.get().undos;const r=[];for(;t.head&&!(t.head.type==="stop"&&t.head.id===n);)t.head.type==="diff"&&r.push(t.head.diff),t=t.tail;if(!t.head||((o=t.head)==null?void 0:o.id)!==n)return console.error("Could not find mark to squash to: ",n),this;if(r.length===0)return this;const s=qp();return Gc(s,r.reverse()),this.stacks.update(({redos:i})=>({undos:t.push({type:"diff",diff:s}),redos:i})),this});g(this,"mark",(n=ct())=>(gs(()=>{this.flushPendingDiff(),this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"stop",id:n}),redos:r}))}),n));this.store=n.store,this.annotateError=n.annotateError??Su,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:ic()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(t.changes);break;case"paused":break;default:cn(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const n=this.pendingDiff.clear();this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"diff",diff:n}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}clear(){this.stacks.set({undos:ic(),redos:ic()}),this.pendingDiff.clear()}debug(){const{undos:n,redos:t}=this.stacks.get();return{undos:n.toArray(),redos:t.toArray(),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const jG={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class OG{constructor(){g(this,"diff",qp());g(this,"isEmptyAtom",Mt("PendingDiff.isEmpty",!0))}clear(){const n=this.diff;return this.diff=qp(),this.isEmptyAtom.set(!0),n}isEmpty(){return this.isEmptyAtom.get()}apply(n){Gc(this.diff,[n]),this.isEmptyAtom.set(pT(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}class DG{constructor(n){g(this,"scribbleItems",new Map);g(this,"state","paused");g(this,"addScribble",(n,t=ct())=>{const r={id:t,scribble:{id:t,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...n,state:"starting"},timeoutMs:0,delayRemaining:n.delay??0,prev:null,next:null};return this.scribbleItems.set(t,r),r});g(this,"stop",n=>{const t=this.scribbleItems.get(n);if(!t)throw Error(`Scribble with id ${n} not found`);return t.delayRemaining=Math.min(t.delayRemaining,200),t.scribble.state="stopping",t});g(this,"addPoint",(n,t,r)=>{const s=this.scribbleItems.get(n);if(!s)throw Error(`Scribble with id ${n} not found`);const{prev:o}=s,i={x:t,y:r,z:.5};return(!o||b.Dist(o,i)>=1)&&(s.next=i),s});g(this,"tick",n=>{this.scribbleItems.size!==0&&this.editor.run(()=>{this.scribbleItems.forEach(t=>{if(t.scribble.state==="starting"){const{next:l,prev:c}=t;l&&l!==c&&(t.prev=l,t.scribble.points.push(l)),t.scribble.points.length>8&&(t.scribble.state="active");return}t.delayRemaining>0&&(t.delayRemaining=Math.max(0,t.delayRemaining-n)),t.timeoutMs+=n,t.timeoutMs>=16&&(t.timeoutMs=0);const{delayRemaining:r,timeoutMs:s,prev:o,next:i,scribble:a}=t;switch(a.state){case"active":{i&&i!==o?(t.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):s===0&&(a.points.length>1?a.points.shift():t.delayRemaining=a.delay);break}case"stopping":{if(t.delayRemaining===0&&s===0){if(a.points.length===1){this.scribbleItems.delete(t.id);return}a.shrink&&(a.size=Math.max(1,a.size*(1-a.shrink))),a.points.shift()}break}}}),this.editor.updateInstanceState({scribbles:Array.from(this.scribbleItems.values()).map(({scribble:t})=>({...t,points:[...t.points]})).slice(-5)})})});this.editor=n}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}}var RG=Object.defineProperty,LG=Object.getOwnPropertyDescriptor,fg=(e,n,t,r)=>{for(var s=LG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&RG(n,t,s),s};const ue=e=>Math.round(e*10**8)/10**8;function Ls(e,n,t,r,s){const o=e.filter(a=>(r==="forward"?a.startNode.id===n:a.endNode.id===n)&&ue(a.length)===ue(t)&&Lr(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=Ls(e,l,t,r,Lr(a.breadthIntersection[0],a.breadthIntersection[1],s[0],s[1]));o.push(...c)}}),o}function $G(e){e.sort((n,t)=>t.gaps.length-n.gaps.length);for(let n=e.length-1;n>0;n--){const t=e[n];for(let r=n-1;r>=0;r--){const s=e[r];if(s.direction===t.direction&&t.gaps.every(o=>s.gaps.some(i=>ue(o.startEdge[0].x)===ue(i.startEdge[0].x)&&ue(o.startEdge[0].y)===ue(i.startEdge[0].y)&&ue(o.startEdge[1].x)===ue(i.startEdge[1].x)&&ue(o.startEdge[1].y)===ue(i.startEdge[1].y))&&s.gaps.some(i=>ue(o.endEdge[0].x)===ue(i.endEdge[0].x)&&ue(o.endEdge[0].y)===ue(i.endEdge[0].y)&&ue(o.endEdge[1].x)===ue(i.endEdge[1].x)&&ue(o.endEdge[1].y)===ue(i.endEdge[1].y)))){e.splice(n,1);break}}}}class Qu{constructor(n){g(this,"editor");this.manager=n,this.editor=n.editor}getSnapPointsCache(){const{editor:n}=this;return n.store.createComputedCache("snapPoints",t=>{const r=n.getShapePageTransform(t.id);if(!r)return;const o=n.getShapeUtil(t).getBoundsSnapGeometry(t).points??n.getShapeGeometry(t).bounds.cornersAndCenter;if(!(!r||!o))return o.map((i,a)=>{const{x:l,y:c}=oe.applyToPoint(r,i);return{x:l,y:c,id:`${t.id}:${a}`}})})}getSnapPoints(n){return this.getSnapPointsCache().get(n)??[]}getSnappablePoints(){const n=this.getSnapPointsCache(),t=this.manager.getSnappableShapes(),r=[];for(const s of t){const o=n.get(s);o&&r.push(...o)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),n=>({id:n,pageBounds:xr(this.editor.getShapePageBounds(n))}))}getVisibleGaps(){const n=[],t=[];let r,s;const o=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;aa.pageBounds.minY-l.pageBounds.minY);for(let a=0;a({id:"selection:"+C,x:v+s.x,y:w+s.y})),c=i,u=[],h=[],p=new b(o,o);this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const f=new b(n==="x"?0:((x=u[0])==null?void 0:x.nudge)??0,n==="y"?0:((m=h[0])==null?void 0:m.nudge)??0);p.x=0,p.y=0,u.length=0,h.length=0,l.forEach(v=>{v.x+=f.x,v.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const S=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:h}),y=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h});return this.manager.setIndicators([...y,...S]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:n,dragDelta:t,handle:r,isAspectRatioLocked:s,isResizingFromCenter:o}){var I,_;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=Q.Resize(n,r,o?t.x*2:t.x,o?t.y*2:t.y,s);let u=r;l<0&&(u=KK(u)),c<0&&(u=HK(u)),o&&(a.center=n.center);const h=u==="top"||u==="bottom",p=u==="left"||u==="right",f=VC(u,a),S=this.getSnappablePoints(),y=[],x=[],m=new b(i,i);this.collectPointSnaps({minOffset:m,nearestSnapsX:y,nearestSnapsY:x,otherNodeSnapPoints:S,selectionSnapPoints:f});const v=new b(h?0:((I=y[0])==null?void 0:I.nudge)??0,p?0:((_=x[0])==null?void 0:_.nudge)??0);if(s&&WK(u)&&v.len()!==0){const T=y.length&&x.length?Math.abs(v.x)n.width&&ue(Math.abs(c))<=ue(t.x)){ue(Math.abs(c))C==="gap_center"),w=v&&Lr(a.breadthIntersection[0],a.breadthIntersection[1],v.gap.breadthIntersection[0],v.gap.breadthIntersection[1]);v&&v.gap.length>a.length&&w?r[r.indexOf(v)]=m:(!v||!w)&&r.push(m)}const h=a.startNode.pageBounds.minX-a.length,p=n.maxX,f=h-p;ue(Math.abs(f))<=ue(t.x)&&(ue(Math.abs(f))n.height&&ue(Math.abs(c))<=ue(t.y)){ue(Math.abs(c))C==="gap_center"),w=v&&oc(v.gap.breadthIntersection[0],v.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);v&&v.gap.length>a.length&&w?s[s.indexOf(v)]=m:(!v||!w)&&s.push(m);continue}const h=a.startNode.pageBounds.minY-a.length,p=n.maxY,f=h-p;ue(Math.abs(f))<=ue(t.y)&&(ue(Math.abs(f))0){for(const o of n)if(o.type==="points"){const i=ue(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=ue(o.points.otherPoint.y);s[i]||(s[i]=[]),s[i].push(o.points)}}return Object.values(r).concat(Object.values(s)).map(o=>({id:ct(),type:"points",points:R0(o.map(i=>b.From(i.otherPoint)).concat(o.map(i=>b.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:n,nearestSnapsX:t,nearestSnapsY:r}){const{vertical:s,horizontal:o}=this.getVisibleGaps(),i={top:n.sides[0],right:n.sides[1],bottom:[n.corners[3],n.corners[2]],left:[n.corners[0],n.corners[3]]},a=[];if(t.length>0)for(const l of t){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const y=(f-n.width)/2,x=Lr(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ct(),gaps:[...Ls(o,h.id,y,"backward",x),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:S},...Ls(o,p.id,y,"forward",x)]});break}case"gap_duplicate":{const y=Lr(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ct(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(x=>x.clone().addXY(-h.pageBounds.width,0))},{startEdge:u,endEdge:S},...Ls(o,p.id,f,"forward",y)]:[...Ls(o,h.id,f,"backward",y),{startEdge:u,endEdge:S},{startEdge:S.map(x=>x.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:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const y=(f-n.height)/2,x=Lr(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ct(),gaps:[...Ls(s,h.id,y,"backward",x),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:S},...Ls(s,l.gap.endNode.id,y,"forward",x)]});break}case"gap_duplicate":{const y=Lr(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ct(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(x=>x.clone().addXY(0,-h.pageBounds.height))},{startEdge:u,endEdge:S},...Ls(s,p.id,f,"forward",y)]:[...Ls(s,h.id,f,"backward",y),{startEdge:u,endEdge:S},{startEdge:S.map(x=>x.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return $G(a),a}}fg([G],Qu.prototype,"getSnapPointsCache");fg([G],Qu.prototype,"getSnappablePoints");fg([G],Qu.prototype,"getSnappableGapNodes");fg([G],Qu.prototype,"getVisibleGaps");function VC(e,n){const{minX:t,maxX:r,minY:s,maxY:o}=n,i=[];switch(e){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:t,y:s})}switch(e){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:s})}switch(e){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:o})}switch(e){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:t,y:o})}return i}var NG=Object.defineProperty,FG=Object.getOwnPropertyDescriptor,zG=(e,n,t,r)=>{for(var s=FG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&NG(n,t,s),s};const BG=()=>null,UG=()=>[];class eA{constructor(n){g(this,"editor");this.manager=n,this.editor=n.editor}getSnapGeometryCache(){const{editor:n}=this;return n.store.createComputedCache("handle snap geometry",t=>{const r=n.getShapeUtil(t).getHandleSnapGeometry(t);return{outline:r.outline===void 0?n.getShapeGeometry(t):r.outline,points:r.points??[],getSelfSnapOutline:r.getSelfSnapOutline??BG,getSelfSnapPoints:r.getSelfSnapPoints??UG}})}*iterateSnapPointsInPageSpace(n,t){var s,o;const r=(s=this.getSnapGeometryCache().get(n))==null?void 0:s.getSelfSnapPoints(t);if(r&&r.length){const i=xr(this.editor.getShapePageTransform(n));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.points;if(!a||!a.length)continue;const l=xr(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(n,t){var s,o;const r=(s=this.getSnapGeometryCache().get(n))==null?void 0:s.getSelfSnapOutline(t);r&&(yield{shapeId:n,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(o=this.getSnapGeometryCache().get(i))==null?void 0:o.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:r}){const s=this.manager.getSnapThreshold();let o=s,i=null;for(const c of this.iterateSnapPointsInPageSpace(n,t))b.DistMin(r,c,o)&&(o=b.Dist(r,c),i=c);if(i)return i;let a=s,l=null;for(const{shapeId:c,outline:u}of this.iterateSnapOutlines(n,t)){const h=xr(this.editor.getShapePageTransform(c)),p=this.editor.getPointInShapeSpace(c,r),f=u.nearestPoint(p),S=h.applyToPoint(f);b.DistMin(r,S,a)&&(a=b.Dist(r,S),l=S)}return l||null}snapHandle({currentShapeId:n,handle:t}){const s=xr(this.editor.getShapePageTransform(n)).applyToPoint(t),o=this.getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:s});return o?(this.manager.setIndicators([{id:ct(),type:"points",points:[o]}]),{nudge:b.Sub(o,s)}):null}}zG([G],eA.prototype,"getSnapGeometryCache");var HG=Object.defineProperty,KG=Object.getOwnPropertyDescriptor,cw=(e,n,t,r)=>{for(var s=KG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&HG(n,t,s),s};let gg=class{constructor(n){g(this,"shapeBounds");g(this,"handles");g(this,"_snapIndicators",Mt("snapLines",void 0));this.editor=n,this.shapeBounds=new Qu(this),this.handles=new eA(this)}getIndicators(){return this._snapIndicators.get()??Gs}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(n){this._snapIndicators.set(n)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:n}=this,t=n.getViewportPageBounds(),r=n.getSelectedShapeIds(),s=new Set,o=i=>{if(An(i)){const l=n.getShape(i);l&&n.isShapeOfType(l,"frame")&&s.add(i)}const a=n.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=n.getShape(l);if(!c||!n.getShapeUtil(c).canSnap(c))continue;const h=n.getShapePageBounds(l);if(h&&t.includes(h)){if(n.isShapeOfType(c,"group")){o(l);continue}s.add(l)}}};return o(this.getCurrentCommonAncestor()??n.getCurrentPageId()),s}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}};cw([G],gg.prototype,"getSnapThreshold");cw([G],gg.prototype,"getSnappableShapes");cw([G],gg.prototype,"getCurrentCommonAncestor");const WG=/\r?\n|\r/g;function YC(e){return e.replace(WG,` `).split(` `).map(n=>n||" ").join(` -`)}const GG={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},VG=/\s/;class YG{constructor(n){g(this,"baseElm");g(this,"measureText",(n,t)=>{var i;const r=(i=this.baseElm)==null?void 0:i.cloneNode();this.baseElm.insertAdjacentElement("afterend",r),r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("font-family",t.fontFamily),r.style.setProperty("font-style",t.fontStyle),r.style.setProperty("font-weight",t.fontWeight),r.style.setProperty("font-size",t.fontSize+"px"),r.style.setProperty("line-height",t.lineHeight*t.fontSize+"px"),r.style.setProperty("max-width",t.maxWidth===null?null:t.maxWidth+"px"),r.style.setProperty("min-width",t.minWidth===null?null:t.minWidth+"px"),r.style.setProperty("padding",t.padding),r.style.setProperty("overflow-wrap",t.disableOverflowWrapBreaking?"normal":"break-word"),r.textContent=YC(n);const s=r.scrollWidth,o=r.getBoundingClientRect();return r.remove(),{x:0,y:0,w:o.width,h:o.height,scrollWidth:s}});this.editor=n;const t=this.editor.getContainer(),r=document.createElement("div");r.classList.add("tl-text"),r.classList.add("tl-text-measure"),r.tabIndex=-1,t.appendChild(r),this.baseElm=r,n.disposables.add(()=>{r.remove()})}measureElementTextNodeSpans(n,{shouldTruncateToFirstLine:t=!1}={}){const r=[],s=n.getBoundingClientRect(),o=-s.left,i=-s.top,a=new Range,l=n.childNodes[0];let c=0,u=null,h=null,p=0,f=0,S=!1;for(const m of n.childNodes)if(m.nodeType===Node.TEXT_NODE)for(const x of m.textContent??""){a.setStart(l,c),a.setEnd(l,c+x.length);const y=a.getClientRects(),v=y[y.length-1],w=v.top+i,C=v.left+o,E=v.right+o,k=C{var n;this.isPaused=!1,(n=this.cancelRaf)==null||n.call(this),this.cancelRaf=XC(this.tick),this.now=Date.now()});g(this,"tick",()=>{if(this.isPaused)return;const n=Date.now(),t=n-this.now;this.now=n,this.updatePointerVelocity(t),this.editor.emit("frame",t),this.editor.emit("tick",t),this.cancelRaf=XC(this.tick)});g(this,"dispose",()=>{var n;this.isPaused=!0,(n=this.cancelRaf)==null||n.call(this)});g(this,"prevPoint",new b);g(this,"updatePointerVelocity",n=>{const{prevPoint:t,editor:{inputs:{currentScreenPoint:r,pointerVelocity:s}}}=this;if(n===0)return;const o=b.Sub(r,t);this.prevPoint=r.clone();const i=o.len(),a=i?o.div(i):new b(0,0),l=s.clone().lrp(a.mul(i/n),.5);Math.abs(l.x)<.01&&(l.x=0),Math.abs(l.y)<.01&&(l.y=0),s.equals(l)||(this.editor.inputs.pointerVelocity=l)});this.editor=n,this.editor.disposables.add(this.dispose),this.start()}}var qG=Object.defineProperty,ZG=Object.getOwnPropertyDescriptor,Mr=(e,n,t,r)=>{for(var s=ZG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&qG(n,t,s),s};class hr{constructor(n,t){g(this,"systemColorScheme",Mt("systemColorScheme","light"));g(this,"updateUserPreferences",n=>{this.user.setUserPreferences({...this.user.userPreferences.get(),...n})});if(this.user=n,this.inferDarkMode=t,typeof window>"u"||!("matchMedia"in window))return;const r=window.matchMedia("(prefers-color-scheme: dark)");r!=null&&r.matches&&this.systemColorScheme.set("dark"),r==null||r.addEventListener("change",s=>{s.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")})}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),isSnapMode:this.getIsSnapMode(),colorScheme:this.user.userPreferences.get().colorScheme,isDarkMode:this.getIsDarkMode(),isWrapMode:this.getIsWrapMode(),isDynamicResizeMode:this.getIsDynamicResizeMode()}}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??Ds.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??Ds.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??Ds.name}getLocale(){return this.user.userPreferences.get().locale??Ds.locale}getColor(){return this.user.userPreferences.get().color??Ds.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??Ds.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??Ds.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??Ds.isDynamicSizeMode}getIsPasteAtCursorMode(){return this.user.userPreferences.get().isPasteAtCursorMode??Ds.isPasteAtCursorMode}}Mr([G],hr.prototype,"getUserPreferences");Mr([G],hr.prototype,"getIsDarkMode");Mr([G],hr.prototype,"getEdgeScrollSpeed");Mr([G],hr.prototype,"getAnimationSpeed");Mr([G],hr.prototype,"getId");Mr([G],hr.prototype,"getName");Mr([G],hr.prototype,"getLocale");Mr([G],hr.prototype,"getColor");Mr([G],hr.prototype,"getIsSnapMode");Mr([G],hr.prototype,"getIsWrapMode");Mr([G],hr.prototype,"getIsDynamicResizeMode");Mr([G],hr.prototype,"getIsPasteAtCursorMode");const QG={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"},JG=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class se{constructor(n,t){g(this,"performanceTracker");g(this,"id");g(this,"type");g(this,"shapeType");g(this,"initial");g(this,"children");g(this,"isLockable");g(this,"parent");g(this,"_path");g(this,"_current");g(this,"_isActive");g(this,"transition",(n,t={})=>{var o;const r=n.split(".");let s=this;for(let i=0;i{var s;const t=QG[n.name],r=this._current.__unsafe__getWithoutCapture();(s=this[t])==null||s.call(this,n),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(n)});g(this,"enter",(n,t)=>{var r;if(xt.measurePerformance.get()&&JG.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,n,t),this.children&&this.initial&&this.getIsActive()){const s=this.children[this.initial];this._current.set(s),s.enter(n,t)}});g(this,"exit",(n,t)=>{var r,s;xt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,n,t),this.getIsActive()||(s=this.getCurrent())==null||s.exit(n,t)});g(this,"_currentToolIdMask",Mt("curent tool id mask",void 0));g(this,"onWheel");g(this,"onPointerDown");g(this,"onPointerMove");g(this,"onLongPress");g(this,"onPointerUp");g(this,"onDoubleClick");g(this,"onTripleClick");g(this,"onQuadrupleClick");g(this,"onRightClick");g(this,"onMiddleClick");g(this,"onKeyDown");g(this,"onKeyUp");g(this,"onKeyRepeat");g(this,"onCancel");g(this,"onComplete");g(this,"onInterrupt");g(this,"onTick");g(this,"onEnter");g(this,"onExit");this.editor=n;const{id:r,children:s,initial:o,isLockable:i}=this.constructor;this.id=r,this._isActive=Mt("toolIsActive"+this.id,!1),this._current=Mt("toolState"+this.id,void 0),this._path=G("toolPath"+this.id,()=>{const a=this.getCurrent();return this.id+(a?`.${a.getPath()}`:"")}),this.parent=t??{},this.parent?s&&o?(this.type="branch",this.initial=o,this.children=Object.fromEntries(s().map(a=>[a.id,new a(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(a=>[a.id,new a(this.editor,this)])),this._current.set(this.children[this.initial]))),this.isLockable=i,this.performanceTracker=new G2}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(n){this._currentToolIdMask.set(n)}}g(se,"id"),g(se,"initial"),g(se,"children"),g(se,"isLockable",!0);class Hh extends se{constructor(){super(...arguments);g(this,"onKeyDown",t=>{var r;switch(t.code){case"KeyZ":{if(!(t.shiftKey||t.ctrlKey)){const s=this.getCurrent();s&&((r=s.getCurrent())==null?void 0:r.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...t,onInteractionEnd:s.id})}break}}})}}g(Hh,"id","root"),g(Hh,"initial",""),g(Hh,"children",()=>[]);var eV=Object.defineProperty,tV=Object.getOwnPropertyDescriptor,ne=(e,n,t,r)=>{for(var s=tV(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&eV(n,t,s),s};class Z extends XW{constructor({store:t,user:r,shapeUtils:s,bindingUtils:o,tools:i,getContainer:a,cameraOptions:l,initialState:c,autoFocus:u,inferDarkMode:h,options:p}){super();g(this,"options");g(this,"store");g(this,"root");g(this,"disposables",new Set);g(this,"isDisposed",!1);g(this,"_tickManager");g(this,"snaps");g(this,"timers");g(this,"user");g(this,"textMeasure");g(this,"environment");g(this,"scribbles");g(this,"sideEffects");g(this,"edgeScrollManager");g(this,"focusManager");g(this,"getContainer");g(this,"shapeUtils");g(this,"styleProps");g(this,"bindingUtils");g(this,"history");g(this,"_shouldIgnoreShapeLock",!1);g(this,"_crashingError",null);g(this,"_updateInstanceState",(t,r)=>{this.run(()=>{this.store.put([{...this.getInstanceState(),...t}])},r)});g(this,"_isChangingStyleTimeout",-1);g(this,"setCursor",t=>(this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...t}}),this));g(this,"_updateCurrentPageState",t=>{this.store.update(t.id??this.getCurrentPageState().id,r=>({...r,...t}))});g(this,"_cameraOptions",Mt("camera options",PC));g(this,"_viewportAnimation",null);g(this,"_willSetInitialBounds",!0);g(this,"_isLockedOnFollowingUser",Mt("isLockedOnFollowingUser",!1));g(this,"_cameraState",Mt("camera state","idle"));g(this,"_cameraStateTimeoutRemaining",0);g(this,"_decayCameraStateTimeout",t=>{this._cameraStateTimeoutRemaining-=t,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"))});g(this,"_tickCameraState",()=>{this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))});g(this,"_currentPageShapeIds");g(this,"_parentIdsToChildIds");g(this,"animatingShapes",new Map);g(this,"_updateShapes",t=>{this.getInstanceState().isReadonly||this.run(()=>{var i,a;const r=[];let s,o;for(let l=0,c=t.length;l{this.inputs.shiftKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Shift",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"ShiftLeft"})});g(this,"_altKeyTimeout",-1);g(this,"_setAltKeyTimeout",()=>{this.inputs.altKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Alt",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"AltLeft"})});g(this,"_ctrlKeyTimeout",-1);g(this,"_setCtrlKeyTimeout",()=>{this.inputs.ctrlKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Ctrl",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"ControlLeft"})});g(this,"_restoreToolId","select");g(this,"_pinchStart",1);g(this,"_didPinch",!1);g(this,"_selectedShapeIdsAtPointerDown",[]);g(this,"_longPressTimeout",-1);g(this,"capturedPointerId",null);g(this,"performanceTracker");g(this,"performanceTrackerTimeout",-1);g(this,"dispatch",t=>(this._pendingEventsForNextTick.push(t),t.type==="pointer"&&t.name==="pointer_move"||t.type==="wheel"||t.type==="pinch"||this._flushEventsForTick(0),this));g(this,"_pendingEventsForNextTick",[]);g(this,"_flushEventForTick",t=>{if(this.getCrashingError())return this;const{inputs:r}=this,{type:s}=t;if(t.type==="misc"){(t.name==="cancel"||t.name==="complete")&&(this.inputs.isDragging=!1,this.inputs.isPanning&&(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0}))),this.root.handleEvent(t);return}t.shiftKey?(clearTimeout(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,r.shiftKey=!0):!t.shiftKey&&r.shiftKey&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=this.timers.setTimeout(this._setShiftKeyTimeout,150)),t.altKey?(clearTimeout(this._altKeyTimeout),this._altKeyTimeout=-1,r.altKey=!0):!t.altKey&&r.altKey&&this._altKeyTimeout===-1&&(this._altKeyTimeout=this.timers.setTimeout(this._setAltKeyTimeout,150)),t.ctrlKey?(clearTimeout(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,r.ctrlKey=!0):!t.ctrlKey&&r.ctrlKey&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=this.timers.setTimeout(this._setCtrlKeyTimeout,150));const{originPagePoint:o,currentPagePoint:i}=r;r.isPointing||(r.isDragging=!1);const a=this.store.unsafeGetWithoutCapture(mn),l=this.store.get(this._getCurrentPageStateId()),c=this._cameraOptions.__unsafe__getWithoutCapture();switch(s){case"pinch":{if(c.isLocked)return;switch(clearTimeout(this._longPressTimeout),this._updateInputsFromEvent(t),t.name){case"pinch_start":{if(r.isPinching)return;r.isEditing||(this._pinchStart=this.getCamera().z,this._selectedShapeIdsAtPointerDown.length||(this._selectedShapeIdsAtPointerDown=[...l.selectedShapeIds]),this._didPinch=!0,r.isPinching=!0,this.interrupt());return}case"pinch":{if(!r.isPinching)return;const{point:{z:u=1},delta:{x:h,y:p}}=t,{x:f,y:S}=b.SubXY(t.point,a.screenBounds.x,a.screenBounds.y);this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:m,y:x,z:y}=Fd(()=>this.getCamera()),{panSpeed:v,zoomSpeed:w}=c;this._setCamera(new b(m+h*v/y-f/y+f/(u*w),x+p*v/y-S/y+S/(u*w),u*w),{immediate:!0});return}case"pinch_end":{if(!r.isPinching)return this;r.isPinching=!1;const{_selectedShapeIdsAtPointerDown:u}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,u.length>0&&this.once("tick",()=>{this._didPinch||this.setSelectedShapes(u)}));return}}}case"wheel":{if(c.isLocked)return;if(this._updateInputsFromEvent(t),!this.getIsMenuOpen()){const{panSpeed:u,zoomSpeed:h,wheelBehavior:p}=c;if(p!=="none"){this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:f,y:S,z:m}=Fd(()=>this.getCamera()),{x,y,z:v=0}=t.delta;let w=p;switch(r.ctrlKey&&(w=p==="pan"?"zoom":"pan"),w){case"zoom":{const{x:C,y:E}=this.inputs.currentScreenPoint;let k=v;p==="zoom"&&(Math.abs(y)>10?k=10*Math.sign(y)/100:k=y/100);const I=m+(k??0)*h*m;this._setCamera(new b(f+(C/I-C)-(C/m-C),S+(E/I-E)-(E/m-E),I),{immediate:!0}),this.maybeTrackPerformance("Zooming");return}case"pan":{this._setCamera(new b(f+x*u/m,S+y*u/m,m),{immediate:!0}),this.maybeTrackPerformance("Panning");return}}}}break}case"pointer":{if(r.isPinching)return;this._updateInputsFromEvent(t);const{isPen:u}=t,{isPenMode:h}=a;switch(t.name){case"pointer_down":{if(h&&!u)return;if(this.clearOpenMenus(),this.inputs.isPanning||(this._longPressTimeout=this.timers.setTimeout(()=>{this.dispatch({...t,point:this.inputs.currentScreenPoint,name:"long_press"})},this.options.longPressDurationMs)),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),t.button===IC&&(this.capturedPointerId=t.pointerId),r.buttons.add(t.button),r.isPointing=!0,r.isDragging=!1,!h&&u&&this.updateInstanceState({isPenMode:!0}),t.button===EC?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):t.button===Gd&&(this.inputs.isPanning||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout)),this.inputs.isPanning)return this.stopCameraAnimation(),this.setCursor({type:"grabbing",rotation:0}),this;break}case"pointer_move":{if(!u&&h)return;const{x:p,y:f,z:S}=Fd(()=>this.getCamera());if(this.inputs.isPanning&&this.inputs.isPointing){const{currentScreenPoint:m,previousScreenPoint:x}=this.inputs,{panSpeed:y}=c,v=b.Sub(m,x);this.setCamera(new b(p+v.x*y/S,f+v.y*y/S,S),{immediate:!0}),this.maybeTrackPerformance("Panning");return}r.isPointing&&!r.isDragging&&b.Dist2(o,i)*this.getZoomLevel()>(a.isCoarsePointer?this.options.coarseDragDistanceSquared:this.options.dragDistanceSquared)/S&&(r.isDragging=!0,clearTimeout(this._longPressTimeout));break}case"pointer_up":{if(r.isDragging=!1,r.isPointing=!1,clearTimeout(this._longPressTimeout),r.buttons.delete(t.button),this.getIsMenuOpen()||a.isPenMode&&!u)return;if(this.capturedPointerId===t.pointerId&&(this.capturedPointerId=null,t.button=0),r.isPanning){r.keys.has("Space")||(r.isPanning=!1);const p=this.inputs.pointerVelocity,f=Math.min(2,p.len());switch(t.button){case IC:{this.setCursor({type:"grab",rotation:0});break}case Gd:this.inputs.keys.has(" ")?this.setCursor({type:"grab",rotation:0}):this.setCursor({type:this._prevCursor,rotation:0})}f>0&&this.slideCamera({speed:f,direction:p})}else t.button===EC&&(this.complete(),this.setCurrentTool(this._restoreToolId));break}}break}case"keyboard":{switch(t.key==="ShiftRight"&&(t.key="ShiftLeft"),t.key==="AltRight"&&(t.key="AltLeft"),t.code==="ControlRight"&&(t.code="ControlLeft"),t.name){case"key_down":{r.keys.add(t.code),t.code==="Space"&&!t.ctrlKey&&(this.inputs.isPanning||(this._prevCursor=a.cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout),this.setCursor({type:this.inputs.isPointing?"grabbing":"grab",rotation:0}));break}case"key_up":{r.keys.delete(t.code),t.code==="Space"&&(this.inputs.buttons.has(Gd)||(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0})));break}}break}}if(t.type==="pointer"){t.button===Gd?t.name="middle_click":t.button===J0&&(t.name="right_click");const{isPenMode:u}=this.store.unsafeGetWithoutCapture(mn);if(t.isPen===u){const h=this._clickManager.handlePointerEvent(t);if(t.name!==h.name){this.root.handleEvent(t),this.emit("event",t),this.root.handleEvent(h),this.emit("event",h);return}}}return this.root.handleEvent(t),this.emit("event",t),this});this.options={...lG,...p},this.store=t,this.disposables.add(this.store.dispose.bind(this.store)),this.history=new AG({store:t,annotateError:T=>{this.annotateError(T,{origin:"history.batch",willCrashApp:!0}),this.crash(T)}}),this.snaps=new gg(this),this.timers=new U9,this.disposables.add(this.timers.dispose.bind(this.timers)),this._cameraOptions.set({...PC,...l}),this.user=new hr(r??zM(),h??!1),this.getContainer=a??(()=>document.body),this.textMeasure=new YG(this),this._tickManager=new XG(this);class f extends Hh{}g(f,"initial",c??""),this.root=new f(this),this.root.children={};const S=qM(s),m={},x={},y=new Map;for(const T of S){const M=new T(this);m[T.type]=M;const D=ST(T.props??{});x[T.type]=D;for(const $ of D.keys())if(!y.has($.id))y.set($.id,$);else if(y.get($.id)!==$)throw Error(`Multiple style props with id "${$.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=m,this.styleProps=x;const v=VM(o),w={};for(const T of v){const M=new T(this);w[T.type]=M}this.bindingUtils=w;for(const T of[...i]){if(ms(this.root.children,T.id))throw Error(`Can't override tool with id "${T.id}"`);this.root.children[T.id]=new T(this,this.root)}this.environment=new _G(this),this.scribbles=new DG(this);const C=(T,M)=>{let D=null;const $=T.selectedShapeIds.filter(R=>!M.has(R));$.length!==T.selectedShapeIds.length&&(D||(D={...T}),D.selectedShapeIds=$);const j=T.erasingShapeIds.filter(R=>!M.has(R));j.length!==T.erasingShapeIds.length&&(D||(D={...T}),D.erasingShapeIds=j),T.hoveredShapeId&&M.has(T.hoveredShapeId)&&(D||(D={...T}),D.hoveredShapeId=null),T.editingShapeId&&M.has(T.editingShapeId)&&(D||(D={...T}),D.editingShapeId=null);const O=T.hintingShapeIds.filter(R=>!M.has(R));return O.length!==T.hintingShapeIds.length&&(D||(D={...T}),D.hintingShapeIds=O),T.focusedGroupId&&M.has(T.focusedGroupId)&&(D||(D={...T}),D.focusedGroupId=null),D};this.sideEffects=this.store.sideEffects;let E=new Map;const k=new Set,I=new Set;let _=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var T,M,D,$;k.clear();for(const j of I){I.delete(j);const O=this.getShape(j);if(!O)continue;const R=this.getShapeUtil(O),K=(T=R.onChildrenChange)==null?void 0:T.call(R,O);K!=null&&K.length&&this.updateShapes(K)}if(_.size){const j=_;_=new Set;for(const O of j){const R=this.getBindingUtil(O);(M=R.onOperationComplete)==null||M.call(R)}}if(E.size){const j=E;E=new Map;for(const O of j.values())($=(D=this.getBindingUtil(O.binding)).onAfterDelete)==null||$.call(D,O)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(T,M)=>{var D,$,j,O;for(const R of this.getBindingsInvolvingShape(M))_.add(R.type),R.fromId===M.id&&(($=(D=this.getBindingUtil(R)).onAfterChangeFromShape)==null||$.call(D,{binding:R,shapeBefore:T,shapeAfter:M})),R.toId===M.id&&((O=(j=this.getBindingUtil(R)).onAfterChangeToShape)==null||O.call(j,{binding:R,shapeBefore:T,shapeAfter:M}));if(T.parentId!==M.parentId){const R=K=>{var z,W,Y,q;const B=this.getShape(K);if(B)for(const ae of this.getBindingsInvolvingShape(B))_.add(ae.type),ae.fromId===B.id&&((W=(z=this.getBindingUtil(ae)).onAfterChangeFromShape)==null||W.call(z,{binding:ae,shapeBefore:B,shapeAfter:B})),ae.toId===B.id&&((q=(Y=this.getBindingUtil(ae)).onAfterChangeToShape)==null||q.call(Y,{binding:ae,shapeBefore:B,shapeAfter:B}))};R(M.id),this.visitDescendants(M.id,R)}if(T.parentId!==M.parentId&&Tn(M.parentId)){const R=new Set([T.id]);this.visitDescendants(T.id,K=>{R.add(K)});for(const K of this.getPageStates()){if(K.pageId===M.parentId)continue;const B=C(K,R);B&&this.store.put([B])}}T.parentId&&An(T.parentId)&&I.add(T.parentId),M.parentId!==T.parentId&&An(M.parentId)&&I.add(M.parentId)},beforeDelete:T=>{var j,O,R,K;if(k.has(T.id))return;T.parentId&&An(T.parentId)&&I.add(T.parentId),k.add(T.id);const M=[];for(const B of this.getBindingsInvolvingShape(T)){_.add(B.type),M.push(B.id);const z=this.getBindingUtil(B);B.fromId===T.id?((j=z.onBeforeIsolateToShape)==null||j.call(z,{binding:B,removedShape:T}),(O=z.onBeforeDeleteFromShape)==null||O.call(z,{binding:B,shape:T})):((R=z.onBeforeIsolateFromShape)==null||R.call(z,{binding:B,removedShape:T}),(K=z.onBeforeDeleteToShape)==null||K.call(z,{binding:B,shape:T}))}M.length&&this.deleteBindings(M);const D=new Set([T.id]),$=me(this.getPageStates().map(B=>C(B,D)));$.length&&this.store.put($)}},binding:{beforeCreate:T=>{var D,$;const M=($=(D=this.getBindingUtil(T)).onBeforeCreate)==null?void 0:$.call(D,{binding:T});return M||T},afterCreate:T=>{var M,D;_.add(T.type),(D=(M=this.getBindingUtil(T)).onAfterCreate)==null||D.call(M,{binding:T})},beforeChange:(T,M)=>{var $,j;const D=(j=($=this.getBindingUtil(M)).onBeforeChange)==null?void 0:j.call($,{bindingBefore:T,bindingAfter:M});return D||M},afterChange:(T,M)=>{var D,$;_.add(M.type),($=(D=this.getBindingUtil(M)).onAfterChange)==null||$.call(D,{bindingBefore:T,bindingAfter:M})},beforeDelete:T=>{var M,D;(D=(M=this.getBindingUtil(T)).onBeforeDelete)==null||D.call(M,{binding:T})},afterDelete:T=>{var M,D;(D=(M=this.getBindingUtil(T)).onAfterDelete)==null||D.call(M,{binding:T}),_.add(T.type)}},page:{afterCreate:T=>{const M=us.createId(T.id),D=zr.createId(T.id);this.store.has(M)||this.store.put([us.create({id:M})]),this.store.has(D)||this.store.put([zr.create({id:D,pageId:T.id})])},afterDelete:(T,M)=>{var j,O;if(((j=this.getInstanceState())==null?void 0:j.currentPageId)===T.id){const R=(O=this.getPages().find(K=>K.id!==T.id))==null?void 0:O.id;R?this.store.put([{...this.getInstanceState(),currentPageId:R}]):M==="user"&&this.store.ensureStoreIsUsable()}const D=us.createId(T.id),$=zr.createId(T.id);this.store.remove([D,$])}},instance:{afterChange:(T,M,D)=>{var $;if(!this.store.has(M.currentPageId)){const j=this.store.has(T.currentPageId)?T.currentPageId:($=this.getPages()[0])==null?void 0:$.id;j?this.store.update(M.id,O=>({...O,currentPageId:j})):D==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(T,M)=>{if((T==null?void 0:T.selectedShapeIds)!==(M==null?void 0:M.selectedShapeIds)){const D=M.selectedShapeIds.filter(j=>{var R,K;let O=(R=this.getShape(j))==null?void 0:R.parentId;for(;An(O);){if(M.selectedShapeIds.includes(O))return!1;O=(K=this.getShape(O))==null?void 0:K.parentId}return!0});let $=null;if(D.length>0){const j=this.findCommonAncestor(me(D.map(O=>this.getShape(O))),O=>this.isShapeOfType(O,"group"));j&&($=j)}else M!=null&&M.focusedGroupId&&($=M.focusedGroupId);(D.length!==M.selectedShapeIds.length||$!==M.focusedGroupId)&&this.store.put([{...M,selectedShapeIds:D,focusedGroupId:$??null}])}}}})),this._currentPageShapeIds=wG(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=xG(this.store),this.disposables.add(this.store.listen(T=>{this.emit("change",T)})),this.disposables.add(this.history.dispose),this.run(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})},{history:"ignore"}),c&&this.root.children[c]===void 0)throw Error(`No state found for initialState "${c}".`);this.root.enter(void 0,"initial"),this.edgeScrollManager=new EG(this),this.focusManager=new kG(this,u),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 G2}dispose(){this.disposables.forEach(t=>t()),this.disposables.clear(),this.isDisposed=!0}getShapeUtil(t){const r=typeof t=="string"?t:t.type,s=$n(this.shapeUtils,r);return Ye(s,`No shape util found for type "${r}"`),s}getBindingUtil(t){const r=typeof t=="string"?t:t.type,s=$n(this.bindingUtils,r);return Ye(s,`No binding util found for type "${r}"`),s}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}clearHistory(){return this.history.clear(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(t){return this.history.mark(t),this}squashToMark(t){return this.history.squashToMark(t),this}bail(){return this.history.bail(),this}bailToMark(t){return this.history.bailToMark(t),this}run(t,r){const s=this._shouldIgnoreShapeLock;this._shouldIgnoreShapeLock=(r==null?void 0:r.ignoreShapeLock)??s;try{this.history.batch(t,r)}finally{this._shouldIgnoreShapeLock=s}return this}batch(t,r){return this.run(t,r)}annotateError(t,{origin:r,willCrashApp:s,tags:o,extras:i}){const a=this.createErrorAnnotations(r,s);return L0(t,{tags:{...a.tags,...o},extras:{...a.extras,...i}}),s&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(t,r){try{const s=this.getEditingShapeId();return{tags:{origin:t,willCrashApp:r},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:s?this.getShape(s):void 0,inputs:this.inputs}}}catch{return{tags:{origin:t,willCrashApp:r},extras:{}}}}getCrashingError(){return this._crashingError}crash(t){return this._crashingError=t,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:t}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(t){const r=t.split(".").reverse();let s=this.root;for(;r.length>0;){const o=r.pop();if(!o)return!0;const i=s.getCurrent();if((i==null?void 0:i.id)===o){if(r.length===0)return!0;s=i;continue}else return!1}return!1}isInAny(...t){return t.some(r=>this.isIn(r))}setCurrentTool(t,r={}){return this.root.transition(t,r),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const t=this.getCurrentTool();return t?t.getCurrentToolIdMask()??t.id:""}getStateDescendant(t){var o;const r=t.split(".").reverse();let s=this.root;for(;r.length>0;){const i=r.pop();if(!i)return s;const a=(o=s.children)==null?void 0:o[i];if(!a)return;s=a}return s}getDocumentSettings(){return this.store.get(wv)}updateDocumentSettings(t){return this.run(()=>{this.store.put([{...this.getDocumentSettings(),...t}])},{history:"ignore"}),this}getInstanceState(){return this.store.get(mn)}updateInstanceState(t,r){return this._updateInstanceState(t,{history:"ignore",...r}),t.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),t.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},2e3))),this}getOpenMenus(){return this.getInstanceState().openMenus}addOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)||(r.add(t),this.updateInstanceState({openMenus:[...r]})),this}deleteOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)&&(r.delete(t),this.updateInstanceState({openMenus:[...r]})),this}clearOpenMenus(){return this.getOpenMenus().length&&this.updateInstanceState({openMenus:[]}),this}getIsMenuOpen(){return this.getOpenMenus().length>0}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return zr.createId(this.getCurrentPageId())}updateCurrentPageState(t){return this._updateCurrentPageState(t),this}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:t}=this.getCurrentPageState();return me(t.map(r=>this.store.get(r)))}setSelectedShapes(t){return this.run(()=>{const r=t.map(i=>typeof i=="string"?i:i.id),{selectedShapeIds:s}=this.getCurrentPageState(),o=new Set(s);if(r.length===o.size&&r.every(i=>o.has(i)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:r}])},{history:"record-preserveRedoStack"})}isAncestorSelected(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null,s=this.getShape(r);if(!s)return!1;const o=this.getSelectedShapeIds();return!!this.findShapeAncestor(s,i=>o.includes(i.id))}select(...t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);return this.setSelectedShapes(r),this}deselect(...t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=this.getSelectedShapeIds();return s.length>0&&r.length>0&&this.setSelectedShapes(s.filter(o=>!r.includes(o))),this}selectAll(){const t=this.getSortedChildIdsForParent(this.getCurrentPageId());return t.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(t)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var t;return((t=this.getOnlySelectedShape())==null?void 0:t.id)??null}getOnlySelectedShape(){const t=this.getSelectedShapes();return t.length===1?t[0]:null}getSelectionPageBounds(){const t=this.getCurrentPageState().selectedShapeIds;return t.length===0?null:Q.Common(me(t.map(r=>this.getShapePageBounds(r))))}getSelectionRotation(){const t=this.getSelectedShapeIds();let r=!1,s=0;for(let o=0,i=t.length;o{const i=this.getShapePageTransform(o);return i?i.applyToPoints(this.getShapeGeometry(o).bounds.corners):[]}).map(o=>o.rot(-r)));return s.point=s.point.rot(r),s}getSelectionRotatedScreenBounds(){const t=this.getSelectionRotatedPageBounds();if(!t)return;const{x:r,y:s}=this.pageToScreen(t.point),o=this.getZoomLevel();return new Q(r,s,t.width*o,t.height*o)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const t=this.getFocusedGroupId();return t?this.getShape(t):void 0}setFocusedGroup(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==null){const s=this.getShape(r);if(!s)throw Error(`Editor.setFocusedGroup: Shape with id ${r} does not exist`);if(!this.isShapeOfType(s,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${s.type}`)}return r===this.getFocusedGroupId()?this:this.run(()=>{this.store.update(this.getCurrentPageState().id,s=>({...s,focusedGroupId:r}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const t=this.getFocusedGroup();if(t){const r=this.findShapeAncestor(t,s=>this.isShapeOfType(s,"group"));this.setFocusedGroup((r==null?void 0:r.id)??null),this.select(t.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const t=this.getEditingShapeId();return t?this.getShape(t):void 0}setEditingShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==this.getEditingShapeId()){if(r){const s=this.getShape(r);if(s&&this.getShapeUtil(s).canEdit(s))return this.run(()=>{this._updateCurrentPageState({editingShapeId:r})},{history:"ignore"}),this}this.run(()=>{this._updateCurrentPageState({editingShapeId:null})},{history:"ignore"})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const t=this.getHoveredShapeId();return t?this.getShape(t):void 0}setHoveredShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;return r===this.getHoveredShapeId()?this:(this.run(()=>{this.updateCurrentPageState({hoveredShapeId:r})},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const t=this.getHintingShapeIds();return me(t.map(r=>this.getShape(r)))}setHintingShapes(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);return this.run(()=>{this._updateCurrentPageState({hintingShapeIds:R0(r)})},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const t=this.getErasingShapeIds();return me(t.map(r=>this.getShape(r)))}setErasingShapes(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);r.sort();const s=this.getErasingShapeIds();return this.run(()=>{if(r.length===s.length){for(let o=0;o{if(!r)this.updateCurrentPageState({croppingShapeId:null});else{const s=this.getShape(r),o=this.getShapeUtil(s);s&&o.canCrop(s)&&this.updateCurrentPageState({croppingShapeId:r})}},{history:"ignore"}),this}_unsafe_getCameraId(){return us.createId(this.getCurrentPageId())}getCamera(){const t=this.store.get(this._unsafe_getCameraId());if(this._isLockedOnFollowingUser.get()){const r=this.getCameraForFollowing();if(r)return{...t,...r}}return t}getViewportPageBoundsForFollowing(){const t=this.getInstanceState().followingUserId;if(!t)return null;const r=this.getCollaborators().find(p=>p.userId===t);if(!r)return null;const{w:s,h:o}=r.screenBounds,{x:i,y:a,z:l}=r.camera,c=new Q(-i,-a,s/l,o/l),u=this.getViewportScreenBounds().clone(),h=u.width/u.height;return u.width=c.width,u.height=u.width/h,u.heightw){const{x:j,y:O,z:R}=s,K=-j+h.w/R/2,B=-O+h.h/R/2;a=kt(a,C,w);const z=-j+h.w/a/2,W=-O+h.h/a/2;o=j+z-K,i=O+W-B}const E=S/a-m.x,k=f/a-m.y,I=(h.w-S*2)/a-m.w,_=(h.h-f*2)/a-m.h,T=E+I*p.origin.x,M=k+_*p.origin.y,D=typeof p.behavior=="string"?p.behavior:p.behavior.x,$=typeof p.behavior=="string"?p.behavior:p.behavior.y;if(r!=null&&r.reset)o=T,i=M;else{switch(D){case"fixed":{o=T;break}case"contain":{au||a{const l={...s,x:o,y:i,z:a};this.run(()=>{this.store.put([l])},{history:"ignore"});const{currentScreenPoint:c,currentPagePoint:u}=this.inputs,{screenBounds:h}=this.store.unsafeGetWithoutCapture(mn);if(c.x/a-o!==u.x||c.y/a-i!==u.y){const p={type:"pointer",target:"canvas",name:"pointer_move",point:b.AddXY(c,h.x,h.y),pointerId:CC.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,button:0,isPen:this.getInstanceState().isPenMode??!1};r!=null&&r.immediate?this._flushEventForTick(p):this.dispatch(p)}this._tickCameraState()}),this)}setCamera(t,r){const{isLocked:s}=this._cameraOptions.__unsafe__getWithoutCapture();if(s&&!(r!=null&&r.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const o=b.Cast(t);Number.isFinite(o.x)||(o.x=0),Number.isFinite(o.y)||(o.y=0),(o.z===void 0||!Number.isFinite(o.z))&&(t.z=this.getZoomLevel());const i=this.getConstrainedCamera(o,r);if(r!=null&&r.animation){const{width:a,height:l}=this.getViewportScreenBounds();this._animateToViewport(new Q(-i.x,-i.y,a/i.z,l/i.z),r)}else this._setCamera(i,{...r,force:!0});return this}centerOnPoint(t,r){const{isLocked:s}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const{width:o,height:i}=this.getViewportPageBounds();return this.setCamera(new b(-(t.x-o/2),-(t.y-i/2),this.getCamera().z),r),this}zoomToFit(t){const r=[...this.getCurrentPageShapeIds()];if(r.length<=0)return this;const s=Q.Common(me(r.map(o=>this.getShapePageBounds(o))));return this.zoomToBounds(s,t),this}resetZoom(t=this.getViewportScreenCenter(),r){const{isLocked:s,constraints:o}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const i=this.getCamera(),{x:a,y:l,z:c}=i,{x:u,y:h}=t;let p=1;if(o){const f=this.getInitialZoom();c!==f&&(p=f)}return this.setCamera(new b(a+(u/p-u)-(u/c-u),l+(h/p-h)-(h/c-h),p),r),this}zoomIn(t=this.getViewportScreenCenter(),r){const{isLocked:s}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const{x:o,y:i,z:a}=this.getCamera(),{zoomSteps:l}=this.getCameraOptions();if(l!==null&&l.length>1){const c=this.getBaseZoom();let u=Ut(l)*c;for(let h=1;h1){const i=this.getBaseZoom(),{x:a,y:l,z:c}=this.getCamera();let u=o[0]*i;for(let h=o.length-1;h>0;h--){const p=o[h-1]*i,f=o[h]*i;if(!(f-c>=(f-p)/2)){u=p;break}}this.setCamera(new b(a+(t.x/u-t.x)-(t.x/c-t.x),l+(t.y/u-t.y)-(t.y/c-t.y),u),r)}return this}zoomToSelection(t){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const s=this.getSelectionPageBounds();return s&&this.zoomToBounds(s,{targetZoom:Math.max(1,this.getZoomLevel()),...t}),this}zoomToBounds(t,r){const s=this._cameraOptions.__unsafe__getWithoutCapture();if(s.isLocked&&!(r!=null&&r.force))return this;const o=this.getViewportScreenBounds(),i=(r==null?void 0:r.inset)??Math.min(jH,o.width*.28),a=this.getBaseZoom(),l=s.zoomSteps[0],c=Ut(s.zoomSteps);let u=kt(Math.min((o.width-i)/t.w,(o.height-i)/t.h),l*a,c*a);return(r==null?void 0:r.targetZoom)!==void 0&&(u=Math.min(r.targetZoom,u)),this.setCamera(new b(-t.x+(o.width-t.w*u)/2/u,-t.y+(o.height-t.h*u)/2/u,u),r),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(t){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=t;const{elapsed:r,easing:s,duration:o,start:i,end:a}=this._viewportAnimation;if(r>o){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new b(-a.x,-a.y,this.getViewportScreenBounds().width/a.width));return}const l=o-r,c=s(1-l/o),u=i.minX+(a.minX-i.minX)*c,h=i.minY+(a.minY-i.minY)*c,p=i.maxX+(a.maxX-i.maxX)*c;this._setCamera(new b(-u,-h,this.getViewportScreenBounds().width/(p-u)),{force:!0})}_animateToViewport(t,r={animation:ny}){const{animation:s,...o}=r;if(!s)return;const{duration:i=0,easing:a=At.easeInOutCubic}=s,l=this.user.getAnimationSpeed(),c=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),i===0||l===0?this._setCamera(new b(-t.x,-t.y,this.getViewportScreenBounds().width/t.width),{...o}):(this._viewportAnimation={elapsed:0,duration:i/l,easing:a,start:c.clone(),end:t.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(t={}){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:o,friction:i=this.options.cameraSlideFriction,direction:a,speedThreshold:l=.01}=t;let c=Math.min(o,1);const u=()=>{this.off("tick",h),this.off("stop-camera-animation",u)};this.once("stop-camera-animation",u);const h=p=>{const{x:f,y:S,z:m}=this.getCamera(),x=b.Mul(a,c*p/m);c*=1-i,co.userId===t);return s?(this.run(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const o=s.currentPageId===this.getCurrentPageId();o||this.setCurrentPage(s.currentPageId),r&&r.animation&&!o&&(r.animation=void 0),this.centerOnPoint(s.cursor,r);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,t]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(t);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(t,r=!1){t.width=Math.max(t.width,1),t.height=Math.max(t.height,1);const s=[t.minY!==0,!Wo(document.body.scrollWidth,t.maxX,1),!Wo(document.body.scrollHeight,t.maxY,1),t.minX!==0],{screenBounds:o,insets:i}=this.getInstanceState();if(t.equals(o)&&s.every((l,c)=>l===i[c]))return this;const{_willSetInitialBounds:a}=this;if(this._willSetInitialBounds=!1,a)this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this.setCamera(this.getCamera());else if(r&&!this.getInstanceState().followingUserId){const l=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this.centerOnPoint(l)}else this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this._setCamera(b.From({...this.getCamera()}));return this._tickCameraState(),this}getViewportScreenBounds(){const{x:t,y:r,w:s,h:o}=this.getInstanceState().screenBounds;return new Q(t,r,s,o)}getViewportScreenCenter(){const t=this.getViewportScreenBounds();return new b(t.midX-t.minX,t.midY-t.minY)}getViewportPageBounds(){const{w:t,h:r}=this.getViewportScreenBounds(),{x:s,y:o,z:i}=this.getCamera();return new Q(-s,-o,t/i,r/i)}screenToPage(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(mn),{x:s,y:o,z:i=1}=this.getCamera();return new b((t.x-r.x)/i-s,(t.y-r.y)/i-o,t.z??.5)}pageToScreen(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(mn),{x:s,y:o,z:i=1}=this.getCamera();return new b((t.x+s)*i+r.x,(t.y+o)*i+r.y,t.z??.5)}pageToViewport(t){const{x:r,y:s,z:o=1}=this.getCamera();return new b((t.x+r)*o,(t.y+s)*o,t.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const t=this._getCollaboratorsQuery().get();return t.length?[...new Set(t.map(s=>s.userId))].sort().map(s=>t.filter(i=>i.userId===s).sort((i,a)=>a.lastActivityTimestamp-i.lastActivityTimestamp)[0]):Gs}getCollaboratorsOnCurrentPage(){const t=this.getCurrentPageId();return this.getCollaborators().filter(r=>r.currentPageId===t)}startFollowingUser(t){this.stopFollowingUser();const r=this._getCollaboratorsQuery().get().filter(i=>i.userId===t);if(!r.length)return console.warn("User not found"),this;const s=this.user.getId();if(s||console.warn("You should set the userId for the current instance before following a user"),r.some(i=>i.followingUserId===s))return this;const o=G("latestLeaderPresence",()=>this.getCollaborators().find(i=>i.userId===t));return gs(()=>{this.updateInstanceState({followingUserId:t},{history:"ignore"});const i=oa("update current page",()=>{const c=o.get();if(!c){this.stopFollowingUser();return}c.currentPageId!==this.getCurrentPageId()&&this.getPage(c.currentPageId)&&this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:c.currentPageId}]),this._isLockedOnFollowingUser.set(!0)},{history:"ignore"})}),a=()=>{i(),this._isLockedOnFollowingUser.set(!1),this.off("frame",l),this.off("stop-following",a)},l=()=>{if(!o.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const u=this.user.getAnimationSpeed();if(u===0){this._isLockedOnFollowingUser.set(!0);return}const h=this.getViewportPageBoundsForFollowing();if(!h){this.stopFollowingUser();return}const p=this.getViewportPageBounds(),f=Math.abs(h.minX-p.minX)+Math.abs(h.maxX-p.maxX),S=Math.abs(h.minY-p.minY)+Math.abs(h.maxY-p.maxY);if(f{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")},{history:"ignore"}),this}getUnorderedRenderingShapes(t){const r=[];let s=this.options.maxShapesPerPage*2,o=this.options.maxShapesPerPage;const i=this.getErasingShapeIds(),a=(c,u,h)=>{const p=this.getShape(c);if(!p)return;u*=p.opacity;let f=!1;const S=this.getShapeUtil(p);t&&(f=!h&&i.includes(c),f&&(u*=.32)),r.push({id:c,shape:p,util:S,index:s,backgroundIndex:o,opacity:u}),s+=1,o+=1;const m=this.getSortedChildIdsForParent(c);if(!m.length)return;let x=null;S.providesBackgroundForChildren(p)&&(x=o,o=s,s+=this.options.maxShapesPerPage);for(const y of m)a(y,u,h||f);x!==null&&(o=x)},l=t?[this.getCurrentPage()]:this.getPages();for(const c of l)for(const u of this.getSortedChildIdsForParent(c.id))a(u,1,!1);return r}getCameraState(){return this._cameraState.get()}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(L9)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return this._getAllPagesQuery().get().sort(an)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(t){return this.store.get(typeof t=="string"?t:t.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(t){const r=typeof t=="string"?t:t.id,s=this.store.query.exec("shape",{parentId:{eq:r}});return this.getShapeAndDescendantIds(s.map(o=>o.id))}setCurrentPage(t){const r=typeof t=="string"?t:t.id;return this.store.has(r)?(this.stopFollowingUser(),this.complete(),this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:r}])},{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(t){return this.getInstanceState().isReadonly?this:this.getPage(t.id)?this.run(()=>this.store.update(t.id,s=>({...s,...t}))):this}createPage(t){return this.run(()=>{if(this.getInstanceState().isReadonly||this.getPages().length>=this.options.maxPages)return;const r=this.getPages(),s=hG(t.name??"Page 1",r.map(a=>a.name));let o=t.index;(!o||r.some(a=>a.index===o))&&(o=Fr(r[r.length-1].index));const i=to.create({meta:{},...t,name:s,index:o});this.store.put([i])}),this}deletePage(t){const r=typeof t=="string"?t:t.id;return this.run(()=>{if(this.getInstanceState().isReadonly)return;const s=this.getPages();if(s.length===1)return;const o=this.getPage(r);if(o){if(r===this.getCurrentPageId()){const i=s.findIndex(l=>l.id===r),a=s[i-1]??s[i+1];this.setCurrentPage(a.id)}this.store.remove([o.id])}}),this}duplicatePage(t,r=to.createId()){if(this.getPages().length>=this.options.maxPages)return this;const s=typeof t=="string"?t:t.id,o=this.getPage(s);if(!o)return this;const i={...this.getCamera()},a=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(o.id));return this.run(()=>{var u;const l=this.getPages(),c=vu(o.index,(u=l[l.indexOf(o)+1])==null?void 0:u.index);if(this.createPage({name:o.name+" Copy",id:r,index:c}),this.setCurrentPage(r),this.setCamera(i),a)return this.putContentOntoCurrentPage(a)}),this}renamePage(t,r){const s=typeof t=="string"?t:t.id;return this.getInstanceState().isReadonly?this:(this.updatePage({id:s,name:r}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.run(()=>this.store.put(t),{history:"ignore"}),this)}updateAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.run(()=>{this.store.put(t.map(r=>({...this.store.get(r.id),...r})))},{history:"ignore"}),this)}deleteAssets(t){if(this.getInstanceState().isReadonly)return this;const r=typeof t[0]=="string"?t:t.map(s=>s.id);return r.length<=0?this:(this.run(()=>this.store.remove(r),{history:"ignore"}),this)}getAsset(t){return this.store.get(typeof t=="string"?t:t.id)}async resolveAssetUrl(t,r){if(!t)return null;const s=this.getAsset(t);if(!s)return null;const{screenScale:o=1,shouldResolveToOriginal:i=!1}=r,l=Math.max(.125,(h=>Math.pow(2,Math.ceil(Math.log2(h))))(o)),c="connection"in navigator?navigator.connection.effectiveType:null,u=this.getInstanceState().devicePixelRatio;return await this.store.props.assets.resolve(s,{screenScale:o||1,steppedScreenScale:l,dpr:u,networkEffectiveType:c,shouldResolveToOriginal:i})}async uploadAsset(t,r){return await this.store.props.assets.upload(t,r)}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",t=>this.getShapeUtil(t).getGeometry(t),(t,r)=>t.props===r.props)}getShapeGeometry(t){return this._getShapeGeometryCache().get(typeof t=="string"?t:t.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",t=>{var r,s;return(s=(r=this.getShapeUtil(t)).getHandles)==null?void 0:s.call(r,t)})}getShapeHandles(t){return this._getShapeHandlesCache().get(typeof t=="string"?t:t.id)}getShapeLocalTransform(t){const r=typeof t=="string"?t:t.id,s=this.getShape(r);if(!s)throw Error("Editor.getTransform: shape not found");return oe.Identity().translate(s.x,s.y).rotate(s.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",t=>{if(Tn(t.parentId))return this.getShapeLocalTransform(t);const r=this._getShapePageTransformCache().get(t.parentId)??oe.Identity();return oe.Compose(r,this.getShapeLocalTransform(t))})}getShapeParentTransform(t){const r=typeof t=="string"?t:t.id,s=this.getShape(r);return!s||Tn(s.parentId)?oe.Identity():this._getShapePageTransformCache().get(s.parentId)??oe.Identity()}getShapePageTransform(t){const r=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(r)??oe.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",t=>{const r=this._getShapePageTransformCache().get(t.id);return r?Q.FromPoints(oe.applyToPoints(r,this.getShapeGeometry(t).vertices)):new Q})}getShapePageBounds(t){return this._getShapePageBoundsCache().get(typeof t=="string"?t:t.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",t=>{const r=this._getShapeMaskCache().get(t.id);if(!r)return;if(r.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const s=this._getShapePageTransformCache().get(t.id);return s?`polygon(${oe.applyToPoints(oe.Inverse(s),r).map(i=>`${i.x}px ${i.y}px`).join(",")})`:void 0})}getShapeClipPath(t){return this._getShapeClipPathCache().get(typeof t=="string"?t:t.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",t=>{if(Tn(t.parentId))return;const r=this.getShapeAncestors(t.id).filter(o=>this.isShapeOfType(o,"frame"));return r.length===0?void 0:r.map(o=>this._getShapePageTransformCache().get(o.id).applyToPoints(this.getShapeGeometry(o).vertices)).reduce((o,i)=>{if(!(i&&o))return;const a=KC(o,i);return a?a.map(b.Cast):[]})})}getShapeMask(t){return this._getShapeMaskCache().get(typeof t=="string"?t:t.id)}getShapeMaskedPageBounds(t){return typeof t!="string"&&(t=t.id),this._getShapeMaskedPageBoundsCache().get(t)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",t=>{const r=this._getShapePageBoundsCache().get(t.id);if(!r)return;const s=this._getShapeMaskCache().get(t.id);if(s){if(s.length===0)return;const{corners:o}=r;if(o.every((a,l)=>a&&b.Equals(a,s[l])))return r.clone();const i=KC(s,o);return i?Q.FromPoints(i):void 0}return r})}getShapeAncestors(t,r=[]){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return r;const i=o.parentId;if(Tn(i))return r.reverse(),r;const a=this.store.get(i);return a?(r.push(a),this.getShapeAncestors(a,r)):r}findShapeAncestor(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return;const i=o.parentId;if(Tn(i))return;const a=this.getShape(i);if(a)return r(a)?a:this.findShapeAncestor(a,r)}hasAncestor(t,r){const s=typeof t=="string"?t:t==null?void 0:t.id,o=s&&this.getShape(s);return o?o.parentId===r?!0:this.hasAncestor(this.getShapeParent(o),r):!1}findCommonAncestor(t,r){var c;if(t.length===0)return;const s=typeof t[0]=="string"?t:t.map(u=>u.id),o=me(s.map(u=>this.getShape(u)));if(o.length===1){const u=o[0].parentId;return Tn(u)?void 0:r?(c=this.findShapeAncestor(o[0],r))==null?void 0:c.id:u}const[i,...a]=o;let l=this.getShapeParent(i);for(;l;){if(r&&!r(l)){l=this.getShapeParent(l);continue}if(a.every(u=>this.hasAncestor(u,l.id)))return l.id;l=this.getShapeParent(l)}}isShapeOrAncestorLocked(t){const r=typeof t=="string"?this.getShape(t):t;return r===void 0?!1:r.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(r))}_notVisibleShapes(){return vG(this)}getCulledShapes(){const t=this._notVisibleShapes().get(),r=this.getSelectedShapeIds(),s=this.getEditingShapeId(),o=new Set(t);return s&&o.delete(s),r.forEach(i=>{o.delete(i)}),o}getCurrentPageBounds(){let t;return this.getCurrentPageShapeIdsSorted().forEach(r=>{const s=this.getShapeMaskedPageBounds(r);s&&(t?t=t.expand(s):t=s.clone())}),t}getSelectedShapeAtPoint(t){const r=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(s=>s.type!=="group"&&r.includes(s.id)).reverse().find(s=>this.isPointInShape(s,t,{hitInside:!0,margin:0}))}getShapeAtPoint(t,r={}){const s=this.getZoomLevel(),o=this.getViewportPageBounds(),{filter:i,margin:a=0,hitLocked:l=!1,hitLabels:c=!1,hitInside:u=!1,hitFrameInside:h=!1}=r;let p=1/0,f=null,S=1/0,m=null;const x=(r.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(y=>{if(y.isLocked&&!l||this.isShapeOfType(y,"group"))return!1;const v=this.getShapeMask(y);return v&&!sr(t,v)?!1:i?i(y):!0});for(let y=x.length-1;y>=0;y--){const v=x[y],w=this.getShapeGeometry(v),C=w instanceof Wr,E=this.getPointInShapeSpace(v,t);if((this.isShapeOfType(v,"arrow")||this.isShapeOfType(v,"geo")&&v.props.fill==="none")&&v.props.text.trim()){for(const I of w.children)if(I.isLabel&&I.isPointInBounds(E))return v}if(this.isShapeOfType(v,"frame")){const I=w.distanceToPoint(E,u);if(Math.abs(I)<=a)return m||v;if(w.hitTestPoint(E,0,!0))return m||f||(h?v:void 0);continue}let k;if(C){let I=1/0;for(const _ of w.children){if(_.isLabel&&!c)continue;const T=_.distanceToPoint(E,u);Tthis.isPointInShape(s,t,r))}isPointInShape(t,r,s={}){const{hitInside:o=!1,margin:i=0}=s,a=typeof t=="string"?t:t.id,l=this.getShapeMask(a);return l&&!sr(r,l)?!1:this.getShapeGeometry(a).hitTestPoint(this.getPointInShapeSpace(t,r),i,o)}getPointInShapeSpace(t,r){const s=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(s).clone().invert().applyToPoint(r)}getPointInParentSpace(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return new b(0,0);if(Tn(o.parentId))return b.From(r);const i=this.getShapePageTransform(o.parentId);return i?i.clone().invert().applyToPoint(r):b.From(r)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),t=>this.store.get(t))}getCurrentPageShapesSorted(){const t=[],r=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let s=0,o=r.length;s!t.has(r))}isShapeOfType(t,r){const s=typeof t=="string"?this.getShape(t):t;return s?s.type===r:!1}getShape(t){const r=typeof t=="string"?t:t.id;if(An(r))return this.store.get(r)}getShapeParent(t){const r=typeof t=="string"?t:t==null?void 0:t.id;if(!r)return;const s=this.getShape(r);if(!(s===void 0||!An(s.parentId)))return this.store.get(s.parentId)}getShapeNearestSibling(t,r){return r?r.parentId===t.parentId?r:this.findShapeAncestor(r,o=>o.parentId===t.parentId):void 0}isShapeInPage(t,r=this.getCurrentPageId()){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return!1;let i=!1;if(o.parentId===r)i=!0;else{let a=this.getShape(o.parentId);e:for(;a;){if(a.parentId===r){i=!0;break e}a=this.getShape(a.parentId)}}return i}getAncestorPageId(t){const r=typeof t=="string"?t:t==null?void 0:t.id,s=r&&this.getShape(r);if(s)return Tn(s.parentId)?s.parentId:this.getAncestorPageId(this.getShape(s.parentId))}reparentShapes(t,r,s){const o=typeof t[0]=="string"?t:t.map(f=>f.id);if(o.length===0)return this;const i=[],a=Tn(r)?oe.Identity():this.getShapePageTransform(r),l=a.rotation();let c=[];const u=me(this.getSortedChildIdsForParent(r).map(f=>this.getShape(f)));if(s){const f=u.find(S=>S.index===s);if(f){const S=u[u.indexOf(f)+1];S?c=fl(s,S.index,o.length):c=qm(s,o.length)}else{const S=u.sort(an).find(m=>m.index>s);S?c=fl(s,S.index,o.length):c=qm(s,o.length)}}else{const f=u.length&&u[u.length-1];c=f?qm(f.index,o.length):xu(o.length)}const h=a.clone().invert(),p=me(o.map(f=>this.getShape(f)));return this.run(()=>{for(let f=0;fthis.getShape(o)).sort(an))r.add(s.id),this.visitDescendants(s,o=>{r.add(o)});return r}getDroppingOverShape(t,r=[]){const s=this.getCurrentPageShapesSorted();for(let o=s.length-1;o>=0;o--){const i=s[o];if(this.getSelectedShapeIds().includes(i.id)||!this.getShapeUtil(i).canDropShapes(i,r)||r.find(l=>l.id===i.id||this.hasAncestor(i,l.id)))continue;const a=this.getShapeMaskedPageBounds(i.id);if(a&&a.containsPoint(t)&&this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(i,t),0,!0))return i}}getOutermostSelectableShape(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);let i=o,a=o;const l=this.getFocusedGroup();for(;a;){if(this.isShapeOfType(a,"group")&&(l==null?void 0:l.id)!==a.id&&!this.hasAncestor(l,a.id)&&((r==null?void 0:r(a))??!0))i=a;else if((l==null?void 0:l.id)===a.id)break;a=this.getShapeParent(a)}return i}_getBindingsIndexCache(){const t=yG(this);return this.store.createComputedCache("bindingsIndex",r=>t.get().get(r.id))}getBinding(t){return this.store.get(t)}getBindingsFromShape(t,r){const s=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(s).filter(o=>o.fromId===s&&o.type===r)}getBindingsToShape(t,r){const s=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(s).filter(o=>o.toId===s&&o.type===r)}getBindingsInvolvingShape(t,r){const s=typeof t=="string"?t:t.id,o=this._getBindingsIndexCache().get(s)??Gs;return r?o.filter(i=>i.type===r):o}createBindings(t){const r=[];for(const s of t){const o=this.getShape(s.fromId),i=this.getShape(s.toId);if(!o||!i||!this.canBindShapes({fromShape:o,toShape:i,binding:s}))continue;const l=this.getBindingUtil(s.type).getDefaultProps(),c=this.store.schema.types.binding.create({...s,id:s.id??Oi(),props:{...l,...s.props}});r.push(c)}return this.store.put(r),this}createBinding(t){return this.createBindings([t])}updateBindings(t){const r=[];for(const s of t){if(!s)continue;const o=this.getBinding(s.id);if(!o)continue;const i=ns(o,s);if(i===o)continue;const a=this.getShape(i.fromId),l=this.getShape(i.toId);!a||!l||this.canBindShapes({fromShape:a,toShape:l,binding:i})&&r.push(i)}return this.store.put(r),this}updateBinding(t){return this.updateBindings([t])}deleteBindings(t,{isolateShapes:r=!1}={}){const s=t.map(o=>typeof o=="string"?o:o.id);return r?this.store.atomic(()=>{var o,i;for(const a of s){const l=this.getBinding(a);if(!l)continue;const c=this.getBindingUtil(l);(o=c.onBeforeIsolateFromShape)==null||o.call(c,{binding:l,removedShape:this.getShape(l.toId)}),(i=c.onBeforeIsolateToShape)==null||i.call(c,{binding:l,removedShape:this.getShape(l.fromId)}),this.store.remove([a])}}):this.store.remove(s),this}deleteBinding(t,r){return this.deleteBindings([t],r)}canBindShapes({fromShape:t,toShape:r,binding:s}){const o=typeof t=="string"?t:t.type,i=typeof r=="string"?r:r.type,a=typeof s=="string"?s:s.type,l={fromShapeType:o,toShapeType:i,bindingType:a};return o===i?this.getShapeUtil(o).canBind(l):this.getShapeUtil(o).canBind(l)&&this.getShapeUtil(i).canBind(l)}rotateShapesBy(t,r){if((typeof t[0]=="string"?t:t.map(i=>i.id)).length<=0)return this;const o=ZM({editor:this});return o?(Uh({delta:r,snapshot:o,editor:this,stage:"one-off"}),this):this}getChangesToTranslateShape(t,r){var i,a,l;let s=t;const o=this.getShapeUtil(t);return s=ns(s,((i=o.onTranslateStart)==null?void 0:i.call(o,s))??void 0),s=ns(s,{id:t.id,type:t.type,x:r.x,y:r.y}),s=ns(s,((a=o.onTranslate)==null?void 0:a.call(o,t,s))??void 0),s=ns(s,((l=o.onTranslateEnd)==null?void 0:l.call(o,t,s))??void 0),s}nudgeShapes(t,r){const s=typeof t[0]=="string"?t:t.map(i=>i.id);if(s.length<=0)return this;const o=[];for(const i of s){const a=this.getShape(i),l=b.From(r),c=this.getShapeParentTransform(a);c&&l.rot(-c.rotation()),o.push(this.getChangesToTranslateShape(a,l.add(a)))}return this.updateShapes(o),this}duplicateShapes(t,r){return this.run(()=>{const s=typeof t[0]=="string"?t:t.map(p=>p.id);if(s.length<=0)return this;const o=new Set(s),i=this.getShapeAndDescendantIds(s),a=[...i].reverse(),l=new Map;for(const p of i)l.set(p,je());const{shapesToCreate:c,bindingsToCreate:u}=qC(this,i,p=>{const f=[];for(const m of p){const x=this.getBinding(m);if(!x)continue;const y=Oi();f.push({...x,id:y,fromId:xr(l.get(x.fromId)),toId:xr(l.get(x.toId))})}const S=[];for(const m of a){const x=xr(l.get(m)),y=this.getShape(m);if(!y)continue;let v=0,w=0;if(r&&o.has(m)){const M=this.getShapeParentTransform(y),D=new b(r.x,r.y).rot(-M.rotation());v=D.x,w=D.y}const C=y.parentId,E=this.getSortedChildIdsForParent(C),k=E.indexOf(y.id),I=E[k+1],_=I?this.getShape(I):null,T=_?vu(y.index,_.index):Fr(y.index);S.push({...y,id:x,x:y.x+v,y:y.y+w,index:T,parentId:l.get(y.parentId)??y.parentId})}return{shapesToCreate:S,bindingsToCreate:f}});if(c.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage){qd(this);return}if(this.createShapes(c),this.createBindings(u),this.setSelectedShapes(me(s.map(p=>l.get(p)))),r!==void 0){const p=this.getSelectionPageBounds(),f=this.getViewportPageBounds();p&&!f.contains(p)&&this.centerOnPoint(p.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(t,r){const s=typeof t[0]=="string"?t:t.map(l=>l.id);if(s.length===0)return this;if(this.getInstanceState().isReadonly)return this;const o=this.getCurrentPageId();if(r===o)return this;if(!this.store.has(r))return this;const i=this.getContentFromCurrentPage(s);if(!i)return this;if(this.getPageShapeIds(r).size+i.shapes.length>this.options.maxShapesPerPage)return qd(this,r),this;const a=this.getCamera().z;return this.run(()=>{this.deleteShapes(s),this.setCurrentPage(r),this.setFocusedGroup(null),this.selectNone(),this.putContentOntoCurrentPage(i,{select:!0,preserveIds:!0,preservePosition:!0}),this.setCamera({...this.getCamera(),z:a}),this.centerOnPoint(this.getSelectionRotatedPageBounds().center)}),this}toggleLock(t){const r=typeof t[0]=="string"?t:t.map(a=>a.id);if(this.getInstanceState().isReadonly||r.length===0)return this;let s=!0,o=!0;const i=[];for(const a of r){const l=this.getShape(a);l&&(i.push(l),l.isLocked?o=!1:s=!1)}return this.run(()=>{o?(this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!0}))),this.setSelectedShapes([])):s?this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!1}))):this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!0})))}),this}sendToBack(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"toBack",r);return s&&this.updateShapes(s),this}sendBackward(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"backward",r);return s&&this.updateShapes(s),this}bringForward(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"forward",r);return s&&this.updateShapes(s),this}bringToFront(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"toFront",r);return s&&this.updateShapes(s),this}flipShapes(t,r){const s=typeof t[0]=="string"?t:t.map(a=>a.id);if(this.getInstanceState().isReadonly)return this;let o=me(s.map(a=>this.getShape(a)));if(!o.length)return this;o=me(o.map(a=>this.isShapeOfType(a,"group")?this.getSortedChildIdsForParent(a.id).map(l=>this.getShape(l)):a).flat());const i=Q.Common(me(o.map(a=>this.getShapePageBounds(a)))).center;return this.run(()=>{for(const a of o){const l=this.getShapeGeometry(a).bounds,c=this.getShapePageTransform(a.id);c&&this.resizeShape(a.id,{x:r==="horizontal"?-1:1,y:r==="vertical"?-1:1},{initialBounds:l,initialPageTransform:c,initialShape:a,mode:"scale_shape",isAspectRatioLocked:this.getShapeUtil(a).isAspectRatioLocked(a),scaleOrigin:i,scaleAxisRotation:0})}}),this}stackShapes(t,r,s){const o=typeof t[0]=="string"?t:t.map(x=>x.id);if(this.getInstanceState().isReadonly)return this;const i=o.map(x=>this.getShape(x)).filter(x=>x?this.getShapeUtil(x).canBeLaidOut(x):!1),a=i.length;if(s===0&&a<3||a<2)return this;const l=Object.fromEntries(i.map(x=>[x.id,this.getShapePageBounds(x)]));let c,u,h,p;r==="horizontal"?(c="x",u="minX",h="maxX",p="width"):(c="y",u="minY",h="maxY",p="height");let f;if(s===0){const x=[];i.sort((v,w)=>l[v.id][u]-l[w.id][u]);for(let v=0;vT.gap===I);_?_.count++:x.push({gap:I,count:1})}let y=0;x.forEach(v=>{v.count>y&&(y=v.count,f=v.gap)}),y===1&&(f=Math.max(0,x.reduce((v,w)=>v+w.gap*w.count,0)/(a-1)))}else f=s;const S=[];let m=l[i[0].id][h];return i.forEach((x,y)=>{var k,I;if(y===0)return;const v={x:0,y:0};v[c]=m+f-l[x.id][c];const w=this.getShapeParent(x),C=w?b.Rot(v,-this.getShapePageTransform(w).decompose().rotation):v,E=(I=(k=this.getShapeUtil(x)).onTranslateStart)==null?void 0:I.call(k,x);S.push(E?{...E,[c]:x[c]+C[c]}:{id:x.id,type:x.type,[c]:x[c]+C[c]}),m+=l[x.id][p]+f}),this.updateShapes(S),this}packShapes(t,r){var I,_;const s=typeof t[0]=="string"?t:t.map(T=>T.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=s.map(T=>this.getShape(T)).filter(T=>T?this.getShapeUtil(T).canBeLaidOut(T):!1),i={},a={};let l,c,u=0;for(let T=0;Ti[M.id].height-i[T.id].height);const f=Math.max(Math.ceil(Math.sqrt(u/.95)),p),S=[new Q(h.x,h.y,f,1/0)];let m=0,x=0,y,v;for(let T=0;T=0;M--)if(y=S[M],!(c.width>y.width||c.height>y.height)){c.x=y.x,c.y=y.y,x=Math.max(x,c.maxY),m=Math.max(m,c.maxX),c.width===y.width&&c.height===y.height?(v=S.pop(),Mc.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=me(s.map(c=>this.getShape(c))),i=Object.fromEntries(o.map(c=>[c.id,this.getShapePageBounds(c)])),a=Q.Common(me(Object.values(i))),l=[];return o.forEach(c=>{const u=i[c.id];if(!u)return;const h={x:0,y:0};switch(r){case"top":{h.y=a.minY-u.minY;break}case"center-vertical":{h.y=a.midY-u.minY-u.height/2;break}case"bottom":{h.y=a.maxY-u.minY-u.height;break}case"left":{h.x=a.minX-u.minX;break}case"center-horizontal":{h.x=a.midX-u.minX-u.width/2;break}case"right":{h.x=a.maxX-u.minX-u.width;break}}const p=this.getShapeParent(c),f=p?b.Rot(h,-this.getShapePageTransform(p).decompose().rotation):h;l.push(this.getChangesToTranslateShape(c,b.Add(c,f)))}),this.updateShapes(l),this}distributeShapes(t,r){const s=typeof t[0]=="string"?t:t.map(w=>w.id);if(this.getInstanceState().isReadonly)return this;if(s.length<3)return this;const o=s.length,i=me(s.map(w=>this.getShape(w))),a=Object.fromEntries(i.map(w=>[w.id,this.getShapePageBounds(w)]));let l,c,u,h,p;r==="horizontal"?(l="x",c="minX",u="maxX",h="midX",p="width"):(l="y",c="minY",u="maxY",h="midY",p="height");const f=[],S=i.sort((w,C)=>a[w.id][c]-a[C.id][c])[0],m=i.sort((w,C)=>a[C.id][u]-a[w.id][u])[0],x=a[S.id][h],y=(a[m.id][h]-x)/(o-1),v=x+y;return i.filter(w=>w!==S&&w!==m).sort((w,C)=>a[w.id][h]-a[C.id][h]).forEach((w,C)=>{const E={x:0,y:0};E[l]=v+y*C-a[w.id][p]/2-a[w.id][l];const k=this.getShapeParent(w),I=k?b.Rot(E,-this.getShapePageTransform(k).rotation()):E;f.push(this.getChangesToTranslateShape(w,b.Add(w,I)))}),this.updateShapes(f),this}stretchShapes(t,r){const s=typeof t[0]=="string"?t:t.map(c=>c.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=me(s.map(c=>this.getShape(c))),i=Object.fromEntries(s.map(c=>[c,this.getShapeGeometry(c).bounds])),a=Object.fromEntries(s.map(c=>[c,this.getShapePageBounds(c)])),l=Q.Common(me(Object.values(a)));switch(r){case"vertical":{this.run(()=>{for(const c of o){if(this.getShapePageTransform(c).rotation()%Le)continue;const h=i[c.id],p=a[c.id],f=new b(0,l.minY-p.minY),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:m,y:x}=b.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:m,y:x}]);const y=new b(1,l.height/p.height);this.resizeShape(c.id,y,{initialBounds:h,scaleOrigin:new b(p.center.x,l.minY),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}case"horizontal":{this.run(()=>{for(const c of o){const u=i[c.id],h=a[c.id];if(this.getShapePageTransform(c).rotation()%Le)continue;const f=new b(l.minX-h.minX,0),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:m,y:x}=b.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:m,y:x}]);const y=new b(l.width/h.width,1);this.resizeShape(c.id,y,{initialBounds:u,scaleOrigin:new b(l.minX,h.center.y),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}}return this}resizeShape(t,r,s={}){var S,m,x;const o=typeof t=="string"?t:t.id;if(this.getInstanceState().isReadonly)return this;Number.isFinite(r.x)||(r=new b(1,r.y)),Number.isFinite(r.y)||(r=new b(r.x,1));const i=s.initialShape??this.getShape(o);if(!i)return this;const a=s.scaleOrigin??((S=this.getShapePageBounds(o))==null?void 0:S.center);if(!a)return this;const l=s.initialPageTransform?oe.Cast(s.initialPageTransform):this.getShapePageTransform(o);if(!l)return this;const c=l.rotation();if(c==null)return this;const u=s.scaleAxisRotation??c,h=s.initialBounds??this.getShapeGeometry(o).bounds;if(!h)return this;const p=s.isAspectRatioLocked??this.getShapeUtil(i).isAspectRatioLocked(i);if(!aM(c,u))return this._resizeUnalignedShape(o,r,{...s,initialBounds:h,scaleOrigin:a,scaleAxisRotation:u,initialPageTransform:l,isAspectRatioLocked:p,initialShape:i});const f=this.getShapeUtil(i);if(p&&(Math.abs(r.x)>Math.abs(r.y)?r=new b(r.x,Math.sign(r.y)*Math.abs(r.x)):r=new b(Math.sign(r.x)*Math.abs(r.y),r.y)),f.onResize&&f.canResize(i)){const y=this._scalePagePoint(oe.applyToPoint(l,new b(0,0)),a,r,u),v=this.getPointInParentSpace(i.id,y),w=new b(r.x,r.y),C=Wo((c-u)%Math.PI,0);w.x=C?r.x:r.y,w.y=C?r.y:r.x;const E=oe.applyToPoint(l,new b),{x:k,y:I}=this.getPointInParentSpace(i.id,E);let _=i;s.skipStartAndEndCallbacks||(_=ns(i,((m=f.onResizeStart)==null?void 0:m.call(f,i))??void 0)),_=ns(_,{id:o,type:i.type,x:v.x,y:v.y,...f.onResize({...i,x:k,y:I},{newPoint:v,handle:s.dragHandle??"bottom_right",mode:s.mode??"scale_shape",scaleX:w.x,scaleY:w.y,initialBounds:h,initialShape:i})}),s.skipStartAndEndCallbacks||(_=ns(_,((x=f.onResizeEnd)==null?void 0:x.call(f,i,_))??void 0)),this.updateShapes([_])}else{const y=oe.applyToPoint(l,h.center),v=this._scalePagePoint(y,a,r,u),w=this.getPointInParentSpace(i.id,y),C=this.getPointInParentSpace(i.id,v),E=b.Sub(C,w);this.updateShapes([{id:o,type:i.type,x:i.x+E.x,y:i.y+E.y}])}return this}_scalePagePoint(t,r,s,o){const i=b.RotWith(t,r,-o).sub(r),a=b.MulV(i,s);return b.Add(a,r).rotWith(r,o)}_resizeUnalignedShape(t,r,s){const{type:o}=s.initialShape,i=new b(r.x,r.y);if(Math.abs(r.x)>Math.abs(r.y)?i.x=Math.sign(r.x)*Math.abs(r.y):i.y=Math.sign(r.y)*Math.abs(r.x),this.resizeShape(t,i,{initialShape:s.initialShape,initialBounds:s.initialBounds,isAspectRatioLocked:s.isAspectRatioLocked}),Math.sign(r.x)*Math.sign(r.y)<0){let{rotation:y}=oe.Decompose(s.initialPageTransform);y-=2*y,this.updateShapes([{id:t,type:o,rotation:y}])}const a=oe.applyToPoint(s.initialPageTransform,s.initialBounds.center),l=this._scalePagePoint(a,s.scaleOrigin,r,s.scaleAxisRotation),c=this.getShapePageBounds(t),u=this.getShapePageTransform(t),h=c.center,p=u.point();if(!h||!p)return this;const f=b.Sub(l,h),S=b.Add(p,f),{x:m,y:x}=this.getPointInParentSpace(t,S);return this.updateShapes([{id:t,type:o,x:m,y:x}]),this}getInitialMetaForShape(t){return{}}createShape(t){return this.createShapes([t]),this}createShapes(t){if(!Array.isArray(t))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getInstanceState().isReadonly)return this;if(t.length<=0)return this;const r=this.getCurrentPageShapeIds();if(t.length+r.size>this.options.maxShapesPerPage)return qd(this),this;const o=this.getFocusedGroupId();return this.run(()=>{var h,p;const i=this.getCurrentPageShapesSorted(),a=t.map(f=>{if(f.id||(f={id:je(),...f}),!f.parentId||!(this.store.has(f.parentId)||t.some(S=>S.id===f.parentId))){let S=this.getFocusedGroupId();for(let x=i.length-1;x>=0;x--){const y=i[x];if(this.getShapeUtil(y).canReceiveNewChildrenOfType(y,f.type)&&this.isPointInShape(y,{x:f.x??0,y:f.y??0},{margin:0,hitInside:!0})){S=y.id;break}}const m=f.parentId;if(S===f.id&&(S=o),S!==m&&(f={...f},f.parentId=S,An(S))){const x=this.getPointInShapeSpace(this.getShape(S),{x:f.x??0,y:f.y??0});f.x=x.x,f.y=x.y,f.rotation=-this.getShapePageTransform(S).rotation()+(f.rotation??0)}}return f}),l=new Map,c=[],{opacityForNextShape:u}=this.getInstanceState();for(const f of a){const S=this.getShapeUtil(f);let m=f.index;if(!m){const w=f.parentId??o;l.has(w)||l.set(w,this.getHighestIndexForParent(w)),m=l.get(w),l.set(w,Fr(m))}const x=S.getDefaultProps();for(const[w,C]of this.styleProps[f.type])x[C]=this.getStyleForNextShape(w);let y=this.store.schema.types.shape.create({...f,index:m,opacity:f.opacity??u,parentId:f.parentId??o,props:"props"in f?{...x,...f.props}:x});if(y.index===void 0)throw Error("no index!");const v=(p=(h=this.getShapeUtil(y)).onBeforeCreate)==null?void 0:p.call(h,y);v&&(y=v),c.push(y)}c.forEach(f=>{f.meta={...this.getInitialMetaForShape(f),...f.meta}}),this.store.put(c)}),this}animateShape(t,r={animation:ny}){return this.animateShapes([t],r)}animateShapes(t,r={animation:ny}){if(!r.animation)return this;const{duration:s=500,easing:o=At.linear}=r.animation,i=ct();let a=s,l;const c=[];let u,h;for(let f=0,S=t.length;f{var y,v;if(a-=f,a<0){const{animatingShapes:w}=this,C=t.filter(E=>E&&w.get(E.id)===i);C.length&&this.updateShapes(C),this.off("tick",p);return}l=o(1-a/s);const{animatingShapes:S}=this,m=[];let x;for(let w=0,C=c.length;wx.id);if(i.length<=1)return this;const a=me((this._shouldIgnoreShapeLock?i:this._getUnlockedShapeIds(i)).map(x=>this.getShape(x))),l=a.sort(an).map(x=>x.id),c=Q.Common(me(a.map(x=>this.getShapePageBounds(x)))),{x:u,y:h}=c.point,p=this.findCommonAncestor(a)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const f=a.filter(x=>x.parentId===p).sort(an),S=(m=f[f.length-1])==null?void 0:m.index;return this.run(()=>{this.createShapes([{id:s,type:"group",parentId:p,index:S,x:u,y:h,opacity:1,props:{}}]),this.reparentShapes(l,s),o&&this.select(s)}),this}ungroupShapes(t,r={}){if(this.getInstanceState().isReadonly)return this;const{select:s=!0}=r,o=typeof t[0]=="string"?t:t.map(c=>c.id),i=me((this._shouldIgnoreShapeLock?o:this._getUnlockedShapeIds(o)).map(c=>this.getShape(c)));if(i.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const a=new Set,l=[];return i.forEach(c=>{this.isShapeOfType(c,"group")?l.push(c):a.add(c.id)}),l.length===0?this:(this.run(()=>{let c;for(let u=0,h=l.length;uu.id)),s&&this.select(...a)}),this)}updateShape(t){return this.updateShapes([t]),this}updateShapes(t){const r=Array(t.length);for(let s=0,o=t.length;s{var s;return!((s=this.getShape(r))!=null&&s.isLocked)})}deleteShapes(t){if(this.getInstanceState().isReadonly)return this;if(!Array.isArray(t))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const r=typeof t[0]=="string"?t:t.map(i=>i.id),s=this._shouldIgnoreShapeLock?r:this._getUnlockedShapeIds(r);if(s.length===0)return this;const o=new Set(s);for(const i of s)this.visitDescendants(i,a=>{o.add(a)});return this.run(()=>this.store.remove([...o]))}deleteShape(t){return this.deleteShapes([typeof t=="string"?t:t.id]),this}_extractSharedStyles(t,r){if(this.isShapeOfType(t,"group")){const s=this._parentIdsToChildIds.get()[t.id];if(!s)return;for(let o=0,i=s.length;o0)return this._getSelectionSharedStyles();const t=this.root.getCurrent(),r=new Tv;if(!t)return r;if(t.shapeType)for(const s of this.styleProps[t.shapeType].keys())r.applyValue(s,this.getStyleForNextShape(s));return r}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const t=[],r=o=>{const i=this.getShape(o);if(i)if(this.isShapeOfType(i,"group"))for(const a of this.getSortedChildIdsForParent(i.id))r(a);else t.push(i)};for(const o of this.getSelectedShapeIds())r(o);let s=null;for(const o of t)if(s===null)s=o.opacity;else if(s!==o.opacity)return{type:"mixed"};if(s!==null)return{type:"shared",value:s}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(t,r){return this.updateInstanceState({opacityForNextShape:t},r),this}setOpacityForSelectedShapes(t){const r=this.getSelectedShapes();if(r.length>0){const s=[],o=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i);for(const l of a)o(this.getShape(l))}else s.push(i)};for(const i of r)o(i);this.updateShapes(s.map(i=>({id:i.id,type:i.type,opacity:t})))}return this}setStyleForNextShapes(t,r,s){const o=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...o,[t.id]:r}},s),this}setStyleForSelectedShapes(t,r){const s=this.getSelectedShapes();if(s.length>0){const o=[],i=a=>{if(this.isShapeOfType(a,"group")){const l=this.getSortedChildIdsForParent(a.id);for(const c of l)i(this.getShape(c))}else{const l=this.getShapeUtil(a),c=this.styleProps[a.type].get(t);if(c){const u={id:a.id,type:a.type,props:{[c]:r}};o.push({util:l,originalShape:a,updatePartial:u})}}};for(const a of s)i(a);this.updateShapes(o.map(({updatePartial:a})=>a))}return this}registerExternalAssetHandler(t,r){return this.externalAssetContentHandlers[t]=r,this}async getAssetForExternalContent(t){var r,s;return await((s=(r=this.externalAssetContentHandlers)[t.type])==null?void 0:s.call(r,t))}hasExternalAssetHandler(t){return!!this.externalAssetContentHandlers[t]}registerExternalContentHandler(t,r){return this.externalContentHandlers[t]=r,this}async putExternalContent(t){var r,s;return(s=(r=this.externalContentHandlers)[t.type])==null?void 0:s.call(r,t)}getContentFromCurrentPage(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);if(!r||r.length===0)return;const s=this.getShapeAndDescendantIds(r);return qC(this,s,o=>{const i=[];for(const h of o){const p=this.getBinding(h);p&&i.push(p)}const a=[],l=[];for(const h of s){const p=this.getShape(h);if(!p)continue;if(!s.has(p.parentId)){const S=this.getShapePageTransform(p.id),m=S.point();l.push({...p,x:m.x,y:m.y,rotation:S.rotation(),parentId:this.getCurrentPageId()}),a.push(p.id)}else l.push(p)}const c=[],u=new Set;for(const h of l){if(!("assetId"in h.props))continue;const p=h.props.assetId;if(!p||u.has(p))continue;u.add(p);const f=this.getAsset(p);f&&c.push(f)}return{schema:this.store.schema.serialize(),shapes:l,rootShapeIds:a,bindings:i,assets:c}})}async resolveAssetsInContent(t){if(!t)return;const r=[];return await Promise.allSettled(t.assets.map(async s=>{var o,i;if((s.type==="image"||s.type==="video")&&!((o=s.props.src)!=null&&o.startsWith("data:image"))&&!((i=s.props.src)!=null&&i.startsWith("http"))){const a=Be(s),l=await this.store.props.assets.resolve(s,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginal:!0});a.props.src=await ji.blobToDataUrl(await vs(l).then(c=>c.blob())),r.push(a)}else r.push(s)})),t.assets=r,t}putContentOntoCurrentPage(t,r={}){var D,$;if(this.getInstanceState().isReadonly)return this;if(!t.schema)throw Error(`Could not put content: -content is missing a schema.`);const{select:s=!1,preserveIds:o=!1,preservePosition:i=!1}=r;let{point:a=void 0}=r;const l=this.getCurrentPageId(),{rootShapeIds:c}=t,u=[],h=[],p=[],f={store:{...Object.fromEntries(t.assets.map(j=>[j.id,j])),...Object.fromEntries(t.shapes.map(j=>[j.id,j])),...Object.fromEntries(((D=t.bindings)==null?void 0:D.map(j=>[j.id,j]))??[])},schema:t.schema},S=this.store.schema.migrateStoreSnapshot(f);if(S.type==="error")throw Error("Could not put content: could not migrate content");for(const j of Object.values(S.value))switch(j.typeName){case"asset":{u.push(j);break}case"shape":{h.push(j);break}case"binding":{p.push(j);break}}const m=new Map(o?h.map(j=>[j.id,j.id]):h.map(j=>[j.id,je()])),x=new Map(o?p.map(j=>[j.id,j.id]):p.map(j=>[j.id,Oi()]));let y=this.getCurrentPageId(),v=1/0,w=[];for(const j of this.getSelectedShapes()){if(v===0)break;const O=this.isShapeOfType(j,"frame"),R=this.getShapeAncestors(j);O&&R.push(j);const K=O?R.length+1:R.length;if(KR.id===c[0]);this.isShapeOfType(j,"frame")&&this.isShapeOfType(O,"frame")&&O.props.w===(j==null?void 0:j.props.w)&&O.props.h===(j==null?void 0:j.props.h)&&(C=!0)}}else y=l}C||(C=m.has(y)),C&&(y=this.getShape(y).parentId);let E=this.getHighestIndexForParent(y);const k=[],I=h.map(j=>{const O=m.get(j.id),R={...j,id:O};return c.includes(j.id)&&(R.parentId=l,k.push(R)),m.has(R.parentId)?R.parentId=m.get(j.parentId):(c.push(R.id),R.index=E,E=Fr(E)),R});if(I.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage)return qd(this),this;const _=p.map(j=>({...j,id:xr(x.get(j.id)),fromId:xr(m.get(j.fromId)),toId:xr(m.get(j.toId))})),T=[],M=[];for(const j of u)this.store.has(j.id)||((j.type==="image"||j.type==="video")&&(($=j.props.src)!=null&&$.startsWith("data:image"))&&(M.push(Be(j)),j.props.src=null),T.push(j));return Promise.allSettled(M.map(async j=>{const O=await uG(j.props.src,j.props.name,j.props.mimeType??"image/png"),R=await this.getAssetForExternalContent({type:"file",file:O});if(!R){this.deleteAssets([j.id]);return}this.updateAssets([{...R,id:j.id}])})),this.run(()=>{T.length>0&&this.createAssets(T),this.createShapes(I),this.createBindings(_),s&&this.select(...k.map(B=>B.id)),y!==l&&this.reparentShapes(k.map(B=>B.id),y);const j=I.map(B=>this.getShape(B.id)),O=Q.Common(j.map(B=>this.getShapePageBounds(B)));if(a===void 0)if(Tn(y)){const B=this.getViewportPageBounds();i||B.includes(Q.From(O))?a=O.center:a=B.center}else{const B=this.getShape(y);a=oe.applyToPoint(this.getShapePageTransform(B),this.getShapeGeometry(B).bounds.center)}if(k.length===1){const B=k[0];if(this.isShapeOfType(B,"frame"))for(;this.getShapesAtPoint(a).some(z=>this.isShapeOfType(z,"frame")&&z.props.w===B.props.w&&z.props.h===B.props.h);)a.x+=O.w+16}const R=Q.Common(me(k.map(({id:B})=>this.getShapePageBounds(B)))).center,K=b.Sub(a,R);this.updateShapes(k.map(({id:B})=>{const z=this.getShape(B),W=this.getShapeParentTransform(B).decompose().rotation,Y=b.Rot(K,-W);return{id:z.id,type:z.type,x:z.x+Y.x,y:z.y+Y.y}}))}),this}async getSvgElement(t,r={}){const s=await PG(this,t,r);if(!s)return;const o=document.createDocumentFragment(),i=a0(o);ta.flushSync(()=>{i.render(s.jsx)});const a=o.firstElementChild;return Ye(a instanceof SVGSVGElement,"Expected an SVG element"),i.unmount(),{svg:a,width:s.width,height:s.height}}async getSvgString(t,r={}){const s=await this.getSvgElement(t,r);return s?{svg:new XMLSerializer().serializeToString(s.svg),width:s.width,height:s.height}:void 0}async getSvg(t,r={}){const s=await this.getSvgElement(t,r);if(s)return s.svg}_updateInputsFromEvent(t){const{pointerVelocity:r,previousScreenPoint:s,previousPagePoint:o,currentScreenPoint:i,currentPagePoint:a}=this.inputs,{screenBounds:l}=this.store.unsafeGetWithoutCapture(mn),{x:c,y:u,z:h}=Fd(()=>this.getCamera()),p=t.point.x-l.x,f=t.point.y-l.y,S=t.point.z??.5;s.setTo(i),o.setTo(a),i.set(p,f);const m=p/h-c,x=f/h-u;isFinite(m)&&isFinite(x)&&a.set(m,x,S),this.inputs.isPen=t.type==="pointer"&&t.isPen,(t.name==="pointer_down"||this.inputs.isPinching)&&(r.set(0,0),this.inputs.originScreenPoint.setTo(i),this.inputs.originPagePoint.setTo(a)),this.run(()=>{var y;this.store.put([{id:of,typeName:"pointer",x:a.x,y:a.y,lastActivityTimestamp:t.type==="pointer"&&t.pointerId===CC.CAMERA_MOVE?((y=this.store.unsafeGetWithoutCapture(of))==null?void 0:y.lastActivityTimestamp)??this._tickManager.now:this._tickManager.now,meta:{}}])},{history:"ignore"})}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}focus({focusContainer:t=!0}={}){return this.getIsFocused()?this:(t&&this.focusManager.focus(),this.updateInstanceState({isFocused:!0}),this)}blur({blurContainer:t=!0}={}){return this.getIsFocused()?(t?this.focusManager.blur():this.complete(),this.updateInstanceState({isFocused:!1}),this):this}getIsFocused(){return this.getInstanceState().isFocused}getSnapshot(){return tG(this.store)}loadSnapshot(t){return GM(this.store,t),this}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_flushEventsForTick(t){this.run(()=>{if(this._pendingEventsForNextTick.length>0){const r=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const s of r)this._flushEventForTick(s)}t>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:t}),this.scribbles.tick(t)})}maybeTrackPerformance(t){xt.measurePerformance.get()&&(this.performanceTracker.isStarted()?clearTimeout(this.performanceTrackerTimeout):this.performanceTracker.start(t),this.performanceTrackerTimeout=this.timers.setTimeout(()=>{this.performanceTracker.stop()},50))}}ne([G],Z.prototype,"getCanUndo");ne([G],Z.prototype,"getCanRedo");ne([G],Z.prototype,"getPath");ne([G],Z.prototype,"getCurrentTool");ne([G],Z.prototype,"getCurrentToolId");ne([G],Z.prototype,"getDocumentSettings");ne([G],Z.prototype,"getInstanceState");ne([G],Z.prototype,"getOpenMenus");ne([G],Z.prototype,"getIsMenuOpen");ne([G],Z.prototype,"getPageStates");ne([G],Z.prototype,"_getPageStatesQuery");ne([G],Z.prototype,"getCurrentPageState");ne([G],Z.prototype,"_getCurrentPageStateId");ne([G],Z.prototype,"getSelectedShapeIds");ne([G],Z.prototype,"getSelectedShapes");ne([G],Z.prototype,"getOnlySelectedShapeId");ne([G],Z.prototype,"getOnlySelectedShape");ne([G],Z.prototype,"getSelectionPageBounds");ne([G],Z.prototype,"getSelectionRotation");ne([G],Z.prototype,"getSelectionRotatedPageBounds");ne([G],Z.prototype,"getSelectionRotatedScreenBounds");ne([G],Z.prototype,"getFocusedGroupId");ne([G],Z.prototype,"getFocusedGroup");ne([G],Z.prototype,"getEditingShapeId");ne([G],Z.prototype,"getEditingShape");ne([G],Z.prototype,"getHoveredShapeId");ne([G],Z.prototype,"getHoveredShape");ne([G],Z.prototype,"getHintingShapeIds");ne([G],Z.prototype,"getHintingShape");ne([G],Z.prototype,"getErasingShapeIds");ne([G],Z.prototype,"getErasingShapes");ne([G],Z.prototype,"_unsafe_getCameraId");ne([G],Z.prototype,"getCamera");ne([G],Z.prototype,"getViewportPageBoundsForFollowing");ne([G],Z.prototype,"getCameraForFollowing");ne([G],Z.prototype,"getZoomLevel");ne([G],Z.prototype,"getViewportScreenBounds");ne([G],Z.prototype,"getViewportScreenCenter");ne([G],Z.prototype,"getViewportPageBounds");ne([G],Z.prototype,"_getCollaboratorsQuery");ne([G],Z.prototype,"getCollaborators");ne([G],Z.prototype,"getCollaboratorsOnCurrentPage");ne([G],Z.prototype,"getRenderingShapes");ne([G],Z.prototype,"_getAllPagesQuery");ne([G],Z.prototype,"getPages");ne([G],Z.prototype,"getCurrentPageId");ne([G],Z.prototype,"getCurrentPageShapeIdsSorted");ne([G],Z.prototype,"_getAllAssetsQuery");ne([G],Z.prototype,"_getShapeGeometryCache");ne([G],Z.prototype,"_getShapeHandlesCache");ne([G],Z.prototype,"_getShapePageTransformCache");ne([G],Z.prototype,"_getShapePageBoundsCache");ne([G],Z.prototype,"_getShapeClipPathCache");ne([G],Z.prototype,"_getShapeMaskCache");ne([G],Z.prototype,"_getShapeMaskedPageBoundsCache");ne([G],Z.prototype,"_notVisibleShapes");ne([G],Z.prototype,"getCulledShapes");ne([G],Z.prototype,"getCurrentPageBounds");ne([G],Z.prototype,"getCurrentPageShapes");ne([G],Z.prototype,"getCurrentPageShapesSorted");ne([G],Z.prototype,"getCurrentPageRenderingShapesSorted");ne([G],Z.prototype,"_getBindingsIndexCache");ne([G],Z.prototype,"_getSelectionSharedStyles");ne([G({isEqual:(e,n)=>e.equals(n)})],Z.prototype,"getSharedStyles");ne([G],Z.prototype,"getSharedOpacity");ne([G],Z.prototype,"getIsFocused");function qd(e,n=e.getCurrentPageId()){const t=e.getPage(n).name;e.emit("max-shapes",{name:t,pageId:n,count:e.options.maxShapesPerPage})}function ns(e,n){if(!n)return e;let t=null;const r=Object.entries(n);for(let s=0,o=r.length;s{const s=e.store.extractingChanges(()=>{const o=new Set,i=new Set;for(const a of n)if(e.getShape(a))for(const c of e.getBindingsInvolvingShape(a)){const u=n.has(c.fromId),h=n.has(c.toId);if(u&&h){o.add(c.id);continue}(!u||!h)&&i.add(c.id)}e.deleteBindings([...i],{isolateShapes:!0});try{r=Ho.ok(t(o))}catch(a){r=Ho.err(a)}});e.store.applyDiff(Sv(s))},{history:"ignore"}),r.ok)return r.value;throw r.error}function ZC(e,n){if(!n.constraints)throw Error("Should have constraints here");const{padding:{x:t,y:r}}=n.constraints,s=e.getViewportScreenBounds(),o=Q.From(n.constraints.bounds),i=(s.w-t*2)/o.w,a=(s.h-r*2)/o.h;return{zx:i,zy:a}}function Ju(){const e=F(),n=JM();return H("isDarkMode",()=>(n==null?void 0:n.isDarkMode)??e.user.getIsDarkMode(),[n,e])}const QC="",JC="",Zd='';function xo(e,n,t,r,s,o=16,i=16){const a=(-t-n)*(Me/180),l=Math.sin(a),c=Math.cos(a),u=1*c-1*l,h=1*l+1*c;return`url("data:image/svg+xml,`+e.replaceAll('"',"'")+`") ${o} ${i}, pointer`}const nV=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],rV={none:()=>"none","ew-resize":(e,n,t)=>xo(JC,e,0,n,t),"ns-resize":(e,n,t)=>xo(JC,e,90,n,t),"nesw-resize":(e,n,t)=>xo(QC,e,0,n,t),"nwse-resize":(e,n,t)=>xo(QC,e,90,n,t),"nwse-rotate":(e,n,t)=>xo(Zd,e,0,n,t),"nesw-rotate":(e,n,t)=>xo(Zd,e,90,n,t),"senw-rotate":(e,n,t)=>xo(Zd,e,180,n,t),"swne-rotate":(e,n,t)=>xo(Zd,e,270,n,t)};function Xn(e,n=0,t="black"){return rV[e](kH(n),!1,t)}function sV(){const e=F(),n=$t(),t=Ju();Ko("useCursor",()=>{const{type:r,rotation:s}=e.getInstanceState().cursor;if(nV.includes(r)){n.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}n.style.setProperty("--tl-cursor",Xn(r,s,t?"white":"black"))},[e,n,t])}function oV(){const e=F(),n=$t(),t=Ju(),r=H(xt.forceSrgb);Ce.useEffect(()=>{t?(n.setAttribute("data-color-mode","dark"),n.classList.remove("tl-theme__light"),n.classList.add("tl-theme__dark")):(n.setAttribute("data-color-mode","light"),n.classList.remove("tl-theme__dark"),n.classList.add("tl-theme__light")),r?n.classList.add("tl-theme__force-sRGB"):n.classList.remove("tl-theme__force-sRGB")},[e,n,r,t])}function nA(e){const n=P.useRef();return P.useLayoutEffect(()=>{n.current=e}),P.useDebugValue(e),P.useCallback((...t)=>{const r=n.current;return Ye(r,"fn does not exist"),r(...t)},[])}function iV(){const[e,n]=P.useState(0);P.useEffect(()=>n(t=>t+1),[])}const aV=e=>e.props.src,lV={upload:(e,n)=>ji.blobToDataUrl(n)};function cV(e){return"schema"in e&&e.schema?e.schema:gH({shapes:"shapeUtils"in e&&e.shapeUtils?eI(qM(e.shapeUtils)):void 0,bindings:"bindingUtils"in e&&e.bindingUtils?eI(VM(e.bindingUtils)):void 0,migrations:"migrations"in e?e.migrations:void 0})}function ff({initialData:e,defaultName:n="",id:t,assets:r=lV,onMount:s,collaboration:o,...i}={}){const a=cV(i),l=new H0({id:t,schema:a,initialData:e,props:{defaultName:n,assets:{upload:r.upload,resolve:r.resolve??aV},onMount:c=>{Ye(c instanceof Z),s==null||s(c)},collaboration:o}});if(i.snapshot){if(e)throw new Error("Cannot provide both initialData and snapshot");GM(l,i.snapshot)}return l}function eI(e){return Object.fromEntries(e.map(n=>[n.type,{props:n.props,migrations:n.migrations}]))}const uV=(e,n)=>n.some(t=>e instanceof t);let tI,nI;function dV(){return tI||(tI=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function hV(){return nI||(nI=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const rA=new WeakMap,Mv=new WeakMap,sA=new WeakMap,ly=new WeakMap,uw=new WeakMap;function pV(e){const n=new Promise((t,r)=>{const s=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(Vs(e.result)),s()},i=()=>{r(e.error),s()};e.addEventListener("success",o),e.addEventListener("error",i)});return n.then(t=>{t instanceof IDBCursor&&rA.set(t,e)}).catch(()=>{}),uw.set(n,e),n}function fV(e){if(Mv.has(e))return;const n=new Promise((t,r)=>{const s=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),s()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});Mv.set(e,n)}let Av={get(e,n,t){if(e instanceof IDBTransaction){if(n==="done")return Mv.get(e);if(n==="objectStoreNames")return e.objectStoreNames||sA.get(e);if(n==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Vs(e[n])},set(e,n,t){return e[n]=t,!0},has(e,n){return e instanceof IDBTransaction&&(n==="done"||n==="store")?!0:n in e}};function gV(e){Av=e(Av)}function mV(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(n,...t){const r=e.call(cy(this),n,...t);return sA.set(r,n.sort?n.sort():[n]),Vs(r)}:hV().includes(e)?function(...n){return e.apply(cy(this),n),Vs(rA.get(this))}:function(...n){return Vs(e.apply(cy(this),n))}}function yV(e){return typeof e=="function"?mV(e):(e instanceof IDBTransaction&&fV(e),uV(e,dV())?new Proxy(e,Av):e)}function Vs(e){if(e instanceof IDBRequest)return pV(e);if(ly.has(e))return ly.get(e);const n=yV(e);return n!==e&&(ly.set(e,n),uw.set(n,e)),n}const cy=e=>uw.get(e);function oA(e,n,{blocked:t,upgrade:r,blocking:s,terminated:o}={}){const i=indexedDB.open(e,n),a=Vs(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Vs(i.result),l.oldVersion,l.newVersion,Vs(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 iA(e,{blocked:n}={}){const t=indexedDB.deleteDatabase(e);return n&&t.addEventListener("blocked",r=>n(r.oldVersion,r)),Vs(t).then(()=>{})}const SV=["get","getKey","getAll","getAllKeys","count"],vV=["put","add","delete","clear"],uy=new Map;function rI(e,n){if(!(e instanceof IDBDatabase&&!(n in e)&&typeof n=="string"))return;if(uy.get(n))return uy.get(n);const t=n.replace(/FromIndex$/,""),r=n!==t,s=vV.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||SV.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 uy.set(n,o),o}gV(e=>({...e,get:(n,t,r)=>rI(n,t)||e.get(n,t,r),has:(n,t)=>!!rI(n,t)||e.has(n,t)}));const xV="TLDRAW_DOCUMENT_v2",wV="TLDRAW_ASSET_STORE_v1",aA="TLDRAW_DB_NAME_INDEX_v2",be={Records:"records",Schema:"schema",SessionState:"session_state",Assets:"assets"};async function lA(e){const n=xV+e;return PV(n),await oA(n,4,{upgrade(t){t.objectStoreNames.contains(be.Records)||t.createObjectStore(be.Records),t.objectStoreNames.contains(be.Schema)||t.createObjectStore(be.Schema),t.objectStoreNames.contains(be.SessionState)||t.createObjectStore(be.SessionState),t.objectStoreNames.contains(be.Assets)||t.createObjectStore(be.Assets)}})}async function bV(e){const n=window.indexedDB.databases?(await window.indexedDB.databases()).map(p=>p.name):dw(),t=wV+e;if(!n.find(p=>p===t))return;const s=await oA(t,1,{upgrade(p){p.objectStoreNames.contains("assets")||p.createObjectStore("assets")}}),o=s.transaction(["assets"],"readonly"),i=o.objectStore("assets"),a=await i.getAllKeys(),l=await Promise.all(a.map(async p=>[p,await i.get(p)]));await o.done;const c=await lA(e),u=c.transaction([be.Assets],"readwrite"),h=u.objectStore(be.Assets);for(const[p,f]of l)h.put(f,p);await u.done,s.close(),c.close(),await iA(t)}const Qc=class Qc{constructor(n){g(this,"getDbPromise");g(this,"isClosed",!1);g(this,"pendingTransactionSet",new Set);Qc.connectedInstances.add(this),this.getDbPromise=(async()=>(await bV(n),await lA(n)))()}getDb(){return this.getDbPromise}pending(){return Promise.allSettled([this.getDbPromise,...this.pendingTransactionSet]).then(Su)}async close(){this.isClosed||(this.isClosed=!0,await this.pending(),(await this.getDb()).close(),Qc.connectedInstances.delete(this))}tx(n,t,r){const s=(async()=>{Ye(!this.isClosed,"db is closed");const i=(await this.getDb()).transaction(t,n),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:n}={}){return await this.tx("readonly",[be.Records,be.Schema,be.SessionState],async t=>{var l,c;const r=t.objectStore(be.Records),s=t.objectStore(be.Schema),o=t.objectStore(be.SessionState);let i=n?(l=await o.get(n))==null?void 0:l.snapshot:null;return i||(i=(c=(await o.getAll()).sort((h,p)=>h.updatedAt-p.updatedAt).pop())==null?void 0:c.snapshot),{records:await r.getAll(),schema:await s.get(be.Schema),sessionStateSnapshot:i}})}async storeChanges({schema:n,changes:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[be.Records,be.Schema,be.SessionState],async o=>{const i=o.objectStore(be.Records),a=o.objectStore(be.Schema),l=o.objectStore(be.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(n.serialize(),be.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:n,snapshot:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[be.Records,be.Schema,be.SessionState],async o=>{const i=o.objectStore(be.Records),a=o.objectStore(be.Schema),l=o.objectStore(be.SessionState);await i.clear();for(const[c,u]of Object.entries(t))await i.put(u,c);a.put(n.serialize(),be.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",[be.SessionState],async n=>{const t=n.objectStore(be.SessionState),r=(await t.getAll()).sort((o,i)=>o.updatedAt-i.updatedAt);if(r.length<10){await n.done;return}const s=r.slice(0,r.length-10);for(const{id:o}of s)await t.delete(o)})}async getAsset(n){return await this.tx("readonly",[be.Assets],async t=>await t.objectStore(be.Assets).get(n))}async storeAsset(n,t){await this.tx("readwrite",[be.Assets],async r=>{await r.objectStore(be.Assets).put(t,n)})}};g(Qc,"connectedInstances",new Set);let gf=Qc;function dw(){const e=JSON.parse(N0(aA)||"[]")??[];return Array.isArray(e)?e:[]}function PV(e){const n=new Set(dw());n.add(e),F0(aA,JSON.stringify([...n]))}function CV(){window.alert(`Oops! We could not save changes to your browser's storage. We now need to reload the page and try again. +`)}const GG={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},VG=/\s/;class YG{constructor(n){g(this,"baseElm");g(this,"measureText",(n,t)=>{var i;const r=(i=this.baseElm)==null?void 0:i.cloneNode();this.baseElm.insertAdjacentElement("afterend",r),r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("font-family",t.fontFamily),r.style.setProperty("font-style",t.fontStyle),r.style.setProperty("font-weight",t.fontWeight),r.style.setProperty("font-size",t.fontSize+"px"),r.style.setProperty("line-height",t.lineHeight*t.fontSize+"px"),r.style.setProperty("max-width",t.maxWidth===null?null:t.maxWidth+"px"),r.style.setProperty("min-width",t.minWidth===null?null:t.minWidth+"px"),r.style.setProperty("padding",t.padding),r.style.setProperty("overflow-wrap",t.disableOverflowWrapBreaking?"normal":"break-word"),r.textContent=YC(n);const s=r.scrollWidth,o=r.getBoundingClientRect();return r.remove(),{x:0,y:0,w:o.width,h:o.height,scrollWidth:s}});this.editor=n;const t=this.editor.getContainer(),r=document.createElement("div");r.classList.add("tl-text"),r.classList.add("tl-text-measure"),r.tabIndex=-1,t.appendChild(r),this.baseElm=r,n.disposables.add(()=>{r.remove()})}measureElementTextNodeSpans(n,{shouldTruncateToFirstLine:t=!1}={}){const r=[],s=n.getBoundingClientRect(),o=-s.left,i=-s.top,a=new Range,l=n.childNodes[0];let c=0,u=null,h=null,p=0,f=0,S=!1;for(const y of n.childNodes)if(y.nodeType===Node.TEXT_NODE)for(const x of y.textContent??""){a.setStart(l,c),a.setEnd(l,c+x.length);const m=a.getClientRects(),v=m[m.length-1],w=v.top+i,C=v.left+o,E=v.right+o,k=C{var n;this.isPaused=!1,(n=this.cancelRaf)==null||n.call(this),this.cancelRaf=XC(this.tick),this.now=Date.now()});g(this,"tick",()=>{if(this.isPaused)return;const n=Date.now(),t=n-this.now;this.now=n,this.updatePointerVelocity(t),this.editor.emit("frame",t),this.editor.emit("tick",t),this.cancelRaf=XC(this.tick)});g(this,"dispose",()=>{var n;this.isPaused=!0,(n=this.cancelRaf)==null||n.call(this)});g(this,"prevPoint",new b);g(this,"updatePointerVelocity",n=>{const{prevPoint:t,editor:{inputs:{currentScreenPoint:r,pointerVelocity:s}}}=this;if(n===0)return;const o=b.Sub(r,t);this.prevPoint=r.clone();const i=o.len(),a=i?o.div(i):new b(0,0),l=s.clone().lrp(a.mul(i/n),.5);Math.abs(l.x)<.01&&(l.x=0),Math.abs(l.y)<.01&&(l.y=0),s.equals(l)||(this.editor.inputs.pointerVelocity=l)});this.editor=n,this.editor.disposables.add(this.dispose),this.start()}}var qG=Object.defineProperty,ZG=Object.getOwnPropertyDescriptor,Mr=(e,n,t,r)=>{for(var s=ZG(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&qG(n,t,s),s};class hr{constructor(n,t){g(this,"systemColorScheme",Mt("systemColorScheme","light"));g(this,"updateUserPreferences",n=>{this.user.setUserPreferences({...this.user.userPreferences.get(),...n})});if(this.user=n,this.inferDarkMode=t,typeof window>"u"||!("matchMedia"in window))return;const r=window.matchMedia("(prefers-color-scheme: dark)");r!=null&&r.matches&&this.systemColorScheme.set("dark"),r==null||r.addEventListener("change",s=>{s.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")})}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),isSnapMode:this.getIsSnapMode(),colorScheme:this.user.userPreferences.get().colorScheme,isDarkMode:this.getIsDarkMode(),isWrapMode:this.getIsWrapMode(),isDynamicResizeMode:this.getIsDynamicResizeMode()}}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??Ds.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??Ds.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??Ds.name}getLocale(){return this.user.userPreferences.get().locale??Ds.locale}getColor(){return this.user.userPreferences.get().color??Ds.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??Ds.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??Ds.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??Ds.isDynamicSizeMode}getIsPasteAtCursorMode(){return this.user.userPreferences.get().isPasteAtCursorMode??Ds.isPasteAtCursorMode}}Mr([G],hr.prototype,"getUserPreferences");Mr([G],hr.prototype,"getIsDarkMode");Mr([G],hr.prototype,"getEdgeScrollSpeed");Mr([G],hr.prototype,"getAnimationSpeed");Mr([G],hr.prototype,"getId");Mr([G],hr.prototype,"getName");Mr([G],hr.prototype,"getLocale");Mr([G],hr.prototype,"getColor");Mr([G],hr.prototype,"getIsSnapMode");Mr([G],hr.prototype,"getIsWrapMode");Mr([G],hr.prototype,"getIsDynamicResizeMode");Mr([G],hr.prototype,"getIsPasteAtCursorMode");const QG={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"},JG=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class se{constructor(n,t){g(this,"performanceTracker");g(this,"id");g(this,"type");g(this,"shapeType");g(this,"initial");g(this,"children");g(this,"isLockable");g(this,"parent");g(this,"_path");g(this,"_current");g(this,"_isActive");g(this,"transition",(n,t={})=>{var o;const r=n.split(".");let s=this;for(let i=0;i{var s;const t=QG[n.name],r=this._current.__unsafe__getWithoutCapture();(s=this[t])==null||s.call(this,n),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(n)});g(this,"enter",(n,t)=>{var r;if(xt.measurePerformance.get()&&JG.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,n,t),this.children&&this.initial&&this.getIsActive()){const s=this.children[this.initial];this._current.set(s),s.enter(n,t)}});g(this,"exit",(n,t)=>{var r,s;xt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,n,t),this.getIsActive()||(s=this.getCurrent())==null||s.exit(n,t)});g(this,"_currentToolIdMask",Mt("curent tool id mask",void 0));g(this,"onWheel");g(this,"onPointerDown");g(this,"onPointerMove");g(this,"onLongPress");g(this,"onPointerUp");g(this,"onDoubleClick");g(this,"onTripleClick");g(this,"onQuadrupleClick");g(this,"onRightClick");g(this,"onMiddleClick");g(this,"onKeyDown");g(this,"onKeyUp");g(this,"onKeyRepeat");g(this,"onCancel");g(this,"onComplete");g(this,"onInterrupt");g(this,"onTick");g(this,"onEnter");g(this,"onExit");this.editor=n;const{id:r,children:s,initial:o,isLockable:i}=this.constructor;this.id=r,this._isActive=Mt("toolIsActive"+this.id,!1),this._current=Mt("toolState"+this.id,void 0),this._path=G("toolPath"+this.id,()=>{const a=this.getCurrent();return this.id+(a?`.${a.getPath()}`:"")}),this.parent=t??{},this.parent?s&&o?(this.type="branch",this.initial=o,this.children=Object.fromEntries(s().map(a=>[a.id,new a(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(a=>[a.id,new a(this.editor,this)])),this._current.set(this.children[this.initial]))),this.isLockable=i,this.performanceTracker=new G2}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(n){this._currentToolIdMask.set(n)}}g(se,"id"),g(se,"initial"),g(se,"children"),g(se,"isLockable",!0);class Hh extends se{constructor(){super(...arguments);g(this,"onKeyDown",t=>{var r;switch(t.code){case"KeyZ":{if(!(t.shiftKey||t.ctrlKey)){const s=this.getCurrent();s&&((r=s.getCurrent())==null?void 0:r.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...t,onInteractionEnd:s.id})}break}}})}}g(Hh,"id","root"),g(Hh,"initial",""),g(Hh,"children",()=>[]);var eV=Object.defineProperty,tV=Object.getOwnPropertyDescriptor,ne=(e,n,t,r)=>{for(var s=tV(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&eV(n,t,s),s};class Z extends XW{constructor({store:t,user:r,shapeUtils:s,bindingUtils:o,tools:i,getContainer:a,cameraOptions:l,initialState:c,autoFocus:u,inferDarkMode:h,options:p}){super();g(this,"options");g(this,"store");g(this,"root");g(this,"disposables",new Set);g(this,"isDisposed",!1);g(this,"_tickManager");g(this,"snaps");g(this,"timers");g(this,"user");g(this,"textMeasure");g(this,"environment");g(this,"scribbles");g(this,"sideEffects");g(this,"edgeScrollManager");g(this,"focusManager");g(this,"getContainer");g(this,"shapeUtils");g(this,"styleProps");g(this,"bindingUtils");g(this,"history");g(this,"_shouldIgnoreShapeLock",!1);g(this,"_crashingError",null);g(this,"_updateInstanceState",(t,r)=>{this.run(()=>{this.store.put([{...this.getInstanceState(),...t}])},r)});g(this,"_isChangingStyleTimeout",-1);g(this,"setCursor",t=>(this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...t}}),this));g(this,"_updateCurrentPageState",t=>{this.store.update(t.id??this.getCurrentPageState().id,r=>({...r,...t}))});g(this,"_cameraOptions",Mt("camera options",PC));g(this,"_viewportAnimation",null);g(this,"_willSetInitialBounds",!0);g(this,"_isLockedOnFollowingUser",Mt("isLockedOnFollowingUser",!1));g(this,"_cameraState",Mt("camera state","idle"));g(this,"_cameraStateTimeoutRemaining",0);g(this,"_decayCameraStateTimeout",t=>{this._cameraStateTimeoutRemaining-=t,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"))});g(this,"_tickCameraState",()=>{this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))});g(this,"_currentPageShapeIds");g(this,"_parentIdsToChildIds");g(this,"animatingShapes",new Map);g(this,"_updateShapes",t=>{this.getInstanceState().isReadonly||this.run(()=>{var i,a;const r=[];let s,o;for(let l=0,c=t.length;l{this.inputs.shiftKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Shift",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"ShiftLeft"})});g(this,"_altKeyTimeout",-1);g(this,"_setAltKeyTimeout",()=>{this.inputs.altKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Alt",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"AltLeft"})});g(this,"_ctrlKeyTimeout",-1);g(this,"_setCtrlKeyTimeout",()=>{this.inputs.ctrlKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Ctrl",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"ControlLeft"})});g(this,"_restoreToolId","select");g(this,"_pinchStart",1);g(this,"_didPinch",!1);g(this,"_selectedShapeIdsAtPointerDown",[]);g(this,"_longPressTimeout",-1);g(this,"capturedPointerId",null);g(this,"performanceTracker");g(this,"performanceTrackerTimeout",-1);g(this,"dispatch",t=>(this._pendingEventsForNextTick.push(t),t.type==="pointer"&&t.name==="pointer_move"||t.type==="wheel"||t.type==="pinch"||this._flushEventsForTick(0),this));g(this,"_pendingEventsForNextTick",[]);g(this,"_flushEventForTick",t=>{if(this.getCrashingError())return this;const{inputs:r}=this,{type:s}=t;if(t.type==="misc"){(t.name==="cancel"||t.name==="complete")&&(this.inputs.isDragging=!1,this.inputs.isPanning&&(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0}))),this.root.handleEvent(t);return}t.shiftKey?(clearTimeout(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,r.shiftKey=!0):!t.shiftKey&&r.shiftKey&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=this.timers.setTimeout(this._setShiftKeyTimeout,150)),t.altKey?(clearTimeout(this._altKeyTimeout),this._altKeyTimeout=-1,r.altKey=!0):!t.altKey&&r.altKey&&this._altKeyTimeout===-1&&(this._altKeyTimeout=this.timers.setTimeout(this._setAltKeyTimeout,150)),t.ctrlKey?(clearTimeout(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,r.ctrlKey=!0):!t.ctrlKey&&r.ctrlKey&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=this.timers.setTimeout(this._setCtrlKeyTimeout,150));const{originPagePoint:o,currentPagePoint:i}=r;r.isPointing||(r.isDragging=!1);const a=this.store.unsafeGetWithoutCapture(mn),l=this.store.get(this._getCurrentPageStateId()),c=this._cameraOptions.__unsafe__getWithoutCapture();switch(s){case"pinch":{if(c.isLocked)return;switch(clearTimeout(this._longPressTimeout),this._updateInputsFromEvent(t),t.name){case"pinch_start":{if(r.isPinching)return;r.isEditing||(this._pinchStart=this.getCamera().z,this._selectedShapeIdsAtPointerDown.length||(this._selectedShapeIdsAtPointerDown=[...l.selectedShapeIds]),this._didPinch=!0,r.isPinching=!0,this.interrupt());return}case"pinch":{if(!r.isPinching)return;const{point:{z:u=1},delta:{x:h,y:p}}=t,{x:f,y:S}=b.SubXY(t.point,a.screenBounds.x,a.screenBounds.y);this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:y,y:x,z:m}=Fd(()=>this.getCamera()),{panSpeed:v,zoomSpeed:w}=c;this._setCamera(new b(y+h*v/m-f/m+f/(u*w),x+p*v/m-S/m+S/(u*w),u*w),{immediate:!0});return}case"pinch_end":{if(!r.isPinching)return this;r.isPinching=!1;const{_selectedShapeIdsAtPointerDown:u}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,u.length>0&&this.once("tick",()=>{this._didPinch||this.setSelectedShapes(u)}));return}}}case"wheel":{if(c.isLocked)return;if(this._updateInputsFromEvent(t),!this.getIsMenuOpen()){const{panSpeed:u,zoomSpeed:h,wheelBehavior:p}=c;if(p!=="none"){this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:f,y:S,z:y}=Fd(()=>this.getCamera()),{x,y:m,z:v=0}=t.delta;let w=p;switch(r.ctrlKey&&(w=p==="pan"?"zoom":"pan"),w){case"zoom":{const{x:C,y:E}=this.inputs.currentScreenPoint;let k=v;p==="zoom"&&(Math.abs(m)>10?k=10*Math.sign(m)/100:k=m/100);const I=y+(k??0)*h*y;this._setCamera(new b(f+(C/I-C)-(C/y-C),S+(E/I-E)-(E/y-E),I),{immediate:!0}),this.maybeTrackPerformance("Zooming");return}case"pan":{this._setCamera(new b(f+x*u/y,S+m*u/y,y),{immediate:!0}),this.maybeTrackPerformance("Panning");return}}}}break}case"pointer":{if(r.isPinching)return;this._updateInputsFromEvent(t);const{isPen:u}=t,{isPenMode:h}=a;switch(t.name){case"pointer_down":{if(h&&!u)return;if(this.clearOpenMenus(),this.inputs.isPanning||(this._longPressTimeout=this.timers.setTimeout(()=>{this.dispatch({...t,point:this.inputs.currentScreenPoint,name:"long_press"})},this.options.longPressDurationMs)),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),t.button===IC&&(this.capturedPointerId=t.pointerId),r.buttons.add(t.button),r.isPointing=!0,r.isDragging=!1,!h&&u&&this.updateInstanceState({isPenMode:!0}),t.button===EC?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):t.button===Gd&&(this.inputs.isPanning||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout)),this.inputs.isPanning)return this.stopCameraAnimation(),this.setCursor({type:"grabbing",rotation:0}),this;break}case"pointer_move":{if(!u&&h)return;const{x:p,y:f,z:S}=Fd(()=>this.getCamera());if(this.inputs.isPanning&&this.inputs.isPointing){const{currentScreenPoint:y,previousScreenPoint:x}=this.inputs,{panSpeed:m}=c,v=b.Sub(y,x);this.setCamera(new b(p+v.x*m/S,f+v.y*m/S,S),{immediate:!0}),this.maybeTrackPerformance("Panning");return}r.isPointing&&!r.isDragging&&b.Dist2(o,i)*this.getZoomLevel()>(a.isCoarsePointer?this.options.coarseDragDistanceSquared:this.options.dragDistanceSquared)/S&&(r.isDragging=!0,clearTimeout(this._longPressTimeout));break}case"pointer_up":{if(r.isDragging=!1,r.isPointing=!1,clearTimeout(this._longPressTimeout),r.buttons.delete(t.button),this.getIsMenuOpen()||a.isPenMode&&!u)return;if(this.capturedPointerId===t.pointerId&&(this.capturedPointerId=null,t.button=0),r.isPanning){r.keys.has("Space")||(r.isPanning=!1);const p=this.inputs.pointerVelocity,f=Math.min(2,p.len());switch(t.button){case IC:{this.setCursor({type:"grab",rotation:0});break}case Gd:this.inputs.keys.has(" ")?this.setCursor({type:"grab",rotation:0}):this.setCursor({type:this._prevCursor,rotation:0})}f>0&&this.slideCamera({speed:f,direction:p})}else t.button===EC&&(this.complete(),this.setCurrentTool(this._restoreToolId));break}}break}case"keyboard":{switch(t.key==="ShiftRight"&&(t.key="ShiftLeft"),t.key==="AltRight"&&(t.key="AltLeft"),t.code==="ControlRight"&&(t.code="ControlLeft"),t.name){case"key_down":{r.keys.add(t.code),t.code==="Space"&&!t.ctrlKey&&(this.inputs.isPanning||(this._prevCursor=a.cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout),this.setCursor({type:this.inputs.isPointing?"grabbing":"grab",rotation:0}));break}case"key_up":{r.keys.delete(t.code),t.code==="Space"&&(this.inputs.buttons.has(Gd)||(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0})));break}}break}}if(t.type==="pointer"){t.button===Gd?t.name="middle_click":t.button===J0&&(t.name="right_click");const{isPenMode:u}=this.store.unsafeGetWithoutCapture(mn);if(t.isPen===u){const h=this._clickManager.handlePointerEvent(t);if(t.name!==h.name){this.root.handleEvent(t),this.emit("event",t),this.root.handleEvent(h),this.emit("event",h);return}}}return this.root.handleEvent(t),this.emit("event",t),this});this.options={...lG,...p},this.store=t,this.disposables.add(this.store.dispose.bind(this.store)),this.history=new AG({store:t,annotateError:T=>{this.annotateError(T,{origin:"history.batch",willCrashApp:!0}),this.crash(T)}}),this.snaps=new gg(this),this.timers=new U9,this.disposables.add(this.timers.dispose.bind(this.timers)),this._cameraOptions.set({...PC,...l}),this.user=new hr(r??zM(),h??!1),this.getContainer=a??(()=>document.body),this.textMeasure=new YG(this),this._tickManager=new XG(this);class f extends Hh{}g(f,"initial",c??""),this.root=new f(this),this.root.children={};const S=qM(s),y={},x={},m=new Map;for(const T of S){const M=new T(this);y[T.type]=M;const D=ST(T.props??{});x[T.type]=D;for(const $ of D.keys())if(!m.has($.id))m.set($.id,$);else if(m.get($.id)!==$)throw Error(`Multiple style props with id "${$.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=y,this.styleProps=x;const v=VM(o),w={};for(const T of v){const M=new T(this);w[T.type]=M}this.bindingUtils=w;for(const T of[...i]){if(ms(this.root.children,T.id))throw Error(`Can't override tool with id "${T.id}"`);this.root.children[T.id]=new T(this,this.root)}this.environment=new _G(this),this.scribbles=new DG(this);const C=(T,M)=>{let D=null;const $=T.selectedShapeIds.filter(R=>!M.has(R));$.length!==T.selectedShapeIds.length&&(D||(D={...T}),D.selectedShapeIds=$);const j=T.erasingShapeIds.filter(R=>!M.has(R));j.length!==T.erasingShapeIds.length&&(D||(D={...T}),D.erasingShapeIds=j),T.hoveredShapeId&&M.has(T.hoveredShapeId)&&(D||(D={...T}),D.hoveredShapeId=null),T.editingShapeId&&M.has(T.editingShapeId)&&(D||(D={...T}),D.editingShapeId=null);const O=T.hintingShapeIds.filter(R=>!M.has(R));return O.length!==T.hintingShapeIds.length&&(D||(D={...T}),D.hintingShapeIds=O),T.focusedGroupId&&M.has(T.focusedGroupId)&&(D||(D={...T}),D.focusedGroupId=null),D};this.sideEffects=this.store.sideEffects;let E=new Map;const k=new Set,I=new Set;let _=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var T,M,D,$;k.clear();for(const j of I){I.delete(j);const O=this.getShape(j);if(!O)continue;const R=this.getShapeUtil(O),K=(T=R.onChildrenChange)==null?void 0:T.call(R,O);K!=null&&K.length&&this.updateShapes(K)}if(_.size){const j=_;_=new Set;for(const O of j){const R=this.getBindingUtil(O);(M=R.onOperationComplete)==null||M.call(R)}}if(E.size){const j=E;E=new Map;for(const O of j.values())($=(D=this.getBindingUtil(O.binding)).onAfterDelete)==null||$.call(D,O)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(T,M)=>{var D,$,j,O;for(const R of this.getBindingsInvolvingShape(M))_.add(R.type),R.fromId===M.id&&(($=(D=this.getBindingUtil(R)).onAfterChangeFromShape)==null||$.call(D,{binding:R,shapeBefore:T,shapeAfter:M})),R.toId===M.id&&((O=(j=this.getBindingUtil(R)).onAfterChangeToShape)==null||O.call(j,{binding:R,shapeBefore:T,shapeAfter:M}));if(T.parentId!==M.parentId){const R=K=>{var z,W,Y,q;const B=this.getShape(K);if(B)for(const ae of this.getBindingsInvolvingShape(B))_.add(ae.type),ae.fromId===B.id&&((W=(z=this.getBindingUtil(ae)).onAfterChangeFromShape)==null||W.call(z,{binding:ae,shapeBefore:B,shapeAfter:B})),ae.toId===B.id&&((q=(Y=this.getBindingUtil(ae)).onAfterChangeToShape)==null||q.call(Y,{binding:ae,shapeBefore:B,shapeAfter:B}))};R(M.id),this.visitDescendants(M.id,R)}if(T.parentId!==M.parentId&&Tn(M.parentId)){const R=new Set([T.id]);this.visitDescendants(T.id,K=>{R.add(K)});for(const K of this.getPageStates()){if(K.pageId===M.parentId)continue;const B=C(K,R);B&&this.store.put([B])}}T.parentId&&An(T.parentId)&&I.add(T.parentId),M.parentId!==T.parentId&&An(M.parentId)&&I.add(M.parentId)},beforeDelete:T=>{var j,O,R,K;if(k.has(T.id))return;T.parentId&&An(T.parentId)&&I.add(T.parentId),k.add(T.id);const M=[];for(const B of this.getBindingsInvolvingShape(T)){_.add(B.type),M.push(B.id);const z=this.getBindingUtil(B);B.fromId===T.id?((j=z.onBeforeIsolateToShape)==null||j.call(z,{binding:B,removedShape:T}),(O=z.onBeforeDeleteFromShape)==null||O.call(z,{binding:B,shape:T})):((R=z.onBeforeIsolateFromShape)==null||R.call(z,{binding:B,removedShape:T}),(K=z.onBeforeDeleteToShape)==null||K.call(z,{binding:B,shape:T}))}M.length&&this.deleteBindings(M);const D=new Set([T.id]),$=me(this.getPageStates().map(B=>C(B,D)));$.length&&this.store.put($)}},binding:{beforeCreate:T=>{var D,$;const M=($=(D=this.getBindingUtil(T)).onBeforeCreate)==null?void 0:$.call(D,{binding:T});return M||T},afterCreate:T=>{var M,D;_.add(T.type),(D=(M=this.getBindingUtil(T)).onAfterCreate)==null||D.call(M,{binding:T})},beforeChange:(T,M)=>{var $,j;const D=(j=($=this.getBindingUtil(M)).onBeforeChange)==null?void 0:j.call($,{bindingBefore:T,bindingAfter:M});return D||M},afterChange:(T,M)=>{var D,$;_.add(M.type),($=(D=this.getBindingUtil(M)).onAfterChange)==null||$.call(D,{bindingBefore:T,bindingAfter:M})},beforeDelete:T=>{var M,D;(D=(M=this.getBindingUtil(T)).onBeforeDelete)==null||D.call(M,{binding:T})},afterDelete:T=>{var M,D;(D=(M=this.getBindingUtil(T)).onAfterDelete)==null||D.call(M,{binding:T}),_.add(T.type)}},page:{afterCreate:T=>{const M=us.createId(T.id),D=zr.createId(T.id);this.store.has(M)||this.store.put([us.create({id:M})]),this.store.has(D)||this.store.put([zr.create({id:D,pageId:T.id})])},afterDelete:(T,M)=>{var j,O;if(((j=this.getInstanceState())==null?void 0:j.currentPageId)===T.id){const R=(O=this.getPages().find(K=>K.id!==T.id))==null?void 0:O.id;R?this.store.put([{...this.getInstanceState(),currentPageId:R}]):M==="user"&&this.store.ensureStoreIsUsable()}const D=us.createId(T.id),$=zr.createId(T.id);this.store.remove([D,$])}},instance:{afterChange:(T,M,D)=>{var $;if(!this.store.has(M.currentPageId)){const j=this.store.has(T.currentPageId)?T.currentPageId:($=this.getPages()[0])==null?void 0:$.id;j?this.store.update(M.id,O=>({...O,currentPageId:j})):D==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(T,M)=>{if((T==null?void 0:T.selectedShapeIds)!==(M==null?void 0:M.selectedShapeIds)){const D=M.selectedShapeIds.filter(j=>{var R,K;let O=(R=this.getShape(j))==null?void 0:R.parentId;for(;An(O);){if(M.selectedShapeIds.includes(O))return!1;O=(K=this.getShape(O))==null?void 0:K.parentId}return!0});let $=null;if(D.length>0){const j=this.findCommonAncestor(me(D.map(O=>this.getShape(O))),O=>this.isShapeOfType(O,"group"));j&&($=j)}else M!=null&&M.focusedGroupId&&($=M.focusedGroupId);(D.length!==M.selectedShapeIds.length||$!==M.focusedGroupId)&&this.store.put([{...M,selectedShapeIds:D,focusedGroupId:$??null}])}}}})),this._currentPageShapeIds=wG(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=xG(this.store),this.disposables.add(this.store.listen(T=>{this.emit("change",T)})),this.disposables.add(this.history.dispose),this.run(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})},{history:"ignore"}),c&&this.root.children[c]===void 0)throw Error(`No state found for initialState "${c}".`);this.root.enter(void 0,"initial"),this.edgeScrollManager=new EG(this),this.focusManager=new kG(this,u),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 G2}dispose(){this.disposables.forEach(t=>t()),this.disposables.clear(),this.isDisposed=!0}getShapeUtil(t){const r=typeof t=="string"?t:t.type,s=$n(this.shapeUtils,r);return Ye(s,`No shape util found for type "${r}"`),s}getBindingUtil(t){const r=typeof t=="string"?t:t.type,s=$n(this.bindingUtils,r);return Ye(s,`No binding util found for type "${r}"`),s}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}clearHistory(){return this.history.clear(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(t){return this.history.mark(t),this}squashToMark(t){return this.history.squashToMark(t),this}bail(){return this.history.bail(),this}bailToMark(t){return this.history.bailToMark(t),this}run(t,r){const s=this._shouldIgnoreShapeLock;this._shouldIgnoreShapeLock=(r==null?void 0:r.ignoreShapeLock)??s;try{this.history.batch(t,r)}finally{this._shouldIgnoreShapeLock=s}return this}batch(t,r){return this.run(t,r)}annotateError(t,{origin:r,willCrashApp:s,tags:o,extras:i}){const a=this.createErrorAnnotations(r,s);return L0(t,{tags:{...a.tags,...o},extras:{...a.extras,...i}}),s&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(t,r){try{const s=this.getEditingShapeId();return{tags:{origin:t,willCrashApp:r},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:s?this.getShape(s):void 0,inputs:this.inputs}}}catch{return{tags:{origin:t,willCrashApp:r},extras:{}}}}getCrashingError(){return this._crashingError}crash(t){return this._crashingError=t,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:t}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(t){const r=t.split(".").reverse();let s=this.root;for(;r.length>0;){const o=r.pop();if(!o)return!0;const i=s.getCurrent();if((i==null?void 0:i.id)===o){if(r.length===0)return!0;s=i;continue}else return!1}return!1}isInAny(...t){return t.some(r=>this.isIn(r))}setCurrentTool(t,r={}){return this.root.transition(t,r),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const t=this.getCurrentTool();return t?t.getCurrentToolIdMask()??t.id:""}getStateDescendant(t){var o;const r=t.split(".").reverse();let s=this.root;for(;r.length>0;){const i=r.pop();if(!i)return s;const a=(o=s.children)==null?void 0:o[i];if(!a)return;s=a}return s}getDocumentSettings(){return this.store.get(wv)}updateDocumentSettings(t){return this.run(()=>{this.store.put([{...this.getDocumentSettings(),...t}])},{history:"ignore"}),this}getInstanceState(){return this.store.get(mn)}updateInstanceState(t,r){return this._updateInstanceState(t,{history:"ignore",...r}),t.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),t.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},2e3))),this}getOpenMenus(){return this.getInstanceState().openMenus}addOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)||(r.add(t),this.updateInstanceState({openMenus:[...r]})),this}deleteOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)&&(r.delete(t),this.updateInstanceState({openMenus:[...r]})),this}clearOpenMenus(){return this.getOpenMenus().length&&this.updateInstanceState({openMenus:[]}),this}getIsMenuOpen(){return this.getOpenMenus().length>0}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return zr.createId(this.getCurrentPageId())}updateCurrentPageState(t){return this._updateCurrentPageState(t),this}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:t}=this.getCurrentPageState();return me(t.map(r=>this.store.get(r)))}setSelectedShapes(t){return this.run(()=>{const r=t.map(i=>typeof i=="string"?i:i.id),{selectedShapeIds:s}=this.getCurrentPageState(),o=new Set(s);if(r.length===o.size&&r.every(i=>o.has(i)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:r}])},{history:"record-preserveRedoStack"})}isAncestorSelected(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null,s=this.getShape(r);if(!s)return!1;const o=this.getSelectedShapeIds();return!!this.findShapeAncestor(s,i=>o.includes(i.id))}select(...t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);return this.setSelectedShapes(r),this}deselect(...t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=this.getSelectedShapeIds();return s.length>0&&r.length>0&&this.setSelectedShapes(s.filter(o=>!r.includes(o))),this}selectAll(){const t=this.getSortedChildIdsForParent(this.getCurrentPageId());return t.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(t)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var t;return((t=this.getOnlySelectedShape())==null?void 0:t.id)??null}getOnlySelectedShape(){const t=this.getSelectedShapes();return t.length===1?t[0]:null}getSelectionPageBounds(){const t=this.getCurrentPageState().selectedShapeIds;return t.length===0?null:Q.Common(me(t.map(r=>this.getShapePageBounds(r))))}getSelectionRotation(){const t=this.getSelectedShapeIds();let r=!1,s=0;for(let o=0,i=t.length;o{const i=this.getShapePageTransform(o);return i?i.applyToPoints(this.getShapeGeometry(o).bounds.corners):[]}).map(o=>o.rot(-r)));return s.point=s.point.rot(r),s}getSelectionRotatedScreenBounds(){const t=this.getSelectionRotatedPageBounds();if(!t)return;const{x:r,y:s}=this.pageToScreen(t.point),o=this.getZoomLevel();return new Q(r,s,t.width*o,t.height*o)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const t=this.getFocusedGroupId();return t?this.getShape(t):void 0}setFocusedGroup(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==null){const s=this.getShape(r);if(!s)throw Error(`Editor.setFocusedGroup: Shape with id ${r} does not exist`);if(!this.isShapeOfType(s,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${s.type}`)}return r===this.getFocusedGroupId()?this:this.run(()=>{this.store.update(this.getCurrentPageState().id,s=>({...s,focusedGroupId:r}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const t=this.getFocusedGroup();if(t){const r=this.findShapeAncestor(t,s=>this.isShapeOfType(s,"group"));this.setFocusedGroup((r==null?void 0:r.id)??null),this.select(t.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const t=this.getEditingShapeId();return t?this.getShape(t):void 0}setEditingShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==this.getEditingShapeId()){if(r){const s=this.getShape(r);if(s&&this.getShapeUtil(s).canEdit(s))return this.run(()=>{this._updateCurrentPageState({editingShapeId:r})},{history:"ignore"}),this}this.run(()=>{this._updateCurrentPageState({editingShapeId:null})},{history:"ignore"})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const t=this.getHoveredShapeId();return t?this.getShape(t):void 0}setHoveredShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;return r===this.getHoveredShapeId()?this:(this.run(()=>{this.updateCurrentPageState({hoveredShapeId:r})},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const t=this.getHintingShapeIds();return me(t.map(r=>this.getShape(r)))}setHintingShapes(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);return this.run(()=>{this._updateCurrentPageState({hintingShapeIds:R0(r)})},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const t=this.getErasingShapeIds();return me(t.map(r=>this.getShape(r)))}setErasingShapes(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);r.sort();const s=this.getErasingShapeIds();return this.run(()=>{if(r.length===s.length){for(let o=0;o{if(!r)this.updateCurrentPageState({croppingShapeId:null});else{const s=this.getShape(r),o=this.getShapeUtil(s);s&&o.canCrop(s)&&this.updateCurrentPageState({croppingShapeId:r})}},{history:"ignore"}),this}_unsafe_getCameraId(){return us.createId(this.getCurrentPageId())}getCamera(){const t=this.store.get(this._unsafe_getCameraId());if(this._isLockedOnFollowingUser.get()){const r=this.getCameraForFollowing();if(r)return{...t,...r}}return t}getViewportPageBoundsForFollowing(){const t=this.getInstanceState().followingUserId;if(!t)return null;const r=this.getCollaborators().find(p=>p.userId===t);if(!r)return null;const{w:s,h:o}=r.screenBounds,{x:i,y:a,z:l}=r.camera,c=new Q(-i,-a,s/l,o/l),u=this.getViewportScreenBounds().clone(),h=u.width/u.height;return u.width=c.width,u.height=u.width/h,u.heightw){const{x:j,y:O,z:R}=s,K=-j+h.w/R/2,B=-O+h.h/R/2;a=kt(a,C,w);const z=-j+h.w/a/2,W=-O+h.h/a/2;o=j+z-K,i=O+W-B}const E=S/a-y.x,k=f/a-y.y,I=(h.w-S*2)/a-y.w,_=(h.h-f*2)/a-y.h,T=E+I*p.origin.x,M=k+_*p.origin.y,D=typeof p.behavior=="string"?p.behavior:p.behavior.x,$=typeof p.behavior=="string"?p.behavior:p.behavior.y;if(r!=null&&r.reset)o=T,i=M;else{switch(D){case"fixed":{o=T;break}case"contain":{au||a{const l={...s,x:o,y:i,z:a};this.run(()=>{this.store.put([l])},{history:"ignore"});const{currentScreenPoint:c,currentPagePoint:u}=this.inputs,{screenBounds:h}=this.store.unsafeGetWithoutCapture(mn);if(c.x/a-o!==u.x||c.y/a-i!==u.y){const p={type:"pointer",target:"canvas",name:"pointer_move",point:b.AddXY(c,h.x,h.y),pointerId:CC.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,button:0,isPen:this.getInstanceState().isPenMode??!1};r!=null&&r.immediate?this._flushEventForTick(p):this.dispatch(p)}this._tickCameraState()}),this)}setCamera(t,r){const{isLocked:s}=this._cameraOptions.__unsafe__getWithoutCapture();if(s&&!(r!=null&&r.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const o=b.Cast(t);Number.isFinite(o.x)||(o.x=0),Number.isFinite(o.y)||(o.y=0),(o.z===void 0||!Number.isFinite(o.z))&&(t.z=this.getZoomLevel());const i=this.getConstrainedCamera(o,r);if(r!=null&&r.animation){const{width:a,height:l}=this.getViewportScreenBounds();this._animateToViewport(new Q(-i.x,-i.y,a/i.z,l/i.z),r)}else this._setCamera(i,{...r,force:!0});return this}centerOnPoint(t,r){const{isLocked:s}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const{width:o,height:i}=this.getViewportPageBounds();return this.setCamera(new b(-(t.x-o/2),-(t.y-i/2),this.getCamera().z),r),this}zoomToFit(t){const r=[...this.getCurrentPageShapeIds()];if(r.length<=0)return this;const s=Q.Common(me(r.map(o=>this.getShapePageBounds(o))));return this.zoomToBounds(s,t),this}resetZoom(t=this.getViewportScreenCenter(),r){const{isLocked:s,constraints:o}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const i=this.getCamera(),{x:a,y:l,z:c}=i,{x:u,y:h}=t;let p=1;if(o){const f=this.getInitialZoom();c!==f&&(p=f)}return this.setCamera(new b(a+(u/p-u)-(u/c-u),l+(h/p-h)-(h/c-h),p),r),this}zoomIn(t=this.getViewportScreenCenter(),r){const{isLocked:s}=this.getCameraOptions();if(s&&!(r!=null&&r.force))return this;const{x:o,y:i,z:a}=this.getCamera(),{zoomSteps:l}=this.getCameraOptions();if(l!==null&&l.length>1){const c=this.getBaseZoom();let u=Ut(l)*c;for(let h=1;h1){const i=this.getBaseZoom(),{x:a,y:l,z:c}=this.getCamera();let u=o[0]*i;for(let h=o.length-1;h>0;h--){const p=o[h-1]*i,f=o[h]*i;if(!(f-c>=(f-p)/2)){u=p;break}}this.setCamera(new b(a+(t.x/u-t.x)-(t.x/c-t.x),l+(t.y/u-t.y)-(t.y/c-t.y),u),r)}return this}zoomToSelection(t){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;const s=this.getSelectionPageBounds();return s&&this.zoomToBounds(s,{targetZoom:Math.max(1,this.getZoomLevel()),...t}),this}zoomToBounds(t,r){const s=this._cameraOptions.__unsafe__getWithoutCapture();if(s.isLocked&&!(r!=null&&r.force))return this;const o=this.getViewportScreenBounds(),i=(r==null?void 0:r.inset)??Math.min(jH,o.width*.28),a=this.getBaseZoom(),l=s.zoomSteps[0],c=Ut(s.zoomSteps);let u=kt(Math.min((o.width-i)/t.w,(o.height-i)/t.h),l*a,c*a);return(r==null?void 0:r.targetZoom)!==void 0&&(u=Math.min(r.targetZoom,u)),this.setCamera(new b(-t.x+(o.width-t.w*u)/2/u,-t.y+(o.height-t.h*u)/2/u,u),r),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(t){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=t;const{elapsed:r,easing:s,duration:o,start:i,end:a}=this._viewportAnimation;if(r>o){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new b(-a.x,-a.y,this.getViewportScreenBounds().width/a.width));return}const l=o-r,c=s(1-l/o),u=i.minX+(a.minX-i.minX)*c,h=i.minY+(a.minY-i.minY)*c,p=i.maxX+(a.maxX-i.maxX)*c;this._setCamera(new b(-u,-h,this.getViewportScreenBounds().width/(p-u)),{force:!0})}_animateToViewport(t,r={animation:ny}){const{animation:s,...o}=r;if(!s)return;const{duration:i=0,easing:a=At.easeInOutCubic}=s,l=this.user.getAnimationSpeed(),c=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),i===0||l===0?this._setCamera(new b(-t.x,-t.y,this.getViewportScreenBounds().width/t.width),{...o}):(this._viewportAnimation={elapsed:0,duration:i/l,easing:a,start:c.clone(),end:t.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(t={}){const{isLocked:r}=this.getCameraOptions();if(r&&!(t!=null&&t.force))return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:o,friction:i=this.options.cameraSlideFriction,direction:a,speedThreshold:l=.01}=t;let c=Math.min(o,1);const u=()=>{this.off("tick",h),this.off("stop-camera-animation",u)};this.once("stop-camera-animation",u);const h=p=>{const{x:f,y:S,z:y}=this.getCamera(),x=b.Mul(a,c*p/y);c*=1-i,co.userId===t);return s?(this.run(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const o=s.currentPageId===this.getCurrentPageId();o||this.setCurrentPage(s.currentPageId),r&&r.animation&&!o&&(r.animation=void 0),this.centerOnPoint(s.cursor,r);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,t]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(t);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(t,r=!1){t.width=Math.max(t.width,1),t.height=Math.max(t.height,1);const s=[t.minY!==0,!Wo(document.body.scrollWidth,t.maxX,1),!Wo(document.body.scrollHeight,t.maxY,1),t.minX!==0],{screenBounds:o,insets:i}=this.getInstanceState();if(t.equals(o)&&s.every((l,c)=>l===i[c]))return this;const{_willSetInitialBounds:a}=this;if(this._willSetInitialBounds=!1,a)this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this.setCamera(this.getCamera());else if(r&&!this.getInstanceState().followingUserId){const l=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this.centerOnPoint(l)}else this.updateInstanceState({screenBounds:t.toJson(),insets:s}),this._setCamera(b.From({...this.getCamera()}));return this._tickCameraState(),this}getViewportScreenBounds(){const{x:t,y:r,w:s,h:o}=this.getInstanceState().screenBounds;return new Q(t,r,s,o)}getViewportScreenCenter(){const t=this.getViewportScreenBounds();return new b(t.midX-t.minX,t.midY-t.minY)}getViewportPageBounds(){const{w:t,h:r}=this.getViewportScreenBounds(),{x:s,y:o,z:i}=this.getCamera();return new Q(-s,-o,t/i,r/i)}screenToPage(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(mn),{x:s,y:o,z:i=1}=this.getCamera();return new b((t.x-r.x)/i-s,(t.y-r.y)/i-o,t.z??.5)}pageToScreen(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(mn),{x:s,y:o,z:i=1}=this.getCamera();return new b((t.x+s)*i+r.x,(t.y+o)*i+r.y,t.z??.5)}pageToViewport(t){const{x:r,y:s,z:o=1}=this.getCamera();return new b((t.x+r)*o,(t.y+s)*o,t.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const t=this._getCollaboratorsQuery().get();return t.length?[...new Set(t.map(s=>s.userId))].sort().map(s=>t.filter(i=>i.userId===s).sort((i,a)=>a.lastActivityTimestamp-i.lastActivityTimestamp)[0]):Gs}getCollaboratorsOnCurrentPage(){const t=this.getCurrentPageId();return this.getCollaborators().filter(r=>r.currentPageId===t)}startFollowingUser(t){this.stopFollowingUser();const r=this._getCollaboratorsQuery().get().filter(i=>i.userId===t);if(!r.length)return console.warn("User not found"),this;const s=this.user.getId();if(s||console.warn("You should set the userId for the current instance before following a user"),r.some(i=>i.followingUserId===s))return this;const o=G("latestLeaderPresence",()=>this.getCollaborators().find(i=>i.userId===t));return gs(()=>{this.updateInstanceState({followingUserId:t},{history:"ignore"});const i=oa("update current page",()=>{const c=o.get();if(!c){this.stopFollowingUser();return}c.currentPageId!==this.getCurrentPageId()&&this.getPage(c.currentPageId)&&this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:c.currentPageId}]),this._isLockedOnFollowingUser.set(!0)},{history:"ignore"})}),a=()=>{i(),this._isLockedOnFollowingUser.set(!1),this.off("frame",l),this.off("stop-following",a)},l=()=>{if(!o.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const u=this.user.getAnimationSpeed();if(u===0){this._isLockedOnFollowingUser.set(!0);return}const h=this.getViewportPageBoundsForFollowing();if(!h){this.stopFollowingUser();return}const p=this.getViewportPageBounds(),f=Math.abs(h.minX-p.minX)+Math.abs(h.maxX-p.maxX),S=Math.abs(h.minY-p.minY)+Math.abs(h.maxY-p.maxY);if(f{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")},{history:"ignore"}),this}getUnorderedRenderingShapes(t){const r=[];let s=this.options.maxShapesPerPage*2,o=this.options.maxShapesPerPage;const i=this.getErasingShapeIds(),a=(c,u,h)=>{const p=this.getShape(c);if(!p)return;u*=p.opacity;let f=!1;const S=this.getShapeUtil(p);t&&(f=!h&&i.includes(c),f&&(u*=.32)),r.push({id:c,shape:p,util:S,index:s,backgroundIndex:o,opacity:u}),s+=1,o+=1;const y=this.getSortedChildIdsForParent(c);if(!y.length)return;let x=null;S.providesBackgroundForChildren(p)&&(x=o,o=s,s+=this.options.maxShapesPerPage);for(const m of y)a(m,u,h||f);x!==null&&(o=x)},l=t?[this.getCurrentPage()]:this.getPages();for(const c of l)for(const u of this.getSortedChildIdsForParent(c.id))a(u,1,!1);return r}getCameraState(){return this._cameraState.get()}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(L9)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return this._getAllPagesQuery().get().sort(an)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(t){return this.store.get(typeof t=="string"?t:t.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(t){const r=typeof t=="string"?t:t.id,s=this.store.query.exec("shape",{parentId:{eq:r}});return this.getShapeAndDescendantIds(s.map(o=>o.id))}setCurrentPage(t){const r=typeof t=="string"?t:t.id;return this.store.has(r)?(this.stopFollowingUser(),this.complete(),this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:r}])},{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(t){return this.getInstanceState().isReadonly?this:this.getPage(t.id)?this.run(()=>this.store.update(t.id,s=>({...s,...t}))):this}createPage(t){return this.run(()=>{if(this.getInstanceState().isReadonly||this.getPages().length>=this.options.maxPages)return;const r=this.getPages(),s=hG(t.name??"Page 1",r.map(a=>a.name));let o=t.index;(!o||r.some(a=>a.index===o))&&(o=Fr(r[r.length-1].index));const i=to.create({meta:{},...t,name:s,index:o});this.store.put([i])}),this}deletePage(t){const r=typeof t=="string"?t:t.id;return this.run(()=>{if(this.getInstanceState().isReadonly)return;const s=this.getPages();if(s.length===1)return;const o=this.getPage(r);if(o){if(r===this.getCurrentPageId()){const i=s.findIndex(l=>l.id===r),a=s[i-1]??s[i+1];this.setCurrentPage(a.id)}this.store.remove([o.id])}}),this}duplicatePage(t,r=to.createId()){if(this.getPages().length>=this.options.maxPages)return this;const s=typeof t=="string"?t:t.id,o=this.getPage(s);if(!o)return this;const i={...this.getCamera()},a=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(o.id));return this.run(()=>{var u;const l=this.getPages(),c=vu(o.index,(u=l[l.indexOf(o)+1])==null?void 0:u.index);if(this.createPage({name:o.name+" Copy",id:r,index:c}),this.setCurrentPage(r),this.setCamera(i),a)return this.putContentOntoCurrentPage(a)}),this}renamePage(t,r){const s=typeof t=="string"?t:t.id;return this.getInstanceState().isReadonly?this:(this.updatePage({id:s,name:r}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.run(()=>this.store.put(t),{history:"ignore"}),this)}updateAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.run(()=>{this.store.put(t.map(r=>({...this.store.get(r.id),...r})))},{history:"ignore"}),this)}deleteAssets(t){if(this.getInstanceState().isReadonly)return this;const r=typeof t[0]=="string"?t:t.map(s=>s.id);return r.length<=0?this:(this.run(()=>this.store.remove(r),{history:"ignore"}),this)}getAsset(t){return this.store.get(typeof t=="string"?t:t.id)}async resolveAssetUrl(t,r){if(!t)return null;const s=this.getAsset(t);if(!s)return null;const{screenScale:o=1,shouldResolveToOriginal:i=!1}=r,l=Math.max(.125,(h=>Math.pow(2,Math.ceil(Math.log2(h))))(o)),c="connection"in navigator?navigator.connection.effectiveType:null,u=this.getInstanceState().devicePixelRatio;return await this.store.props.assets.resolve(s,{screenScale:o||1,steppedScreenScale:l,dpr:u,networkEffectiveType:c,shouldResolveToOriginal:i})}async uploadAsset(t,r){return await this.store.props.assets.upload(t,r)}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",t=>this.getShapeUtil(t).getGeometry(t),(t,r)=>t.props===r.props)}getShapeGeometry(t){return this._getShapeGeometryCache().get(typeof t=="string"?t:t.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",t=>{var r,s;return(s=(r=this.getShapeUtil(t)).getHandles)==null?void 0:s.call(r,t)})}getShapeHandles(t){return this._getShapeHandlesCache().get(typeof t=="string"?t:t.id)}getShapeLocalTransform(t){const r=typeof t=="string"?t:t.id,s=this.getShape(r);if(!s)throw Error("Editor.getTransform: shape not found");return oe.Identity().translate(s.x,s.y).rotate(s.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",t=>{if(Tn(t.parentId))return this.getShapeLocalTransform(t);const r=this._getShapePageTransformCache().get(t.parentId)??oe.Identity();return oe.Compose(r,this.getShapeLocalTransform(t))})}getShapeParentTransform(t){const r=typeof t=="string"?t:t.id,s=this.getShape(r);return!s||Tn(s.parentId)?oe.Identity():this._getShapePageTransformCache().get(s.parentId)??oe.Identity()}getShapePageTransform(t){const r=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(r)??oe.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",t=>{const r=this._getShapePageTransformCache().get(t.id);return r?Q.FromPoints(oe.applyToPoints(r,this.getShapeGeometry(t).vertices)):new Q})}getShapePageBounds(t){return this._getShapePageBoundsCache().get(typeof t=="string"?t:t.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",t=>{const r=this._getShapeMaskCache().get(t.id);if(!r)return;if(r.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const s=this._getShapePageTransformCache().get(t.id);return s?`polygon(${oe.applyToPoints(oe.Inverse(s),r).map(i=>`${i.x}px ${i.y}px`).join(",")})`:void 0})}getShapeClipPath(t){return this._getShapeClipPathCache().get(typeof t=="string"?t:t.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",t=>{if(Tn(t.parentId))return;const r=this.getShapeAncestors(t.id).filter(o=>this.isShapeOfType(o,"frame"));return r.length===0?void 0:r.map(o=>this._getShapePageTransformCache().get(o.id).applyToPoints(this.getShapeGeometry(o).vertices)).reduce((o,i)=>{if(!(i&&o))return;const a=KC(o,i);return a?a.map(b.Cast):[]})})}getShapeMask(t){return this._getShapeMaskCache().get(typeof t=="string"?t:t.id)}getShapeMaskedPageBounds(t){return typeof t!="string"&&(t=t.id),this._getShapeMaskedPageBoundsCache().get(t)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",t=>{const r=this._getShapePageBoundsCache().get(t.id);if(!r)return;const s=this._getShapeMaskCache().get(t.id);if(s){if(s.length===0)return;const{corners:o}=r;if(o.every((a,l)=>a&&b.Equals(a,s[l])))return r.clone();const i=KC(s,o);return i?Q.FromPoints(i):void 0}return r})}getShapeAncestors(t,r=[]){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return r;const i=o.parentId;if(Tn(i))return r.reverse(),r;const a=this.store.get(i);return a?(r.push(a),this.getShapeAncestors(a,r)):r}findShapeAncestor(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return;const i=o.parentId;if(Tn(i))return;const a=this.getShape(i);if(a)return r(a)?a:this.findShapeAncestor(a,r)}hasAncestor(t,r){const s=typeof t=="string"?t:t==null?void 0:t.id,o=s&&this.getShape(s);return o?o.parentId===r?!0:this.hasAncestor(this.getShapeParent(o),r):!1}findCommonAncestor(t,r){var c;if(t.length===0)return;const s=typeof t[0]=="string"?t:t.map(u=>u.id),o=me(s.map(u=>this.getShape(u)));if(o.length===1){const u=o[0].parentId;return Tn(u)?void 0:r?(c=this.findShapeAncestor(o[0],r))==null?void 0:c.id:u}const[i,...a]=o;let l=this.getShapeParent(i);for(;l;){if(r&&!r(l)){l=this.getShapeParent(l);continue}if(a.every(u=>this.hasAncestor(u,l.id)))return l.id;l=this.getShapeParent(l)}}isShapeOrAncestorLocked(t){const r=typeof t=="string"?this.getShape(t):t;return r===void 0?!1:r.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(r))}_notVisibleShapes(){return vG(this)}getCulledShapes(){const t=this._notVisibleShapes().get(),r=this.getSelectedShapeIds(),s=this.getEditingShapeId(),o=new Set(t);return s&&o.delete(s),r.forEach(i=>{o.delete(i)}),o}getCurrentPageBounds(){let t;return this.getCurrentPageShapeIdsSorted().forEach(r=>{const s=this.getShapeMaskedPageBounds(r);s&&(t?t=t.expand(s):t=s.clone())}),t}getSelectedShapeAtPoint(t){const r=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(s=>s.type!=="group"&&r.includes(s.id)).reverse().find(s=>this.isPointInShape(s,t,{hitInside:!0,margin:0}))}getShapeAtPoint(t,r={}){const s=this.getZoomLevel(),o=this.getViewportPageBounds(),{filter:i,margin:a=0,hitLocked:l=!1,hitLabels:c=!1,hitInside:u=!1,hitFrameInside:h=!1}=r;let p=1/0,f=null,S=1/0,y=null;const x=(r.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(m=>{if(m.isLocked&&!l||this.isShapeOfType(m,"group"))return!1;const v=this.getShapeMask(m);return v&&!sr(t,v)?!1:i?i(m):!0});for(let m=x.length-1;m>=0;m--){const v=x[m],w=this.getShapeGeometry(v),C=w instanceof Wr,E=this.getPointInShapeSpace(v,t);if((this.isShapeOfType(v,"arrow")||this.isShapeOfType(v,"geo")&&v.props.fill==="none")&&v.props.text.trim()){for(const I of w.children)if(I.isLabel&&I.isPointInBounds(E))return v}if(this.isShapeOfType(v,"frame")){const I=w.distanceToPoint(E,u);if(Math.abs(I)<=a)return y||v;if(w.hitTestPoint(E,0,!0))return y||f||(h?v:void 0);continue}let k;if(C){let I=1/0;for(const _ of w.children){if(_.isLabel&&!c)continue;const T=_.distanceToPoint(E,u);Tthis.isPointInShape(s,t,r))}isPointInShape(t,r,s={}){const{hitInside:o=!1,margin:i=0}=s,a=typeof t=="string"?t:t.id,l=this.getShapeMask(a);return l&&!sr(r,l)?!1:this.getShapeGeometry(a).hitTestPoint(this.getPointInShapeSpace(t,r),i,o)}getPointInShapeSpace(t,r){const s=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(s).clone().invert().applyToPoint(r)}getPointInParentSpace(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return new b(0,0);if(Tn(o.parentId))return b.From(r);const i=this.getShapePageTransform(o.parentId);return i?i.clone().invert().applyToPoint(r):b.From(r)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),t=>this.store.get(t))}getCurrentPageShapesSorted(){const t=[],r=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let s=0,o=r.length;s!t.has(r))}isShapeOfType(t,r){const s=typeof t=="string"?this.getShape(t):t;return s?s.type===r:!1}getShape(t){const r=typeof t=="string"?t:t.id;if(An(r))return this.store.get(r)}getShapeParent(t){const r=typeof t=="string"?t:t==null?void 0:t.id;if(!r)return;const s=this.getShape(r);if(!(s===void 0||!An(s.parentId)))return this.store.get(s.parentId)}getShapeNearestSibling(t,r){return r?r.parentId===t.parentId?r:this.findShapeAncestor(r,o=>o.parentId===t.parentId):void 0}isShapeInPage(t,r=this.getCurrentPageId()){const s=typeof t=="string"?t:t.id,o=this.getShape(s);if(!o)return!1;let i=!1;if(o.parentId===r)i=!0;else{let a=this.getShape(o.parentId);e:for(;a;){if(a.parentId===r){i=!0;break e}a=this.getShape(a.parentId)}}return i}getAncestorPageId(t){const r=typeof t=="string"?t:t==null?void 0:t.id,s=r&&this.getShape(r);if(s)return Tn(s.parentId)?s.parentId:this.getAncestorPageId(this.getShape(s.parentId))}reparentShapes(t,r,s){const o=typeof t[0]=="string"?t:t.map(f=>f.id);if(o.length===0)return this;const i=[],a=Tn(r)?oe.Identity():this.getShapePageTransform(r),l=a.rotation();let c=[];const u=me(this.getSortedChildIdsForParent(r).map(f=>this.getShape(f)));if(s){const f=u.find(S=>S.index===s);if(f){const S=u[u.indexOf(f)+1];S?c=fl(s,S.index,o.length):c=qm(s,o.length)}else{const S=u.sort(an).find(y=>y.index>s);S?c=fl(s,S.index,o.length):c=qm(s,o.length)}}else{const f=u.length&&u[u.length-1];c=f?qm(f.index,o.length):xu(o.length)}const h=a.clone().invert(),p=me(o.map(f=>this.getShape(f)));return this.run(()=>{for(let f=0;fthis.getShape(o)).sort(an))r.add(s.id),this.visitDescendants(s,o=>{r.add(o)});return r}getDroppingOverShape(t,r=[]){const s=this.getCurrentPageShapesSorted();for(let o=s.length-1;o>=0;o--){const i=s[o];if(this.getSelectedShapeIds().includes(i.id)||!this.getShapeUtil(i).canDropShapes(i,r)||r.find(l=>l.id===i.id||this.hasAncestor(i,l.id)))continue;const a=this.getShapeMaskedPageBounds(i.id);if(a&&a.containsPoint(t)&&this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(i,t),0,!0))return i}}getOutermostSelectableShape(t,r){const s=typeof t=="string"?t:t.id,o=this.getShape(s);let i=o,a=o;const l=this.getFocusedGroup();for(;a;){if(this.isShapeOfType(a,"group")&&(l==null?void 0:l.id)!==a.id&&!this.hasAncestor(l,a.id)&&((r==null?void 0:r(a))??!0))i=a;else if((l==null?void 0:l.id)===a.id)break;a=this.getShapeParent(a)}return i}_getBindingsIndexCache(){const t=yG(this);return this.store.createComputedCache("bindingsIndex",r=>t.get().get(r.id))}getBinding(t){return this.store.get(t)}getBindingsFromShape(t,r){const s=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(s).filter(o=>o.fromId===s&&o.type===r)}getBindingsToShape(t,r){const s=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(s).filter(o=>o.toId===s&&o.type===r)}getBindingsInvolvingShape(t,r){const s=typeof t=="string"?t:t.id,o=this._getBindingsIndexCache().get(s)??Gs;return r?o.filter(i=>i.type===r):o}createBindings(t){const r=[];for(const s of t){const o=this.getShape(s.fromId),i=this.getShape(s.toId);if(!o||!i||!this.canBindShapes({fromShape:o,toShape:i,binding:s}))continue;const l=this.getBindingUtil(s.type).getDefaultProps(),c=this.store.schema.types.binding.create({...s,id:s.id??Oi(),props:{...l,...s.props}});r.push(c)}return this.store.put(r),this}createBinding(t){return this.createBindings([t])}updateBindings(t){const r=[];for(const s of t){if(!s)continue;const o=this.getBinding(s.id);if(!o)continue;const i=ns(o,s);if(i===o)continue;const a=this.getShape(i.fromId),l=this.getShape(i.toId);!a||!l||this.canBindShapes({fromShape:a,toShape:l,binding:i})&&r.push(i)}return this.store.put(r),this}updateBinding(t){return this.updateBindings([t])}deleteBindings(t,{isolateShapes:r=!1}={}){const s=t.map(o=>typeof o=="string"?o:o.id);return r?this.store.atomic(()=>{var o,i;for(const a of s){const l=this.getBinding(a);if(!l)continue;const c=this.getBindingUtil(l);(o=c.onBeforeIsolateFromShape)==null||o.call(c,{binding:l,removedShape:this.getShape(l.toId)}),(i=c.onBeforeIsolateToShape)==null||i.call(c,{binding:l,removedShape:this.getShape(l.fromId)}),this.store.remove([a])}}):this.store.remove(s),this}deleteBinding(t,r){return this.deleteBindings([t],r)}canBindShapes({fromShape:t,toShape:r,binding:s}){const o=typeof t=="string"?t:t.type,i=typeof r=="string"?r:r.type,a=typeof s=="string"?s:s.type,l={fromShapeType:o,toShapeType:i,bindingType:a};return o===i?this.getShapeUtil(o).canBind(l):this.getShapeUtil(o).canBind(l)&&this.getShapeUtil(i).canBind(l)}rotateShapesBy(t,r){if((typeof t[0]=="string"?t:t.map(i=>i.id)).length<=0)return this;const o=ZM({editor:this});return o?(Uh({delta:r,snapshot:o,editor:this,stage:"one-off"}),this):this}getChangesToTranslateShape(t,r){var i,a,l;let s=t;const o=this.getShapeUtil(t);return s=ns(s,((i=o.onTranslateStart)==null?void 0:i.call(o,s))??void 0),s=ns(s,{id:t.id,type:t.type,x:r.x,y:r.y}),s=ns(s,((a=o.onTranslate)==null?void 0:a.call(o,t,s))??void 0),s=ns(s,((l=o.onTranslateEnd)==null?void 0:l.call(o,t,s))??void 0),s}nudgeShapes(t,r){const s=typeof t[0]=="string"?t:t.map(i=>i.id);if(s.length<=0)return this;const o=[];for(const i of s){const a=this.getShape(i),l=b.From(r),c=this.getShapeParentTransform(a);c&&l.rot(-c.rotation()),o.push(this.getChangesToTranslateShape(a,l.add(a)))}return this.updateShapes(o),this}duplicateShapes(t,r){return this.run(()=>{const s=typeof t[0]=="string"?t:t.map(p=>p.id);if(s.length<=0)return this;const o=new Set(s),i=this.getShapeAndDescendantIds(s),a=[...i].reverse(),l=new Map;for(const p of i)l.set(p,je());const{shapesToCreate:c,bindingsToCreate:u}=qC(this,i,p=>{const f=[];for(const y of p){const x=this.getBinding(y);if(!x)continue;const m=Oi();f.push({...x,id:m,fromId:xr(l.get(x.fromId)),toId:xr(l.get(x.toId))})}const S=[];for(const y of a){const x=xr(l.get(y)),m=this.getShape(y);if(!m)continue;let v=0,w=0;if(r&&o.has(y)){const M=this.getShapeParentTransform(m),D=new b(r.x,r.y).rot(-M.rotation());v=D.x,w=D.y}const C=m.parentId,E=this.getSortedChildIdsForParent(C),k=E.indexOf(m.id),I=E[k+1],_=I?this.getShape(I):null,T=_?vu(m.index,_.index):Fr(m.index);S.push({...m,id:x,x:m.x+v,y:m.y+w,index:T,parentId:l.get(m.parentId)??m.parentId})}return{shapesToCreate:S,bindingsToCreate:f}});if(c.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage){qd(this);return}if(this.createShapes(c),this.createBindings(u),this.setSelectedShapes(me(s.map(p=>l.get(p)))),r!==void 0){const p=this.getSelectionPageBounds(),f=this.getViewportPageBounds();p&&!f.contains(p)&&this.centerOnPoint(p.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(t,r){const s=typeof t[0]=="string"?t:t.map(l=>l.id);if(s.length===0)return this;if(this.getInstanceState().isReadonly)return this;const o=this.getCurrentPageId();if(r===o)return this;if(!this.store.has(r))return this;const i=this.getContentFromCurrentPage(s);if(!i)return this;if(this.getPageShapeIds(r).size+i.shapes.length>this.options.maxShapesPerPage)return qd(this,r),this;const a=this.getCamera().z;return this.run(()=>{this.deleteShapes(s),this.setCurrentPage(r),this.setFocusedGroup(null),this.selectNone(),this.putContentOntoCurrentPage(i,{select:!0,preserveIds:!0,preservePosition:!0}),this.setCamera({...this.getCamera(),z:a}),this.centerOnPoint(this.getSelectionRotatedPageBounds().center)}),this}toggleLock(t){const r=typeof t[0]=="string"?t:t.map(a=>a.id);if(this.getInstanceState().isReadonly||r.length===0)return this;let s=!0,o=!0;const i=[];for(const a of r){const l=this.getShape(a);l&&(i.push(l),l.isLocked?o=!1:s=!1)}return this.run(()=>{o?(this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!0}))),this.setSelectedShapes([])):s?this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!1}))):this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!0})))}),this}sendToBack(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"toBack",r);return s&&this.updateShapes(s),this}sendBackward(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"backward",r);return s&&this.updateShapes(s),this}bringForward(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"forward",r);return s&&this.updateShapes(s),this}bringToFront(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id),s=Xd(this,"toFront",r);return s&&this.updateShapes(s),this}flipShapes(t,r){const s=typeof t[0]=="string"?t:t.map(a=>a.id);if(this.getInstanceState().isReadonly)return this;let o=me(s.map(a=>this.getShape(a)));if(!o.length)return this;o=me(o.map(a=>this.isShapeOfType(a,"group")?this.getSortedChildIdsForParent(a.id).map(l=>this.getShape(l)):a).flat());const i=Q.Common(me(o.map(a=>this.getShapePageBounds(a)))).center;return this.run(()=>{for(const a of o){const l=this.getShapeGeometry(a).bounds,c=this.getShapePageTransform(a.id);c&&this.resizeShape(a.id,{x:r==="horizontal"?-1:1,y:r==="vertical"?-1:1},{initialBounds:l,initialPageTransform:c,initialShape:a,mode:"scale_shape",isAspectRatioLocked:this.getShapeUtil(a).isAspectRatioLocked(a),scaleOrigin:i,scaleAxisRotation:0})}}),this}stackShapes(t,r,s){const o=typeof t[0]=="string"?t:t.map(x=>x.id);if(this.getInstanceState().isReadonly)return this;const i=o.map(x=>this.getShape(x)).filter(x=>x?this.getShapeUtil(x).canBeLaidOut(x):!1),a=i.length;if(s===0&&a<3||a<2)return this;const l=Object.fromEntries(i.map(x=>[x.id,this.getShapePageBounds(x)]));let c,u,h,p;r==="horizontal"?(c="x",u="minX",h="maxX",p="width"):(c="y",u="minY",h="maxY",p="height");let f;if(s===0){const x=[];i.sort((v,w)=>l[v.id][u]-l[w.id][u]);for(let v=0;vT.gap===I);_?_.count++:x.push({gap:I,count:1})}let m=0;x.forEach(v=>{v.count>m&&(m=v.count,f=v.gap)}),m===1&&(f=Math.max(0,x.reduce((v,w)=>v+w.gap*w.count,0)/(a-1)))}else f=s;const S=[];let y=l[i[0].id][h];return i.forEach((x,m)=>{var k,I;if(m===0)return;const v={x:0,y:0};v[c]=y+f-l[x.id][c];const w=this.getShapeParent(x),C=w?b.Rot(v,-this.getShapePageTransform(w).decompose().rotation):v,E=(I=(k=this.getShapeUtil(x)).onTranslateStart)==null?void 0:I.call(k,x);S.push(E?{...E,[c]:x[c]+C[c]}:{id:x.id,type:x.type,[c]:x[c]+C[c]}),y+=l[x.id][p]+f}),this.updateShapes(S),this}packShapes(t,r){var I,_;const s=typeof t[0]=="string"?t:t.map(T=>T.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=s.map(T=>this.getShape(T)).filter(T=>T?this.getShapeUtil(T).canBeLaidOut(T):!1),i={},a={};let l,c,u=0;for(let T=0;Ti[M.id].height-i[T.id].height);const f=Math.max(Math.ceil(Math.sqrt(u/.95)),p),S=[new Q(h.x,h.y,f,1/0)];let y=0,x=0,m,v;for(let T=0;T=0;M--)if(m=S[M],!(c.width>m.width||c.height>m.height)){c.x=m.x,c.y=m.y,x=Math.max(x,c.maxY),y=Math.max(y,c.maxX),c.width===m.width&&c.height===m.height?(v=S.pop(),Mc.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=me(s.map(c=>this.getShape(c))),i=Object.fromEntries(o.map(c=>[c.id,this.getShapePageBounds(c)])),a=Q.Common(me(Object.values(i))),l=[];return o.forEach(c=>{const u=i[c.id];if(!u)return;const h={x:0,y:0};switch(r){case"top":{h.y=a.minY-u.minY;break}case"center-vertical":{h.y=a.midY-u.minY-u.height/2;break}case"bottom":{h.y=a.maxY-u.minY-u.height;break}case"left":{h.x=a.minX-u.minX;break}case"center-horizontal":{h.x=a.midX-u.minX-u.width/2;break}case"right":{h.x=a.maxX-u.minX-u.width;break}}const p=this.getShapeParent(c),f=p?b.Rot(h,-this.getShapePageTransform(p).decompose().rotation):h;l.push(this.getChangesToTranslateShape(c,b.Add(c,f)))}),this.updateShapes(l),this}distributeShapes(t,r){const s=typeof t[0]=="string"?t:t.map(w=>w.id);if(this.getInstanceState().isReadonly)return this;if(s.length<3)return this;const o=s.length,i=me(s.map(w=>this.getShape(w))),a=Object.fromEntries(i.map(w=>[w.id,this.getShapePageBounds(w)]));let l,c,u,h,p;r==="horizontal"?(l="x",c="minX",u="maxX",h="midX",p="width"):(l="y",c="minY",u="maxY",h="midY",p="height");const f=[],S=i.sort((w,C)=>a[w.id][c]-a[C.id][c])[0],y=i.sort((w,C)=>a[C.id][u]-a[w.id][u])[0],x=a[S.id][h],m=(a[y.id][h]-x)/(o-1),v=x+m;return i.filter(w=>w!==S&&w!==y).sort((w,C)=>a[w.id][h]-a[C.id][h]).forEach((w,C)=>{const E={x:0,y:0};E[l]=v+m*C-a[w.id][p]/2-a[w.id][l];const k=this.getShapeParent(w),I=k?b.Rot(E,-this.getShapePageTransform(k).rotation()):E;f.push(this.getChangesToTranslateShape(w,b.Add(w,I)))}),this.updateShapes(f),this}stretchShapes(t,r){const s=typeof t[0]=="string"?t:t.map(c=>c.id);if(this.getInstanceState().isReadonly)return this;if(s.length<2)return this;const o=me(s.map(c=>this.getShape(c))),i=Object.fromEntries(s.map(c=>[c,this.getShapeGeometry(c).bounds])),a=Object.fromEntries(s.map(c=>[c,this.getShapePageBounds(c)])),l=Q.Common(me(Object.values(a)));switch(r){case"vertical":{this.run(()=>{for(const c of o){if(this.getShapePageTransform(c).rotation()%Le)continue;const h=i[c.id],p=a[c.id],f=new b(0,l.minY-p.minY),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:y,y:x}=b.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:y,y:x}]);const m=new b(1,l.height/p.height);this.resizeShape(c.id,m,{initialBounds:h,scaleOrigin:new b(p.center.x,l.minY),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}case"horizontal":{this.run(()=>{for(const c of o){const u=i[c.id],h=a[c.id];if(this.getShapePageTransform(c).rotation()%Le)continue;const f=new b(l.minX-h.minX,0),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:y,y:x}=b.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:y,y:x}]);const m=new b(l.width/h.width,1);this.resizeShape(c.id,m,{initialBounds:u,scaleOrigin:new b(l.minX,h.center.y),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}}return this}resizeShape(t,r,s={}){var S,y,x;const o=typeof t=="string"?t:t.id;if(this.getInstanceState().isReadonly)return this;Number.isFinite(r.x)||(r=new b(1,r.y)),Number.isFinite(r.y)||(r=new b(r.x,1));const i=s.initialShape??this.getShape(o);if(!i)return this;const a=s.scaleOrigin??((S=this.getShapePageBounds(o))==null?void 0:S.center);if(!a)return this;const l=s.initialPageTransform?oe.Cast(s.initialPageTransform):this.getShapePageTransform(o);if(!l)return this;const c=l.rotation();if(c==null)return this;const u=s.scaleAxisRotation??c,h=s.initialBounds??this.getShapeGeometry(o).bounds;if(!h)return this;const p=s.isAspectRatioLocked??this.getShapeUtil(i).isAspectRatioLocked(i);if(!aM(c,u))return this._resizeUnalignedShape(o,r,{...s,initialBounds:h,scaleOrigin:a,scaleAxisRotation:u,initialPageTransform:l,isAspectRatioLocked:p,initialShape:i});const f=this.getShapeUtil(i);if(p&&(Math.abs(r.x)>Math.abs(r.y)?r=new b(r.x,Math.sign(r.y)*Math.abs(r.x)):r=new b(Math.sign(r.x)*Math.abs(r.y),r.y)),f.onResize&&f.canResize(i)){const m=this._scalePagePoint(oe.applyToPoint(l,new b(0,0)),a,r,u),v=this.getPointInParentSpace(i.id,m),w=new b(r.x,r.y),C=Wo((c-u)%Math.PI,0);w.x=C?r.x:r.y,w.y=C?r.y:r.x;const E=oe.applyToPoint(l,new b),{x:k,y:I}=this.getPointInParentSpace(i.id,E);let _=i;s.skipStartAndEndCallbacks||(_=ns(i,((y=f.onResizeStart)==null?void 0:y.call(f,i))??void 0)),_=ns(_,{id:o,type:i.type,x:v.x,y:v.y,...f.onResize({...i,x:k,y:I},{newPoint:v,handle:s.dragHandle??"bottom_right",mode:s.mode??"scale_shape",scaleX:w.x,scaleY:w.y,initialBounds:h,initialShape:i})}),s.skipStartAndEndCallbacks||(_=ns(_,((x=f.onResizeEnd)==null?void 0:x.call(f,i,_))??void 0)),this.updateShapes([_])}else{const m=oe.applyToPoint(l,h.center),v=this._scalePagePoint(m,a,r,u),w=this.getPointInParentSpace(i.id,m),C=this.getPointInParentSpace(i.id,v),E=b.Sub(C,w);this.updateShapes([{id:o,type:i.type,x:i.x+E.x,y:i.y+E.y}])}return this}_scalePagePoint(t,r,s,o){const i=b.RotWith(t,r,-o).sub(r),a=b.MulV(i,s);return b.Add(a,r).rotWith(r,o)}_resizeUnalignedShape(t,r,s){const{type:o}=s.initialShape,i=new b(r.x,r.y);if(Math.abs(r.x)>Math.abs(r.y)?i.x=Math.sign(r.x)*Math.abs(r.y):i.y=Math.sign(r.y)*Math.abs(r.x),this.resizeShape(t,i,{initialShape:s.initialShape,initialBounds:s.initialBounds,isAspectRatioLocked:s.isAspectRatioLocked}),Math.sign(r.x)*Math.sign(r.y)<0){let{rotation:m}=oe.Decompose(s.initialPageTransform);m-=2*m,this.updateShapes([{id:t,type:o,rotation:m}])}const a=oe.applyToPoint(s.initialPageTransform,s.initialBounds.center),l=this._scalePagePoint(a,s.scaleOrigin,r,s.scaleAxisRotation),c=this.getShapePageBounds(t),u=this.getShapePageTransform(t),h=c.center,p=u.point();if(!h||!p)return this;const f=b.Sub(l,h),S=b.Add(p,f),{x:y,y:x}=this.getPointInParentSpace(t,S);return this.updateShapes([{id:t,type:o,x:y,y:x}]),this}getInitialMetaForShape(t){return{}}createShape(t){return this.createShapes([t]),this}createShapes(t){if(!Array.isArray(t))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getInstanceState().isReadonly)return this;if(t.length<=0)return this;const r=this.getCurrentPageShapeIds();if(t.length+r.size>this.options.maxShapesPerPage)return qd(this),this;const o=this.getFocusedGroupId();return this.run(()=>{var h,p;const i=this.getCurrentPageShapesSorted(),a=t.map(f=>{if(f.id||(f={id:je(),...f}),!f.parentId||!(this.store.has(f.parentId)||t.some(S=>S.id===f.parentId))){let S=this.getFocusedGroupId();for(let x=i.length-1;x>=0;x--){const m=i[x];if(this.getShapeUtil(m).canReceiveNewChildrenOfType(m,f.type)&&this.isPointInShape(m,{x:f.x??0,y:f.y??0},{margin:0,hitInside:!0})){S=m.id;break}}const y=f.parentId;if(S===f.id&&(S=o),S!==y&&(f={...f},f.parentId=S,An(S))){const x=this.getPointInShapeSpace(this.getShape(S),{x:f.x??0,y:f.y??0});f.x=x.x,f.y=x.y,f.rotation=-this.getShapePageTransform(S).rotation()+(f.rotation??0)}}return f}),l=new Map,c=[],{opacityForNextShape:u}=this.getInstanceState();for(const f of a){const S=this.getShapeUtil(f);let y=f.index;if(!y){const w=f.parentId??o;l.has(w)||l.set(w,this.getHighestIndexForParent(w)),y=l.get(w),l.set(w,Fr(y))}const x=S.getDefaultProps();for(const[w,C]of this.styleProps[f.type])x[C]=this.getStyleForNextShape(w);let m=this.store.schema.types.shape.create({...f,index:y,opacity:f.opacity??u,parentId:f.parentId??o,props:"props"in f?{...x,...f.props}:x});if(m.index===void 0)throw Error("no index!");const v=(p=(h=this.getShapeUtil(m)).onBeforeCreate)==null?void 0:p.call(h,m);v&&(m=v),c.push(m)}c.forEach(f=>{f.meta={...this.getInitialMetaForShape(f),...f.meta}}),this.store.put(c)}),this}animateShape(t,r={animation:ny}){return this.animateShapes([t],r)}animateShapes(t,r={animation:ny}){if(!r.animation)return this;const{duration:s=500,easing:o=At.linear}=r.animation,i=ct();let a=s,l;const c=[];let u,h;for(let f=0,S=t.length;f{var m,v;if(a-=f,a<0){const{animatingShapes:w}=this,C=t.filter(E=>E&&w.get(E.id)===i);C.length&&this.updateShapes(C),this.off("tick",p);return}l=o(1-a/s);const{animatingShapes:S}=this,y=[];let x;for(let w=0,C=c.length;wx.id);if(i.length<=1)return this;const a=me((this._shouldIgnoreShapeLock?i:this._getUnlockedShapeIds(i)).map(x=>this.getShape(x))),l=a.sort(an).map(x=>x.id),c=Q.Common(me(a.map(x=>this.getShapePageBounds(x)))),{x:u,y:h}=c.point,p=this.findCommonAncestor(a)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const f=a.filter(x=>x.parentId===p).sort(an),S=(y=f[f.length-1])==null?void 0:y.index;return this.run(()=>{this.createShapes([{id:s,type:"group",parentId:p,index:S,x:u,y:h,opacity:1,props:{}}]),this.reparentShapes(l,s),o&&this.select(s)}),this}ungroupShapes(t,r={}){if(this.getInstanceState().isReadonly)return this;const{select:s=!0}=r,o=typeof t[0]=="string"?t:t.map(c=>c.id),i=me((this._shouldIgnoreShapeLock?o:this._getUnlockedShapeIds(o)).map(c=>this.getShape(c)));if(i.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const a=new Set,l=[];return i.forEach(c=>{this.isShapeOfType(c,"group")?l.push(c):a.add(c.id)}),l.length===0?this:(this.run(()=>{let c;for(let u=0,h=l.length;uu.id)),s&&this.select(...a)}),this)}updateShape(t){return this.updateShapes([t]),this}updateShapes(t){const r=Array(t.length);for(let s=0,o=t.length;s{var s;return!((s=this.getShape(r))!=null&&s.isLocked)})}deleteShapes(t){if(this.getInstanceState().isReadonly)return this;if(!Array.isArray(t))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const r=typeof t[0]=="string"?t:t.map(i=>i.id),s=this._shouldIgnoreShapeLock?r:this._getUnlockedShapeIds(r);if(s.length===0)return this;const o=new Set(s);for(const i of s)this.visitDescendants(i,a=>{o.add(a)});return this.run(()=>this.store.remove([...o]))}deleteShape(t){return this.deleteShapes([typeof t=="string"?t:t.id]),this}_extractSharedStyles(t,r){if(this.isShapeOfType(t,"group")){const s=this._parentIdsToChildIds.get()[t.id];if(!s)return;for(let o=0,i=s.length;o0)return this._getSelectionSharedStyles();const t=this.root.getCurrent(),r=new Tv;if(!t)return r;if(t.shapeType)for(const s of this.styleProps[t.shapeType].keys())r.applyValue(s,this.getStyleForNextShape(s));return r}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const t=[],r=o=>{const i=this.getShape(o);if(i)if(this.isShapeOfType(i,"group"))for(const a of this.getSortedChildIdsForParent(i.id))r(a);else t.push(i)};for(const o of this.getSelectedShapeIds())r(o);let s=null;for(const o of t)if(s===null)s=o.opacity;else if(s!==o.opacity)return{type:"mixed"};if(s!==null)return{type:"shared",value:s}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(t,r){return this.updateInstanceState({opacityForNextShape:t},r),this}setOpacityForSelectedShapes(t){const r=this.getSelectedShapes();if(r.length>0){const s=[],o=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i);for(const l of a)o(this.getShape(l))}else s.push(i)};for(const i of r)o(i);this.updateShapes(s.map(i=>({id:i.id,type:i.type,opacity:t})))}return this}setStyleForNextShapes(t,r,s){const o=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...o,[t.id]:r}},s),this}setStyleForSelectedShapes(t,r){const s=this.getSelectedShapes();if(s.length>0){const o=[],i=a=>{if(this.isShapeOfType(a,"group")){const l=this.getSortedChildIdsForParent(a.id);for(const c of l)i(this.getShape(c))}else{const l=this.getShapeUtil(a),c=this.styleProps[a.type].get(t);if(c){const u={id:a.id,type:a.type,props:{[c]:r}};o.push({util:l,originalShape:a,updatePartial:u})}}};for(const a of s)i(a);this.updateShapes(o.map(({updatePartial:a})=>a))}return this}registerExternalAssetHandler(t,r){return this.externalAssetContentHandlers[t]=r,this}async getAssetForExternalContent(t){var r,s;return await((s=(r=this.externalAssetContentHandlers)[t.type])==null?void 0:s.call(r,t))}hasExternalAssetHandler(t){return!!this.externalAssetContentHandlers[t]}registerExternalContentHandler(t,r){return this.externalContentHandlers[t]=r,this}async putExternalContent(t){var r,s;return(s=(r=this.externalContentHandlers)[t.type])==null?void 0:s.call(r,t)}getContentFromCurrentPage(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);if(!r||r.length===0)return;const s=this.getShapeAndDescendantIds(r);return qC(this,s,o=>{const i=[];for(const h of o){const p=this.getBinding(h);p&&i.push(p)}const a=[],l=[];for(const h of s){const p=this.getShape(h);if(!p)continue;if(!s.has(p.parentId)){const S=this.getShapePageTransform(p.id),y=S.point();l.push({...p,x:y.x,y:y.y,rotation:S.rotation(),parentId:this.getCurrentPageId()}),a.push(p.id)}else l.push(p)}const c=[],u=new Set;for(const h of l){if(!("assetId"in h.props))continue;const p=h.props.assetId;if(!p||u.has(p))continue;u.add(p);const f=this.getAsset(p);f&&c.push(f)}return{schema:this.store.schema.serialize(),shapes:l,rootShapeIds:a,bindings:i,assets:c}})}async resolveAssetsInContent(t){if(!t)return;const r=[];return await Promise.allSettled(t.assets.map(async s=>{var o,i;if((s.type==="image"||s.type==="video")&&!((o=s.props.src)!=null&&o.startsWith("data:image"))&&!((i=s.props.src)!=null&&i.startsWith("http"))){const a=Be(s),l=await this.store.props.assets.resolve(s,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginal:!0});a.props.src=await ji.blobToDataUrl(await vs(l).then(c=>c.blob())),r.push(a)}else r.push(s)})),t.assets=r,t}putContentOntoCurrentPage(t,r={}){var D,$;if(this.getInstanceState().isReadonly)return this;if(!t.schema)throw Error(`Could not put content: +content is missing a schema.`);const{select:s=!1,preserveIds:o=!1,preservePosition:i=!1}=r;let{point:a=void 0}=r;const l=this.getCurrentPageId(),{rootShapeIds:c}=t,u=[],h=[],p=[],f={store:{...Object.fromEntries(t.assets.map(j=>[j.id,j])),...Object.fromEntries(t.shapes.map(j=>[j.id,j])),...Object.fromEntries(((D=t.bindings)==null?void 0:D.map(j=>[j.id,j]))??[])},schema:t.schema},S=this.store.schema.migrateStoreSnapshot(f);if(S.type==="error")throw Error("Could not put content: could not migrate content");for(const j of Object.values(S.value))switch(j.typeName){case"asset":{u.push(j);break}case"shape":{h.push(j);break}case"binding":{p.push(j);break}}const y=new Map(o?h.map(j=>[j.id,j.id]):h.map(j=>[j.id,je()])),x=new Map(o?p.map(j=>[j.id,j.id]):p.map(j=>[j.id,Oi()]));let m=this.getCurrentPageId(),v=1/0,w=[];for(const j of this.getSelectedShapes()){if(v===0)break;const O=this.isShapeOfType(j,"frame"),R=this.getShapeAncestors(j);O&&R.push(j);const K=O?R.length+1:R.length;if(KR.id===c[0]);this.isShapeOfType(j,"frame")&&this.isShapeOfType(O,"frame")&&O.props.w===(j==null?void 0:j.props.w)&&O.props.h===(j==null?void 0:j.props.h)&&(C=!0)}}else m=l}C||(C=y.has(m)),C&&(m=this.getShape(m).parentId);let E=this.getHighestIndexForParent(m);const k=[],I=h.map(j=>{const O=y.get(j.id),R={...j,id:O};return c.includes(j.id)&&(R.parentId=l,k.push(R)),y.has(R.parentId)?R.parentId=y.get(j.parentId):(c.push(R.id),R.index=E,E=Fr(E)),R});if(I.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage)return qd(this),this;const _=p.map(j=>({...j,id:xr(x.get(j.id)),fromId:xr(y.get(j.fromId)),toId:xr(y.get(j.toId))})),T=[],M=[];for(const j of u)this.store.has(j.id)||((j.type==="image"||j.type==="video")&&(($=j.props.src)!=null&&$.startsWith("data:image"))&&(M.push(Be(j)),j.props.src=null),T.push(j));return Promise.allSettled(M.map(async j=>{const O=await uG(j.props.src,j.props.name,j.props.mimeType??"image/png"),R=await this.getAssetForExternalContent({type:"file",file:O});if(!R){this.deleteAssets([j.id]);return}this.updateAssets([{...R,id:j.id}])})),this.run(()=>{T.length>0&&this.createAssets(T),this.createShapes(I),this.createBindings(_),s&&this.select(...k.map(B=>B.id)),m!==l&&this.reparentShapes(k.map(B=>B.id),m);const j=I.map(B=>this.getShape(B.id)),O=Q.Common(j.map(B=>this.getShapePageBounds(B)));if(a===void 0)if(Tn(m)){const B=this.getViewportPageBounds();i||B.includes(Q.From(O))?a=O.center:a=B.center}else{const B=this.getShape(m);a=oe.applyToPoint(this.getShapePageTransform(B),this.getShapeGeometry(B).bounds.center)}if(k.length===1){const B=k[0];if(this.isShapeOfType(B,"frame"))for(;this.getShapesAtPoint(a).some(z=>this.isShapeOfType(z,"frame")&&z.props.w===B.props.w&&z.props.h===B.props.h);)a.x+=O.w+16}const R=Q.Common(me(k.map(({id:B})=>this.getShapePageBounds(B)))).center,K=b.Sub(a,R);this.updateShapes(k.map(({id:B})=>{const z=this.getShape(B),W=this.getShapeParentTransform(B).decompose().rotation,Y=b.Rot(K,-W);return{id:z.id,type:z.type,x:z.x+Y.x,y:z.y+Y.y}}))}),this}async getSvgElement(t,r={}){const s=await PG(this,t,r);if(!s)return;const o=document.createDocumentFragment(),i=a0(o);ta.flushSync(()=>{i.render(s.jsx)});const a=o.firstElementChild;return Ye(a instanceof SVGSVGElement,"Expected an SVG element"),i.unmount(),{svg:a,width:s.width,height:s.height}}async getSvgString(t,r={}){const s=await this.getSvgElement(t,r);return s?{svg:new XMLSerializer().serializeToString(s.svg),width:s.width,height:s.height}:void 0}async getSvg(t,r={}){const s=await this.getSvgElement(t,r);if(s)return s.svg}_updateInputsFromEvent(t){const{pointerVelocity:r,previousScreenPoint:s,previousPagePoint:o,currentScreenPoint:i,currentPagePoint:a}=this.inputs,{screenBounds:l}=this.store.unsafeGetWithoutCapture(mn),{x:c,y:u,z:h}=Fd(()=>this.getCamera()),p=t.point.x-l.x,f=t.point.y-l.y,S=t.point.z??.5;s.setTo(i),o.setTo(a),i.set(p,f);const y=p/h-c,x=f/h-u;isFinite(y)&&isFinite(x)&&a.set(y,x,S),this.inputs.isPen=t.type==="pointer"&&t.isPen,(t.name==="pointer_down"||this.inputs.isPinching)&&(r.set(0,0),this.inputs.originScreenPoint.setTo(i),this.inputs.originPagePoint.setTo(a)),this.run(()=>{var m;this.store.put([{id:of,typeName:"pointer",x:a.x,y:a.y,lastActivityTimestamp:t.type==="pointer"&&t.pointerId===CC.CAMERA_MOVE?((m=this.store.unsafeGetWithoutCapture(of))==null?void 0:m.lastActivityTimestamp)??this._tickManager.now:this._tickManager.now,meta:{}}])},{history:"ignore"})}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}focus({focusContainer:t=!0}={}){return this.getIsFocused()?this:(t&&this.focusManager.focus(),this.updateInstanceState({isFocused:!0}),this)}blur({blurContainer:t=!0}={}){return this.getIsFocused()?(t?this.focusManager.blur():this.complete(),this.updateInstanceState({isFocused:!1}),this):this}getIsFocused(){return this.getInstanceState().isFocused}getSnapshot(){return tG(this.store)}loadSnapshot(t){return GM(this.store,t),this}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_flushEventsForTick(t){this.run(()=>{if(this._pendingEventsForNextTick.length>0){const r=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const s of r)this._flushEventForTick(s)}t>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:t}),this.scribbles.tick(t)})}maybeTrackPerformance(t){xt.measurePerformance.get()&&(this.performanceTracker.isStarted()?clearTimeout(this.performanceTrackerTimeout):this.performanceTracker.start(t),this.performanceTrackerTimeout=this.timers.setTimeout(()=>{this.performanceTracker.stop()},50))}}ne([G],Z.prototype,"getCanUndo");ne([G],Z.prototype,"getCanRedo");ne([G],Z.prototype,"getPath");ne([G],Z.prototype,"getCurrentTool");ne([G],Z.prototype,"getCurrentToolId");ne([G],Z.prototype,"getDocumentSettings");ne([G],Z.prototype,"getInstanceState");ne([G],Z.prototype,"getOpenMenus");ne([G],Z.prototype,"getIsMenuOpen");ne([G],Z.prototype,"getPageStates");ne([G],Z.prototype,"_getPageStatesQuery");ne([G],Z.prototype,"getCurrentPageState");ne([G],Z.prototype,"_getCurrentPageStateId");ne([G],Z.prototype,"getSelectedShapeIds");ne([G],Z.prototype,"getSelectedShapes");ne([G],Z.prototype,"getOnlySelectedShapeId");ne([G],Z.prototype,"getOnlySelectedShape");ne([G],Z.prototype,"getSelectionPageBounds");ne([G],Z.prototype,"getSelectionRotation");ne([G],Z.prototype,"getSelectionRotatedPageBounds");ne([G],Z.prototype,"getSelectionRotatedScreenBounds");ne([G],Z.prototype,"getFocusedGroupId");ne([G],Z.prototype,"getFocusedGroup");ne([G],Z.prototype,"getEditingShapeId");ne([G],Z.prototype,"getEditingShape");ne([G],Z.prototype,"getHoveredShapeId");ne([G],Z.prototype,"getHoveredShape");ne([G],Z.prototype,"getHintingShapeIds");ne([G],Z.prototype,"getHintingShape");ne([G],Z.prototype,"getErasingShapeIds");ne([G],Z.prototype,"getErasingShapes");ne([G],Z.prototype,"_unsafe_getCameraId");ne([G],Z.prototype,"getCamera");ne([G],Z.prototype,"getViewportPageBoundsForFollowing");ne([G],Z.prototype,"getCameraForFollowing");ne([G],Z.prototype,"getZoomLevel");ne([G],Z.prototype,"getViewportScreenBounds");ne([G],Z.prototype,"getViewportScreenCenter");ne([G],Z.prototype,"getViewportPageBounds");ne([G],Z.prototype,"_getCollaboratorsQuery");ne([G],Z.prototype,"getCollaborators");ne([G],Z.prototype,"getCollaboratorsOnCurrentPage");ne([G],Z.prototype,"getRenderingShapes");ne([G],Z.prototype,"_getAllPagesQuery");ne([G],Z.prototype,"getPages");ne([G],Z.prototype,"getCurrentPageId");ne([G],Z.prototype,"getCurrentPageShapeIdsSorted");ne([G],Z.prototype,"_getAllAssetsQuery");ne([G],Z.prototype,"_getShapeGeometryCache");ne([G],Z.prototype,"_getShapeHandlesCache");ne([G],Z.prototype,"_getShapePageTransformCache");ne([G],Z.prototype,"_getShapePageBoundsCache");ne([G],Z.prototype,"_getShapeClipPathCache");ne([G],Z.prototype,"_getShapeMaskCache");ne([G],Z.prototype,"_getShapeMaskedPageBoundsCache");ne([G],Z.prototype,"_notVisibleShapes");ne([G],Z.prototype,"getCulledShapes");ne([G],Z.prototype,"getCurrentPageBounds");ne([G],Z.prototype,"getCurrentPageShapes");ne([G],Z.prototype,"getCurrentPageShapesSorted");ne([G],Z.prototype,"getCurrentPageRenderingShapesSorted");ne([G],Z.prototype,"_getBindingsIndexCache");ne([G],Z.prototype,"_getSelectionSharedStyles");ne([G({isEqual:(e,n)=>e.equals(n)})],Z.prototype,"getSharedStyles");ne([G],Z.prototype,"getSharedOpacity");ne([G],Z.prototype,"getIsFocused");function qd(e,n=e.getCurrentPageId()){const t=e.getPage(n).name;e.emit("max-shapes",{name:t,pageId:n,count:e.options.maxShapesPerPage})}function ns(e,n){if(!n)return e;let t=null;const r=Object.entries(n);for(let s=0,o=r.length;s{const s=e.store.extractingChanges(()=>{const o=new Set,i=new Set;for(const a of n)if(e.getShape(a))for(const c of e.getBindingsInvolvingShape(a)){const u=n.has(c.fromId),h=n.has(c.toId);if(u&&h){o.add(c.id);continue}(!u||!h)&&i.add(c.id)}e.deleteBindings([...i],{isolateShapes:!0});try{r=Ho.ok(t(o))}catch(a){r=Ho.err(a)}});e.store.applyDiff(Sv(s))},{history:"ignore"}),r.ok)return r.value;throw r.error}function ZC(e,n){if(!n.constraints)throw Error("Should have constraints here");const{padding:{x:t,y:r}}=n.constraints,s=e.getViewportScreenBounds(),o=Q.From(n.constraints.bounds),i=(s.w-t*2)/o.w,a=(s.h-r*2)/o.h;return{zx:i,zy:a}}function Ju(){const e=F(),n=JM();return H("isDarkMode",()=>(n==null?void 0:n.isDarkMode)??e.user.getIsDarkMode(),[n,e])}const QC="",JC="",Zd='';function xo(e,n,t,r,s,o=16,i=16){const a=(-t-n)*(Me/180),l=Math.sin(a),c=Math.cos(a),u=1*c-1*l,h=1*l+1*c;return`url("data:image/svg+xml,`+e.replaceAll('"',"'")+`") ${o} ${i}, pointer`}const nV=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],rV={none:()=>"none","ew-resize":(e,n,t)=>xo(JC,e,0,n,t),"ns-resize":(e,n,t)=>xo(JC,e,90,n,t),"nesw-resize":(e,n,t)=>xo(QC,e,0,n,t),"nwse-resize":(e,n,t)=>xo(QC,e,90,n,t),"nwse-rotate":(e,n,t)=>xo(Zd,e,0,n,t),"nesw-rotate":(e,n,t)=>xo(Zd,e,90,n,t),"senw-rotate":(e,n,t)=>xo(Zd,e,180,n,t),"swne-rotate":(e,n,t)=>xo(Zd,e,270,n,t)};function Xn(e,n=0,t="black"){return rV[e](kH(n),!1,t)}function sV(){const e=F(),n=$t(),t=Ju();Ko("useCursor",()=>{const{type:r,rotation:s}=e.getInstanceState().cursor;if(nV.includes(r)){n.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}n.style.setProperty("--tl-cursor",Xn(r,s,t?"white":"black"))},[e,n,t])}function oV(){const e=F(),n=$t(),t=Ju(),r=H(xt.forceSrgb);Ce.useEffect(()=>{t?(n.setAttribute("data-color-mode","dark"),n.classList.remove("tl-theme__light"),n.classList.add("tl-theme__dark")):(n.setAttribute("data-color-mode","light"),n.classList.remove("tl-theme__dark"),n.classList.add("tl-theme__light")),r?n.classList.add("tl-theme__force-sRGB"):n.classList.remove("tl-theme__force-sRGB")},[e,n,r,t])}function nA(e){const n=P.useRef();return P.useLayoutEffect(()=>{n.current=e}),P.useDebugValue(e),P.useCallback((...t)=>{const r=n.current;return Ye(r,"fn does not exist"),r(...t)},[])}function iV(){const[e,n]=P.useState(0);P.useEffect(()=>n(t=>t+1),[])}const aV=e=>e.props.src,lV={upload:(e,n)=>ji.blobToDataUrl(n)};function cV(e){return"schema"in e&&e.schema?e.schema:gH({shapes:"shapeUtils"in e&&e.shapeUtils?eI(qM(e.shapeUtils)):void 0,bindings:"bindingUtils"in e&&e.bindingUtils?eI(VM(e.bindingUtils)):void 0,migrations:"migrations"in e?e.migrations:void 0})}function ff({initialData:e,defaultName:n="",id:t,assets:r=lV,onMount:s,collaboration:o,...i}={}){const a=cV(i),l=new H0({id:t,schema:a,initialData:e,props:{defaultName:n,assets:{upload:r.upload,resolve:r.resolve??aV},onMount:c=>{Ye(c instanceof Z),s==null||s(c)},collaboration:o}});if(i.snapshot){if(e)throw new Error("Cannot provide both initialData and snapshot");GM(l,i.snapshot)}return l}function eI(e){return Object.fromEntries(e.map(n=>[n.type,{props:n.props,migrations:n.migrations}]))}const uV=(e,n)=>n.some(t=>e instanceof t);let tI,nI;function dV(){return tI||(tI=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function hV(){return nI||(nI=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const rA=new WeakMap,Mv=new WeakMap,sA=new WeakMap,ly=new WeakMap,uw=new WeakMap;function pV(e){const n=new Promise((t,r)=>{const s=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(Vs(e.result)),s()},i=()=>{r(e.error),s()};e.addEventListener("success",o),e.addEventListener("error",i)});return n.then(t=>{t instanceof IDBCursor&&rA.set(t,e)}).catch(()=>{}),uw.set(n,e),n}function fV(e){if(Mv.has(e))return;const n=new Promise((t,r)=>{const s=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),s()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),s()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)});Mv.set(e,n)}let Av={get(e,n,t){if(e instanceof IDBTransaction){if(n==="done")return Mv.get(e);if(n==="objectStoreNames")return e.objectStoreNames||sA.get(e);if(n==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Vs(e[n])},set(e,n,t){return e[n]=t,!0},has(e,n){return e instanceof IDBTransaction&&(n==="done"||n==="store")?!0:n in e}};function gV(e){Av=e(Av)}function mV(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(n,...t){const r=e.call(cy(this),n,...t);return sA.set(r,n.sort?n.sort():[n]),Vs(r)}:hV().includes(e)?function(...n){return e.apply(cy(this),n),Vs(rA.get(this))}:function(...n){return Vs(e.apply(cy(this),n))}}function yV(e){return typeof e=="function"?mV(e):(e instanceof IDBTransaction&&fV(e),uV(e,dV())?new Proxy(e,Av):e)}function Vs(e){if(e instanceof IDBRequest)return pV(e);if(ly.has(e))return ly.get(e);const n=yV(e);return n!==e&&(ly.set(e,n),uw.set(n,e)),n}const cy=e=>uw.get(e);function oA(e,n,{blocked:t,upgrade:r,blocking:s,terminated:o}={}){const i=indexedDB.open(e,n),a=Vs(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Vs(i.result),l.oldVersion,l.newVersion,Vs(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 iA(e,{blocked:n}={}){const t=indexedDB.deleteDatabase(e);return n&&t.addEventListener("blocked",r=>n(r.oldVersion,r)),Vs(t).then(()=>{})}const SV=["get","getKey","getAll","getAllKeys","count"],vV=["put","add","delete","clear"],uy=new Map;function rI(e,n){if(!(e instanceof IDBDatabase&&!(n in e)&&typeof n=="string"))return;if(uy.get(n))return uy.get(n);const t=n.replace(/FromIndex$/,""),r=n!==t,s=vV.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(s||SV.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 uy.set(n,o),o}gV(e=>({...e,get:(n,t,r)=>rI(n,t)||e.get(n,t,r),has:(n,t)=>!!rI(n,t)||e.has(n,t)}));const xV="TLDRAW_DOCUMENT_v2",wV="TLDRAW_ASSET_STORE_v1",aA="TLDRAW_DB_NAME_INDEX_v2",be={Records:"records",Schema:"schema",SessionState:"session_state",Assets:"assets"};async function lA(e){const n=xV+e;return PV(n),await oA(n,4,{upgrade(t){t.objectStoreNames.contains(be.Records)||t.createObjectStore(be.Records),t.objectStoreNames.contains(be.Schema)||t.createObjectStore(be.Schema),t.objectStoreNames.contains(be.SessionState)||t.createObjectStore(be.SessionState),t.objectStoreNames.contains(be.Assets)||t.createObjectStore(be.Assets)}})}async function bV(e){const n=window.indexedDB.databases?(await window.indexedDB.databases()).map(p=>p.name):dw(),t=wV+e;if(!n.find(p=>p===t))return;const s=await oA(t,1,{upgrade(p){p.objectStoreNames.contains("assets")||p.createObjectStore("assets")}}),o=s.transaction(["assets"],"readonly"),i=o.objectStore("assets"),a=await i.getAllKeys(),l=await Promise.all(a.map(async p=>[p,await i.get(p)]));await o.done;const c=await lA(e),u=c.transaction([be.Assets],"readwrite"),h=u.objectStore(be.Assets);for(const[p,f]of l)h.put(f,p);await u.done,s.close(),c.close(),await iA(t)}const Qc=class Qc{constructor(n){g(this,"getDbPromise");g(this,"isClosed",!1);g(this,"pendingTransactionSet",new Set);Qc.connectedInstances.add(this),this.getDbPromise=(async()=>(await bV(n),await lA(n)))()}getDb(){return this.getDbPromise}pending(){return Promise.allSettled([this.getDbPromise,...this.pendingTransactionSet]).then(Su)}async close(){this.isClosed||(this.isClosed=!0,await this.pending(),(await this.getDb()).close(),Qc.connectedInstances.delete(this))}tx(n,t,r){const s=(async()=>{Ye(!this.isClosed,"db is closed");const i=(await this.getDb()).transaction(t,n),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:n}={}){return await this.tx("readonly",[be.Records,be.Schema,be.SessionState],async t=>{var l,c;const r=t.objectStore(be.Records),s=t.objectStore(be.Schema),o=t.objectStore(be.SessionState);let i=n?(l=await o.get(n))==null?void 0:l.snapshot:null;return i||(i=(c=(await o.getAll()).sort((h,p)=>h.updatedAt-p.updatedAt).pop())==null?void 0:c.snapshot),{records:await r.getAll(),schema:await s.get(be.Schema),sessionStateSnapshot:i}})}async storeChanges({schema:n,changes:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[be.Records,be.Schema,be.SessionState],async o=>{const i=o.objectStore(be.Records),a=o.objectStore(be.Schema),l=o.objectStore(be.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(n.serialize(),be.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:n,snapshot:t,sessionId:r,sessionStateSnapshot:s}){await this.tx("readwrite",[be.Records,be.Schema,be.SessionState],async o=>{const i=o.objectStore(be.Records),a=o.objectStore(be.Schema),l=o.objectStore(be.SessionState);await i.clear();for(const[c,u]of Object.entries(t))await i.put(u,c);a.put(n.serialize(),be.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",[be.SessionState],async n=>{const t=n.objectStore(be.SessionState),r=(await t.getAll()).sort((o,i)=>o.updatedAt-i.updatedAt);if(r.length<10){await n.done;return}const s=r.slice(0,r.length-10);for(const{id:o}of s)await t.delete(o)})}async getAsset(n){return await this.tx("readonly",[be.Assets],async t=>await t.objectStore(be.Assets).get(n))}async storeAsset(n,t){await this.tx("readwrite",[be.Assets],async r=>{await r.objectStore(be.Assets).put(t,n)})}};g(Qc,"connectedInstances",new Set);let gf=Qc;function dw(){const e=JSON.parse(N0(aA)||"[]")??[];return Array.isArray(e)?e:[]}function PV(e){const n=new Set(dw());n.add(e),F0(aA,JSON.stringify([...n]))}function CV(){window.alert(`Oops! We could not save changes to your browser's storage. We now need to reload the page and try again. Keep seeing this message? • If you're using tldraw in a private or "incognito" window, try loading tldraw in a regular window or in a different browser. @@ -156,7 +156,7 @@ To remove the watermark, please purchase a license at tldraw.dev. pointer-events: all; } } -`}),d.jsx("div",{className:h,"data-debug":i,draggable:!1,...t,children:d.jsx("a",{href:"https://tldraw.dev",target:"_blank",rel:"noreferrer",draggable:!1,onPointerDown:Dt,style:{mask:p,WebkitMask:p}})})]})}),WV=[],GV=[],VV=[],YV="tl-container",XV=P.memo(function({store:n,components:t,className:r,user:s,...o}){const[i,a]=Ce.useState(null),l=P.useMemo(()=>s??zM(),[s]),c=(t==null?void 0:t.ErrorFallback)===void 0?AM:t==null?void 0:t.ErrorFallback,u={...o,shapeUtils:o.shapeUtils??WV,bindingUtils:o.bindingUtils??GV,tools:o.tools??VV,components:t};return d.jsx("div",{ref:a,"data-tldraw":rM,draggable:!1,className:le(`${YV} tl-theme__light`,r),onPointerDown:Dt,tabIndex:-1,children:d.jsx(Pu,{fallback:c,onError:h=>L0(h,{tags:{origin:"react.tldraw-before-app"}}),children:i&&d.jsx(zV,{licenseKey:o.licenseKey,children:d.jsx(DH,{container:i,children:d.jsx(NW,{overrides:t,children:n?n instanceof H0?d.jsx(hA,{...u,store:n,user:l}):d.jsx(dA,{...u,store:n,user:l}):d.jsx(qV,{...u,store:n,user:l})})})})})})});function qV(e){const{defaultName:n,snapshot:t,initialData:r,shapeUtils:s,bindingUtils:o,persistenceKey:i,sessionId:a,user:l,assets:c}=e,u=jV({shapeUtils:s,bindingUtils:o,initialData:r,persistenceKey:i,sessionId:a,defaultName:n,snapshot:t,assets:c});return d.jsx(dA,{...e,store:u,user:l})}const dA=P.memo(function({store:n,user:t,...r}){const s=$t();P.useLayoutEffect(()=>{t.userPreferences.get().colorScheme==="dark"&&(s.classList.remove("tl-theme__light"),s.classList.add("tl-theme__dark"))},[s,t]);const{LoadingScreen:o}=st();switch(n.status){case"error":throw n.error;case"loading":return o?d.jsx(o,{}):null}return d.jsx(hA,{...r,store:n.store,user:t})}),hy=()=>document.location.search.includes("tldraw_preserve_focus");function hA({onMount:e,children:n,store:t,tools:r,shapeUtils:s,bindingUtils:o,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:u,options:h,licenseKey:p}){const{ErrorFallback:f}=st(),S=$t(),[m,x]=cA(null),y=P.useRef({autoFocus:l&&!hy(),inferDarkMode:c,initialState:a,cameraOptions:u});P.useLayoutEffect(()=>{y.current={autoFocus:l&&!hy(),inferDarkMode:c,initialState:a,cameraOptions:u}},[l,c,a,u]),P.useLayoutEffect(()=>{const{autoFocus:C,inferDarkMode:E,initialState:k,cameraOptions:I}=y.current,_=new Z({store:t,shapeUtils:s,bindingUtils:o,tools:r,getContainer:()=>S,user:i,initialState:k,autoFocus:C,inferDarkMode:E,cameraOptions:I,options:h,licenseKey:p});return x(_),()=>{_.dispose()}},[o,S,h,s,t,r,i,x,p]),P.useLayoutEffect(()=>{m&&u&&m.setCameraOptions(u)},[m,u]);const v=P.useSyncExternalStore(P.useCallback(C=>m?(m.on("crash",C),()=>m.off("crash",C)):()=>{},[m]),()=>(m==null?void 0:m.getCrashingError())??null);P.useEffect(function(){if(!m)return;function E(){m&&m.focus()}function k(){m&&m.blur()}if(l&&hy())return m.getContainer().addEventListener("pointerdown",E),document.body.addEventListener("pointerdown",k),()=>{var I;(I=m.getContainer())==null||I.removeEventListener("pointerdown",E),document.body.removeEventListener("pointerdown",k)}},[m,l]);const{Canvas:w}=st();return m?d.jsx(Pu,{fallback:f,onError:C=>m.annotateError(C,{origin:"react.tldraw",willCrashApp:!0}),children:v?d.jsx(QV,{crashingError:v}):d.jsx(cg.Provider,{value:m,children:d.jsxs(ZV,{onMount:e,children:[n??(w?d.jsx(w,{}):null),d.jsx(KV,{})]})})}):null}function ZV({children:e,onMount:n}){return OV(),sV(),oV(),iV(),fA(t=>{const r=t.store.props.onMount(t),s=n==null?void 0:n(t);return()=>{r==null||r(),s==null||s()}}),e}function QV({crashingError:e}){throw e}function pw({children:e}){return d.jsx("div",{className:"tl-loading",children:e})}function pA({children:e}){return d.jsx("div",{className:"tl-loading",children:e})}function fA(e){const n=F(),t=nA(r=>{let s;return r.run(()=>{s=e==null?void 0:e(r),r.emit("mount")},{history:"ignore"}),window.tldrawReady=!0,s});Ce.useLayoutEffect(()=>{if(n)return t==null?void 0:t(n)},[n,t])}function Wi({children:e,className:n="",...t}){return d.jsx("div",{...t,className:le("tl-html-container",n),children:e})}class Wh{constructor(n){this.editor=n}}g(Wh,"props"),g(Wh,"migrations"),g(Wh,"type");function fw(e,n,t={}){const{newPoint:r,handle:s,scaleX:o,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=t;let h=e.props.w*o,p=e.props.h*i;const f=new b(0,0);if(h>0){if(h0){if(pfw(t,r))}getGeometry(t){return new no({width:t.props.w,height:t.props.h,isFilled:!0})}getHandleSnapGeometry(t){return{points:this.getGeometry(t).bounds.cornersAndCenter}}getInterpolatedProps(t,r,s){return{...r.props,w:On(t.props.w,r.props.w,s),h:On(t.props.h,r.props.h,s)}}}var By;let JV=(By=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(By,"id","idle"),By);var Uy;let eY=(Uy=class extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"wasFocusedOnEnter",!1);g(this,"onEnter",()=>{this.wasFocusedOnEnter=!this.editor.getIsMenuOpen()});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,s=this.parent.shapeType,o=je();this.markId=`creating:${o}`,this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:s,x:r.x,y:r.y,props:{w:1,h:1}}]).select(o),this.editor.setCurrentTool("select.resizing",{...t,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:this.parent.onCreate})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:t}=this.editor.inputs;if(!this.wasFocusedOnEnter)return;this.editor.mark(this.markId);const r=this.parent.shapeType,s=je();this.editor.mark(this.markId),this.editor.createShapes([{id:s,type:r,x:t.x,y:t.y}]);const o=this.editor.getShape(s);if(!o){this.cancel();return}let{w:i,h:a}=o.props;const l=new b(i/2,a/2),c=this.editor.getShapeParentTransform(o);c&&l.rot(-c.rotation());let u=1;this.editor.user.getIsDynamicResizeMode()&&(u=1/this.editor.getZoomLevel(),i*=u,a*=u,l.mul(u));const h=Be(o);h.x=o.x-l.x,h.y=o.y-l.y,h.props.w=i,h.props.h=a,"scale"in o.props&&(h.props.scale=u),this.editor.updateShape(h),this.editor.setSelectedShapes([s]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},g(Uy,"id","pointing"),Uy);class Gh extends se{constructor(){super(...arguments);g(this,"onCreate")}}g(Gh,"id","box"),g(Gh,"initial","idle"),g(Gh,"children",()=>[JV,eY]);function mg(e){const n=F();return H("isEditing",()=>n.getEditingShapeId()===e,[n,e])}function ss(e){const n=F();return P.useMemo(function(){const s=c=>{if(c.isKilled)return;if(c.button===J0){n.dispatch({type:"pointer",target:"selection",handle:e,name:"right_click",...Nn(c)});return}if(c.button!==0)return;const u=df(c.currentTarget);function h(){u.removeEventListener("pointerup",h),Yu(u,c)}Vu(u,c),u.addEventListener("pointerup",h),n.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:e,...Nn(c)}),Dt(c)};let o,i;function a(c){c.isKilled||c.button===0&&(c.clientX===o&&c.clientY===i||(o=c.clientX,i=c.clientY,n.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:e,...Nn(c)})))}return{onPointerDown:s,onPointerMove:a,onPointerUp:c=>{c.isKilled||c.button===0&&n.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:e,...Nn(c)})}}},[n,e])}function tY(e){const[n,t]=P.useState(()=>({store:ff(e),opts:e}));if(!eT(n.opts,e)){const r={store:ff(e),opts:e};return t(r),r.store}return n.store}const nY=20,rY=8;function gw(e,n=nY){return Math.max(rY,Math.ceil(e/n))}class Ua extends li{constructor(t){super({...t,isFilled:!1,isClosed:!1});g(this,"_center");g(this,"radius");g(this,"start");g(this,"end");g(this,"largeArcFlag");g(this,"sweepFlag");g(this,"measure");g(this,"angleStart");g(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=b.Angle(r,i),this.angleEnd=b.Angle(r,a),this.radius=b.Dist(r,i),this.measure=TH(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=Cv(s,a,i,r.angle(t));if(u<=0)return l;if(u>=1)return c;const h=r.clone().add(t.clone().sub(r).uni().mul(o));let p,f=1/0,S;for(const m of[l,c,h])S=b.Dist2(t,m),S{const h=Cv(i,a,l,s.angle(u));return h>=0&&h<=1})}getVertices(){const{_center:t,measure:r,length:s,radius:o,angleStart:i}=this,a=[];for(let l=0,c=gw(Math.abs(s));lt+r.length,0)}getVertices(){const t=this.segments.reduce((r,s)=>r.concat(s.vertices),[]);return t.push(this.points[this.points.length-1]),t}nearestPoint(t){let r,s=1/0,o,i;for(const a of this.segments)i=a.nearestPoint(t),o=b.Dist2(i,t),os.hitTestLineSegment(t,r))}getSvgPathData(){let t=this.segments.reduce((r,s,o)=>r+s.getSvgPathData(o===0),"");return this.isClosed&&(t+="Z"),t}}class oY extends li{constructor(t){super({...t,isClosed:!0});g(this,"w");g(this,"h");g(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;rs.hitTestLineSegment(t,r))}getBounds(){return new Q(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 oM(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`}}class iY extends li{constructor(t){super({...t,isClosed:!0});g(this,"w");g(this,"h");g(this,"a");g(this,"b");g(this,"c");g(this,"d");this.config=t;const{width:r,height:s}=t;if(this.w=r,this.h=s,s>r){const o=r/2;this.a=new Ua({start:new b(0,o),end:new b(r,o),center:new b(r/2,o),sweepFlag:1,largeArcFlag:1}),this.b=new Hs({start:new b(r,o),end:new b(r,s-o)}),this.c=new Ua({start:new b(r,s-o),end:new b(0,s-o),center:new b(r/2,s-o),sweepFlag:1,largeArcFlag:1}),this.d=new Hs({start:new b(0,s-o),end:new b(0,o)})}else{const o=s/2;this.a=new Ua({start:new b(o,s),end:new b(o,0),center:new b(o,o),sweepFlag:1,largeArcFlag:1}),this.b=new Hs({start:new b(o,0),end:new b(r-o,0)}),this.c=new Ua({start:new b(r-o,0),end:new b(r-o,s),center:new b(r-o,o),sweepFlag:1,largeArcFlag:1}),this.d=new Hs({start:new b(r-o,s),end:new b(o,s)})}}nearestPoint(t){let r,s=1/0,o,i;const{a,b:l,c,d:u}=this;for(const h of[a,l,c,u])i=h.nearestPoint(t),o=b.Dist2(i,t),ol.hitTestLineSegment(t,r))}getVertices(){const{a:t,b:r,c:s,d:o}=this;return[t,r,s,o].reduce((i,a)=>(i.push(...a.vertices),i),[])}getBounds(){return new Q(0,0,this.w,this.h)}getLength(){const{h:t,w:r}=this;return t>r?(Me*(r/2)+(t-r))*2:(Me*(t/2)+(r-t))*2}getSvgPathData(){const{a:t,b:r,c:s,d:o}=this;return[t,r,s,o].map((i,a)=>i.getSvgPathData(a===0)).join(" ")+" Z"}}async function aY({shouldReload:e=!0}={}){N9();for(const n of gf.connectedInstances)await n.close();await Promise.all(dw().map(n=>iA(n))),$9(),e&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=aY);function lY(e,n="_blank"){rw.openWindow(e,n)}function cY({children:e}){const n=F();return H("shouldDisplayHandles",()=>{if(n.isInAny("select.idle","select.pointing_handle","select.pointing_shape"))return!0;if(n.isInAny("select.editing_shape")){const r=n.getOnlySelectedShape();return r&&n.isShapeOfType(r,"note")}return!1},[n])?d.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}):null}const{PI:uY}=Math,nl=uY+1e-4;function gA(e,n={}){const{size:t=16,smoothing:r=.5}=n;if(e.length===0||t<=0)return{left:[],right:[]};const s=e[0],o=e[e.length-1],i=o.runningLength,a=Math.pow(t*r,2),l=[],c=[];let u=e[0].vector,h=e[0].point,p=h,f=h,S=p,m=!1,x;for(let y=0;y-.62&&i-x.runningLength>x.radius){const M=u.clone().mul(x.radius);u.clone().cpr(E)<0?(f=b.Add(v,M),S=b.Sub(v,M)):(f=b.Sub(v,M),S=b.Add(v,M)),l.push(f),c.push(S)}else{const M=u.clone().mul(x.radius).per(),D=b.Sub(x.input,M);for(let $=1/13,j=0;j<1;j+=$)f=b.RotWith(D,x.input,nl*j),l.push(f),S=b.RotWith(D,x.input,nl+nl*-j),c.push(S)}h=f,p=S,_&&(m=!0);continue}if(m=!1,x===s||x===o){const M=b.Per(w).mul(x.radius);l.push(b.Sub(v,M)),c.push(b.Add(v,M));continue}const T=b.Lrp(E,w,k).per().mul(x.radius);f=b.Sub(v,T),(y<=1||b.Dist2(h,f)>a)&&(l.push(f),h=f),S=b.Add(v,T),(y<=1||b.Dist2(p,S)>a)&&(c.push(S),p=S),u=w}return{left:l,right:c}}function mw(e,n={}){const{size:t=16,start:r={},end:s={},last:o=!1}=n,{cap:i=!0}=r,{cap:a=!0}=s;if(e.length===0||t<=0)return[];const l=e[0],c=e[e.length-1],u=c.runningLength,h=r.taper===!1?0:r.taper===!0?Math.max(t,u):r.taper,p=s.taper===!1?0:s.taper===!0?Math.max(t,u):s.taper,{left:f,right:S}=gA(e,n),m=l.point,x=e.length>1?e[e.length-1].point:b.AddXY(l.point,1,1);if(e.length===1&&(!(h||p)||o)){const C=b.Add(m,b.Sub(m,x).uni().per().mul(-l.radius)),E=[];for(let k=1/13,I=k;I<=1;I+=k)E.push(b.RotWith(C,m,nl*2*I));return E}const y=[];if(!(h||p&&e.length===1))if(i)for(let C=1/8,E=C;E<=1;E+=C){const k=b.RotWith(S[0],m,nl*E);y.push(k)}else{const C=b.Sub(f[0],S[0]),E=b.Mul(C,.5),k=b.Mul(C,.51);y.push(b.Sub(m,E),b.Sub(m,k),b.Add(m,k),b.Add(m,E))}const v=[],w=c.vector.clone().per().neg();if(p||h&&e.length===1)v.push(x);else if(a){const C=b.Add(x,b.Mul(w,c.radius));for(let E=1/29,k=E;k<1;k+=E)v.push(b.RotWith(C,x,nl*3*k))}else v.push(b.Add(x,b.Mul(w,c.radius)),b.Add(x,b.Mul(w,c.radius*.99)),b.Sub(x,b.Mul(w,c.radius*.99)),b.Sub(x,b.Mul(w,c.radius)));return f.concat(v,S.reverse(),y)}const dY=.025,hY=.01;function Ps(e,n={}){var x;const{streamline:t=.5,size:r=16,simulatePressure:s=!1}=n;if(e.length===0)return[];const o=.15+(1-t)*.85;let i=e.map(b.From),a=0;if(!s){let y=i[0];for(;y&&!(y.z>=dY);)i.shift(),y=i[0]}if(!s){let y=i[i.length-1];for(;y&&!(y.z>=hY);)i.pop(),y=i[i.length-1]}if(i.length===0)return[{point:b.From(e[0]),input:b.From(e[0]),pressure:s?.5:.15,vector:new b(1,1),distance:0,runningLength:0,radius:1}];let l=i[1];for(;l&&!(b.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&&!(b.Dist2(l,c)>(r/3)**2);)i.pop(),l=i[i.length-1],a++;i.push(c);const u=n.last||!n.simulatePressure||i.length>1&&b.Dist2(i[i.length-1],i[i.length-2])0;if(i.length===2&&n.simulatePressure){const y=i[1];i=i.slice(0,-1);for(let v=1;v<5;v++){const w=b.Lrp(i[0],y,v/4);w.z=(i[0].z+(y.z-i[0].z))*v/4,i.push(w)}}const h=[{point:i[0],input:i[0],pressure:s?.5:i[0].z,vector:new b(1,1),distance:0,runningLength:0,radius:1}];let p=0,f=h[0],S,m;u&&t>0&&i.push(i[i.length-1].clone());for(let y=1,v=i.length;yv.pressure));h.forEach(v=>v.pressure=y)}return h}const{min:wo}=Math,py=.275;function Sg(e,n){const{size:t=16,thinning:r=.5,simulatePressure:s=!0,easing:o=x=>x,start:i={},end:a={}}=n,{easing:l=At.easeOutQuad}=i,{easing:c=At.easeOutCubic}=a,u=e[e.length-1].runningLength;let h,p=e[0].pressure,f;if(!s&&uMath.max(y,v.pressure),.5);return e.forEach(y=>{y.pressure=x,y.radius=t*o(.5-r*(.5-y.pressure))}),e}else{let x;for(let y=0,v=e.length;yt*5));y++){const w=wo(1,f.distance/t);if(s){const C=wo(1,1-w);x=wo(1,p+(C-p)*(w*py))}else x=wo(1,p+(f.pressure-p)*.5);p=p+(x-p)*.5}for(let y=0;y{const t=F();return H("should display",()=>t.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","text.resizing"),[t])?d.jsx(EM,{bounds:e,rotation:n}):null};function co(){const e=F();return H("isReadonlyMode",()=>e.getInstanceState().isReadonly,[e])}function gY({size:e,width:n,height:t,hideAlternateHandles:r}){const s=N(e/3),o=s/2;return d.jsxs("svg",{className:"tl-overlays__item",children:[d.jsx("polyline",{className:"tl-corner-crop-handle",points:` +`}),d.jsx("div",{className:h,"data-debug":i,draggable:!1,...t,children:d.jsx("a",{href:"https://tldraw.dev",target:"_blank",rel:"noreferrer",draggable:!1,onPointerDown:Dt,style:{mask:p,WebkitMask:p}})})]})}),WV=[],GV=[],VV=[],YV="tl-container",XV=P.memo(function({store:n,components:t,className:r,user:s,...o}){const[i,a]=Ce.useState(null),l=P.useMemo(()=>s??zM(),[s]),c=(t==null?void 0:t.ErrorFallback)===void 0?AM:t==null?void 0:t.ErrorFallback,u={...o,shapeUtils:o.shapeUtils??WV,bindingUtils:o.bindingUtils??GV,tools:o.tools??VV,components:t};return d.jsx("div",{ref:a,"data-tldraw":rM,draggable:!1,className:le(`${YV} tl-theme__light`,r),onPointerDown:Dt,tabIndex:-1,children:d.jsx(Pu,{fallback:c,onError:h=>L0(h,{tags:{origin:"react.tldraw-before-app"}}),children:i&&d.jsx(zV,{licenseKey:o.licenseKey,children:d.jsx(DH,{container:i,children:d.jsx(NW,{overrides:t,children:n?n instanceof H0?d.jsx(hA,{...u,store:n,user:l}):d.jsx(dA,{...u,store:n,user:l}):d.jsx(qV,{...u,store:n,user:l})})})})})})});function qV(e){const{defaultName:n,snapshot:t,initialData:r,shapeUtils:s,bindingUtils:o,persistenceKey:i,sessionId:a,user:l,assets:c}=e,u=jV({shapeUtils:s,bindingUtils:o,initialData:r,persistenceKey:i,sessionId:a,defaultName:n,snapshot:t,assets:c});return d.jsx(dA,{...e,store:u,user:l})}const dA=P.memo(function({store:n,user:t,...r}){const s=$t();P.useLayoutEffect(()=>{t.userPreferences.get().colorScheme==="dark"&&(s.classList.remove("tl-theme__light"),s.classList.add("tl-theme__dark"))},[s,t]);const{LoadingScreen:o}=st();switch(n.status){case"error":throw n.error;case"loading":return o?d.jsx(o,{}):null}return d.jsx(hA,{...r,store:n.store,user:t})}),hy=()=>document.location.search.includes("tldraw_preserve_focus");function hA({onMount:e,children:n,store:t,tools:r,shapeUtils:s,bindingUtils:o,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:u,options:h,licenseKey:p}){const{ErrorFallback:f}=st(),S=$t(),[y,x]=cA(null),m=P.useRef({autoFocus:l&&!hy(),inferDarkMode:c,initialState:a,cameraOptions:u});P.useLayoutEffect(()=>{m.current={autoFocus:l&&!hy(),inferDarkMode:c,initialState:a,cameraOptions:u}},[l,c,a,u]),P.useLayoutEffect(()=>{const{autoFocus:C,inferDarkMode:E,initialState:k,cameraOptions:I}=m.current,_=new Z({store:t,shapeUtils:s,bindingUtils:o,tools:r,getContainer:()=>S,user:i,initialState:k,autoFocus:C,inferDarkMode:E,cameraOptions:I,options:h,licenseKey:p});return x(_),()=>{_.dispose()}},[o,S,h,s,t,r,i,x,p]),P.useLayoutEffect(()=>{y&&u&&y.setCameraOptions(u)},[y,u]);const v=P.useSyncExternalStore(P.useCallback(C=>y?(y.on("crash",C),()=>y.off("crash",C)):()=>{},[y]),()=>(y==null?void 0:y.getCrashingError())??null);P.useEffect(function(){if(!y)return;function E(){y&&y.focus()}function k(){y&&y.blur()}if(l&&hy())return y.getContainer().addEventListener("pointerdown",E),document.body.addEventListener("pointerdown",k),()=>{var I;(I=y.getContainer())==null||I.removeEventListener("pointerdown",E),document.body.removeEventListener("pointerdown",k)}},[y,l]);const{Canvas:w}=st();return y?d.jsx(Pu,{fallback:f,onError:C=>y.annotateError(C,{origin:"react.tldraw",willCrashApp:!0}),children:v?d.jsx(QV,{crashingError:v}):d.jsx(cg.Provider,{value:y,children:d.jsxs(ZV,{onMount:e,children:[n??(w?d.jsx(w,{}):null),d.jsx(KV,{})]})})}):null}function ZV({children:e,onMount:n}){return OV(),sV(),oV(),iV(),fA(t=>{const r=t.store.props.onMount(t),s=n==null?void 0:n(t);return()=>{r==null||r(),s==null||s()}}),e}function QV({crashingError:e}){throw e}function pw({children:e}){return d.jsx("div",{className:"tl-loading",children:e})}function pA({children:e}){return d.jsx("div",{className:"tl-loading",children:e})}function fA(e){const n=F(),t=nA(r=>{let s;return r.run(()=>{s=e==null?void 0:e(r),r.emit("mount")},{history:"ignore"}),window.tldrawReady=!0,s});Ce.useLayoutEffect(()=>{if(n)return t==null?void 0:t(n)},[n,t])}function Wi({children:e,className:n="",...t}){return d.jsx("div",{...t,className:le("tl-html-container",n),children:e})}class Wh{constructor(n){this.editor=n}}g(Wh,"props"),g(Wh,"migrations"),g(Wh,"type");function fw(e,n,t={}){const{newPoint:r,handle:s,scaleX:o,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=t;let h=e.props.w*o,p=e.props.h*i;const f=new b(0,0);if(h>0){if(h0){if(pfw(t,r))}getGeometry(t){return new no({width:t.props.w,height:t.props.h,isFilled:!0})}getHandleSnapGeometry(t){return{points:this.getGeometry(t).bounds.cornersAndCenter}}getInterpolatedProps(t,r,s){return{...r.props,w:On(t.props.w,r.props.w,s),h:On(t.props.h,r.props.h,s)}}}var By;let JV=(By=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(By,"id","idle"),By);var Uy;let eY=(Uy=class extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"wasFocusedOnEnter",!1);g(this,"onEnter",()=>{this.wasFocusedOnEnter=!this.editor.getIsMenuOpen()});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,s=this.parent.shapeType,o=je();this.markId=`creating:${o}`,this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:s,x:r.x,y:r.y,props:{w:1,h:1}}]).select(o),this.editor.setCurrentTool("select.resizing",{...t,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:this.parent.onCreate})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:t}=this.editor.inputs;if(!this.wasFocusedOnEnter)return;this.editor.mark(this.markId);const r=this.parent.shapeType,s=je();this.editor.mark(this.markId),this.editor.createShapes([{id:s,type:r,x:t.x,y:t.y}]);const o=this.editor.getShape(s);if(!o){this.cancel();return}let{w:i,h:a}=o.props;const l=new b(i/2,a/2),c=this.editor.getShapeParentTransform(o);c&&l.rot(-c.rotation());let u=1;this.editor.user.getIsDynamicResizeMode()&&(u=1/this.editor.getZoomLevel(),i*=u,a*=u,l.mul(u));const h=Be(o);h.x=o.x-l.x,h.y=o.y-l.y,h.props.w=i,h.props.h=a,"scale"in o.props&&(h.props.scale=u),this.editor.updateShape(h),this.editor.setSelectedShapes([s]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},g(Uy,"id","pointing"),Uy);class Gh extends se{constructor(){super(...arguments);g(this,"onCreate")}}g(Gh,"id","box"),g(Gh,"initial","idle"),g(Gh,"children",()=>[JV,eY]);function mg(e){const n=F();return H("isEditing",()=>n.getEditingShapeId()===e,[n,e])}function ss(e){const n=F();return P.useMemo(function(){const s=c=>{if(c.isKilled)return;if(c.button===J0){n.dispatch({type:"pointer",target:"selection",handle:e,name:"right_click",...Nn(c)});return}if(c.button!==0)return;const u=df(c.currentTarget);function h(){u.removeEventListener("pointerup",h),Yu(u,c)}Vu(u,c),u.addEventListener("pointerup",h),n.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:e,...Nn(c)}),Dt(c)};let o,i;function a(c){c.isKilled||c.button===0&&(c.clientX===o&&c.clientY===i||(o=c.clientX,i=c.clientY,n.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:e,...Nn(c)})))}return{onPointerDown:s,onPointerMove:a,onPointerUp:c=>{c.isKilled||c.button===0&&n.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:e,...Nn(c)})}}},[n,e])}function tY(e){const[n,t]=P.useState(()=>({store:ff(e),opts:e}));if(!eT(n.opts,e)){const r={store:ff(e),opts:e};return t(r),r.store}return n.store}const nY=20,rY=8;function gw(e,n=nY){return Math.max(rY,Math.ceil(e/n))}class Ua extends li{constructor(t){super({...t,isFilled:!1,isClosed:!1});g(this,"_center");g(this,"radius");g(this,"start");g(this,"end");g(this,"largeArcFlag");g(this,"sweepFlag");g(this,"measure");g(this,"angleStart");g(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=b.Angle(r,i),this.angleEnd=b.Angle(r,a),this.radius=b.Dist(r,i),this.measure=TH(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=Cv(s,a,i,r.angle(t));if(u<=0)return l;if(u>=1)return c;const h=r.clone().add(t.clone().sub(r).uni().mul(o));let p,f=1/0,S;for(const y of[l,c,h])S=b.Dist2(t,y),S{const h=Cv(i,a,l,s.angle(u));return h>=0&&h<=1})}getVertices(){const{_center:t,measure:r,length:s,radius:o,angleStart:i}=this,a=[];for(let l=0,c=gw(Math.abs(s));lt+r.length,0)}getVertices(){const t=this.segments.reduce((r,s)=>r.concat(s.vertices),[]);return t.push(this.points[this.points.length-1]),t}nearestPoint(t){let r,s=1/0,o,i;for(const a of this.segments)i=a.nearestPoint(t),o=b.Dist2(i,t),os.hitTestLineSegment(t,r))}getSvgPathData(){let t=this.segments.reduce((r,s,o)=>r+s.getSvgPathData(o===0),"");return this.isClosed&&(t+="Z"),t}}class oY extends li{constructor(t){super({...t,isClosed:!0});g(this,"w");g(this,"h");g(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;rs.hitTestLineSegment(t,r))}getBounds(){return new Q(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 oM(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`}}class iY extends li{constructor(t){super({...t,isClosed:!0});g(this,"w");g(this,"h");g(this,"a");g(this,"b");g(this,"c");g(this,"d");this.config=t;const{width:r,height:s}=t;if(this.w=r,this.h=s,s>r){const o=r/2;this.a=new Ua({start:new b(0,o),end:new b(r,o),center:new b(r/2,o),sweepFlag:1,largeArcFlag:1}),this.b=new Hs({start:new b(r,o),end:new b(r,s-o)}),this.c=new Ua({start:new b(r,s-o),end:new b(0,s-o),center:new b(r/2,s-o),sweepFlag:1,largeArcFlag:1}),this.d=new Hs({start:new b(0,s-o),end:new b(0,o)})}else{const o=s/2;this.a=new Ua({start:new b(o,s),end:new b(o,0),center:new b(o,o),sweepFlag:1,largeArcFlag:1}),this.b=new Hs({start:new b(o,0),end:new b(r-o,0)}),this.c=new Ua({start:new b(r-o,0),end:new b(r-o,s),center:new b(r-o,o),sweepFlag:1,largeArcFlag:1}),this.d=new Hs({start:new b(r-o,s),end:new b(o,s)})}}nearestPoint(t){let r,s=1/0,o,i;const{a,b:l,c,d:u}=this;for(const h of[a,l,c,u])i=h.nearestPoint(t),o=b.Dist2(i,t),ol.hitTestLineSegment(t,r))}getVertices(){const{a:t,b:r,c:s,d:o}=this;return[t,r,s,o].reduce((i,a)=>(i.push(...a.vertices),i),[])}getBounds(){return new Q(0,0,this.w,this.h)}getLength(){const{h:t,w:r}=this;return t>r?(Me*(r/2)+(t-r))*2:(Me*(t/2)+(r-t))*2}getSvgPathData(){const{a:t,b:r,c:s,d:o}=this;return[t,r,s,o].map((i,a)=>i.getSvgPathData(a===0)).join(" ")+" Z"}}async function aY({shouldReload:e=!0}={}){N9();for(const n of gf.connectedInstances)await n.close();await Promise.all(dw().map(n=>iA(n))),$9(),e&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=aY);function lY(e,n="_blank"){rw.openWindow(e,n)}function cY({children:e}){const n=F();return H("shouldDisplayHandles",()=>{if(n.isInAny("select.idle","select.pointing_handle","select.pointing_shape"))return!0;if(n.isInAny("select.editing_shape")){const r=n.getOnlySelectedShape();return r&&n.isShapeOfType(r,"note")}return!1},[n])?d.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}):null}const{PI:uY}=Math,nl=uY+1e-4;function gA(e,n={}){const{size:t=16,smoothing:r=.5}=n;if(e.length===0||t<=0)return{left:[],right:[]};const s=e[0],o=e[e.length-1],i=o.runningLength,a=Math.pow(t*r,2),l=[],c=[];let u=e[0].vector,h=e[0].point,p=h,f=h,S=p,y=!1,x;for(let m=0;m-.62&&i-x.runningLength>x.radius){const M=u.clone().mul(x.radius);u.clone().cpr(E)<0?(f=b.Add(v,M),S=b.Sub(v,M)):(f=b.Sub(v,M),S=b.Add(v,M)),l.push(f),c.push(S)}else{const M=u.clone().mul(x.radius).per(),D=b.Sub(x.input,M);for(let $=1/13,j=0;j<1;j+=$)f=b.RotWith(D,x.input,nl*j),l.push(f),S=b.RotWith(D,x.input,nl+nl*-j),c.push(S)}h=f,p=S,_&&(y=!0);continue}if(y=!1,x===s||x===o){const M=b.Per(w).mul(x.radius);l.push(b.Sub(v,M)),c.push(b.Add(v,M));continue}const T=b.Lrp(E,w,k).per().mul(x.radius);f=b.Sub(v,T),(m<=1||b.Dist2(h,f)>a)&&(l.push(f),h=f),S=b.Add(v,T),(m<=1||b.Dist2(p,S)>a)&&(c.push(S),p=S),u=w}return{left:l,right:c}}function mw(e,n={}){const{size:t=16,start:r={},end:s={},last:o=!1}=n,{cap:i=!0}=r,{cap:a=!0}=s;if(e.length===0||t<=0)return[];const l=e[0],c=e[e.length-1],u=c.runningLength,h=r.taper===!1?0:r.taper===!0?Math.max(t,u):r.taper,p=s.taper===!1?0:s.taper===!0?Math.max(t,u):s.taper,{left:f,right:S}=gA(e,n),y=l.point,x=e.length>1?e[e.length-1].point:b.AddXY(l.point,1,1);if(e.length===1&&(!(h||p)||o)){const C=b.Add(y,b.Sub(y,x).uni().per().mul(-l.radius)),E=[];for(let k=1/13,I=k;I<=1;I+=k)E.push(b.RotWith(C,y,nl*2*I));return E}const m=[];if(!(h||p&&e.length===1))if(i)for(let C=1/8,E=C;E<=1;E+=C){const k=b.RotWith(S[0],y,nl*E);m.push(k)}else{const C=b.Sub(f[0],S[0]),E=b.Mul(C,.5),k=b.Mul(C,.51);m.push(b.Sub(y,E),b.Sub(y,k),b.Add(y,k),b.Add(y,E))}const v=[],w=c.vector.clone().per().neg();if(p||h&&e.length===1)v.push(x);else if(a){const C=b.Add(x,b.Mul(w,c.radius));for(let E=1/29,k=E;k<1;k+=E)v.push(b.RotWith(C,x,nl*3*k))}else v.push(b.Add(x,b.Mul(w,c.radius)),b.Add(x,b.Mul(w,c.radius*.99)),b.Sub(x,b.Mul(w,c.radius*.99)),b.Sub(x,b.Mul(w,c.radius)));return f.concat(v,S.reverse(),m)}const dY=.025,hY=.01;function Ps(e,n={}){var x;const{streamline:t=.5,size:r=16,simulatePressure:s=!1}=n;if(e.length===0)return[];const o=.15+(1-t)*.85;let i=e.map(b.From),a=0;if(!s){let m=i[0];for(;m&&!(m.z>=dY);)i.shift(),m=i[0]}if(!s){let m=i[i.length-1];for(;m&&!(m.z>=hY);)i.pop(),m=i[i.length-1]}if(i.length===0)return[{point:b.From(e[0]),input:b.From(e[0]),pressure:s?.5:.15,vector:new b(1,1),distance:0,runningLength:0,radius:1}];let l=i[1];for(;l&&!(b.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&&!(b.Dist2(l,c)>(r/3)**2);)i.pop(),l=i[i.length-1],a++;i.push(c);const u=n.last||!n.simulatePressure||i.length>1&&b.Dist2(i[i.length-1],i[i.length-2])0;if(i.length===2&&n.simulatePressure){const m=i[1];i=i.slice(0,-1);for(let v=1;v<5;v++){const w=b.Lrp(i[0],m,v/4);w.z=(i[0].z+(m.z-i[0].z))*v/4,i.push(w)}}const h=[{point:i[0],input:i[0],pressure:s?.5:i[0].z,vector:new b(1,1),distance:0,runningLength:0,radius:1}];let p=0,f=h[0],S,y;u&&t>0&&i.push(i[i.length-1].clone());for(let m=1,v=i.length;mv.pressure));h.forEach(v=>v.pressure=m)}return h}const{min:wo}=Math,py=.275;function Sg(e,n){const{size:t=16,thinning:r=.5,simulatePressure:s=!0,easing:o=x=>x,start:i={},end:a={}}=n,{easing:l=At.easeOutQuad}=i,{easing:c=At.easeOutCubic}=a,u=e[e.length-1].runningLength;let h,p=e[0].pressure,f;if(!s&&uMath.max(m,v.pressure),.5);return e.forEach(m=>{m.pressure=x,m.radius=t*o(.5-r*(.5-m.pressure))}),e}else{let x;for(let m=0,v=e.length;mt*5));m++){const w=wo(1,f.distance/t);if(s){const C=wo(1,1-w);x=wo(1,p+(C-p)*(w*py))}else x=wo(1,p+(f.pressure-p)*.5);p=p+(x-p)*.5}for(let m=0;m{const t=F();return H("should display",()=>t.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","text.resizing"),[t])?d.jsx(EM,{bounds:e,rotation:n}):null};function co(){const e=F();return H("isReadonlyMode",()=>e.getInstanceState().isReadonly,[e])}function gY({size:e,width:n,height:t,hideAlternateHandles:r}){const s=N(e/3),o=s/2;return d.jsxs("svg",{className:"tl-overlays__item",children:[d.jsx("polyline",{className:"tl-corner-crop-handle",points:` ${N(0-o)},${N(e)} ${N(0-o)},${N(0-o)} ${N(e)},${N(0-o)}`,strokeWidth:s,"data-testid":"selection.crop.top_left","aria-label":"top_left handle"}),d.jsx("line",{className:le("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(n/2-e),y1:N(0-o),x2:N(n/2+e),y2:N(0-o),strokeWidth:s,"data-testid":"selection.crop.top","aria-label":"top handle"}),d.jsx("polyline",{className:le("tl-corner-crop-handle",{"tl-hidden":r}),points:` @@ -168,7 +168,7 @@ To remove the watermark, please purchase a license at tldraw.dev. ${N(n-e)},${N(t+o)}`,strokeWidth:s,"data-testid":"selection.crop.bottom_right","aria-label":"bottom_right handle"}),d.jsx("line",{className:le("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(n/2-e),y1:N(t+o),x2:N(n/2+e),y2:N(t+o),strokeWidth:s,"data-testid":"selection.crop.bottom","aria-label":"bottom handle"}),d.jsx("polyline",{className:le("tl-corner-crop-handle",{"tl-hidden":r}),points:` ${N(0+e)},${N(t+o)} ${N(0-o)},${N(t+o)} - ${N(0-o)},${N(t-e)}`,strokeWidth:s,"data-testid":"selection.crop.bottom_left","aria-label":"bottom_left handle"}),d.jsx("line",{className:le("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(0-o),y1:N(t/2-e),x2:N(0-o),y2:N(t/2+e),strokeWidth:s,"data-testid":"selection.crop.left","aria-label":"left handle"})]})}const mY=Lt(function({bounds:n,rotation:t}){const r=F(),s=P.useRef(null),o=co(),i=ss("top"),a=ss("right"),l=ss("bottom"),c=ss("left"),u=ss("top_left"),h=ss("top_right"),p=ss("bottom_right"),f=ss("bottom_left"),S=!r.getIsMenuOpen()&&r.getInstanceState().cursor.type==="default",m=r.getInstanceState().isCoarsePointer,x=r.getOnlySelectedShape(),y=x&&r.isShapeOrAncestorLocked(x),v=x?r.getShapeUtil(x).expandSelectionOutlinePx(x):0;if(jl(s,n==null?void 0:n.x,n==null?void 0:n.y,1,r.getSelectionRotation(),{x:-v,y:-v}),!n)return null;n=n.clone().expandBy(v).zeroFix();const w=r.getZoomLevel(),C=r.getInstanceState().isChangingStyle,E=n.width,k=n.height,I=8/w,_=E=4;return d.jsx("svg",{className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:d.jsxs("g",{ref:s,children:[W&&d.jsx("rect",{className:"tl-selection__fg__outline",width:N(E),height:N(k)}),d.jsx(eh,{"data-testid":"selection.rotate.top-left",cx:0,cy:0,targetSize:R,corner:"top_left_rotate",cursor:S?Xn("nwse-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.top-right",cx:E+R*3,cy:0,targetSize:R,corner:"top_right_rotate",cursor:S?Xn("nesw-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.bottom-left",cx:0,cy:k+R*3,targetSize:R,corner:"bottom_left_rotate",cursor:S?Xn("swne-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.bottom-right",cx:E+R*3,cy:k+R*3,targetSize:R,corner:"bottom_right_rotate",cursor:S?Xn("senw-rotate",t):void 0,isHidden:Ae}),d.jsx(SY,{"data-testid":"selection.rotate.mobile",cx:M?-R*1.5:E/2,cy:M?k/2:-R*1.5,size:I,isHidden:ot}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.top","aria-label":"top target",pointerEvents:"all",x:0,y:N(0-(D?B*2:B)),width:N(E),height:N(Math.max(1,B*2)),style:S?{cursor:Xn("ns-resize",t)}:void 0,...i}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Zt}),"data-testid":"selection.resize.right","aria-label":"right target",pointerEvents:"all",x:N(E-(M?0:K)),y:0,height:N(k),width:N(Math.max(1,K*2)),style:S?{cursor:Xn("ew-resize",t)}:void 0,...a}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.bottom","aria-label":"bottom target",pointerEvents:"all",x:0,y:N(k-(D?0:B)),width:N(E),height:N(Math.max(1,B*2)),style:S?{cursor:Xn("ns-resize",t)}:void 0,...l}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Zt}),"data-testid":"selection.resize.left","aria-label":"left target",pointerEvents:"all",x:N(0-(M?K*2:K)),y:0,height:N(k),width:N(Math.max(1,K*2)),style:S?{cursor:Xn("ew-resize",t)}:void 0,...c}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Ne}),"data-testid":"selection.target.top-left","aria-label":"top-left target",pointerEvents:"all",x:N(0-(M?K*2:K*1.5)),y:N(0-(D?B*2:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nwse-resize",t)}:void 0,...u}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Vn}),"data-testid":"selection.target.top-right","aria-label":"top-right target",pointerEvents:"all",x:N(E-(M?0:K*1.5)),y:N(0-(D?B*2:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nesw-resize",t)}:void 0,...h}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":_n}),"data-testid":"selection.target.bottom-right","aria-label":"bottom-right target",pointerEvents:"all",x:N(E-(M?K:K*1.5)),y:N(k-(D?B:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nwse-resize",t)}:void 0,...p}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Nt}),"data-testid":"selection.target.bottom-left","aria-label":"bottom-left target",pointerEvents:"all",x:N(0-(M?K*3:K*1.5)),y:N(k-(D?0:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nesw-resize",t)}:void 0,...f}),we&&d.jsxs(d.Fragment,{children:[d.jsx("rect",{"data-testid":"selection.resize.top-left",className:le("tl-corner-handle",{"tl-hidden":Ne}),"aria-label":"top_left handle",x:N(0-I/2),y:N(0-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.top-right",className:le("tl-corner-handle",{"tl-hidden":Vn}),"aria-label":"top_right handle",x:N(E-I/2),y:N(0-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.bottom-right",className:le("tl-corner-handle",{"tl-hidden":_n}),"aria-label":"bottom_right handle",x:N(E-I/2),y:N(k-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.bottom-left",className:le("tl-corner-handle",{"tl-hidden":Nt}),"aria-label":"bottom_left handle",x:N(0-I/2),y:N(k-I/2),width:N(I),height:N(I)})]}),$l&&d.jsxs(d.Fragment,{children:[d.jsx("rect",{"data-testid":"selection.text-resize.left.handle",className:"tl-text-handle","aria-label":"bottom_left handle",x:N(0-I/4),y:N(k/2-Ms/2),rx:I/4,width:N(I/2),height:N(Ms)}),d.jsx("rect",{"data-testid":"selection.text-resize.right.handle",className:"tl-text-handle","aria-label":"bottom_left handle",rx:I/4,x:N(E-I/4),y:N(k/2-Ms/2),width:N(I/2),height:N(Ms)})]}),Y&&d.jsx(gY,{size:I,width:E,height:k,hideAlternateHandles:Oe})]})})}),eh=function({cx:n,cy:t,targetSize:r,corner:s,cursor:o,isHidden:i,"data-testid":a}){const l=ss(s);return d.jsx("rect",{className:le("tl-transparent","tl-rotate-corner",{"tl-hidden":i}),"data-testid":a,"aria-label":`${s} target`,pointerEvents:"all",x:N(n-r*3),y:N(t-r*3),width:N(Math.max(1,r*3)),height:N(Math.max(1,r*3)),cursor:o,...l})},yY=Math.sqrt(Math.PI),SY=function({cx:n,cy:t,size:r,isHidden:s,"data-testid":o}){const i=ss("mobile_rotate"),a=F(),l=H("zoom level",()=>a.getZoomLevel(),[a]),c=Math.max(14*(1/l),20/Math.max(1,l));return d.jsxs("g",{children:[d.jsx("circle",{"data-testid":o,pointerEvents:"all",className:le("tl-transparent","tl-mobile-rotate__bg",{"tl-hidden":s}),cx:n,cy:t,r:c,...i}),d.jsx("circle",{className:le("tl-mobile-rotate__fg",{"tl-hidden":s}),cx:n,cy:t,r:r/yY})]})};function vY(){const e=F();return H("is in a valid select state",()=>e.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle"),[e])?d.jsx(_M,{}):null}function Ov(e,n,t){const{arrowheadStart:r,arrowheadEnd:s}=n.props,o=Ha(e,n,t),i=o.start.clone(),a=o.end.clone(),l=b.Med(i,a);if(b.Equals(i,a))return{bindings:t,isStraight:!0,start:{handle:i,point:i,arrowhead:n.props.arrowheadStart},end:{handle:a,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:!1,length:0};const c=b.Sub(a,i).uni(),u=mf(e,n,"start"),h=mf(e,n,"end"),p=e.getShapePageTransform(n);iI(a,o.start,p,h),iI(i,o.end,p,u);let f=0,S=0,m=0,x=0,y=Ka*n.props.scale;const v=u&&h&&u.shape===h.shape,w=u&&h?yw(e,u.shape.id,h.shape.id):"safe";w==="safe"&&u&&h&&!v&&!u.isExact&&!h.isExact&&(h.didIntersect&&!u.didIntersect?u.isClosed&&i.setTo(a.clone().add(c.clone().mul(Ka*n.props.scale))):h.didIntersect||h.isClosed&&a.setTo(i.clone().sub(c.clone().mul(Ka*n.props.scale))));const C=b.Sub(a,i),E=b.Len(C)?C.uni():b.From(C),k=!b.Equals(E,c);v||(w!=="start-contains-end"&&u&&r!=="none"&&!u.isExact&&(m=Oo[n.props.size]/2+("size"in u.shape.props?Oo[u.shape.props.size]/2:0),f=(yf+m)*n.props.scale,y+=m*n.props.scale),w!=="end-contains-start"&&h&&s!=="none"&&!h.isExact&&(x=Oo[n.props.size]/2+("size"in h.shape.props?Oo[h.shape.props.size]/2:0),S=(yf+x)*n.props.scale,y+=x*n.props.scale));const I=i.clone().add(E.clone().mul(f*(k?-1:1))),_=a.clone().sub(E.clone().mul(S*(k?-1:1)));b.DistMin(I,_,y)&&(f!==0&&S!==0?(f*=-1.5,S*=-1.5):f!==0?f*=-1:S!==0&&(S*=-1)),i.add(E.clone().mul(f*(k?-1:1))),a.sub(E.clone().mul(S*(k?-1:1))),k?(u&&h&&a.setTo(b.Add(i,E.clone().mul(-Ka*n.props.scale))),l.setTo(b.Med(o.start,o.end))):l.setTo(b.Med(i,a));const T=b.Dist(i,a);return{bindings:t,isStraight:!0,start:{handle:o.start,point:i,arrowhead:n.props.arrowheadStart},end:{handle:o.end,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:T>0,length:T}}function iI(e,n,t,r){if(r===void 0||r.isExact)return;const s=oe.applyToPoint(t,n),o=oe.applyToPoint(t,e),i=oe.applyToPoint(oe.Inverse(r.transform),s),a=oe.applyToPoint(oe.Inverse(r.transform),o),l=r.isClosed,u=(l?iw:nG)(i,a,r.outline);let h;if(u!==null&&(h=u.sort((S,m)=>b.Dist2(S,i)-b.Dist2(m,i))[0]??(l?void 0:a)),h===void 0)return;const p=oe.applyToPoint(r.transform,h),f=oe.applyToPoint(oe.Inverse(t),p);e.setTo(f),r.didIntersect=!0}function xY(e,n,t){const{arrowheadEnd:r,arrowheadStart:s}=n.props,o=n.props.bend;if(Math.abs(o)>Math.abs(n.props.bend*(IY*n.props.scale)))return Ov(e,n,t);const i=Ha(e,n,t),a=b.Med(i.start,i.end),l=b.Sub(i.end,i.start),c=b.Len(l)?l.uni():b.From(l),u=b.Add(a,c.per().mul(-o)),h=mf(e,n,"start"),p=mf(e,n,"end"),f=i.start.clone(),S=i.end.clone(),m=u.clone();if(b.Equals(f,S))return{bindings:t,isStraight:!0,start:{handle:f,point:f,arrowhead:n.props.arrowheadStart},end:{handle:S,point:S,arrowhead:n.props.arrowheadEnd},middle:m,isValid:!1,length:0};const x=n.props.bend<0,y=x?Gu:iM,v=aI(f,S,m),w=b.Angle(v.center,f),C=b.Angle(v.center,S),E=y(w,C);if(v.length===0||v.size===0||!bC(v.length)||!bC(v.size))return Ov(e,n,t);const k=f.clone(),I=S.clone(),_=m.clone(),T=e.getShapePageTransform(n);let M=0,D=0,$=Ka*n.props.scale;if(h&&!h.isExact){const Y=oe.applyToPoint(T,k),q=oe.applyToPoint(T,v.center),ae=oe.applyToPoint(T,I),fe=oe.Inverse(h.transform),we=oe.applyToPoint(fe,Y),J=oe.applyToPoint(fe,q),Ue=oe.applyToPoint(fe,ae),{isClosed:Oe}=h,tt=Oe?kv:HC;let Ae,ot=tt(J,v.radius,h.outline);if(ot){const Ne=J.angle(we),Vn=J.angle(Ue),Nt=y(Ne,Vn);ot=ot.filter(St=>y(Ne,J.angle(St))<=Nt);const _n=Nt*.25;ot.sort(Oe?(St,Zt)=>Math.abs(y(Ne,J.angle(St))-_n)y(Ne,J.angle(St))y(Ne,J.angle(St))<=Nt),ot.sort(Oe?(St,Zt)=>Math.abs(y(Ne,J.angle(St))-_n)y(Ne,J.angle(St))y(w,O))&&I.setTo(v.center).add(b.FromAngle(j+R*(Math.min(.9,Ka*n.props.scale/K)*(x?1:-1))).mul(v.radius)))}wY(v.center,v.radius,k,I,_,E,x),k.equals(I)&&(k.setTo(_.clone().addXY(1,1)),I.setTo(_.clone().subXY(1,1))),f.setTo(k),S.setTo(I),m.setTo(_);const W=aI(f,S,m);return{bindings:t,isStraight:!1,start:{point:f,handle:i.start,arrowhead:n.props.arrowheadStart},end:{point:S,handle:i.end,arrowhead:n.props.arrowheadEnd},middle:m,handleArc:v,bodyArc:W,isValid:W.length!==0&&isFinite(W.center.x)&&isFinite(W.center.y)}}function aI(e,n,t){const r=Q0(e,n,t),s=b.Dist(r,e),o=+b.Clockwise(e,t,n),i=((e.y-n.y)**2+(e.x-n.x)**2)**.5,a=((n.y-t.y)**2+(n.x-t.x)**2)**.5,l=((t.y-e.y)**2+(t.x-e.x)**2)**.5,c=Math.acos((a*a+l*l-i*i)/(2*a*l))*2,u=+(Me>c),h=(Le-c)*(o?1:-1),p=h*s;return{center:r,radius:s,size:h,length:p,largeArcFlag:u,sweepFlag:o}}function wY(e,n,t,r,s,o,i){const a=b.Angle(e,t),l=b.Angle(e,r);let c=Gu(a,l);if(i||(c=Le-c),s.setTo(e).add(b.FromAngle(a+c*(.5*(i?1:-1))).mul(n)),c>o){s.rotWith(e,Me);const u=r.clone();r.setTo(t),t.setTo(u)}}const bY=8;function PY(e){return Math.abs(e.props.bend)l.props.terminal===t);if(!r)return;const s=e.getShape(r.toId);if(!s)return;const o=e.getShapePageTransform(s),i=e.getShapeGeometry(s),a=i instanceof Wr?i.children[0].vertices:i.vertices;return{shape:s,transform:o,isClosed:i.isClosed,isExact:r.props.isExact,didIntersect:!1,outline:a}}function lI(e,n,t,r){const s=e.getShape(t.toId);if(s){const{point:o,size:i}=e.getShapeGeometry(s).bounds,a=b.Add(o,b.MulV(t.props.isPrecise||r?t.props.normalizedAnchor:{x:.5,y:.5},i)),l=oe.applyToPoint(e.getShapePageTransform(s),a);return oe.applyToPoint(oe.Inverse(n),l)}else return new b(0,0)}function Rn(e,n){const t=e.getBindingsFromShape(n,"arrow");return{start:t.find(r=>r.props.terminal==="start"),end:t.find(r=>r.props.terminal==="end")}}const CY=r7("arrow info",(e,n)=>{const t=Rn(e,n);return PY(n)?Ov(e,n,t):xY(e,n,t)});function ds(e,n){const t=typeof n=="string"?n:n.id;return CY.get(e,t)}function Ha(e,n,t){var a,l;const r=e.getShapePageTransform(n),s=yw(e,(a=t.start)==null?void 0:a.toId,(l=t.end)==null?void 0:l.toId),o=t.start?lI(e,r,t.start,s==="double-bound"||s==="start-contains-end"):b.From(n.props.start),i=t.end?lI(e,r,t.end,s==="double-bound"||s==="end-contains-start"):b.From(n.props.end);return{start:o,end:i}}function ac(e,n,t,r){const s=typeof n=="string"?n:n.id,o=typeof t=="string"?t:t.id,i=e.getBindingsFromShape(s,"arrow").filter(l=>l.props.terminal===r.terminal);i.length>1&&e.deleteBindings(i.slice(1));const a=i[0];a?e.updateBinding({...a,toId:o,props:r}):e.createBinding({type:"arrow",fromId:s,toId:o,props:r})}function Vh(e,n,t){const r=e.getBindingsFromShape(n,"arrow").filter(s=>s.props.terminal===t);e.deleteBindings(r)}const Ka=10,yf=10,IY=10,Oo={s:2,m:3.5,l:5,xl:10};function yw(e,n,t){if(!n||!t)return"safe";if(n===t)return"double-bound";const r=e.getShapePageBounds(n),s=e.getShapePageBounds(t);if(r&&s){if(r.contains(s))return"start-contains-end";if(s.contains(r))return"end-contains-start"}return"safe"}class Yh extends Wh{getDefaultProps(){return{isPrecise:!1,isExact:!1,normalizedAnchor:{x:.5,y:.5}}}onAfterCreate({binding:n}){fy(this.editor,this.editor.getShape(n.fromId))}onAfterChange({bindingAfter:n}){fy(this.editor,this.editor.getShape(n.fromId))}onAfterChangeFromShape({shapeAfter:n}){fy(this.editor,n)}onAfterChangeToShape({binding:n}){mA(this.editor,n.fromId)}onBeforeIsolateFromShape({binding:n}){const t=this.editor.getShape(n.fromId);t&&Sf({editor:this.editor,arrow:t,terminal:n.props.terminal})}}g(Yh,"type","arrow"),g(Yh,"props",ET),g(Yh,"migrations",_T);function mA(e,n){var x;const t=e.getShape(n);if(!t)return;const r=Rn(e,t),{start:s,end:o}=r,i=s?e.getShape(s.toId):void 0,a=o?e.getShape(o.toId):void 0,l=e.getAncestorPageId(t);if(!l)return;let c;if(i&&a)c=e.findCommonAncestor([i,a])??l;else if(i||a){const y=(x=i||a)==null?void 0:x.parentId;y&&y===t.parentId?c=t.parentId:c=l}else return;c&&c!==t.parentId&&e.reparentShapes([n],c);const u=e.getShape(n);if(!u)throw Error("no reparented arrow");const h=e.getShapeNearestSibling(u,i),p=e.getShapeNearestSibling(u,a);let f;if(h&&p)f=h.index>p.index?h:p;else if(h&&!p)f=h;else if(p&&!h)f=p;else return;let S;const m=e.getSortedChildIdsForParent(f.parentId).map(y=>e.getShape(y)).filter(y=>y.index>f.index);if(m.length){const y=m.find(v=>v.type!=="arrow");if(u.index>f.index&&(!y||u.index=4;return d.jsx("svg",{className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:d.jsxs("g",{ref:s,children:[W&&d.jsx("rect",{className:"tl-selection__fg__outline",width:N(E),height:N(k)}),d.jsx(eh,{"data-testid":"selection.rotate.top-left",cx:0,cy:0,targetSize:R,corner:"top_left_rotate",cursor:S?Xn("nwse-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.top-right",cx:E+R*3,cy:0,targetSize:R,corner:"top_right_rotate",cursor:S?Xn("nesw-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.bottom-left",cx:0,cy:k+R*3,targetSize:R,corner:"bottom_left_rotate",cursor:S?Xn("swne-rotate",t):void 0,isHidden:Ae}),d.jsx(eh,{"data-testid":"selection.rotate.bottom-right",cx:E+R*3,cy:k+R*3,targetSize:R,corner:"bottom_right_rotate",cursor:S?Xn("senw-rotate",t):void 0,isHidden:Ae}),d.jsx(SY,{"data-testid":"selection.rotate.mobile",cx:M?-R*1.5:E/2,cy:M?k/2:-R*1.5,size:I,isHidden:ot}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.top","aria-label":"top target",pointerEvents:"all",x:0,y:N(0-(D?B*2:B)),width:N(E),height:N(Math.max(1,B*2)),style:S?{cursor:Xn("ns-resize",t)}:void 0,...i}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Zt}),"data-testid":"selection.resize.right","aria-label":"right target",pointerEvents:"all",x:N(E-(M?0:K)),y:0,height:N(k),width:N(Math.max(1,K*2)),style:S?{cursor:Xn("ew-resize",t)}:void 0,...a}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.bottom","aria-label":"bottom target",pointerEvents:"all",x:0,y:N(k-(D?0:B)),width:N(E),height:N(Math.max(1,B*2)),style:S?{cursor:Xn("ns-resize",t)}:void 0,...l}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Zt}),"data-testid":"selection.resize.left","aria-label":"left target",pointerEvents:"all",x:N(0-(M?K*2:K)),y:0,height:N(k),width:N(Math.max(1,K*2)),style:S?{cursor:Xn("ew-resize",t)}:void 0,...c}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Ne}),"data-testid":"selection.target.top-left","aria-label":"top-left target",pointerEvents:"all",x:N(0-(M?K*2:K*1.5)),y:N(0-(D?B*2:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nwse-resize",t)}:void 0,...u}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Vn}),"data-testid":"selection.target.top-right","aria-label":"top-right target",pointerEvents:"all",x:N(E-(M?0:K*1.5)),y:N(0-(D?B*2:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nesw-resize",t)}:void 0,...h}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":_n}),"data-testid":"selection.target.bottom-right","aria-label":"bottom-right target",pointerEvents:"all",x:N(E-(M?K:K*1.5)),y:N(k-(D?B:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nwse-resize",t)}:void 0,...p}),d.jsx("rect",{className:le("tl-transparent",{"tl-hidden":Nt}),"data-testid":"selection.target.bottom-left","aria-label":"bottom-left target",pointerEvents:"all",x:N(0-(M?K*3:K*1.5)),y:N(k-(D?0:B*1.5)),width:N(K*3),height:N(B*3),style:S?{cursor:Xn("nesw-resize",t)}:void 0,...f}),we&&d.jsxs(d.Fragment,{children:[d.jsx("rect",{"data-testid":"selection.resize.top-left",className:le("tl-corner-handle",{"tl-hidden":Ne}),"aria-label":"top_left handle",x:N(0-I/2),y:N(0-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.top-right",className:le("tl-corner-handle",{"tl-hidden":Vn}),"aria-label":"top_right handle",x:N(E-I/2),y:N(0-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.bottom-right",className:le("tl-corner-handle",{"tl-hidden":_n}),"aria-label":"bottom_right handle",x:N(E-I/2),y:N(k-I/2),width:N(I),height:N(I)}),d.jsx("rect",{"data-testid":"selection.resize.bottom-left",className:le("tl-corner-handle",{"tl-hidden":Nt}),"aria-label":"bottom_left handle",x:N(0-I/2),y:N(k-I/2),width:N(I),height:N(I)})]}),$l&&d.jsxs(d.Fragment,{children:[d.jsx("rect",{"data-testid":"selection.text-resize.left.handle",className:"tl-text-handle","aria-label":"bottom_left handle",x:N(0-I/4),y:N(k/2-Ms/2),rx:I/4,width:N(I/2),height:N(Ms)}),d.jsx("rect",{"data-testid":"selection.text-resize.right.handle",className:"tl-text-handle","aria-label":"bottom_left handle",rx:I/4,x:N(E-I/4),y:N(k/2-Ms/2),width:N(I/2),height:N(Ms)})]}),Y&&d.jsx(gY,{size:I,width:E,height:k,hideAlternateHandles:Oe})]})})}),eh=function({cx:n,cy:t,targetSize:r,corner:s,cursor:o,isHidden:i,"data-testid":a}){const l=ss(s);return d.jsx("rect",{className:le("tl-transparent","tl-rotate-corner",{"tl-hidden":i}),"data-testid":a,"aria-label":`${s} target`,pointerEvents:"all",x:N(n-r*3),y:N(t-r*3),width:N(Math.max(1,r*3)),height:N(Math.max(1,r*3)),cursor:o,...l})},yY=Math.sqrt(Math.PI),SY=function({cx:n,cy:t,size:r,isHidden:s,"data-testid":o}){const i=ss("mobile_rotate"),a=F(),l=H("zoom level",()=>a.getZoomLevel(),[a]),c=Math.max(14*(1/l),20/Math.max(1,l));return d.jsxs("g",{children:[d.jsx("circle",{"data-testid":o,pointerEvents:"all",className:le("tl-transparent","tl-mobile-rotate__bg",{"tl-hidden":s}),cx:n,cy:t,r:c,...i}),d.jsx("circle",{className:le("tl-mobile-rotate__fg",{"tl-hidden":s}),cx:n,cy:t,r:r/yY})]})};function vY(){const e=F();return H("is in a valid select state",()=>e.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle"),[e])?d.jsx(_M,{}):null}function Ov(e,n,t){const{arrowheadStart:r,arrowheadEnd:s}=n.props,o=Ha(e,n,t),i=o.start.clone(),a=o.end.clone(),l=b.Med(i,a);if(b.Equals(i,a))return{bindings:t,isStraight:!0,start:{handle:i,point:i,arrowhead:n.props.arrowheadStart},end:{handle:a,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:!1,length:0};const c=b.Sub(a,i).uni(),u=mf(e,n,"start"),h=mf(e,n,"end"),p=e.getShapePageTransform(n);iI(a,o.start,p,h),iI(i,o.end,p,u);let f=0,S=0,y=0,x=0,m=Ka*n.props.scale;const v=u&&h&&u.shape===h.shape,w=u&&h?yw(e,u.shape.id,h.shape.id):"safe";w==="safe"&&u&&h&&!v&&!u.isExact&&!h.isExact&&(h.didIntersect&&!u.didIntersect?u.isClosed&&i.setTo(a.clone().add(c.clone().mul(Ka*n.props.scale))):h.didIntersect||h.isClosed&&a.setTo(i.clone().sub(c.clone().mul(Ka*n.props.scale))));const C=b.Sub(a,i),E=b.Len(C)?C.uni():b.From(C),k=!b.Equals(E,c);v||(w!=="start-contains-end"&&u&&r!=="none"&&!u.isExact&&(y=Oo[n.props.size]/2+("size"in u.shape.props?Oo[u.shape.props.size]/2:0),f=(yf+y)*n.props.scale,m+=y*n.props.scale),w!=="end-contains-start"&&h&&s!=="none"&&!h.isExact&&(x=Oo[n.props.size]/2+("size"in h.shape.props?Oo[h.shape.props.size]/2:0),S=(yf+x)*n.props.scale,m+=x*n.props.scale));const I=i.clone().add(E.clone().mul(f*(k?-1:1))),_=a.clone().sub(E.clone().mul(S*(k?-1:1)));b.DistMin(I,_,m)&&(f!==0&&S!==0?(f*=-1.5,S*=-1.5):f!==0?f*=-1:S!==0&&(S*=-1)),i.add(E.clone().mul(f*(k?-1:1))),a.sub(E.clone().mul(S*(k?-1:1))),k?(u&&h&&a.setTo(b.Add(i,E.clone().mul(-Ka*n.props.scale))),l.setTo(b.Med(o.start,o.end))):l.setTo(b.Med(i,a));const T=b.Dist(i,a);return{bindings:t,isStraight:!0,start:{handle:o.start,point:i,arrowhead:n.props.arrowheadStart},end:{handle:o.end,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:T>0,length:T}}function iI(e,n,t,r){if(r===void 0||r.isExact)return;const s=oe.applyToPoint(t,n),o=oe.applyToPoint(t,e),i=oe.applyToPoint(oe.Inverse(r.transform),s),a=oe.applyToPoint(oe.Inverse(r.transform),o),l=r.isClosed,u=(l?iw:nG)(i,a,r.outline);let h;if(u!==null&&(h=u.sort((S,y)=>b.Dist2(S,i)-b.Dist2(y,i))[0]??(l?void 0:a)),h===void 0)return;const p=oe.applyToPoint(r.transform,h),f=oe.applyToPoint(oe.Inverse(t),p);e.setTo(f),r.didIntersect=!0}function xY(e,n,t){const{arrowheadEnd:r,arrowheadStart:s}=n.props,o=n.props.bend;if(Math.abs(o)>Math.abs(n.props.bend*(IY*n.props.scale)))return Ov(e,n,t);const i=Ha(e,n,t),a=b.Med(i.start,i.end),l=b.Sub(i.end,i.start),c=b.Len(l)?l.uni():b.From(l),u=b.Add(a,c.per().mul(-o)),h=mf(e,n,"start"),p=mf(e,n,"end"),f=i.start.clone(),S=i.end.clone(),y=u.clone();if(b.Equals(f,S))return{bindings:t,isStraight:!0,start:{handle:f,point:f,arrowhead:n.props.arrowheadStart},end:{handle:S,point:S,arrowhead:n.props.arrowheadEnd},middle:y,isValid:!1,length:0};const x=n.props.bend<0,m=x?Gu:iM,v=aI(f,S,y),w=b.Angle(v.center,f),C=b.Angle(v.center,S),E=m(w,C);if(v.length===0||v.size===0||!bC(v.length)||!bC(v.size))return Ov(e,n,t);const k=f.clone(),I=S.clone(),_=y.clone(),T=e.getShapePageTransform(n);let M=0,D=0,$=Ka*n.props.scale;if(h&&!h.isExact){const Y=oe.applyToPoint(T,k),q=oe.applyToPoint(T,v.center),ae=oe.applyToPoint(T,I),fe=oe.Inverse(h.transform),we=oe.applyToPoint(fe,Y),J=oe.applyToPoint(fe,q),Ue=oe.applyToPoint(fe,ae),{isClosed:Oe}=h,tt=Oe?kv:HC;let Ae,ot=tt(J,v.radius,h.outline);if(ot){const Ne=J.angle(we),Vn=J.angle(Ue),Nt=m(Ne,Vn);ot=ot.filter(St=>m(Ne,J.angle(St))<=Nt);const _n=Nt*.25;ot.sort(Oe?(St,Zt)=>Math.abs(m(Ne,J.angle(St))-_n)m(Ne,J.angle(St))m(Ne,J.angle(St))<=Nt),ot.sort(Oe?(St,Zt)=>Math.abs(m(Ne,J.angle(St))-_n)m(Ne,J.angle(St))m(w,O))&&I.setTo(v.center).add(b.FromAngle(j+R*(Math.min(.9,Ka*n.props.scale/K)*(x?1:-1))).mul(v.radius)))}wY(v.center,v.radius,k,I,_,E,x),k.equals(I)&&(k.setTo(_.clone().addXY(1,1)),I.setTo(_.clone().subXY(1,1))),f.setTo(k),S.setTo(I),y.setTo(_);const W=aI(f,S,y);return{bindings:t,isStraight:!1,start:{point:f,handle:i.start,arrowhead:n.props.arrowheadStart},end:{point:S,handle:i.end,arrowhead:n.props.arrowheadEnd},middle:y,handleArc:v,bodyArc:W,isValid:W.length!==0&&isFinite(W.center.x)&&isFinite(W.center.y)}}function aI(e,n,t){const r=Q0(e,n,t),s=b.Dist(r,e),o=+b.Clockwise(e,t,n),i=((e.y-n.y)**2+(e.x-n.x)**2)**.5,a=((n.y-t.y)**2+(n.x-t.x)**2)**.5,l=((t.y-e.y)**2+(t.x-e.x)**2)**.5,c=Math.acos((a*a+l*l-i*i)/(2*a*l))*2,u=+(Me>c),h=(Le-c)*(o?1:-1),p=h*s;return{center:r,radius:s,size:h,length:p,largeArcFlag:u,sweepFlag:o}}function wY(e,n,t,r,s,o,i){const a=b.Angle(e,t),l=b.Angle(e,r);let c=Gu(a,l);if(i||(c=Le-c),s.setTo(e).add(b.FromAngle(a+c*(.5*(i?1:-1))).mul(n)),c>o){s.rotWith(e,Me);const u=r.clone();r.setTo(t),t.setTo(u)}}const bY=8;function PY(e){return Math.abs(e.props.bend)l.props.terminal===t);if(!r)return;const s=e.getShape(r.toId);if(!s)return;const o=e.getShapePageTransform(s),i=e.getShapeGeometry(s),a=i instanceof Wr?i.children[0].vertices:i.vertices;return{shape:s,transform:o,isClosed:i.isClosed,isExact:r.props.isExact,didIntersect:!1,outline:a}}function lI(e,n,t,r){const s=e.getShape(t.toId);if(s){const{point:o,size:i}=e.getShapeGeometry(s).bounds,a=b.Add(o,b.MulV(t.props.isPrecise||r?t.props.normalizedAnchor:{x:.5,y:.5},i)),l=oe.applyToPoint(e.getShapePageTransform(s),a);return oe.applyToPoint(oe.Inverse(n),l)}else return new b(0,0)}function Rn(e,n){const t=e.getBindingsFromShape(n,"arrow");return{start:t.find(r=>r.props.terminal==="start"),end:t.find(r=>r.props.terminal==="end")}}const CY=r7("arrow info",(e,n)=>{const t=Rn(e,n);return PY(n)?Ov(e,n,t):xY(e,n,t)});function ds(e,n){const t=typeof n=="string"?n:n.id;return CY.get(e,t)}function Ha(e,n,t){var a,l;const r=e.getShapePageTransform(n),s=yw(e,(a=t.start)==null?void 0:a.toId,(l=t.end)==null?void 0:l.toId),o=t.start?lI(e,r,t.start,s==="double-bound"||s==="start-contains-end"):b.From(n.props.start),i=t.end?lI(e,r,t.end,s==="double-bound"||s==="end-contains-start"):b.From(n.props.end);return{start:o,end:i}}function ac(e,n,t,r){const s=typeof n=="string"?n:n.id,o=typeof t=="string"?t:t.id,i=e.getBindingsFromShape(s,"arrow").filter(l=>l.props.terminal===r.terminal);i.length>1&&e.deleteBindings(i.slice(1));const a=i[0];a?e.updateBinding({...a,toId:o,props:r}):e.createBinding({type:"arrow",fromId:s,toId:o,props:r})}function Vh(e,n,t){const r=e.getBindingsFromShape(n,"arrow").filter(s=>s.props.terminal===t);e.deleteBindings(r)}const Ka=10,yf=10,IY=10,Oo={s:2,m:3.5,l:5,xl:10};function yw(e,n,t){if(!n||!t)return"safe";if(n===t)return"double-bound";const r=e.getShapePageBounds(n),s=e.getShapePageBounds(t);if(r&&s){if(r.contains(s))return"start-contains-end";if(s.contains(r))return"end-contains-start"}return"safe"}class Yh extends Wh{getDefaultProps(){return{isPrecise:!1,isExact:!1,normalizedAnchor:{x:.5,y:.5}}}onAfterCreate({binding:n}){fy(this.editor,this.editor.getShape(n.fromId))}onAfterChange({bindingAfter:n}){fy(this.editor,this.editor.getShape(n.fromId))}onAfterChangeFromShape({shapeAfter:n}){fy(this.editor,n)}onAfterChangeToShape({binding:n}){mA(this.editor,n.fromId)}onBeforeIsolateFromShape({binding:n}){const t=this.editor.getShape(n.fromId);t&&Sf({editor:this.editor,arrow:t,terminal:n.props.terminal})}}g(Yh,"type","arrow"),g(Yh,"props",ET),g(Yh,"migrations",_T);function mA(e,n){var x;const t=e.getShape(n);if(!t)return;const r=Rn(e,t),{start:s,end:o}=r,i=s?e.getShape(s.toId):void 0,a=o?e.getShape(o.toId):void 0,l=e.getAncestorPageId(t);if(!l)return;let c;if(i&&a)c=e.findCommonAncestor([i,a])??l;else if(i||a){const m=(x=i||a)==null?void 0:x.parentId;m&&m===t.parentId?c=t.parentId:c=l}else return;c&&c!==t.parentId&&e.reparentShapes([n],c);const u=e.getShape(n);if(!u)throw Error("no reparented arrow");const h=e.getShapeNearestSibling(u,i),p=e.getShapeNearestSibling(u,a);let f;if(h&&p)f=h.index>p.index?h:p;else if(h&&!p)f=h;else if(p&&!h)f=p;else return;let S;const y=e.getSortedChildIdsForParent(f.parentId).map(m=>e.getShape(m)).filter(m=>m.index>f.index);if(y.length){const m=y.find(v=>v.type!=="arrow");if(u.index>f.index&&(!m||u.index0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:n.max,height:n.max,min:n.min,step:n.step,sizes:th(gy.area)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},maxHeight:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:1,height:n.max,min:n.min,step:n.step,sizes:th(gy.height)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},maxWidth:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:n.max,height:1,min:n.min,step:n.step,sizes:th(gy.width)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},test:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=qn(qn({},Wa),n);return t.sizes=th(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),nh(t)}};let Sy=null;function BY(){return Sy||(Sy=UY()),Sy}async function UY(){const e=await yy.maxWidth({usePromise:!0}),n=await yy.maxHeight({usePromise:!0}),t=await yy.maxArea({usePromise:!0});return{maxWidth:e.width,maxHeight:n.height,maxArea:t.width*t.height}}const dI=8192,HY=4096*4096;async function KY(e,n){if(e<=dI&&n<=dI&&e*n<=HY)return[e,n];const{maxWidth:t,maxHeight:r,maxArea:s}=await BY(),o=e/n;if(e>t&&(e=t,n=e/o),n>r&&(n=r,e=n*o),e*n>s){const i=Math.sqrt(s/(e*n));e*=i,n*=i}return[e,n]}function WY(e,n){const t=e.w/n.w,r=e.h/n.h;return t<=1&&r<=1?e:t>r?{w:e.w/t,h:e.h/t}:{w:e.w/r,h:e.h/r}}function GY(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function VY(e){const n=new URL(e).host.replace("www.","");for(const t of Wu)if(vA(t.hostnames,n)){const r=t.fromEmbedUrl(e);if(r)return{definition:t,url:r,embedUrl:e}}}const YY=e=>e.split("*").map(n=>GY(n)).join(".+"),vA=(e,n)=>!!e.find(t=>{const r=new RegExp(YY(t));return n.match(r)});function XY(e){const n=new URL(e).host.replace("www.","");for(const t of Wu)if(vA(t.hostnames,n)){const r=t.toEmbedUrl(e);if(r)return{definition:t,embedUrl:r,url:e}}}function xA(e){return XY(e)??VY(e)}function Do(e){try{return xA(e)}catch(n){console.error(n)}}/*! + `),c=new Blob([l],{type:"application/javascript"}),u=URL.createObjectURL(c);a=new Worker(u),URL.revokeObjectURL(u),a.onmessage=function(h){var p=h.data,f=p.width,S=p.height,y=p.benchmark,x=p.isTestPass;x?(lc[r].onSuccess(f,S,y),delete lc[r]):lc[r].onError(f,S,y)}}if(e.usePromise)return new Promise(function(h,p){var f=qn(qn({},e),{},{onError:function(m,v,w){var C;if(e.sizes.length===0)C=!0;else{var E=e.sizes.slice(-1),k=uI(E,1),I=uI(k[0],2),_=I[0],T=I[1];C=m===_&&v===T}s(m,v,w),C&&p({width:m,height:v,benchmark:w})},onSuccess:function(m,v,w){o(m,v,w),h({width:m,height:v,benchmark:w})}});if(a){var S=f.onError,y=f.onSuccess;lc[r]={onError:S,onSuccess:y},a.postMessage(i)}else Xc(f)});if(a)lc[r]={onError:s,onSuccess:o},a.postMessage(i);else return Xc(e)}var yy={maxArea:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:n.max,height:n.max,min:n.min,step:n.step,sizes:th(gy.area)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},maxHeight:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:1,height:n.max,min:n.min,step:n.step,sizes:th(gy.height)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},maxWidth:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=my({width:n.max,height:1,min:n.min,step:n.step,sizes:th(gy.width)}),r=qn(qn(qn({},Wa),n),{},{sizes:t});return nh(r)},test:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=qn(qn({},Wa),n);return t.sizes=th(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),nh(t)}};let Sy=null;function BY(){return Sy||(Sy=UY()),Sy}async function UY(){const e=await yy.maxWidth({usePromise:!0}),n=await yy.maxHeight({usePromise:!0}),t=await yy.maxArea({usePromise:!0});return{maxWidth:e.width,maxHeight:n.height,maxArea:t.width*t.height}}const dI=8192,HY=4096*4096;async function KY(e,n){if(e<=dI&&n<=dI&&e*n<=HY)return[e,n];const{maxWidth:t,maxHeight:r,maxArea:s}=await BY(),o=e/n;if(e>t&&(e=t,n=e/o),n>r&&(n=r,e=n*o),e*n>s){const i=Math.sqrt(s/(e*n));e*=i,n*=i}return[e,n]}function WY(e,n){const t=e.w/n.w,r=e.h/n.h;return t<=1&&r<=1?e:t>r?{w:e.w/t,h:e.h/t}:{w:e.w/r,h:e.h/r}}function GY(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function VY(e){const n=new URL(e).host.replace("www.","");for(const t of Wu)if(vA(t.hostnames,n)){const r=t.fromEmbedUrl(e);if(r)return{definition:t,url:r,embedUrl:e}}}const YY=e=>e.split("*").map(n=>GY(n)).join(".+"),vA=(e,n)=>!!e.find(t=>{const r=new RegExp(YY(t));return n.match(r)});function XY(e){const n=new URL(e).host.replace("www.","");for(const t of Wu)if(vA(t.hostnames,n)){const r=t.toEmbedUrl(e);if(r)return{definition:t,embedUrl:r,url:e}}}function xA(e){return XY(e)??VY(e)}function Do(e){try{return xA(e)}catch(n){console.error(n)}}/*! * MIT License * Adapted (mostly copied) the work of https://github.com/fregante/text-field-edit * Copyright (c) Federico Brigante (bfred.it) @@ -196,12 +196,12 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho `).map(t=>t||" ").join(` `)}};g(fn,"fixNewLines",/\r?\n|\r/g);let ml=fn;function rh(e){if(typeof window.getSelection>"u")return;const n=window.getSelection();if(!n)return;let t=0;if(n.rangeCount!==0){const r=n.getRangeAt(0),s=r.cloneRange();s.selectNodeContents(e),s.setEnd(r.endContainer,r.endOffset),t=s.toString().length}return t}const qY=/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;function wA(e){return qY.test(e)}function ZY(e){return e.replace(/\t/g,Ga)}function QY(e){const n=e.split(` `);for(;n[0]&&n[0].trim().length===0;)n.shift();let t=1/0;for(const r of n)if(r.trim().length>0){const s=r.length-r.trimStart().length;t=Math.min(t,s)}return n.map(r=>r.slice(t)).join(` -`)}function JY(e){return e.replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function eX(e){return JY(QY(ZY(e)))}function tX(e,{maxImageDimension:n,maxAssetSize:t,acceptedImageMimeTypes:r,acceptedVideoMimeTypes:s},{toasts:o,msg:i}){e.registerExternalAssetHandler("file",async({file:a})=>{const l=a.name;let c=a;const u=r.includes(c.type),h=s.includes(c.type);!u&&!h&&o.addToast({title:i("assets.files.type-not-allowed"),severity:"error"}),Ye(u||h,`File type not allowed: ${c.type}`),c.size>t&&o.addToast({title:i("assets.files.size-too-big"),severity:"error"}),Ye(c.size<=t,`File size too big: ${(c.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),c.type==="video/quicktime"&&(c=new File([c],c.name,{type:"video/mp4"}));let p=u?await cs.getImageSize(c):await cs.getVideoSize(c);const f=await cs.isAnimated(c)||h,S=C9(await c.arrayBuffer());if(isFinite(n)){const y=WY(p,{w:n,h:n});p!==y&&cs.isStaticImageType(c.type)&&(p=y)}const x={id:_i.createId(S),type:u?"image":"video",typeName:"asset",props:{name:l,src:"",w:p.w,h:p.h,fileSize:c.size,mimeType:c.type,isAnimated:f}};return x.props.src=await e.uploadAsset(x,c),_i.create(x)}),e.registerExternalAssetHandler("url",async({url:a})=>{var c,u,h,p,f;let l;try{const m=await(await vs(a,{method:"GET",mode:"no-cors"})).text(),x=new DOMParser().parseFromString(m,"text/html");l={image:((c=x.head.querySelector('meta[property="og:image"]'))==null?void 0:c.getAttribute("content"))??"",favicon:((u=x.head.querySelector('link[rel="apple-touch-icon"]'))==null?void 0:u.getAttribute("href"))??((h=x.head.querySelector('link[rel="icon"]'))==null?void 0:h.getAttribute("href"))??"",title:((p=x.head.querySelector('meta[property="og:title"]'))==null?void 0:p.getAttribute("content"))??a,description:((f=x.head.querySelector('meta[property="og:description"]'))==null?void 0:f.getAttribute("content"))??""},l.image.startsWith("http")||(l.image=new URL(l.image,a).href),l.favicon.startsWith("http")||(l.favicon=new URL(l.favicon,a).href)}catch(S){console.error(S),o.addToast({title:i("assets.url.failed"),severity:"error"}),l={image:"",favicon:"",title:"",description:""}}return{id:_i.createId(fv(a)),typeName:"asset",type:"bookmark",props:{src:a,description:l.description,image:l.image,favicon:l.favicon,title:l.title},meta:{}}}),e.registerExternalContentHandler("svg-text",async({point:a,text:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=new DOMParser().parseFromString(l,"image/svg+xml").querySelector("svg");if(!u)throw new Error("No element present");let h=parseFloat(u.getAttribute("width")||"0"),p=parseFloat(u.getAttribute("height")||"0");if(!(h&&p)){document.body.appendChild(u);const S=u.getBoundingClientRect();document.body.removeChild(u),h=S.width,p=S.height}const f=await e.getAssetForExternalContent({type:"file",file:new File([l],"asset.svg",{type:"image/svg+xml"})});if(!f)throw Error("Could not create an asset");hI(e,[f],c)}),e.registerExternalContentHandler("embed",({point:a,url:l,embed:c})=>{const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),{width:h,height:p}=c,f=je(),S={id:f,type:"embed",x:u.x-(h||450)/2,y:u.y-(p||450)/2,props:{w:h,h:p,url:l}};e.createShapes([S]).select(f)}),e.registerExternalContentHandler("files",async({point:a,files:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=new b(c.x,c.y),h=[];await Promise.all(l.map(async(p,f)=>{if(p.size>t)return o.addToast({title:i("assets.files.size-too-big"),severity:"error"}),console.warn(`File size too big: ${(p.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),null;if(!p.type)throw new Error("No mime type");if(!r.concat(s).includes(p.type))return o.addToast({title:i("assets.files.type-not-allowed"),severity:"error"}),console.warn(`${p.name} not loaded - Extension not allowed.`),null;try{const S=await e.getAssetForExternalContent({type:"file",file:p});if(!S)throw Error("Could not create an asset");h[f]=S}catch(S){return o.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error(S),null}})),hI(e,me(h),u)}),e.registerExternalContentHandler("text",async({point:a,text:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=e.getShapeUtil("text").getDefaultProps(),h=eX(l),p=e.getOnlySelectedShape();if(p&&"text"in p.props){e.updateShapes([{id:p.id,type:p.type,props:{text:h}}]);return}let f,S,m,x="middle";const y=h.split(` -`).length>1,v=wA(h);y&&(x=y?v?"end":"start":"middle");const w=e.textMeasure.measureText(h,{...Gt,fontFamily:Ss[u.font],fontSize:gl[u.size],maxWidth:null}),C=Math.min(y?e.getViewportPageBounds().width*.9:920,Math.max(200,e.getViewportPageBounds().width*.9));if(w.w>C){const E=e.textMeasure.measureText(h,{...Gt,fontFamily:Ss[u.font],fontSize:gl[u.size],maxWidth:C});f=E.w,S=E.h,m=!1,x=v?"end":"start"}else f=w.w,S=w.h,m=!0;c.y-S/2{const c=Do(l);if(c)return e.putExternalContent({type:"embed",url:c.url,point:a,embed:c.definition});const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),h=_i.createId(fv(l)),p=nX(e,l,u);let f=e.getAsset(h),S=!1;if(!f){S=!0;try{const m=await e.getAssetForExternalContent({type:"url",url:l});if(!m)throw Error("Could not create an asset");f=m}catch{o.addToast({title:i("assets.url.failed"),severity:"error"});return}}e.run(()=>{S&&e.createAssets([f]),e.updateShapes([{id:p.id,type:p.type,props:{assetId:f.id}}])})})}async function hI(e,n,t){if(!n.length)return[];const r=b.From(t),s=[];for(let o=0;o{const o=n.filter(i=>!e.getAsset(i.id));o.length&&e.createAssets(o),e.createShapes(s).select(...s.map(i=>i.id)),bA(e,t)}),s.map(o=>o.id)}function bA(e,n){const t=e.getViewportPageBounds();let r=e.getSelectionPageBounds();if(r){const s=r.center.sub(n);e.updateShapes(e.getSelectedShapes().map(o=>{const i=e.getShapeParentTransform(o).decompose().rotation,a=b.Rot(s,-i);return{id:o.id,type:o.type,x:o.x-a.x,y:o.y-a.y}}))}r=e.getSelectionPageBounds(),r&&!t.contains(r)&&e.zoomToSelection()}function nX(e,n,t){const r={id:je(),type:"bookmark",x:t.x-150,y:t.y-160,opacity:1,props:{assetId:null,url:n}};return e.run(()=>{e.createShapes([r]).select(r.id),bA(e,t)}),e.getShape(r.id)}var Hy;let rX=(Hy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")});g(this,"onKeyUp",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}})}},g(Hy,"id","idle"),Hy);var Ky;let sX=(Ky=class extends se{constructor(){super(...arguments);g(this,"shape");g(this,"markId","");g(this,"onEnter",()=>{this.didTimeout=!1;const t=this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{filter:r=>!r.isLocked&&this.editor.canBindShapes({fromShape:"arrow",toShape:r,binding:"arrow"}),margin:0,hitInside:!0,renderingOnly:!0});t?this.editor.setHintingShapes([t.id]):this.createArrowShape(),this.startPreciseTimeout()});g(this,"onExit",()=>{this.shape=void 0,this.editor.setHintingShapes([]),this.clearPreciseTimeout()});g(this,"onPointerMove",()=>{if(this.editor.inputs.isDragging){if(this.shape||this.createArrowShape(),!this.shape)throw Error("expected shape");this.updateArrowShapeEndHandle(),this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,handle:{id:"end",type:"vertex",index:"a3",x:0,y:0},isCreating:!0,onInteractionEnd:"arrow"})}});g(this,"onPointerUp",()=>{this.cancel()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()});g(this,"preciseTimeout",-1);g(this,"didTimeout",!1)}cancel(){this.shape&&this.editor.bailToMark(this.markId),this.editor.setHintingShapes([]),this.parent.transition("idle")}createArrowShape(){var u;const{originPagePoint:t}=this.editor.inputs,r=je();this.markId=`creating:${r}`,this.editor.mark(this.markId),this.editor.createShape({id:r,type:"arrow",x:t.x,y:t.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const s=this.editor.getShape(r);if(!s)throw Error("expected shape");const o=this.editor.getShapeHandles(s);if(!o)throw Error("expected handles for arrow");const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=o.find(h=>h.id==="start"),c=(u=i.onHandleDrag)==null?void 0:u.call(i,s,{handle:{...l,x:0,y:0},isPrecise:!0,initial:a});c&&this.editor.updateShapes([c]),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.didTimeout,initial:a});c&&this.editor.updateShapes([c])}{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=this.editor.getPointInShapeSpace(t,this.editor.inputs.currentPagePoint),c=r.find(h=>h.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:!1,initial:a});u&&this.editor.updateShapes([u])}this.shape=this.editor.getShape(t.id)}startPreciseTimeout(){this.preciseTimeout=this.editor.timers.setTimeout(()=>{this.getIsActive()&&(this.didTimeout=!0)},320)}clearPreciseTimeout(){clearTimeout(this.preciseTimeout)}},g(Ky,"id","pointing"),Ky);class Xh extends se{constructor(){super(...arguments);g(this,"shapeType","arrow")}}g(Xh,"id","arrow"),g(Xh,"initial","idle"),g(Xh,"children",()=>[rX,sX]);class Sw extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"initialShape");g(this,"shapeType",this.parent.id==="highlight"?"highlight":"draw");g(this,"util",this.editor.getShapeUtil(this.shapeType));g(this,"isPen",!1);g(this,"isPenOrStylus",!1);g(this,"segmentMode","free");g(this,"didJustShiftClickToExtendPreviousShapeLine",!1);g(this,"pagePointWhereCurrentSegmentChanged",{});g(this,"pagePointWhereNextSegmentChanged",null);g(this,"lastRecordedPoint",{});g(this,"mergeNextPoint",!1);g(this,"currentLineLength",0);g(this,"canDraw",!1);g(this,"markId",null);g(this,"onEnter",t=>{this.markId=null,this.info=t,this.canDraw=!this.editor.getIsMenuOpen(),this.lastRecordedPoint=this.editor.inputs.currentPagePoint.clone(),this.canDraw&&this.startShape()});g(this,"onPointerMove",()=>{const{inputs:t}=this.editor;if(this.isPen&&!t.isPen){if(this.markId){this.editor.bailToMark(this.markId),this.startShape();return}}else!this.canDraw&&t.isDragging&&(this.startShape(),this.canDraw=!0);this.canDraw&&(this.isPenOrStylus?b.Dist(t.currentPagePoint,this.lastRecordedPoint)>=1/this.editor.getZoomLevel()?(this.lastRecordedPoint=t.currentPagePoint.clone(),this.mergeNextPoint=!1):this.mergeNextPoint=!0:this.mergeNextPoint=!1,this.updateDrawingShape())});g(this,"onKeyDown",t=>{if(t.key==="Shift")switch(this.segmentMode){case"free":{this.segmentMode="starting_straight",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_free":this.segmentMode="starting_straight"}this.updateDrawingShape()});g(this,"onKeyUp",t=>{if(t.key==="Shift")switch(this.editor.snaps.clearIndicators(),this.segmentMode){case"straight":{this.segmentMode="starting_free",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_straight":{this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";break}}this.updateDrawingShape()});g(this,"onExit",()=>{this.editor.snaps.clearIndicators(),this.pagePointWhereCurrentSegmentChanged=this.editor.inputs.currentPagePoint.clone()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.editor.inputs.isDragging||(this.markId&&this.editor.bailToMark(this.markId),this.cancel())})}canClose(){return this.shapeType!=="highlight"}getIsClosed(t,r,s){if(!this.canClose())return!1;const o=jt[r],i=t[0].points[0],a=t[t.length-1],l=a.points[a.points.length-1];return i!==l&&this.currentLineLength>o*4*s&&b.DistMin(i,l,o*2*s)}startShape(){const{inputs:{originPagePoint:t,isPen:r}}=this.editor;this.markId="draw start "+ct(),this.editor.mark(this.markId);const{z:s=.5}=this.info.point;this.isPen=r,this.isPenOrStylus=r||s>0&&s<.5||s>.5&&s<1;const o=this.isPenOrStylus?s*1.25:.5;if(this.segmentMode=this.editor.inputs.shiftKey?"straight":"free",this.didJustShiftClickToExtendPreviousShapeLine=!1,this.lastRecordedPoint=t.clone(),this.initialShape){const a=this.editor.getShape(this.initialShape.id);if(a&&this.segmentMode==="straight"){this.didJustShiftClickToExtendPreviousShapeLine=!0;const l=Ut(a.props.segments);if(!l)throw Error("Expected a previous segment!");const c=Ut(l.points);if(!c)throw Error("Expected a previous point!");const{x:u,y:h}=this.editor.getPointInShapeSpace(a,t).toFixed(),p={type:this.segmentMode,points:[{x:c.x,y:c.y,z:+o.toFixed(2)},{x:u,y:h,z:+o.toFixed(2)}]},f=oe.applyToPoint(this.editor.getShapePageTransform(a.id),c);this.pagePointWhereCurrentSegmentChanged=f,this.pagePointWhereNextSegmentChanged=null;const S=[...a.props.segments,p];this.currentLineLengththis.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="straight";const x=Ut(l);if(!x)throw Error("Expected a previous segment!");const y=Ut(x.points);if(!y)throw Error("Expected a previous last point!");let v;const w=this.editor.getPointInShapeSpace(a,this.pagePointWhereCurrentSegmentChanged).toFixed().toJson();if(x.type==="straight"){this.currentLineLength+=b.Dist(y,w),v={type:"straight",points:[{...y},w]};const E=this.editor.getShapePageTransform(a);this.pagePointWhereCurrentSegmentChanged=oe.applyToPoint(E,y)}else v={type:"straight",points:[w,f]};const C={id:s,type:this.shapeType,props:{segments:[...l,v]}};this.canClose()&&(C.props.isClosed=this.getIsClosed(l,o,i)),this.editor.updateShapes([C])}break}case"starting_free":{const{pagePointWhereNextSegmentChanged:S}=this;if(S===null)throw Error("We should have a point where the segment changed");if(b.Dist2(S,r.currentPagePoint)>this.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";const x=l.slice(),y=x[x.length-1],v=Ut(y.points);if(!v)throw Error("No previous point!");const w={type:"free",points:[...b.PointsBetween(v,f,6).map(k=>({x:zs(k.x),y:zs(k.y),z:zs(k.z)}))]},C=[...x,w];this.currentLineLength2){let M,D=8/this.editor.getZoomLevel();for(let $=0,j=l.length-2;$this.editor.options.maxPointsPerDrawShape){this.editor.updateShapes([{id:s,type:this.shapeType,props:{isComplete:!0}}]);const v=je(),w=this.editor.getShape(s).props;this.editor.createShapes([{id:v,type:this.shapeType,x:zs(r.currentPagePoint.x),y:zs(r.currentPagePoint.y),props:{isPen:this.isPenOrStylus,scale:w.scale,segments:[{type:"free",points:[{x:0,y:0,z:this.isPenOrStylus?+(h*1.25).toFixed():.5}]}]}}]),this.initialShape=Be(this.editor.getShape(v)),this.mergeNextPoint=!1,this.lastRecordedPoint=r.currentPagePoint.clone(),this.currentLineLength=0}break}}}getLineLength(t){let r=0;for(const s of t)for(let o=0;o{this.parent.transition("drawing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Wy,"id","idle"),Wy);class Pc extends se{constructor(){super(...arguments);g(this,"shapeType","draw");g(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}g(Pc,"id","draw"),g(Pc,"initial","idle"),g(Pc,"isLockable",!1),g(Pc,"children",()=>[PA,Sw]);class Rv extends Gh{constructor(){super(...arguments);g(this,"shapeType","frame");g(this,"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)&&oX(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")})}}g(Rv,"id","frame"),g(Rv,"initial","idle");function oX(e,n,t){return n.includes(e.id)?!1:e.parentId===t.parentId}var Gy;let iX=(Gy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onKeyUp",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Gy,"id","idle"),Gy);var Vy;let aX=(Vy=class extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"onPointerUp",()=>{this.complete()});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,s=je();this.markId=`creating:${s}`,this.editor.mark(this.markId),this.editor.createShapes([{id:s,type:"geo",x:r.x,y:r.y,props:{w:1,h:1,geo:this.editor.getStyleForNextShape(Br),scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]).select(s).setCurrentTool("select.resizing",{...t,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:"geo"})}});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:t}=this.editor.inputs,r=je();this.markId=`creating:${r}`,this.editor.mark(this.markId);const s=this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1,o=this.editor.getStyleForNextShape(Br),i=o==="star"?{w:200,h:190}:o==="cloud"?{w:300,h:180}:{w:200,h:200};this.editor.createShapes([{id:r,type:"geo",x:t.x,y:t.y,props:{geo:this.editor.getStyleForNextShape(Br),scale:s,...i}}]);const a=this.editor.getShape(r);if(!a)return;const{w:l,h:c}=a.props,u=new b(l/2,c/2).mul(s),h=this.editor.getShapeParentTransform(a);h&&u.rot(-h.rotation()),this.editor.select(r),this.editor.updateShape({id:a.id,type:"geo",x:a.x-u.x,y:a.y-u.y,props:{geo:this.editor.getStyleForNextShape(Br),w:l*s,h:c*s}}),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select",{})}cancel(){this.parent.transition("idle")}},g(Vy,"id","pointing"),Vy);class qh extends se{constructor(){super(...arguments);g(this,"shapeType","geo")}}g(qh,"id","geo"),g(qh,"initial","idle"),g(qh,"children",()=>[iX,aX]);class Cc extends se{constructor(){super(...arguments);g(this,"shapeType","highlight");g(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}g(Cc,"id","highlight"),g(Cc,"initial","idle"),g(Cc,"children",()=>[PA,Sw]),g(Cc,"isLockable",!1);var Yy;let lX=(Yy=class extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"onEnter",t=>{this.shapeId=t.shapeId,this.editor.setCursor({type:"cross",rotation:0})});g(this,"onPointerDown",()=>{this.parent.transition("pointing",{shapeId:this.shapeId})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Yy,"id","idle"),Yy);const pI=2;var Xy;let cX=(Xy=class extends se{constructor(){super(...arguments);g(this,"shape",{});g(this,"markId");g(this,"onEnter",t=>{const{inputs:r}=this.editor,{currentPagePoint:s}=r;this.markId=void 0;const o=t.shapeId&&this.editor.getShape(t.shapeId);if(o&&r.shiftKey){this.markId=`creating:${o.id}`,this.editor.mark(this.markId),this.shape=o;const i=this.editor.getShapeHandles(this.shape);if(!i)return;const a=i.filter(f=>f.type==="vertex").sort(an),l=a[a.length-1],c=a[a.length-2],u=oe.applyToPoint(this.editor.getShapeParentTransform(this.shape),new b(this.shape.x,this.shape.y)),h=b.Sub(s,u).addXY(.1,.1),p=Be(this.shape.props.points);if(b.DistMin(l,c,pI)||b.DistMin(h,l,pI))p[l.id]={id:l.id,index:l.index,x:h.x,y:h.y};else{const f=Fr(l.index);p[f]={id:f,index:f,x:h.x,y:h.y}}this.editor.updateShapes([{id:this.shape.id,type:this.shape.type,props:{points:p}}])}else{const i=je();this.markId=`creating:${i}`,this.editor.mark(this.markId),this.editor.createShapes([{id:i,type:"line",x:s.x,y:s.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]),this.editor.select(i),this.shape=this.editor.getShape(i)}});g(this,"onPointerMove",()=>{if(this.shape&&this.editor.inputs.isDragging){const t=this.editor.getShapeHandles(this.shape);if(!t)throw this.markId&&this.editor.bailToMark(this.markId),Error("No handles found");const r=Ut(t);this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,isCreating:!0,handle:{...r,x:r.x-.1,y:r.y-.1},onInteractionEnd:"line"})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"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()}},g(Xy,"id","pointing"),Xy);class Zh extends se{constructor(){super(...arguments);g(this,"shapeType","line")}}g(Zh,"id","line"),g(Zh,"initial","idle"),g(Zh,"children",()=>[lX,cX]);var qy;let uX=(qy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(qy,"id","idle"),qy);function Ke(e,n){var s;const t=new Set;for(const o of n){const i=e.getShape(o);if(!i)continue;e.getShapeUtil(i).onDragShapesOut&&t.add(i);const a=e.getShape(i.parentId);a&&e.getShapeUtil(a).onDragShapesOut&&t.add(a)}const r=new Map;for(const o of t){const i=CA(e,o);i.length&&r.set(o,i)}for(const[o,i]of r){const a=e.getShapeUtil(o),l=me(i.map(c=>e.getShape(c)));(s=a.onDragShapesOut)==null||s.call(a,o,l)}}function CA(e,n){const t=e.getSortedChildIdsForParent(n.id);if(t.length===0)return[];const r=e.getShapePageBounds(n);if(!r)return[];let s,o,i;const a=[];for(const l of t){const c=e.getShapePageBounds(l);if(!c)continue;if(!r.includes(c)){a.push(l);continue}s??(s=e.getShapeGeometry(n)),o??(o=e.getShapePageTransform(n)),i??(i=o.applyToPoints(s.vertices));const u=e.getShapePageTransform(l).clone().invert().applyToPoints(i),{vertices:h,isClosed:p}=e.getShapeGeometry(l);if(!h.some(f=>sr(f,u))){if(p){if(YM(u,h))continue}else if(oG(u,h))continue;a.push(l)}}return a}function vf(e,n,t=!1){e.select(n),e.setEditingShape(n),e.setCurrentTool("select.editing_shape",{target:"shape",shape:n}),t&&e.emit("select-all-text",{shapeId:n.id}),IA(e)}const dX=16;function IA(e){const n=e.getSelectionPageBounds(),t=e.getViewportPageBounds();if(n&&!t.contains(n)){const r=n.clone().expandBy(dX/e.getZoomLevel()).expand(t),s=t.clone().translate({x:(r.center.x-t.center.x)*2,y:(r.center.y-t.center.y)*2});e.zoomToBounds(s,{animation:{duration:e.options.animationMediumMs},inset:0})}}const hX=0,ze=200,vg=new b(ze/2,ze/2),EA=10,pX=e=>[[["a1"],new b(ze*.5,ze*-.5-e.options.adjacentShapeMargin)],[["a2"],new b(ze*1.5+e.options.adjacentShapeMargin,ze*.5)],[["a3"],new b(ze*.5,ze*1.5+e.options.adjacentShapeMargin)],[["a4"],new b(ze*-.5-e.options.adjacentShapeMargin,ze*.5)]];function fX(e,n){if(n===1)return pX(e);const t=ze*n,r=e.options.adjacentShapeMargin*n;return[[["a1"],new b(t*.5,t*-.5-r)],[["a2"],new b(t*1.5+r,t*.5)],[["a3"],new b(t*.5,t*1.5+r)],[["a4"],new b(t*-.5-r,t*.5)]]}function _A(e,n,t,r,s,o){return Object.fromEntries(fX(e,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(n)]}))}function kA(e,n,t,r){const s=new Set(e.getSelectedShapeIds()),o=(ze+e.options.adjacentShapeMargin+r)**2,i=new Map,a=[];for(const u of e.getCurrentPageShapes()){if(!e.isShapeOfType(u,"note")||t!==u.props.scale||s.has(u.id))continue;const h=e.getShapePageTransform(u.id);n===h.rotation()&&(i.set(u,e.getShapePageBounds(u).center),a.push(...Object.values(_A(e,h.point(),n,u.props.growY,r,t))))}const l=a.length;let c;for(const[u,h]of i)for(let p=0;po||e.isPointInShape(u,c)&&(a[p]=void 0));return me(a)}function TA(e,n,t,r,s=!1){let o;const i=e.getCurrentPageShapesSorted(),a=(ze+e.options.adjacentShapeMargin**2)**n.props.scale;for(let l=i.length-1;l>=0;l--){const c=i[l];if(c.type==="note"&&c.id!==n.id){const u=e.getShapePageBounds(c);if(u&&b.Dist2(u.center,t){const{editor:t}=this;if(this.wasFocusedOnEnter=!t.getIsMenuOpen(),this.wasFocusedOnEnter){const r=je();this.markId=`creating:${r}`,t.mark(this.markId);const s=this.editor.inputs.originPagePoint.clone(),o=fI(this.editor,s,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);o&&s.sub(o),this.shape=gI(this.editor,r,s)}});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){if(!this.wasFocusedOnEnter){const r=je(),s=this.editor.inputs.originPagePoint.clone(),o=fI(this.editor,s,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);o&&s.sub(o),this.shape=gI(this.editor,r,s)}this.editor.setCurrentTool("select.translating",{...t,target:"shape",shape:this.shape,onInteractionEnd:"note",isCreating:!0,onCreate:()=>{this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape")}})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()})}complete(){this.wasFocusedOnEnter&&(this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):(this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape",{...this.info,target:"shape",shape:this.shape})))}cancel(){this.editor.bailToMark(this.markId),this.parent.transition("idle",this.info)}},g(Zy,"id","pointing"),Zy);function fI(e,n,t){let r=EA/e.getZoomLevel(),s;for(const o of kA(e,0,t,0)){const i=b.Sub(n,o),a=i.len();a[uX,gX]);function mX(e){const n=e.getShapeAtPoint(e.inputs.currentPagePoint,{hitInside:!1,hitLabels:!1,margin:e.options.hitTestMargin/e.getZoomLevel(),renderingOnly:!0});if(!n)return e.setHoveredShape(null);let t;const r=e.getOutermostSelectableShape(n);return r===n||r.id===e.getFocusedGroupId()||e.getSelectedShapeIds().includes(r.id)?t=n:t=r,e.setHoveredShape(t.id)}const Ks=B2(mX,32);var Qy;let yX=(Qy=class extends se{constructor(){super(...arguments);g(this,"onPointerMove",t=>{switch(t.target){case"shape":case"canvas":Ks(this.editor)}});g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onExit",()=>{Ks.cancel()});g(this,"onKeyDown",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Qy,"id","idle"),Qy);var Jy;let SX=(Jy=class extends se{constructor(){super(...arguments);g(this,"shape");g(this,"markId","");g(this,"onExit",()=>{this.editor.setHintingShapes([])});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{inputs:{originPagePoint:r}}=this.editor,s=je();this.markId=`creating:${s}`,this.editor.mark(this.markId);const o=this.createTextShape(s,r,!1);if(!o){this.cancel();return}this.shape=this.editor.getShape(o),this.editor.select(s),this.editor.setCurrentTool("select.resizing",{...t,target:"selection",handle:"right",isCreating:!0,creationCursorOffset:{x:18,y:1},onInteractionEnd:"text",onCreate:()=>{this.editor.setEditingShape(o.id),this.editor.setCurrentTool("select.editing_shape")}})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.cancel()});g(this,"onCancel",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){var o;this.editor.mark("creating text shape");const t=je(),{currentPagePoint:r}=this.editor.inputs;this.createTextShape(t,r,!0)&&(this.editor.select(t),this.editor.setEditingShape(t),this.editor.setCurrentTool("select"),(o=this.editor.root.getCurrent())==null||o.transition("editing_shape"))}cancel(){this.parent.transition("idle"),this.editor.bailToMark(this.markId)}createTextShape(t,r,s){this.editor.createShape({id:t,type:"text",x:r.x,y:r.y,props:{text:"",autoSize:s,w:20,scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const o=this.editor.getShape(t);if(!o){this.cancel();return}const i=this.editor.getShapePageBounds(o),a=new b;if(s)switch(o.props.textAlign){case"start":{a.x=0;break}case"middle":{a.x=-i.width/2;break}case"end":{a.x=-i.width;break}}else a.x=0;if(a.y=-i.height/2,An(o.parentId)){const l=this.editor.getShapeParentTransform(o);a.rot(-l.rotation())}return this.editor.updateShape({...o,x:o.x+a.x,y:o.y+a.y}),o}},g(Jy,"id","pointing"),Jy);class Ic extends se{constructor(){super(...arguments);g(this,"shapeType","text")}}g(Ic,"id","text"),g(Ic,"initial","idle"),g(Ic,"children",()=>[yX,SX]),g(Ic,"isLockable",!1);const vX=[Ic,Pc,qh,Qh,Zh,Rv,Xh,Cc];function Ar(){return lo({isDarkMode:Ju()})}function xg(e){return{key:`${xs.id}:${e}`,getElement:async()=>{const n=xX(e);if(!n)return null;const t=n.$$_url,r=n.$$_fontface;if(!t||!r)return null;const s=await(await vs(t)).blob(),o=await ji.blobToDataUrl(s),i=r.replace(t,o);return d.jsx("style",{children:i})}}}function xX(e){const n=bT[e];for(const t of document.fonts)if(n.includes(t.family))return t;return null}function vw(e){return{key:`${xs.id}:${e}`,getElement:async()=>e!=="pattern"?null:d.jsx(wX,{})}}function wX(){const e=Ar(),n=8/12;return d.jsxs(d.Fragment,{children:[d.jsxs("mask",{id:"hash_pattern_mask",children:[d.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:"white"}),d.jsxs("g",{strokeLinecap:"round",stroke:"black",children:[d.jsx("line",{x1:n*1,y1:n*3,x2:n*3,y2:n*1}),d.jsx("line",{x1:n*5,y1:n*7,x2:n*7,y2:n*5}),d.jsx("line",{x1:n*9,y1:n*11,x2:n*11,y2:n*9})]})]}),d.jsx("pattern",{id:xf(1,e.id),width:"8",height:"8",patternUnits:"userSpaceOnUse",children:d.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:e.solid,mask:"url(#hash_pattern_mask)"})})]})}function xw(){return{key:`${xs.id}:pattern`,component:IX}}const Ec=8,mI=(e,n,t)=>new Promise((r,s)=>{const o=Ec*n*e,i=document.createElement("canvas");i.width=o,i.height=o;const a=i.getContext("2d");if(!a)return;a.fillStyle=t?nf.darkMode.solid:nf.lightMode.solid,a.fillRect(0,0,o,o),a.globalCompositeOperation="destination-out",a.lineCap="round",a.lineWidth=1.25*n*e;const l=8/12,c=u=>u*n*e;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||xt.throwToBlob.get()?s():r(u)})}),yI=(e,n)=>{const t=document.createElement("canvas");t.width=e[0],t.height=e[1];const r=t.getContext("2d");return r?(n(r),t.toDataURL()):""};let vy=null;function bX(){return vy||(vy={white:yI([1,1],e=>{e.fillStyle="#f8f9fa",e.fillRect(0,0,1,1)}),black:yI([1,1],e=>{e.fillStyle="#212529",e.fillRect(0,0,1,1)})}),vy}function MA(e){return Math.ceil(Math.log2(Math.max(1,e)))}function xf(e,n){const t=MA(e);return`tldraw_hash_pattern_${n}_${t}`}function AA(e){const n=[],r=MA(e);for(let s=0;s<=r;s++)n.push(Math.pow(2,s));return n}function PX(e){const n=bX();return AA(e).flatMap(t=>[{zoom:t,url:n.white,theme:"light"},{zoom:t,url:n.black,theme:"dark"}])}function CX(){const e=F(),n=H("devicePixelRatio",()=>e.getInstanceState().devicePixelRatio,[e]),t=H("maxZoom",()=>Math.ceil(Ut(e.getCameraOptions().zoomSteps)),[e]),[r,s]=P.useState(!1),[o,i]=P.useState(()=>PX(t));return P.useEffect(()=>{const l=Promise.all(AA(t).flatMap(u=>[mI(n,u,!1).then(h=>({zoom:u,theme:"light",url:URL.createObjectURL(h)})),mI(n,u,!0).then(h=>({zoom:u,theme:"dark",url:URL.createObjectURL(h)}))]));let c=!1;return l.then(u=>{c||(i(u),s(!0))}),()=>{c=!0,s(!1),l.then(u=>{for(const{url:h}of u)URL.revokeObjectURL(h)})}},[n,t]),{defs:d.jsx(d.Fragment,{children:o.map(l=>{const c=xf(l.zoom,l.theme);return d.jsx("pattern",{id:c,width:Ec,height:Ec,patternUnits:"userSpaceOnUse",children:d.jsx("image",{href:l.url,width:Ec,height:Ec})},c)})}),isReady:r}}function IX(){const e=F(),n=P.useRef(null),{defs:t,isReady:r}=CX();return P.useEffect(()=>{if(r&&e.environment.isSafari){const s=jA(n.current);s&&e.timers.requestAnimationFrame(()=>{s.style.display="none",e.timers.requestAnimationFrame(()=>{s.style.display=""})})}},[e,r]),d.jsx("g",{ref:n,"data-testid":r?"ready-pattern-fill-defs":void 0,children:t})}function jA(e){return e.classList.contains("tl-html-layer")?e:e.parentElement?jA(e.parentElement):null}const nn=Ce.memo(function({theme:n,d:t,color:r,fill:s,scale:o}){switch(s){case"none":return null;case"solid":return d.jsx("path",{fill:n[r].semi,d:t});case"semi":return d.jsx("path",{fill:n.solid,d:t});case"fill":return d.jsx("path",{fill:n[r].fill,d:t});case"pattern":return d.jsx(EX,{theme:n,color:r,fill:s,d:t,scale:o})}});function EX({d:e,color:n,theme:t}){const r=F(),s=JM(),o=H("zoomLevel",()=>r.getZoomLevel(),[r]),i=r.getZoomLevel()<=.18;return d.jsxs(d.Fragment,{children:[d.jsx("path",{fill:t[n].pattern,d:e}),d.jsx("path",{fill:s?`url(#${xf(1,t.id)})`:i?t[n].semi:`url(#${xf(o,t.id)})`,d:e})]})}function _X(e){return e.replace(/\s/g," ")}function Lv(e,n,t){const{padding:r=0}=t;if(n.length===0)return null;const s=Q.From(n[0].box);for(const{box:c}of n)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 n)a!==null&&u.y>a&&l.push(d.jsx("tspan",{alignmentBaseline:"mathematical",x:o,y:u.y+i,children:` -`},l.length)),l.push(d.jsx("tspan",{alignmentBaseline:"mathematical",x:u.x+o,y:u.y+i,unicodeBidi:"plaintext",children:_X(c)},l.length)),a=u.y;return d.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 kX(e,n,t,r){if((e==="start-legacy"||e==="end-legacy")&&t.length!==0){const s=Q.From(t[0].box);for(const{box:o}of t)s.union(o);if(e==="start-legacy")return(r-2*n-s.width)/2;if(e==="end-legacy")return-(r-2*n-s.width)/2}}function TX(e){return e==="start-legacy"||e==="middle-legacy"||e==="end-legacy"}function wg({fontSize:e,font:n,align:t,verticalAlign:r,text:s,labelColor:o,bounds:i,padding:a=16,stroke:l=!0}){const c=F(),u=Ar(),h={fontSize:e,fontFamily:bT[n],textAlign:t,verticalTextAlign:r,width:Math.ceil(i.width),height:Math.ceil(i.height),padding:a,lineHeight:Gt.lineHeight,fontStyle:"normal",fontWeight:"normal",overflow:"wrap",offsetX:0,offsetY:0,fill:o,stroke:void 0,strokeWidth:void 0},p=c.textMeasure.measureTextSpans(s,h),f=kX(t,a,p,i.width);f&&(h.offsetX=f),h.offsetX+=i.x,h.offsetY+=i.y;const S=Lv(c,p,h);let m=null;return l&&(h.fill=u.background,h.stroke=u.background,h.strokeWidth=2,m=Lv(c,p,h)),d.jsxs(d.Fragment,{children:[m,S]})}const MX=P.forwardRef(function({isEditing:n,text:t,handleFocus:r,handleChange:s,handleKeyDown:o,handleBlur:i,handleInputPointerDown:a,handleDoubleClick:l},c){return d.jsx("textarea",{ref:c,className:"tl-text tl-text-input",name:"text",tabIndex:-1,readOnly:!n,autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",autoSave:"off",placeholder:"",spellCheck:"true",wrap:"off",dir:"auto",defaultValue:t,onFocus:r,onChange:s,onKeyDown:o,onBlur:i,onTouchEnd:Dt,onContextMenu:n?Dt:void 0,onPointerDown:a,onDoubleClick:l,onDragStart:Ie})});function AX(e,n,t){const r=F(),s=P.useRef(null),o=H("isEditing",()=>r.getEditingShapeId()===e,[r]),i=H("isEditingAnything",()=>!!r.getEditingShapeId(),[r]);P.useEffect(()=>{function u({shapeId:h}){var p;h===e&&((p=s.current)==null||p.select())}return r.on("select-all-text",u),()=>{r.off("select-all-text",u)}},[r,e,o]),P.useEffect(()=>{var u,h,p,f;o&&(document.activeElement!==s.current&&((u=s.current)==null||u.focus()),r.getInstanceState().isCoarsePointer&&((h=s.current)==null||h.select()),r.environment.isSafari&&((p=s.current)==null||p.blur(),(f=s.current)==null||f.focus()))},[r,o]);const a=P.useCallback(u=>{if(r.getEditingShapeId()===e)switch(u.key){case"Enter":{(u.ctrlKey||u.metaKey)&&r.complete();break}}},[r,e]),l=P.useCallback(u=>{if(r.getEditingShapeId()!==e)return;let h=ml.normalizeText(u.currentTarget.value);const p=h.replace(/\t/g,Ga);if(p!==h){const f=u.currentTarget.selectionStart;u.currentTarget.value=p,u.currentTarget.selectionStart=f+(p.length-h.length),u.currentTarget.selectionEnd=f+(p.length-h.length),h=p}r.updateShape({id:e,type:n,props:{text:h}})},[r,e,n]),c=P.useCallback(u=>{r.dispatch({...Nn(u),type:"pointer",name:"pointer_down",target:"shape",shape:r.getShape(e)}),Dt(u)},[r,e]);return{rInput:s,handleFocus:Su,handleBlur:Su,handleKeyDown:a,handleChange:l,handleInputPointerDown:c,handleDoubleClick:Dt,isEmpty:t.trim().length===0,isEditing:o,isEditingAnything:i}}const bg=Ce.memo(function({id:n,type:t,text:r,labelColor:s,font:o,fontSize:i,lineHeight:a,align:l,verticalAlign:c,wrap:u,isSelected:h,padding:p=0,onKeyDown:f,classNamePrefix:S,style:m,textWidth:x,textHeight:y}){const{rInput:v,isEmpty:w,isEditing:C,isEditingAnything:E,...k}=AX(n,t,r),[I,_]=P.useState(r);P.useEffect(()=>{C||_(r)},[C,r]);const T=ml.normalizeTextForDom(r),M=T.length>0,D=TX(l);if(!C&&!M)return null;const $=S||"tl-text";return d.jsx("div",{className:`${$}-label tl-text-wrapper`,"data-font":o,"data-align":l,"data-hastext":!w,"data-isediting":C,"data-iseditinganything":E,"data-textwrap":!!u,"data-isselected":h,style:{justifyContent:l==="middle"||D?"center":l,alignItems:c==="middle"?"center":c,padding:p,...m},children:d.jsxs("div",{className:`${$}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:Math.floor(i*a)+"px",minHeight:Math.floor(i*a)+"px",minWidth:Math.ceil(x||0),color:s,width:x?Math.ceil(x):void 0,height:y?Math.ceil(y):void 0},children:[d.jsx("div",{className:`${$} tl-text tl-text-content`,dir:"auto",children:T.split(` -`).map((j,O)=>d.jsx("div",{dir:"auto",children:j},O))}),(E||h)&&d.jsx(MX,{ref:v,text:r,isEditing:C,...k,handleKeyDown:f??k.handleKeyDown},I)]})})});function os(e,n,t={}){const{closed:r=!1,snap:s=1,start:o="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,u=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(o==="outset"?(e+=c/2,f+=c/2):o==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),u=Math.floor(e/c/(2*h)),u-=u%s,u<3&&l==="dashed"?e/n<4?(c=e,u=1,p=0):(c=e*(1/3),p=e*(1/3)):(c=e/u/(2*h),r?(f=c/2,p=(e-u*c)/u):p=(e-u*c)/Math.max(1,u-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}const SI=new WeakMap;function ww(e,n){const t=SI.get(n);if(t)return t;const r=ds(e,n);let s=0,o=0;const i=r.isStraight?new Hs({start:b.From(r.start.point),end:b.From(r.end.point)}):new Ua({center:b.Cast(r.handleArc.center),start:b.Cast(r.start.point),end:b.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});if(n.props.text.trim()){const l=i.bounds,c=$v(n),{w:u,h}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:null});if(s=u,o=h,l.width>l.height){s=Math.max(Math.min(u,64),Math.min(l.width-64,u));const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:s});s=p,o=f}if(s>16*c){s=16*c;const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:s});s=p,o=f}}const a=new b(s,o).addScalar(kY*2*n.props.scale);return SI.set(n,a),a}function OA(e){const n=jt[e.props.size];return(_Y+(n-jt.s)*2+(n===jt.xl?20:0))*e.props.scale}function jX(e,n,t){const r=ww(e,n),s=OA(n),o=b.Nudge(t.start.point,t.end.point,s),i=b.Nudge(t.end.point,t.start.point,s),a=iw(o,i,Q.FromCenter(t.middle,r).corners);if(!a||a.length!==2)return{start:.5,end:.5};let[l,c]=a;b.Dist2(l,o)>b.Dist2(c,o)&&([c,l]=a);const u=o.add(b.Sub(t.middle,l)),h=i.add(b.Sub(t.middle,c)),p=b.Dist(t.start.point,u)/t.length,f=b.Dist(t.start.point,h)/t.length;return{start:p,end:f}}function OX(e,n,t){const r=ww(e,n),s=OA(n),o=Math.sign(n.props.bend),i=s/t.handleArc.radius*o,a=b.Angle(t.bodyArc.center,t.start.point)-i,l=b.Angle(t.bodyArc.center,t.end.point)+i,c=Ki(t.bodyArc.center,t.bodyArc.radius,a),u=Ki(t.bodyArc.center,t.bodyArc.radius,l),h=[],p=vI(t.bodyArc.center,t.bodyArc.radius,a,l,o,Q.FromCenter(c,r).corners);h.push(new at({points:Q.FromCenter(c,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));const f=vI(t.bodyArc.center,t.bodyArc.radius,a,l,o,Q.FromCenter(u,r).corners);h.push(new at({points:Q.FromCenter(u,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));for(const I of[...p??[],...f??[],c,u])h.push(new yg({x:I.x-3,y:I.y-3,radius:3,isFilled:!1,debugColor:"magenta",ignore:!0}));const S=(p&&xI(t.start.point,p))??t.middle,m=(f&&xI(t.end.point,f))??t.middle,x=b.Angle(t.bodyArc.center,t.start.point),y=b.Angle(t.bodyArc.center,t.end.point),v=b.Angle(t.bodyArc.center,S),w=b.Angle(t.bodyArc.center,m);if(ko(x,v,o)>ko(x,w,o))return{start:.5,end:.5,dbg:h};const C=ko(x,y,o),E=ko(x,v,o)/C,k=ko(x,w,o)/C;return{start:E,end:k,dbg:h}}function Jh(e,n){let t;const r=[],s=ds(e,n),o=!!s.bindings.start,i=!!s.bindings.end,a=s.start.arrowhead!=="none",l=s.end.arrowhead!=="none";if(s.isStraight){const u=jX(e,n,s);let h=kt(n.props.labelPosition,a||o?u.start:0,l||i?u.end:1);h=h>=.48&&h<=.52?.5:h,t=b.Lrp(s.start.point,s.end.point,h)}else{const u=OX(e,n,s);u.dbg&&r.push(...u.dbg);let h=kt(n.props.labelPosition,a||o?u.start:0,l||i?u.end:1);h=h>=.48&&h<=.52?.5:h;const p=DX(b.Angle(s.bodyArc.center,s.start.point),b.Angle(s.bodyArc.center,s.end.point),Math.sign(n.props.bend),h);t=Ki(s.bodyArc.center,s.bodyArc.radius,p)}const c=ww(e,n);return{box:Q.FromCenter(t,c),debugGeom:r}}function vI(e,n,t,r,s,o){const i=kv(e,n,o),a=ko(t,r,s);return i==null?void 0:i.filter(l=>{const c=ko(t,b.Angle(e,l),s);return c>=0&&c<=a})}function xI(e,n){let t=null,r=-1/0;for(const s of n){const o=b.Dist2(e,s);o>r&&(t=s,r=o)}return t}function DX(e,n,t,r){const s=ko(e,n,t);return e+s*r*t*-1}function $v(e){return EY[e.props.size]*e.props.scale}function RX(e,n,t){const r=n==="end"?e.end.point:e.start.point,s=n==="end"?e.start.point:e.end.point,o=e.isStraight?b.Dist(s,r):Math.abs(e.bodyArc.length),i=Math.max(Math.min(o/5,t*3),t);let a;if(e.isStraight)a=b.Nudge(r,s,i);else{const l=rG(r,i,e.handleArc.center,e.handleArc.radius);a=n==="end"?e.handleArc.sweepFlag?l[0]:l[1]:e.handleArc.sweepFlag?l[1]:l[0]}return b.IsNaN(a)&&(a=e.start.point),{point:r,int:a}}function LX({point:e,int:n}){const t=b.RotWith(n,e,Me/6),r=b.RotWith(n,e,-Me/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y}`}function $X({point:e,int:n}){const t=b.RotWith(n,e,Me/6),r=b.RotWith(n,e,-Me/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y} Z`}function NX({point:e,int:n}){const t=b.Sub(n,e).div(2),r=b.Add(e,b.Rot(t,Ve)),s=b.Sub(e,b.Rot(t,Ve));return`M ${r.x} ${r.y} L ${n.x} ${n.y} L ${s.x} ${s.y} Z`}function FX({point:e,int:n}){const t=b.Lrp(e,n,.45),r=b.Dist(t,e);return`M ${t.x-r},${t.y} +`)}function JY(e){return e.replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function eX(e){return JY(QY(ZY(e)))}function tX(e,{maxImageDimension:n,maxAssetSize:t,acceptedImageMimeTypes:r,acceptedVideoMimeTypes:s},{toasts:o,msg:i}){e.registerExternalAssetHandler("file",async({file:a})=>{const l=a.name;let c=a;const u=r.includes(c.type),h=s.includes(c.type);!u&&!h&&o.addToast({title:i("assets.files.type-not-allowed"),severity:"error"}),Ye(u||h,`File type not allowed: ${c.type}`),c.size>t&&o.addToast({title:i("assets.files.size-too-big"),severity:"error"}),Ye(c.size<=t,`File size too big: ${(c.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),c.type==="video/quicktime"&&(c=new File([c],c.name,{type:"video/mp4"}));let p=u?await cs.getImageSize(c):await cs.getVideoSize(c);const f=await cs.isAnimated(c)||h,S=C9(await c.arrayBuffer());if(isFinite(n)){const m=WY(p,{w:n,h:n});p!==m&&cs.isStaticImageType(c.type)&&(p=m)}const x={id:_i.createId(S),type:u?"image":"video",typeName:"asset",props:{name:l,src:"",w:p.w,h:p.h,fileSize:c.size,mimeType:c.type,isAnimated:f}};return x.props.src=await e.uploadAsset(x,c),_i.create(x)}),e.registerExternalAssetHandler("url",async({url:a})=>{var c,u,h,p,f;let l;try{const y=await(await vs(a,{method:"GET",mode:"no-cors"})).text(),x=new DOMParser().parseFromString(y,"text/html");l={image:((c=x.head.querySelector('meta[property="og:image"]'))==null?void 0:c.getAttribute("content"))??"",favicon:((u=x.head.querySelector('link[rel="apple-touch-icon"]'))==null?void 0:u.getAttribute("href"))??((h=x.head.querySelector('link[rel="icon"]'))==null?void 0:h.getAttribute("href"))??"",title:((p=x.head.querySelector('meta[property="og:title"]'))==null?void 0:p.getAttribute("content"))??a,description:((f=x.head.querySelector('meta[property="og:description"]'))==null?void 0:f.getAttribute("content"))??""},l.image.startsWith("http")||(l.image=new URL(l.image,a).href),l.favicon.startsWith("http")||(l.favicon=new URL(l.favicon,a).href)}catch(S){console.error(S),o.addToast({title:i("assets.url.failed"),severity:"error"}),l={image:"",favicon:"",title:"",description:""}}return{id:_i.createId(fv(a)),typeName:"asset",type:"bookmark",props:{src:a,description:l.description,image:l.image,favicon:l.favicon,title:l.title},meta:{}}}),e.registerExternalContentHandler("svg-text",async({point:a,text:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=new DOMParser().parseFromString(l,"image/svg+xml").querySelector("svg");if(!u)throw new Error("No element present");let h=parseFloat(u.getAttribute("width")||"0"),p=parseFloat(u.getAttribute("height")||"0");if(!(h&&p)){document.body.appendChild(u);const S=u.getBoundingClientRect();document.body.removeChild(u),h=S.width,p=S.height}const f=await e.getAssetForExternalContent({type:"file",file:new File([l],"asset.svg",{type:"image/svg+xml"})});if(!f)throw Error("Could not create an asset");hI(e,[f],c)}),e.registerExternalContentHandler("embed",({point:a,url:l,embed:c})=>{const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),{width:h,height:p}=c,f=je(),S={id:f,type:"embed",x:u.x-(h||450)/2,y:u.y-(p||450)/2,props:{w:h,h:p,url:l}};e.createShapes([S]).select(f)}),e.registerExternalContentHandler("files",async({point:a,files:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=new b(c.x,c.y),h=[];await Promise.all(l.map(async(p,f)=>{if(p.size>t)return o.addToast({title:i("assets.files.size-too-big"),severity:"error"}),console.warn(`File size too big: ${(p.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),null;if(!p.type)throw new Error("No mime type");if(!r.concat(s).includes(p.type))return o.addToast({title:i("assets.files.type-not-allowed"),severity:"error"}),console.warn(`${p.name} not loaded - Extension not allowed.`),null;try{const S=await e.getAssetForExternalContent({type:"file",file:p});if(!S)throw Error("Could not create an asset");h[f]=S}catch(S){return o.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error(S),null}})),hI(e,me(h),u)}),e.registerExternalContentHandler("text",async({point:a,text:l})=>{const c=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),u=e.getShapeUtil("text").getDefaultProps(),h=eX(l),p=e.getOnlySelectedShape();if(p&&"text"in p.props){e.updateShapes([{id:p.id,type:p.type,props:{text:h}}]);return}let f,S,y,x="middle";const m=h.split(` +`).length>1,v=wA(h);m&&(x=m?v?"end":"start":"middle");const w=e.textMeasure.measureText(h,{...Gt,fontFamily:Ss[u.font],fontSize:gl[u.size],maxWidth:null}),C=Math.min(m?e.getViewportPageBounds().width*.9:920,Math.max(200,e.getViewportPageBounds().width*.9));if(w.w>C){const E=e.textMeasure.measureText(h,{...Gt,fontFamily:Ss[u.font],fontSize:gl[u.size],maxWidth:C});f=E.w,S=E.h,y=!1,x=v?"end":"start"}else f=w.w,S=w.h,y=!0;c.y-S/2{const c=Do(l);if(c)return e.putExternalContent({type:"embed",url:c.url,point:a,embed:c.definition});const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),h=_i.createId(fv(l)),p=nX(e,l,u);let f=e.getAsset(h),S=!1;if(!f){S=!0;try{const y=await e.getAssetForExternalContent({type:"url",url:l});if(!y)throw Error("Could not create an asset");f=y}catch{o.addToast({title:i("assets.url.failed"),severity:"error"});return}}e.run(()=>{S&&e.createAssets([f]),e.updateShapes([{id:p.id,type:p.type,props:{assetId:f.id}}])})})}async function hI(e,n,t){if(!n.length)return[];const r=b.From(t),s=[];for(let o=0;o{const o=n.filter(i=>!e.getAsset(i.id));o.length&&e.createAssets(o),e.createShapes(s).select(...s.map(i=>i.id)),bA(e,t)}),s.map(o=>o.id)}function bA(e,n){const t=e.getViewportPageBounds();let r=e.getSelectionPageBounds();if(r){const s=r.center.sub(n);e.updateShapes(e.getSelectedShapes().map(o=>{const i=e.getShapeParentTransform(o).decompose().rotation,a=b.Rot(s,-i);return{id:o.id,type:o.type,x:o.x-a.x,y:o.y-a.y}}))}r=e.getSelectionPageBounds(),r&&!t.contains(r)&&e.zoomToSelection()}function nX(e,n,t){const r={id:je(),type:"bookmark",x:t.x-150,y:t.y-160,opacity:1,props:{assetId:null,url:n}};return e.run(()=>{e.createShapes([r]).select(r.id),bA(e,t)}),e.getShape(r.id)}var Hy;let rX=(Hy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")});g(this,"onKeyUp",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}})}},g(Hy,"id","idle"),Hy);var Ky;let sX=(Ky=class extends se{constructor(){super(...arguments);g(this,"shape");g(this,"markId","");g(this,"onEnter",()=>{this.didTimeout=!1;const t=this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{filter:r=>!r.isLocked&&this.editor.canBindShapes({fromShape:"arrow",toShape:r,binding:"arrow"}),margin:0,hitInside:!0,renderingOnly:!0});t?this.editor.setHintingShapes([t.id]):this.createArrowShape(),this.startPreciseTimeout()});g(this,"onExit",()=>{this.shape=void 0,this.editor.setHintingShapes([]),this.clearPreciseTimeout()});g(this,"onPointerMove",()=>{if(this.editor.inputs.isDragging){if(this.shape||this.createArrowShape(),!this.shape)throw Error("expected shape");this.updateArrowShapeEndHandle(),this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,handle:{id:"end",type:"vertex",index:"a3",x:0,y:0},isCreating:!0,onInteractionEnd:"arrow"})}});g(this,"onPointerUp",()=>{this.cancel()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()});g(this,"preciseTimeout",-1);g(this,"didTimeout",!1)}cancel(){this.shape&&this.editor.bailToMark(this.markId),this.editor.setHintingShapes([]),this.parent.transition("idle")}createArrowShape(){var u;const{originPagePoint:t}=this.editor.inputs,r=je();this.markId=`creating:${r}`,this.editor.mark(this.markId),this.editor.createShape({id:r,type:"arrow",x:t.x,y:t.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const s=this.editor.getShape(r);if(!s)throw Error("expected shape");const o=this.editor.getShapeHandles(s);if(!o)throw Error("expected handles for arrow");const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=o.find(h=>h.id==="start"),c=(u=i.onHandleDrag)==null?void 0:u.call(i,s,{handle:{...l,x:0,y:0},isPrecise:!0,initial:a});c&&this.editor.updateShapes([c]),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.didTimeout,initial:a});c&&this.editor.updateShapes([c])}{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=this.editor.getPointInShapeSpace(t,this.editor.inputs.currentPagePoint),c=r.find(h=>h.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:!1,initial:a});u&&this.editor.updateShapes([u])}this.shape=this.editor.getShape(t.id)}startPreciseTimeout(){this.preciseTimeout=this.editor.timers.setTimeout(()=>{this.getIsActive()&&(this.didTimeout=!0)},320)}clearPreciseTimeout(){clearTimeout(this.preciseTimeout)}},g(Ky,"id","pointing"),Ky);class Xh extends se{constructor(){super(...arguments);g(this,"shapeType","arrow")}}g(Xh,"id","arrow"),g(Xh,"initial","idle"),g(Xh,"children",()=>[rX,sX]);class Sw extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"initialShape");g(this,"shapeType",this.parent.id==="highlight"?"highlight":"draw");g(this,"util",this.editor.getShapeUtil(this.shapeType));g(this,"isPen",!1);g(this,"isPenOrStylus",!1);g(this,"segmentMode","free");g(this,"didJustShiftClickToExtendPreviousShapeLine",!1);g(this,"pagePointWhereCurrentSegmentChanged",{});g(this,"pagePointWhereNextSegmentChanged",null);g(this,"lastRecordedPoint",{});g(this,"mergeNextPoint",!1);g(this,"currentLineLength",0);g(this,"canDraw",!1);g(this,"markId",null);g(this,"onEnter",t=>{this.markId=null,this.info=t,this.canDraw=!this.editor.getIsMenuOpen(),this.lastRecordedPoint=this.editor.inputs.currentPagePoint.clone(),this.canDraw&&this.startShape()});g(this,"onPointerMove",()=>{const{inputs:t}=this.editor;if(this.isPen&&!t.isPen){if(this.markId){this.editor.bailToMark(this.markId),this.startShape();return}}else!this.canDraw&&t.isDragging&&(this.startShape(),this.canDraw=!0);this.canDraw&&(this.isPenOrStylus?b.Dist(t.currentPagePoint,this.lastRecordedPoint)>=1/this.editor.getZoomLevel()?(this.lastRecordedPoint=t.currentPagePoint.clone(),this.mergeNextPoint=!1):this.mergeNextPoint=!0:this.mergeNextPoint=!1,this.updateDrawingShape())});g(this,"onKeyDown",t=>{if(t.key==="Shift")switch(this.segmentMode){case"free":{this.segmentMode="starting_straight",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_free":this.segmentMode="starting_straight"}this.updateDrawingShape()});g(this,"onKeyUp",t=>{if(t.key==="Shift")switch(this.editor.snaps.clearIndicators(),this.segmentMode){case"straight":{this.segmentMode="starting_free",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_straight":{this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";break}}this.updateDrawingShape()});g(this,"onExit",()=>{this.editor.snaps.clearIndicators(),this.pagePointWhereCurrentSegmentChanged=this.editor.inputs.currentPagePoint.clone()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.editor.inputs.isDragging||(this.markId&&this.editor.bailToMark(this.markId),this.cancel())})}canClose(){return this.shapeType!=="highlight"}getIsClosed(t,r,s){if(!this.canClose())return!1;const o=jt[r],i=t[0].points[0],a=t[t.length-1],l=a.points[a.points.length-1];return i!==l&&this.currentLineLength>o*4*s&&b.DistMin(i,l,o*2*s)}startShape(){const{inputs:{originPagePoint:t,isPen:r}}=this.editor;this.markId="draw start "+ct(),this.editor.mark(this.markId);const{z:s=.5}=this.info.point;this.isPen=r,this.isPenOrStylus=r||s>0&&s<.5||s>.5&&s<1;const o=this.isPenOrStylus?s*1.25:.5;if(this.segmentMode=this.editor.inputs.shiftKey?"straight":"free",this.didJustShiftClickToExtendPreviousShapeLine=!1,this.lastRecordedPoint=t.clone(),this.initialShape){const a=this.editor.getShape(this.initialShape.id);if(a&&this.segmentMode==="straight"){this.didJustShiftClickToExtendPreviousShapeLine=!0;const l=Ut(a.props.segments);if(!l)throw Error("Expected a previous segment!");const c=Ut(l.points);if(!c)throw Error("Expected a previous point!");const{x:u,y:h}=this.editor.getPointInShapeSpace(a,t).toFixed(),p={type:this.segmentMode,points:[{x:c.x,y:c.y,z:+o.toFixed(2)},{x:u,y:h,z:+o.toFixed(2)}]},f=oe.applyToPoint(this.editor.getShapePageTransform(a.id),c);this.pagePointWhereCurrentSegmentChanged=f,this.pagePointWhereNextSegmentChanged=null;const S=[...a.props.segments,p];this.currentLineLengththis.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="straight";const x=Ut(l);if(!x)throw Error("Expected a previous segment!");const m=Ut(x.points);if(!m)throw Error("Expected a previous last point!");let v;const w=this.editor.getPointInShapeSpace(a,this.pagePointWhereCurrentSegmentChanged).toFixed().toJson();if(x.type==="straight"){this.currentLineLength+=b.Dist(m,w),v={type:"straight",points:[{...m},w]};const E=this.editor.getShapePageTransform(a);this.pagePointWhereCurrentSegmentChanged=oe.applyToPoint(E,m)}else v={type:"straight",points:[w,f]};const C={id:s,type:this.shapeType,props:{segments:[...l,v]}};this.canClose()&&(C.props.isClosed=this.getIsClosed(l,o,i)),this.editor.updateShapes([C])}break}case"starting_free":{const{pagePointWhereNextSegmentChanged:S}=this;if(S===null)throw Error("We should have a point where the segment changed");if(b.Dist2(S,r.currentPagePoint)>this.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";const x=l.slice(),m=x[x.length-1],v=Ut(m.points);if(!v)throw Error("No previous point!");const w={type:"free",points:[...b.PointsBetween(v,f,6).map(k=>({x:zs(k.x),y:zs(k.y),z:zs(k.z)}))]},C=[...x,w];this.currentLineLength2){let M,D=8/this.editor.getZoomLevel();for(let $=0,j=l.length-2;$this.editor.options.maxPointsPerDrawShape){this.editor.updateShapes([{id:s,type:this.shapeType,props:{isComplete:!0}}]);const v=je(),w=this.editor.getShape(s).props;this.editor.createShapes([{id:v,type:this.shapeType,x:zs(r.currentPagePoint.x),y:zs(r.currentPagePoint.y),props:{isPen:this.isPenOrStylus,scale:w.scale,segments:[{type:"free",points:[{x:0,y:0,z:this.isPenOrStylus?+(h*1.25).toFixed():.5}]}]}}]),this.initialShape=Be(this.editor.getShape(v)),this.mergeNextPoint=!1,this.lastRecordedPoint=r.currentPagePoint.clone(),this.currentLineLength=0}break}}}getLineLength(t){let r=0;for(const s of t)for(let o=0;o{this.parent.transition("drawing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Wy,"id","idle"),Wy);class Pc extends se{constructor(){super(...arguments);g(this,"shapeType","draw");g(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}g(Pc,"id","draw"),g(Pc,"initial","idle"),g(Pc,"isLockable",!1),g(Pc,"children",()=>[PA,Sw]);class Rv extends Gh{constructor(){super(...arguments);g(this,"shapeType","frame");g(this,"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)&&oX(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")})}}g(Rv,"id","frame"),g(Rv,"initial","idle");function oX(e,n,t){return n.includes(e.id)?!1:e.parentId===t.parentId}var Gy;let iX=(Gy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onKeyUp",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Gy,"id","idle"),Gy);var Vy;let aX=(Vy=class extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"onPointerUp",()=>{this.complete()});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,s=je();this.markId=`creating:${s}`,this.editor.mark(this.markId),this.editor.createShapes([{id:s,type:"geo",x:r.x,y:r.y,props:{w:1,h:1,geo:this.editor.getStyleForNextShape(Br),scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]).select(s).setCurrentTool("select.resizing",{...t,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:"geo"})}});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:t}=this.editor.inputs,r=je();this.markId=`creating:${r}`,this.editor.mark(this.markId);const s=this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1,o=this.editor.getStyleForNextShape(Br),i=o==="star"?{w:200,h:190}:o==="cloud"?{w:300,h:180}:{w:200,h:200};this.editor.createShapes([{id:r,type:"geo",x:t.x,y:t.y,props:{geo:this.editor.getStyleForNextShape(Br),scale:s,...i}}]);const a=this.editor.getShape(r);if(!a)return;const{w:l,h:c}=a.props,u=new b(l/2,c/2).mul(s),h=this.editor.getShapeParentTransform(a);h&&u.rot(-h.rotation()),this.editor.select(r),this.editor.updateShape({id:a.id,type:"geo",x:a.x-u.x,y:a.y-u.y,props:{geo:this.editor.getStyleForNextShape(Br),w:l*s,h:c*s}}),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select",{})}cancel(){this.parent.transition("idle")}},g(Vy,"id","pointing"),Vy);class qh extends se{constructor(){super(...arguments);g(this,"shapeType","geo")}}g(qh,"id","geo"),g(qh,"initial","idle"),g(qh,"children",()=>[iX,aX]);class Cc extends se{constructor(){super(...arguments);g(this,"shapeType","highlight");g(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}g(Cc,"id","highlight"),g(Cc,"initial","idle"),g(Cc,"children",()=>[PA,Sw]),g(Cc,"isLockable",!1);var Yy;let lX=(Yy=class extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"onEnter",t=>{this.shapeId=t.shapeId,this.editor.setCursor({type:"cross",rotation:0})});g(this,"onPointerDown",()=>{this.parent.transition("pointing",{shapeId:this.shapeId})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Yy,"id","idle"),Yy);const pI=2;var Xy;let cX=(Xy=class extends se{constructor(){super(...arguments);g(this,"shape",{});g(this,"markId");g(this,"onEnter",t=>{const{inputs:r}=this.editor,{currentPagePoint:s}=r;this.markId=void 0;const o=t.shapeId&&this.editor.getShape(t.shapeId);if(o&&r.shiftKey){this.markId=`creating:${o.id}`,this.editor.mark(this.markId),this.shape=o;const i=this.editor.getShapeHandles(this.shape);if(!i)return;const a=i.filter(f=>f.type==="vertex").sort(an),l=a[a.length-1],c=a[a.length-2],u=oe.applyToPoint(this.editor.getShapeParentTransform(this.shape),new b(this.shape.x,this.shape.y)),h=b.Sub(s,u).addXY(.1,.1),p=Be(this.shape.props.points);if(b.DistMin(l,c,pI)||b.DistMin(h,l,pI))p[l.id]={id:l.id,index:l.index,x:h.x,y:h.y};else{const f=Fr(l.index);p[f]={id:f,index:f,x:h.x,y:h.y}}this.editor.updateShapes([{id:this.shape.id,type:this.shape.type,props:{points:p}}])}else{const i=je();this.markId=`creating:${i}`,this.editor.mark(this.markId),this.editor.createShapes([{id:i,type:"line",x:s.x,y:s.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]),this.editor.select(i),this.shape=this.editor.getShape(i)}});g(this,"onPointerMove",()=>{if(this.shape&&this.editor.inputs.isDragging){const t=this.editor.getShapeHandles(this.shape);if(!t)throw this.markId&&this.editor.bailToMark(this.markId),Error("No handles found");const r=Ut(t);this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,isCreating:!0,handle:{...r,x:r.x-.1,y:r.y-.1},onInteractionEnd:"line"})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"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()}},g(Xy,"id","pointing"),Xy);class Zh extends se{constructor(){super(...arguments);g(this,"shapeType","line")}}g(Zh,"id","line"),g(Zh,"initial","idle"),g(Zh,"children",()=>[lX,cX]);var qy;let uX=(qy=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(qy,"id","idle"),qy);function Ke(e,n){var s;const t=new Set;for(const o of n){const i=e.getShape(o);if(!i)continue;e.getShapeUtil(i).onDragShapesOut&&t.add(i);const a=e.getShape(i.parentId);a&&e.getShapeUtil(a).onDragShapesOut&&t.add(a)}const r=new Map;for(const o of t){const i=CA(e,o);i.length&&r.set(o,i)}for(const[o,i]of r){const a=e.getShapeUtil(o),l=me(i.map(c=>e.getShape(c)));(s=a.onDragShapesOut)==null||s.call(a,o,l)}}function CA(e,n){const t=e.getSortedChildIdsForParent(n.id);if(t.length===0)return[];const r=e.getShapePageBounds(n);if(!r)return[];let s,o,i;const a=[];for(const l of t){const c=e.getShapePageBounds(l);if(!c)continue;if(!r.includes(c)){a.push(l);continue}s??(s=e.getShapeGeometry(n)),o??(o=e.getShapePageTransform(n)),i??(i=o.applyToPoints(s.vertices));const u=e.getShapePageTransform(l).clone().invert().applyToPoints(i),{vertices:h,isClosed:p}=e.getShapeGeometry(l);if(!h.some(f=>sr(f,u))){if(p){if(YM(u,h))continue}else if(oG(u,h))continue;a.push(l)}}return a}function vf(e,n,t=!1){e.select(n),e.setEditingShape(n),e.setCurrentTool("select.editing_shape",{target:"shape",shape:n}),t&&e.emit("select-all-text",{shapeId:n.id}),IA(e)}const dX=16;function IA(e){const n=e.getSelectionPageBounds(),t=e.getViewportPageBounds();if(n&&!t.contains(n)){const r=n.clone().expandBy(dX/e.getZoomLevel()).expand(t),s=t.clone().translate({x:(r.center.x-t.center.x)*2,y:(r.center.y-t.center.y)*2});e.zoomToBounds(s,{animation:{duration:e.options.animationMediumMs},inset:0})}}const hX=0,ze=200,vg=new b(ze/2,ze/2),EA=10,pX=e=>[[["a1"],new b(ze*.5,ze*-.5-e.options.adjacentShapeMargin)],[["a2"],new b(ze*1.5+e.options.adjacentShapeMargin,ze*.5)],[["a3"],new b(ze*.5,ze*1.5+e.options.adjacentShapeMargin)],[["a4"],new b(ze*-.5-e.options.adjacentShapeMargin,ze*.5)]];function fX(e,n){if(n===1)return pX(e);const t=ze*n,r=e.options.adjacentShapeMargin*n;return[[["a1"],new b(t*.5,t*-.5-r)],[["a2"],new b(t*1.5+r,t*.5)],[["a3"],new b(t*.5,t*1.5+r)],[["a4"],new b(t*-.5-r,t*.5)]]}function _A(e,n,t,r,s,o){return Object.fromEntries(fX(e,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(n)]}))}function kA(e,n,t,r){const s=new Set(e.getSelectedShapeIds()),o=(ze+e.options.adjacentShapeMargin+r)**2,i=new Map,a=[];for(const u of e.getCurrentPageShapes()){if(!e.isShapeOfType(u,"note")||t!==u.props.scale||s.has(u.id))continue;const h=e.getShapePageTransform(u.id);n===h.rotation()&&(i.set(u,e.getShapePageBounds(u).center),a.push(...Object.values(_A(e,h.point(),n,u.props.growY,r,t))))}const l=a.length;let c;for(const[u,h]of i)for(let p=0;po||e.isPointInShape(u,c)&&(a[p]=void 0));return me(a)}function TA(e,n,t,r,s=!1){let o;const i=e.getCurrentPageShapesSorted(),a=(ze+e.options.adjacentShapeMargin**2)**n.props.scale;for(let l=i.length-1;l>=0;l--){const c=i[l];if(c.type==="note"&&c.id!==n.id){const u=e.getShapePageBounds(c);if(u&&b.Dist2(u.center,t){const{editor:t}=this;if(this.wasFocusedOnEnter=!t.getIsMenuOpen(),this.wasFocusedOnEnter){const r=je();this.markId=`creating:${r}`,t.mark(this.markId);const s=this.editor.inputs.originPagePoint.clone(),o=fI(this.editor,s,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);o&&s.sub(o),this.shape=gI(this.editor,r,s)}});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){if(!this.wasFocusedOnEnter){const r=je(),s=this.editor.inputs.originPagePoint.clone(),o=fI(this.editor,s,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);o&&s.sub(o),this.shape=gI(this.editor,r,s)}this.editor.setCurrentTool("select.translating",{...t,target:"shape",shape:this.shape,onInteractionEnd:"note",isCreating:!0,onCreate:()=>{this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape")}})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()})}complete(){this.wasFocusedOnEnter&&(this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):(this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape",{...this.info,target:"shape",shape:this.shape})))}cancel(){this.editor.bailToMark(this.markId),this.parent.transition("idle",this.info)}},g(Zy,"id","pointing"),Zy);function fI(e,n,t){let r=EA/e.getZoomLevel(),s;for(const o of kA(e,0,t,0)){const i=b.Sub(n,o),a=i.len();a[uX,gX]);function mX(e){const n=e.getShapeAtPoint(e.inputs.currentPagePoint,{hitInside:!1,hitLabels:!1,margin:e.options.hitTestMargin/e.getZoomLevel(),renderingOnly:!0});if(!n)return e.setHoveredShape(null);let t;const r=e.getOutermostSelectableShape(n);return r===n||r.id===e.getFocusedGroupId()||e.getSelectedShapeIds().includes(r.id)?t=n:t=r,e.setHoveredShape(t.id)}const Ks=B2(mX,32);var Qy;let yX=(Qy=class extends se{constructor(){super(...arguments);g(this,"onPointerMove",t=>{switch(t.target){case"shape":case"canvas":Ks(this.editor)}});g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});g(this,"onExit",()=>{Ks.cancel()});g(this,"onKeyDown",t=>{var r;if(t.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const s=this.editor.getOnlySelectedShape();s&&this.editor.getShapeUtil(s).canEdit(s)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(s.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...t,target:"shape",shape:s}))}});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(Qy,"id","idle"),Qy);var Jy;let SX=(Jy=class extends se{constructor(){super(...arguments);g(this,"shape");g(this,"markId","");g(this,"onExit",()=>{this.editor.setHintingShapes([])});g(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{inputs:{originPagePoint:r}}=this.editor,s=je();this.markId=`creating:${s}`,this.editor.mark(this.markId);const o=this.createTextShape(s,r,!1);if(!o){this.cancel();return}this.shape=this.editor.getShape(o),this.editor.select(s),this.editor.setCurrentTool("select.resizing",{...t,target:"selection",handle:"right",isCreating:!0,creationCursorOffset:{x:18,y:1},onInteractionEnd:"text",onCreate:()=>{this.editor.setEditingShape(o.id),this.editor.setCurrentTool("select.editing_shape")}})}});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.cancel()});g(this,"onCancel",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}complete(){var o;this.editor.mark("creating text shape");const t=je(),{currentPagePoint:r}=this.editor.inputs;this.createTextShape(t,r,!0)&&(this.editor.select(t),this.editor.setEditingShape(t),this.editor.setCurrentTool("select"),(o=this.editor.root.getCurrent())==null||o.transition("editing_shape"))}cancel(){this.parent.transition("idle"),this.editor.bailToMark(this.markId)}createTextShape(t,r,s){this.editor.createShape({id:t,type:"text",x:r.x,y:r.y,props:{text:"",autoSize:s,w:20,scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const o=this.editor.getShape(t);if(!o){this.cancel();return}const i=this.editor.getShapePageBounds(o),a=new b;if(s)switch(o.props.textAlign){case"start":{a.x=0;break}case"middle":{a.x=-i.width/2;break}case"end":{a.x=-i.width;break}}else a.x=0;if(a.y=-i.height/2,An(o.parentId)){const l=this.editor.getShapeParentTransform(o);a.rot(-l.rotation())}return this.editor.updateShape({...o,x:o.x+a.x,y:o.y+a.y}),o}},g(Jy,"id","pointing"),Jy);class Ic extends se{constructor(){super(...arguments);g(this,"shapeType","text")}}g(Ic,"id","text"),g(Ic,"initial","idle"),g(Ic,"children",()=>[yX,SX]),g(Ic,"isLockable",!1);const vX=[Ic,Pc,qh,Qh,Zh,Rv,Xh,Cc];function Ar(){return lo({isDarkMode:Ju()})}function xg(e){return{key:`${xs.id}:${e}`,getElement:async()=>{const n=xX(e);if(!n)return null;const t=n.$$_url,r=n.$$_fontface;if(!t||!r)return null;const s=await(await vs(t)).blob(),o=await ji.blobToDataUrl(s),i=r.replace(t,o);return d.jsx("style",{children:i})}}}function xX(e){const n=bT[e];for(const t of document.fonts)if(n.includes(t.family))return t;return null}function vw(e){return{key:`${xs.id}:${e}`,getElement:async()=>e!=="pattern"?null:d.jsx(wX,{})}}function wX(){const e=Ar(),n=8/12;return d.jsxs(d.Fragment,{children:[d.jsxs("mask",{id:"hash_pattern_mask",children:[d.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:"white"}),d.jsxs("g",{strokeLinecap:"round",stroke:"black",children:[d.jsx("line",{x1:n*1,y1:n*3,x2:n*3,y2:n*1}),d.jsx("line",{x1:n*5,y1:n*7,x2:n*7,y2:n*5}),d.jsx("line",{x1:n*9,y1:n*11,x2:n*11,y2:n*9})]})]}),d.jsx("pattern",{id:xf(1,e.id),width:"8",height:"8",patternUnits:"userSpaceOnUse",children:d.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:e.solid,mask:"url(#hash_pattern_mask)"})})]})}function xw(){return{key:`${xs.id}:pattern`,component:IX}}const Ec=8,mI=(e,n,t)=>new Promise((r,s)=>{const o=Ec*n*e,i=document.createElement("canvas");i.width=o,i.height=o;const a=i.getContext("2d");if(!a)return;a.fillStyle=t?nf.darkMode.solid:nf.lightMode.solid,a.fillRect(0,0,o,o),a.globalCompositeOperation="destination-out",a.lineCap="round",a.lineWidth=1.25*n*e;const l=8/12,c=u=>u*n*e;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||xt.throwToBlob.get()?s():r(u)})}),yI=(e,n)=>{const t=document.createElement("canvas");t.width=e[0],t.height=e[1];const r=t.getContext("2d");return r?(n(r),t.toDataURL()):""};let vy=null;function bX(){return vy||(vy={white:yI([1,1],e=>{e.fillStyle="#f8f9fa",e.fillRect(0,0,1,1)}),black:yI([1,1],e=>{e.fillStyle="#212529",e.fillRect(0,0,1,1)})}),vy}function MA(e){return Math.ceil(Math.log2(Math.max(1,e)))}function xf(e,n){const t=MA(e);return`tldraw_hash_pattern_${n}_${t}`}function AA(e){const n=[],r=MA(e);for(let s=0;s<=r;s++)n.push(Math.pow(2,s));return n}function PX(e){const n=bX();return AA(e).flatMap(t=>[{zoom:t,url:n.white,theme:"light"},{zoom:t,url:n.black,theme:"dark"}])}function CX(){const e=F(),n=H("devicePixelRatio",()=>e.getInstanceState().devicePixelRatio,[e]),t=H("maxZoom",()=>Math.ceil(Ut(e.getCameraOptions().zoomSteps)),[e]),[r,s]=P.useState(!1),[o,i]=P.useState(()=>PX(t));return P.useEffect(()=>{const l=Promise.all(AA(t).flatMap(u=>[mI(n,u,!1).then(h=>({zoom:u,theme:"light",url:URL.createObjectURL(h)})),mI(n,u,!0).then(h=>({zoom:u,theme:"dark",url:URL.createObjectURL(h)}))]));let c=!1;return l.then(u=>{c||(i(u),s(!0))}),()=>{c=!0,s(!1),l.then(u=>{for(const{url:h}of u)URL.revokeObjectURL(h)})}},[n,t]),{defs:d.jsx(d.Fragment,{children:o.map(l=>{const c=xf(l.zoom,l.theme);return d.jsx("pattern",{id:c,width:Ec,height:Ec,patternUnits:"userSpaceOnUse",children:d.jsx("image",{href:l.url,width:Ec,height:Ec})},c)})}),isReady:r}}function IX(){const e=F(),n=P.useRef(null),{defs:t,isReady:r}=CX();return P.useEffect(()=>{if(r&&e.environment.isSafari){const s=jA(n.current);s&&e.timers.requestAnimationFrame(()=>{s.style.display="none",e.timers.requestAnimationFrame(()=>{s.style.display=""})})}},[e,r]),d.jsx("g",{ref:n,"data-testid":r?"ready-pattern-fill-defs":void 0,children:t})}function jA(e){return e.classList.contains("tl-html-layer")?e:e.parentElement?jA(e.parentElement):null}const nn=Ce.memo(function({theme:n,d:t,color:r,fill:s,scale:o}){switch(s){case"none":return null;case"solid":return d.jsx("path",{fill:n[r].semi,d:t});case"semi":return d.jsx("path",{fill:n.solid,d:t});case"fill":return d.jsx("path",{fill:n[r].fill,d:t});case"pattern":return d.jsx(EX,{theme:n,color:r,fill:s,d:t,scale:o})}});function EX({d:e,color:n,theme:t}){const r=F(),s=JM(),o=H("zoomLevel",()=>r.getZoomLevel(),[r]),i=r.getZoomLevel()<=.18;return d.jsxs(d.Fragment,{children:[d.jsx("path",{fill:t[n].pattern,d:e}),d.jsx("path",{fill:s?`url(#${xf(1,t.id)})`:i?t[n].semi:`url(#${xf(o,t.id)})`,d:e})]})}function _X(e){return e.replace(/\s/g," ")}function Lv(e,n,t){const{padding:r=0}=t;if(n.length===0)return null;const s=Q.From(n[0].box);for(const{box:c}of n)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 n)a!==null&&u.y>a&&l.push(d.jsx("tspan",{alignmentBaseline:"mathematical",x:o,y:u.y+i,children:` +`},l.length)),l.push(d.jsx("tspan",{alignmentBaseline:"mathematical",x:u.x+o,y:u.y+i,unicodeBidi:"plaintext",children:_X(c)},l.length)),a=u.y;return d.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 kX(e,n,t,r){if((e==="start-legacy"||e==="end-legacy")&&t.length!==0){const s=Q.From(t[0].box);for(const{box:o}of t)s.union(o);if(e==="start-legacy")return(r-2*n-s.width)/2;if(e==="end-legacy")return-(r-2*n-s.width)/2}}function TX(e){return e==="start-legacy"||e==="middle-legacy"||e==="end-legacy"}function wg({fontSize:e,font:n,align:t,verticalAlign:r,text:s,labelColor:o,bounds:i,padding:a=16,stroke:l=!0}){const c=F(),u=Ar(),h={fontSize:e,fontFamily:bT[n],textAlign:t,verticalTextAlign:r,width:Math.ceil(i.width),height:Math.ceil(i.height),padding:a,lineHeight:Gt.lineHeight,fontStyle:"normal",fontWeight:"normal",overflow:"wrap",offsetX:0,offsetY:0,fill:o,stroke:void 0,strokeWidth:void 0},p=c.textMeasure.measureTextSpans(s,h),f=kX(t,a,p,i.width);f&&(h.offsetX=f),h.offsetX+=i.x,h.offsetY+=i.y;const S=Lv(c,p,h);let y=null;return l&&(h.fill=u.background,h.stroke=u.background,h.strokeWidth=2,y=Lv(c,p,h)),d.jsxs(d.Fragment,{children:[y,S]})}const MX=P.forwardRef(function({isEditing:n,text:t,handleFocus:r,handleChange:s,handleKeyDown:o,handleBlur:i,handleInputPointerDown:a,handleDoubleClick:l},c){return d.jsx("textarea",{ref:c,className:"tl-text tl-text-input",name:"text",tabIndex:-1,readOnly:!n,autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",autoSave:"off",placeholder:"",spellCheck:"true",wrap:"off",dir:"auto",defaultValue:t,onFocus:r,onChange:s,onKeyDown:o,onBlur:i,onTouchEnd:Dt,onContextMenu:n?Dt:void 0,onPointerDown:a,onDoubleClick:l,onDragStart:Ie})});function AX(e,n,t){const r=F(),s=P.useRef(null),o=H("isEditing",()=>r.getEditingShapeId()===e,[r]),i=H("isEditingAnything",()=>!!r.getEditingShapeId(),[r]);P.useEffect(()=>{function u({shapeId:h}){var p;h===e&&((p=s.current)==null||p.select())}return r.on("select-all-text",u),()=>{r.off("select-all-text",u)}},[r,e,o]),P.useEffect(()=>{var u,h,p,f;o&&(document.activeElement!==s.current&&((u=s.current)==null||u.focus()),r.getInstanceState().isCoarsePointer&&((h=s.current)==null||h.select()),r.environment.isSafari&&((p=s.current)==null||p.blur(),(f=s.current)==null||f.focus()))},[r,o]);const a=P.useCallback(u=>{if(r.getEditingShapeId()===e)switch(u.key){case"Enter":{(u.ctrlKey||u.metaKey)&&r.complete();break}}},[r,e]),l=P.useCallback(u=>{if(r.getEditingShapeId()!==e)return;let h=ml.normalizeText(u.currentTarget.value);const p=h.replace(/\t/g,Ga);if(p!==h){const f=u.currentTarget.selectionStart;u.currentTarget.value=p,u.currentTarget.selectionStart=f+(p.length-h.length),u.currentTarget.selectionEnd=f+(p.length-h.length),h=p}r.updateShape({id:e,type:n,props:{text:h}})},[r,e,n]),c=P.useCallback(u=>{r.dispatch({...Nn(u),type:"pointer",name:"pointer_down",target:"shape",shape:r.getShape(e)}),Dt(u)},[r,e]);return{rInput:s,handleFocus:Su,handleBlur:Su,handleKeyDown:a,handleChange:l,handleInputPointerDown:c,handleDoubleClick:Dt,isEmpty:t.trim().length===0,isEditing:o,isEditingAnything:i}}const bg=Ce.memo(function({id:n,type:t,text:r,labelColor:s,font:o,fontSize:i,lineHeight:a,align:l,verticalAlign:c,wrap:u,isSelected:h,padding:p=0,onKeyDown:f,classNamePrefix:S,style:y,textWidth:x,textHeight:m}){const{rInput:v,isEmpty:w,isEditing:C,isEditingAnything:E,...k}=AX(n,t,r),[I,_]=P.useState(r);P.useEffect(()=>{C||_(r)},[C,r]);const T=ml.normalizeTextForDom(r),M=T.length>0,D=TX(l);if(!C&&!M)return null;const $=S||"tl-text";return d.jsx("div",{className:`${$}-label tl-text-wrapper`,"data-font":o,"data-align":l,"data-hastext":!w,"data-isediting":C,"data-iseditinganything":E,"data-textwrap":!!u,"data-isselected":h,style:{justifyContent:l==="middle"||D?"center":l,alignItems:c==="middle"?"center":c,padding:p,...y},children:d.jsxs("div",{className:`${$}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:Math.floor(i*a)+"px",minHeight:Math.floor(i*a)+"px",minWidth:Math.ceil(x||0),color:s,width:x?Math.ceil(x):void 0,height:m?Math.ceil(m):void 0},children:[d.jsx("div",{className:`${$} tl-text tl-text-content`,dir:"auto",children:T.split(` +`).map((j,O)=>d.jsx("div",{dir:"auto",children:j},O))}),(E||h)&&d.jsx(MX,{ref:v,text:r,isEditing:C,...k,handleKeyDown:f??k.handleKeyDown},I)]})})});function os(e,n,t={}){const{closed:r=!1,snap:s=1,start:o="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,u=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(o==="outset"?(e+=c/2,f+=c/2):o==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),u=Math.floor(e/c/(2*h)),u-=u%s,u<3&&l==="dashed"?e/n<4?(c=e,u=1,p=0):(c=e*(1/3),p=e*(1/3)):(c=e/u/(2*h),r?(f=c/2,p=(e-u*c)/u):p=(e-u*c)/Math.max(1,u-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}const SI=new WeakMap;function ww(e,n){const t=SI.get(n);if(t)return t;const r=ds(e,n);let s=0,o=0;const i=r.isStraight?new Hs({start:b.From(r.start.point),end:b.From(r.end.point)}):new Ua({center:b.Cast(r.handleArc.center),start:b.Cast(r.start.point),end:b.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});if(n.props.text.trim()){const l=i.bounds,c=$v(n),{w:u,h}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:null});if(s=u,o=h,l.width>l.height){s=Math.max(Math.min(u,64),Math.min(l.width-64,u));const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:s});s=p,o=f}if(s>16*c){s=16*c;const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Gt,fontFamily:Ss[n.props.font],fontSize:c,maxWidth:s});s=p,o=f}}const a=new b(s,o).addScalar(kY*2*n.props.scale);return SI.set(n,a),a}function OA(e){const n=jt[e.props.size];return(_Y+(n-jt.s)*2+(n===jt.xl?20:0))*e.props.scale}function jX(e,n,t){const r=ww(e,n),s=OA(n),o=b.Nudge(t.start.point,t.end.point,s),i=b.Nudge(t.end.point,t.start.point,s),a=iw(o,i,Q.FromCenter(t.middle,r).corners);if(!a||a.length!==2)return{start:.5,end:.5};let[l,c]=a;b.Dist2(l,o)>b.Dist2(c,o)&&([c,l]=a);const u=o.add(b.Sub(t.middle,l)),h=i.add(b.Sub(t.middle,c)),p=b.Dist(t.start.point,u)/t.length,f=b.Dist(t.start.point,h)/t.length;return{start:p,end:f}}function OX(e,n,t){const r=ww(e,n),s=OA(n),o=Math.sign(n.props.bend),i=s/t.handleArc.radius*o,a=b.Angle(t.bodyArc.center,t.start.point)-i,l=b.Angle(t.bodyArc.center,t.end.point)+i,c=Ki(t.bodyArc.center,t.bodyArc.radius,a),u=Ki(t.bodyArc.center,t.bodyArc.radius,l),h=[],p=vI(t.bodyArc.center,t.bodyArc.radius,a,l,o,Q.FromCenter(c,r).corners);h.push(new at({points:Q.FromCenter(c,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));const f=vI(t.bodyArc.center,t.bodyArc.radius,a,l,o,Q.FromCenter(u,r).corners);h.push(new at({points:Q.FromCenter(u,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));for(const I of[...p??[],...f??[],c,u])h.push(new yg({x:I.x-3,y:I.y-3,radius:3,isFilled:!1,debugColor:"magenta",ignore:!0}));const S=(p&&xI(t.start.point,p))??t.middle,y=(f&&xI(t.end.point,f))??t.middle,x=b.Angle(t.bodyArc.center,t.start.point),m=b.Angle(t.bodyArc.center,t.end.point),v=b.Angle(t.bodyArc.center,S),w=b.Angle(t.bodyArc.center,y);if(ko(x,v,o)>ko(x,w,o))return{start:.5,end:.5,dbg:h};const C=ko(x,m,o),E=ko(x,v,o)/C,k=ko(x,w,o)/C;return{start:E,end:k,dbg:h}}function Jh(e,n){let t;const r=[],s=ds(e,n),o=!!s.bindings.start,i=!!s.bindings.end,a=s.start.arrowhead!=="none",l=s.end.arrowhead!=="none";if(s.isStraight){const u=jX(e,n,s);let h=kt(n.props.labelPosition,a||o?u.start:0,l||i?u.end:1);h=h>=.48&&h<=.52?.5:h,t=b.Lrp(s.start.point,s.end.point,h)}else{const u=OX(e,n,s);u.dbg&&r.push(...u.dbg);let h=kt(n.props.labelPosition,a||o?u.start:0,l||i?u.end:1);h=h>=.48&&h<=.52?.5:h;const p=DX(b.Angle(s.bodyArc.center,s.start.point),b.Angle(s.bodyArc.center,s.end.point),Math.sign(n.props.bend),h);t=Ki(s.bodyArc.center,s.bodyArc.radius,p)}const c=ww(e,n);return{box:Q.FromCenter(t,c),debugGeom:r}}function vI(e,n,t,r,s,o){const i=kv(e,n,o),a=ko(t,r,s);return i==null?void 0:i.filter(l=>{const c=ko(t,b.Angle(e,l),s);return c>=0&&c<=a})}function xI(e,n){let t=null,r=-1/0;for(const s of n){const o=b.Dist2(e,s);o>r&&(t=s,r=o)}return t}function DX(e,n,t,r){const s=ko(e,n,t);return e+s*r*t*-1}function $v(e){return EY[e.props.size]*e.props.scale}function RX(e,n,t){const r=n==="end"?e.end.point:e.start.point,s=n==="end"?e.start.point:e.end.point,o=e.isStraight?b.Dist(s,r):Math.abs(e.bodyArc.length),i=Math.max(Math.min(o/5,t*3),t);let a;if(e.isStraight)a=b.Nudge(r,s,i);else{const l=rG(r,i,e.handleArc.center,e.handleArc.radius);a=n==="end"?e.handleArc.sweepFlag?l[0]:l[1]:e.handleArc.sweepFlag?l[1]:l[0]}return b.IsNaN(a)&&(a=e.start.point),{point:r,int:a}}function LX({point:e,int:n}){const t=b.RotWith(n,e,Me/6),r=b.RotWith(n,e,-Me/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y}`}function $X({point:e,int:n}){const t=b.RotWith(n,e,Me/6),r=b.RotWith(n,e,-Me/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y} Z`}function NX({point:e,int:n}){const t=b.Sub(n,e).div(2),r=b.Add(e,b.Rot(t,Ve)),s=b.Sub(e,b.Rot(t,Ve));return`M ${r.x} ${r.y} L ${n.x} ${n.y} L ${s.x} ${s.y} Z`}function FX({point:e,int:n}){const t=b.Lrp(e,n,.45),r=b.Dist(t,e);return`M ${t.x-r},${t.y} a ${r},${r} 0 1,0 ${r*2},0 - a ${r},${r} 0 1,0 -${r*2},0 `}function zX({point:e,int:n}){const t=b.Lrp(e,n,.75),r=b.RotWith(t,e,Me/4),s=b.RotWith(t,e,-Me/4),o=b.Lrp(r,s,.5);return o.add(b.Sub(o,e)),`M ${o.x} ${o.y} L ${r.x} ${r.y} ${e.x} ${e.y} L ${s.x} ${s.y} Z`}function BX({int:e,point:n}){const t=b.Lrp(n,e,.85),r=b.Sub(t,n).div(2),s=b.Add(n,b.Rot(r,Ve)),o=b.Sub(n,b.Rot(r,Ve)),i=b.Add(t,b.Rot(r,Ve)),a=b.Sub(t,b.Rot(r,Ve));return`M ${s.x} ${s.y} L ${i.x} ${i.y} L ${a.x} ${a.y} L ${o.x} ${o.y} Z`}function UX({int:e,point:n}){const t=b.Sub(e,n).div(2),r=b.Add(n,b.Rot(t,Ve)),s=b.Sub(n,b.Rot(t,Ve));return`M ${r.x} ${r.y} L ${s.x} ${s.y}`}function wf(e,n,t){const r=n==="end"?e.end.arrowhead:e.start.arrowhead;if(r==="none")return;const s=RX(e,n,t);if(s){switch(r){case"bar":return UX(s);case"square":return BX(s);case"diamond":return zX(s);case"dot":return FX(s);case"inverted":return NX(s);case"arrow":return LX(s);case"triangle":return $X(s)}return""}}function HX(e){const{start:n,end:t,handleArc:{radius:r,largeArcFlag:s,sweepFlag:o}}=e;return`M${n.handle.x},${n.handle.y} A${r} ${r} 0 ${s} ${o} ${t.handle.x},${t.handle.y}`}function DA(e){const{start:n,end:t,bodyArc:{radius:r,largeArcFlag:s,sweepFlag:o}}=e;return`M${n.point.x},${n.point.y} A${r} ${r} 0 ${s} ${o} ${t.point.x},${t.point.y}`}function RA(e,n){return`M${e.x},${e.y}L${n.x},${n.y}`}function KX(e){return RA(e.start.handle,e.end.handle)}function LA(e){return RA(e.start.point,e.end.point)}let WX=0;class ep extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"canSnap",()=>!1);g(this,"hideResizeHandles",()=>!0);g(this,"hideRotateHandle",()=>!0);g(this,"hideSelectionBoundsBg",()=>!0);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"canBeLaidOut",t=>{const r=Rn(this.editor,t);return!r.start&&!r.end});g(this,"onHandleDrag",(t,{handle:r,isPrecise:s})=>{const o=r.id,i=Rn(this.editor,t);if(o==="middle"){const{start:k,end:I}=Ha(this.editor,t,i),_=b.Sub(I,k),T=b.Per(_),M=b.Med(I,k),D=b.Sub(M,T),$=b.Add(M,T),j=b.NearestPointOnLineSegment(D,$,r,!1);let O=b.Dist(j,M);return b.Clockwise(j,I,M)&&(O*=-1),{id:t.id,type:t.type,props:{bend:O}}}const a={id:t.id,type:"arrow",props:{}},l=i[o],u=i[o==="start"?"end":"start"];if(this.editor.inputs.ctrlKey)return Vh(this.editor,t,o),a.props[o]={x:r.x,y:r.y},a;const h=this.editor.getShapePageTransform(t.id).applyToPoint(r),p=this.editor.getShapeAtPoint(h,{hitInside:!0,hitFrameInside:!0,margin:0,filter:k=>!k.isLocked&&this.editor.canBindShapes({fromShape:t,toShape:k,binding:"arrow"})});if(!p)return Vh(this.editor,t,o),a.props[o]={x:r.x,y:r.y},a;const f=this.editor.getShapeGeometry(p),S=Q.ZeroFix(f.bounds),x=this.editor.getShapePageTransform(a.id).applyToPoint(r),y=this.editor.getPointInShapeSpace(p,x);let v=s;v||(!l||l&&p.id!==l.toId)&&(v=this.editor.inputs.pointerVelocity.len()<.5),s||(f.isClosed||(v=!0),u&&p.id===u.toId&&u.props.isPrecise&&(v=!0));const w={x:(y.x-S.minX)/S.width,y:(y.y-S.minY)/S.height};v&&b.Dist(y,S.center){const r=Rn(this.editor,t),s=Ha(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)))){bI.set(t,{pagePosition:o.applyToPoint(t),terminalBindings:Hu(s,(a,l)=>{const c=r[a];return c?{binding:c,shapePosition:l,pagePosition:o.applyToPoint(l)}:null})}),r.start&&(Sf({editor:this.editor,arrow:t,terminal:"start",useHandle:!0}),t=this.editor.getShape(t.id)),r.end&&Sf({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}})}}});g(this,"onTranslate",(t,r)=>{const s=bI.get(t);if(!s)return;const o=this.editor.getShapePageTransform(r.id),i=b.Sub(o.applyToPoint(r),s.pagePosition);for(const a of Object.values(s.terminalBindings)){if(!a)continue;const l=b.Add(a.pagePosition,b.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=Q.ZeroFix(this.editor.getShapeGeometry(c).bounds),h=this.editor.getPointInShapeSpace(c,l),p={x:(h.x-u.minX)/u.width,y:(h.y-u.minY)/u.height};ac(this.editor,r,c.id,{...a.binding.props,normalizedAnchor:p,isPrecise:!0})}else Vh(this.editor,r,a.binding.props.terminal)}});g(this,"_resizeInitialBindings",new eo);g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=this._resizeInitialBindings.get(t,()=>Rn(this.editor,t)),a=Ha(this.editor,t,i),{start:l,end:c}=Be(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 h=Math.abs(s),p=Math.abs(o),f=i!=null&&i.start?b.From(i.start.props.normalizedAnchor):null,S=i!=null&&i.end?b.From(i.end.props.normalizedAnchor):null;return s<0&&o>=0?(u!==0&&(u*=-1,u*=Math.max(h,p)),f&&(f.x=1-f.x),S&&(S.x=1-S.x)):s>=0&&o<0?(u!==0&&(u*=-1,u*=Math.max(h,p)),f&&(f.y=1-f.y),S&&(S.y=1-S.y)):s>=0&&o>=0?u!==0&&(u*=Math.max(h,p)):s<0&&o<0&&(u!==0&&(u*=Math.max(h,p)),f&&(f.x=1-f.x,f.y=1-f.y),S&&(S.x=1-S.x,S.y=1-S.y)),i.start&&f&&ac(this.editor,t,i.start.toId,{...i.start.props,normalizedAnchor:f.toJson()}),i.end&&S&&ac(this.editor,t,i.end.toId,{...i.end.props,normalizedAnchor:S.toJson()}),{props:{start:l,end:c,bend:u}}});g(this,"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"}}}});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])})}canBind({toShapeType:t}){return t!=="arrow"}getDefaultProps(){return{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",text:"",labelPosition:.5,font:"draw",scale:1}}getGeometry(t){const r=ds(this.editor,t),s=[],o=r.isStraight?new Hs({start:b.From(r.start.point),end:b.From(r.end.point)}):new Ua({center:b.Cast(r.handleArc.center),start:b.Cast(r.start.point),end:b.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});let i;if(t.props.text.trim()){const a=Jh(this.editor,t);s.push(...a.debugGeom),i=new no({x:a.box.x,y:a.box.y,width:a.box.w,height:a.box.h,isFilled:!0,isLabel:!0})}return new Wr({children:[...i?[o,i]:[o],...s]})}getHandles(t){const r=ds(this.editor,t);return[{id:"start",type:"vertex",index:"a0",x:r.start.handle.x,y:r.start.handle.y},{id:"middle",type:"virtual",index:"a2",x:r.middle.x,y:r.middle.y},{id:"end",type:"vertex",index:"a3",x:r.end.handle.x,y:r.end.handle.y}].filter(Boolean)}component(t){const r=Ar(),s=this.editor.getOnlySelectedShape(),o=this.editor.isInAny("select.idle","select.pointing_handle","select.dragging_handle","select.translating","arrow.dragging")&&!this.editor.getInstanceState().isReadonly,i=ds(this.editor,t);if(!(i!=null&&i.isValid))return null;const a=Jh(this.editor,t),l=t.id===this.editor.getOnlySelectedShapeId(),u=this.editor.getEditingShapeId()===t.id||t.props.text;return d.jsxs(d.Fragment,{children:[d.jsx(bs,{id:t.id,style:{minWidth:50,minHeight:50},children:d.jsx(wI,{shape:t,shouldDisplayHandles:o&&(s==null?void 0:s.id)===t.id})}),u&&d.jsx(bg,{id:t.id,classNamePrefix:"tl-arrow",type:"arrow",font:t.props.font,fontSize:$v(t),lineHeight:Gt.lineHeight,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:r[t.props.labelColor].solid,textWidth:a.box.w,isSelected:l,padding:0,style:{transform:`translate(${a.box.center.x}px, ${a.box.center.y}px)`}})]})}indicator(t){const r=mg(t.id),s=ds(this.editor,t);if(!s)return null;const{start:o,end:i}=Ha(this.editor,t,s==null?void 0:s.bindings),a=this.editor.getShapeGeometry(t),l=a.bounds,c=t.props.text.trim()?a.children[1]:null;if(b.Equals(o,i))return null;const u=jt[t.props.size]*t.props.scale,h=s.start.arrowhead&&wf(s,"start",u),p=s.end.arrowhead&&wf(s,"end",u),f=s.isStraight?LA(s):DA(s),S=h&&s.start.arrowhead!=="arrow"||p&&s.end.arrowhead!=="arrow"||!!c,m=(t.id+"_clip").replace(":","_");return r&&c?d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5*t.props.scale,ry:3.5*t.props.scale}):d.jsxs("g",{children:[S&&d.jsx("defs",{children:d.jsxs("mask",{id:m,children:[d.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.w+200,height:l.h+200,fill:"white"}),c&&d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,fill:"black",rx:3.5*t.props.scale,ry:3.5*t.props.scale}),h&&d.jsx("path",{d:h,fill:s.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),p&&d.jsx("path",{d:p,fill:s.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),d.jsxs("g",{...S?{mask:`url(#${m})`}:void 0,children:[S&&d.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.width+200,height:l.height+200,opacity:0}),d.jsx("path",{d:f})]}),h&&d.jsx("path",{d:h}),p&&d.jsx("path",{d:p}),c&&d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5,ry:3.5})]})}toSvg(t,r){r.addExportDef(vw(t.props.fill)),t.props.text&&r.addExportDef(xg(t.props.font));const s=lo(r),o=1/t.props.scale;return d.jsxs("g",{transform:`scale(${o})`,children:[d.jsx(wI,{shape:t,shouldDisplayHandles:!1}),d.jsx(wg,{fontSize:$v(t),font:t.props.font,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:s[t.props.labelColor].solid,bounds:Jh(this.editor,t).box,padding:4*t.props.scale})]})}getCanvasSvgDefs(){return[xw(),{key:"arrow:dot",component:VX},{key:"arrow:cross",component:YX}]}getInterpolatedProps(t,r,s){return{...r.props,start:{x:On(t.props.start.x,r.props.start.x,s),y:On(t.props.start.y,r.props.start.y,s)},end:{x:On(t.props.end.x,r.props.end.x,s),y:On(t.props.end.y,r.props.end.y,s)},bend:On(t.props.bend,r.props.bend,s),labelPosition:On(t.props.labelPosition,r.props.labelPosition,s)}}}g(ep,"type","arrow"),g(ep,"props",CT),g(ep,"migrations",IT);function GX(e,n){const t=ds(e,n);return t.isStraight?b.Dist(t.start.handle,t.end.handle):Math.abs(t.handleArc.length)}const wI=Lt(function({shape:n,shouldDisplayHandles:t}){const r=F(),s=Ar(),o=ds(r,n),i=Q.ZeroFix(r.getShapeGeometry(n).bounds),a=Rn(r,n),l=Ce.useMemo(()=>r.environment.isSafari?WX+=1:0,[n]);if(!(o!=null&&o.isValid))return null;const c=jt[n.props.size]*n.props.scale,u=o.start.arrowhead&&wf(o,"start",c),h=o.end.arrowhead&&wf(o,"end",c),p=o.isStraight?LA(o):DA(o);let f=null;if(t){const C=2/r.getZoomLevel(),{strokeDasharray:E,strokeDashoffset:k}=os(GX(r,n),C,{end:"skip",start:"skip",lengthRatio:2.5});f=a.start||a.end?d.jsx("path",{className:"tl-arrow-hint",d:o.isStraight?KX(o):HX(o),strokeDasharray:E,strokeDashoffset:k,strokeWidth:C,markerStart:a.start?a.start.props.isExact?"":a.start.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",markerEnd:a.end?a.end.props.isExact?"":a.end.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",opacity:.16}):null}const{strokeDasharray:S,strokeDashoffset:m}=os(o.isStraight?o.length:Math.abs(o.bodyArc.length),c,{style:n.props.dash}),x=Jh(r,n),y=!(o.start.arrowhead==="none"||o.start.arrowhead==="arrow"),v=!(o.end.arrowhead==="none"||o.end.arrowhead==="arrow"),w=(n.id+"_clip_"+l).replace(":","_");return d.jsxs(d.Fragment,{children:[d.jsx("defs",{children:d.jsxs("mask",{id:w,children:[d.jsx("rect",{x:N(-100+i.minX),y:N(-100+i.minY),width:N(i.width+200),height:N(i.height+200),fill:"white"}),n.props.text.trim()&&d.jsx("rect",{x:x.box.x,y:x.box.y,width:x.box.w,height:x.box.h,fill:"black",rx:4,ry:4}),u&&y&&d.jsx("path",{d:u,fill:o.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),h&&v&&d.jsx("path",{d:h,fill:o.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),d.jsxs("g",{fill:"none",stroke:s[n.props.color].solid,strokeWidth:c,strokeLinejoin:"round",strokeLinecap:"round",pointerEvents:"none",children:[f,d.jsxs("g",{mask:`url(#${w})`,children:[d.jsx("rect",{x:N(i.minX-100),y:N(i.minY-100),width:N(i.width+200),height:N(i.height+200),opacity:0}),d.jsx("path",{d:p,strokeDasharray:S,strokeDashoffset:m})]}),u&&y&&n.props.fill!=="none"&&d.jsx(nn,{theme:s,d:u,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),h&&v&&n.props.fill!=="none"&&d.jsx(nn,{theme:s,d:h,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),u&&d.jsx("path",{d:u}),h&&d.jsx("path",{d:h})]})]})}),bI=new WeakMap;function VX(){return d.jsx("marker",{id:"arrowhead-dot",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"0",children:d.jsx("circle",{cx:"3",cy:"3",r:"2",strokeDasharray:"100%"})})}function YX(){return d.jsxs("marker",{id:"arrowhead-cross",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"auto",children:[d.jsx("line",{x1:"1.5",y1:"1.5",x2:"4.5",y2:"4.5",strokeDasharray:"100%"}),d.jsx("line",{x1:"1.5",y1:"4.5",x2:"4.5",y2:"1.5",strokeDasharray:"100%"})]})}const PI="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 yl({url:e,zoomLevel:n}){return d.jsx("a",{className:le("tl-hyperlink-button",{"tl-hyperlink-button__hidden":n<.32}),href:e,target:"_blank",rel:"noopener noreferrer",onPointerDown:Dt,onPointerUp:Dt,title:e,draggable:!1,children:d.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${PI}") center 100% / 100% no-repeat`,WebkitMask:`url("${PI}") center 100% / 100% no-repeat`}})})}const CI="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",XX=[{offsetX:0,offsetY:2,blur:4,spread:0,color:"#00000029"},{offsetX:0,offsetY:3,blur:6,spread:0,color:"#0000001f"}];function bw(e){return XX.map(t=>{const{offsetX:r,offsetY:s,blur:o,spread:i,color:a}=t,l=new b(r,s),{x:c,y:u}=l.rot(-e);return`${c}px ${u}px ${o}px ${i}px ${a}`}).join(", ")}const qX=300,$A=320,ZX=46,QX=101;class tp extends Ol{constructor(){super(...arguments);g(this,"canResize",()=>!1);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"onBeforeCreate",t=>II(this.editor,t));g(this,"onBeforeUpdate",(t,r)=>{if(t.props.url!==r.props.url)if(ar.isValid(r.props.url))eq(this.editor,r);else return{...r,props:{...r.props,url:t.props.url}};if(t.props.assetId!==r.props.assetId)return II(this.editor,r)})}getDefaultProps(){return{url:"",w:qX,h:$A,assetId:null}}component(t){const r=t.props.assetId?this.editor.getAsset(t.props.assetId):null,s=this.editor.getShapePageTransform(t).rotation(),o=JX(t);return d.jsx(Wi,{children:d.jsxs("div",{className:"tl-bookmark__container",style:{boxShadow:bw(s),maxHeight:t.props.h},children:[(!r||r.props.image)&&d.jsxs("div",{className:"tl-bookmark__image_container",children:[r?d.jsx("img",{className:"tl-bookmark__image",draggable:!1,referrerPolicy:"strict-origin-when-cross-origin",src:r==null?void 0:r.props.image,alt:(r==null?void 0:r.props.title)||""}):d.jsx("div",{className:"tl-bookmark__placeholder"}),(r==null?void 0:r.props.image)&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]}),d.jsxs("div",{className:"tl-bookmark__copy_container",children:[r!=null&&r.props.title?d.jsx("h2",{className:"tl-bookmark__heading",children:r.props.title}):null,r!=null&&r.props.description&&(r!=null&&r.props.image)?d.jsx("p",{className:"tl-bookmark__description",children:r.props.description}):null,d.jsxs("a",{className:"tl-bookmark__link",href:t.props.url||"",target:"_blank",rel:"noopener noreferrer",onPointerDown:Dt,onPointerUp:Dt,onClick:Dt,children:[r!=null&&r.props.favicon?d.jsx("img",{className:"tl-bookmark__favicon",src:r==null?void 0:r.props.favicon,referrerPolicy:"strict-origin-when-cross-origin",alt:`favicon of ${o}`}):d.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${CI}") center 100% / 100% no-repeat`,WebkitMask:`url("${CI}") center 100% / 100% no-repeat`}}),d.jsx("span",{children:o})]})]})]})})}indicator(t){return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:"6",ry:"6"})}}g(tp,"type","bookmark"),g(tp,"props",AT),g(tp,"migrations",jT);function II(e,n){const t=n.props.assetId?e.getAsset(n.props.assetId):null;let r=$A;return t&&(t.props.image||(t.props.title?r=QX:r=ZX)),{...n,props:{...n.props,h:r}}}const JX=e=>{try{return new URL(e.props.url).hostname.replace(/^www\./,"")}catch{return e.props.url}};function eq(e,n){const{url:t}=n.props,r=_i.createId(fv(t));e.getAsset(r)?n.props.assetId!==r&&e.updateShapes([{id:n.id,type:n.type,props:{assetId:r}}]):(e.updateShapes([{id:n.id,type:n.type,props:{assetId:null}}]),tq(e,n))}const tq=Y2(async(e,n)=>{if(e.isDisposed)return;const{url:t}=n.props,r=await e.getAssetForExternalContent({type:"url",url:t});r&&e.run(()=>{e.createAssets([r]),e.updateShapes([{id:n.id,type:n.type,props:{assetId:r.id}}])})},500);function Gi(e,n=!1){const t=e.length;if(t<2)return"";let r=e[0].point,s=e[1].point;if(t===2)return`M${ke(r)}L${ke(s)}`;let o="";for(let i=2,a=t-1;i3?"T":""}${o}L${ke(e[t-1].point)}`}function nq(e,n={}){const{start:t={},end:r={}}=n,{cap:s=!0}=t,{cap:o=!0}=r;Ye(!t.taper&&!r.taper,"cap taper not supported here"),Ye(!t.easing&&!r.easing,"cap easing not supported here"),Ye(s&&o,"cap must be true");const i=Ps(e,n);Sg(i,n);const a=rq(i);let l="";for(const c of a)l+=oq(c,n);return l}function rq(e){if(e.length<=2)return[e];const n=[];let t=[e[0]],r=b.Sub(e[1].point,e[0].point).uni(),s,o,i,a,l;for(let c=1,u=e.length;c.7)&&(b.Dist2(i.point,a.point)+b.Dist2(a.point,l.point))/((i.radius+a.radius+l.radius)/3)**2<1.5){t.push(a),n.push(xy(t)),t=[a];continue}}return t.push(e[e.length-1]),n.push(xy(t)),n}function xy(e){const n=e[0];let t;for(;e.length>2&&(t=e[1],b.Dist2(n.point,t.point)<((n.radius+t.radius)/2*.5)**2);)e.splice(1,1);const r=e[e.length-1];let s;for(;e.length>2&&(s=e[e.length-2],b.Dist2(r.point,s.point)<((r.radius+s.radius)/2*.5)**2);)e.splice(e.length-2,1);return e.length>1&&(e[0]={...e[0],vector:b.Sub(e[0].point,e[1].point).uni()},e[e.length-1]={...e[e.length-1],vector:b.Sub(e[e.length-2].point,e[e.length-1].point).uni()}),e}function sq(e,n,t){return"M "+e+" "+n+" m -"+t+", 0 a "+t+","+t+" 0 1,1 "+t*2+",0 a "+t+","+t+" 0 1,1 -"+t*2+",0"}function oq(e,n={}){if(e.length===0)return"";if(e.length===1)return sq(e[0].point.x,e[0].point.y,e[0].radius);const{left:t,right:r}=gA(e,n);r.reverse();let s=`M${ke(t[0])}T`;for(let o=1;oe*.65+EH(e*Me/2)*.35,aq=e=>({size:e,thinning:.5,streamline:pl(e,[9,16],[.64,.74],!0),smoothing:.62,easing:At.easeOutSine,simulatePressure:!0}),lq=e=>({size:1+e*1.2,thinning:.62,streamline:.62,smoothing:.62,simulatePressure:!1,easing:iq}),EI=e=>({size:e,thinning:0,streamline:pl(e,[9,16],[.64,.74],!0),smoothing:.62,simulatePressure:!1,easing:At.linear}),cq=e=>({size:e,thinning:0,streamline:.62,smoothing:.62,simulatePressure:!1,easing:At.linear});function Pw({strokeWidth:e,showAsComplete:n}){return{size:1+e,thinning:0,streamline:.5,smoothing:.5,simulatePressure:!1,easing:At.easeOutSine,last:n}}function Nv(e,n,t,r){const s=e.isComplete||t;return r?e.isPen?{...cq(n),last:s}:{...EI(n),last:s}:e.dash==="draw"?e.isPen?{...lq(n),last:s}:{...aq(n),last:s}:{...EI(n),last:s}}function Sl(e){const n=[];for(const t of e)if(t.type==="free"||t.points.length<2)n.push(...t.points.map(b.Cast));else{const r=Math.max(4,Math.floor(b.Dist(t.points[0],t.points[1])/16));n.push(...b.PointsBetween(t.points[0],t.points[1],r))}return n}function uq(e,n){return{draw:"none",solid:"none",dotted:`0.1 ${n*2}`,dashed:`${n*2} ${n*2}`}[e.props.dash]}class np extends Ir{constructor(){super(...arguments);g(this,"hideResizeHandles",t=>wy(t));g(this,"hideRotateHandle",t=>wy(t));g(this,"hideSelectionBoundsFg",t=>wy(t));g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=[];for(const a of t.props.segments)i.push({...a,points:a.points.map(({x:l,y:c,z:u})=>({x:zs(s*l),y:zs(o*c),z:u}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",fill:"none",dash:"draw",size:"m",isComplete:!1,isClosed:!1,isPen:!1,scale:1}}getGeometry(t){const r=Sl(t.props.segments),s=(jt[t.props.size]+1)*t.props.scale;if(t.props.segments.length===1){const i=Q.FromPoints(r);if(i.widthi.point);return t.props.isClosed?new at({points:o,isFilled:t.props.fill!=="none"}):new ia({points:o})}component(t){return d.jsx(bs,{id:t.id,children:d.jsx(_I,{shape:t,zoomLevel:this.editor.getZoomLevel()})})}indicator(t){var h;const r=Sl(t.props.segments);let s=(jt[t.props.size]+1)*t.props.scale;const o=this.editor.getZoomLevel();!(o<.5&&o<1.5/s)&&!t.props.isPen&&t.props.dash==="draw"&&r.length===1&&(s+=Yr(t.id)()*(s/6));const a=t.props.isComplete||((h=Ut(t.props.segments))==null?void 0:h.type)==="straight",l=Nv(t.props,s,a,!0),c=Ps(r,l),u=c.length>1?Gi(c,t.props.isClosed):NA(r[0],s);return d.jsx("path",{d:u})}toSvg(t,r){r.addExportDef(vw(t.props.fill));const s=1/t.props.scale;return d.jsx("g",{transform:`scale(${s})`,children:d.jsx(_I,{shape:t,zoomLevel:1})})}getCanvasSvgDefs(){return[xw()]}expandSelectionOutlinePx(t){const r=t.props.dash==="draw"?1.6:1;return jt[t.props.size]*r/2*t.props.scale}}g(np,"type","draw"),g(np,"props",DT),g(np,"migrations",RT);function NA(e,n){const t=(n+1)*.5;return`M ${e.x} ${e.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function wy(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function _I({shape:e,zoomLevel:n}){var h;const t=Ar(),r=Sl(e.props.segments),s=e.props.isComplete||((h=Ut(e.props.segments))==null?void 0:h.type)==="straight";let o=(jt[e.props.size]+1)*e.props.scale;const i=n<.5&&n<1.5/o;!i&&!e.props.isPen&&e.props.dash==="draw"&&r.length===1&&(o+=Yr(e.id)()*(o/6));const a=Nv(e.props,o,s,i);if(!i&&e.props.dash==="draw")return d.jsxs(d.Fragment,{children:[e.props.isClosed&&e.props.fill&&r.length>1?d.jsx(nn,{d:Gi(Ps(r,a),e.props.isClosed),theme:t,color:e.props.color,fill:e.props.isClosed?e.props.fill:"none",scale:e.props.scale}):null,d.jsx("path",{d:nq(r,a),strokeLinecap:"round",fill:t[e.props.color].solid})]});const l=Ps(r,a),c=l.length<2,u=c?NA(r[0],0):Gi(l,e.props.isClosed);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{d:u,theme:t,color:e.props.color,fill:c||e.props.isClosed?e.props.fill:"none",scale:e.props.scale}),d.jsx("path",{d:u,strokeLinecap:"round",fill:c?t[e.props.color].solid:"none",stroke:t[e.props.color].solid,strokeWidth:o,strokeDasharray:c?"none":uq(e,o),strokeDashoffset:"0"})]})}function dq(e,n,t={}){const{newPoint:r,handle:s,scaleX:o,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=t;let h=e.props.w*o,p=e.props.h*i;const f=new b(0,0);if(h>0){if(h0){if(pObject.entries(e).filter(([n,t])=>t).map(([n])=>n).join(" ");class rp extends Ol{constructor(){super(...arguments);g(this,"hideSelectionBoundsFg",t=>!this.canResize(t));g(this,"canEdit",()=>!0);g(this,"canResize",t=>{var r,s;return!!((s=(r=Do(t.props.url))==null?void 0:r.definition)!=null&&s.doesResize)});g(this,"canEditInReadOnly",()=>!0);g(this,"isAspectRatioLocked",t=>{const r=Do(t.props.url);return(r==null?void 0:r.definition.isAspectRatioLocked)??!1});g(this,"onResize",(t,r)=>{const s=this.isAspectRatioLocked(t),o=Do(t.props.url);let i=(o==null?void 0:o.definition.minWidth)??200,a=(o==null?void 0:o.definition.minHeight)??200;if(s){const l=t.props.w/t.props.h;l>1?i*=l:a/=l}return dq(t,r,{minWidth:i,minHeight:a})})}getDefaultProps(){return{w:300,h:300,url:""}}component(t){const{w:r,h:s,url:o}=t.props,i=mg(t.id),a=P.useMemo(()=>xA(o),[o]),l=H("is hovering",()=>{const{editingShapeId:f,hoveredShapeId:S}=this.editor.getCurrentPageState();if(f&&S!==f){const m=this.editor.getShape(f);if(m&&this.editor.isShapeOfType(m,"embed"))return!0}return!1},[]),c=this.editor.getShapePageTransform(t).rotation(),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 d.jsx(Wi,{className:"tl-embed-container",id:t.id,children:d.jsx(pq,{id:f,width:N(r),height:N(s),isInteractive:u,pageRotation:c})})}const p=hq({...lH,...(a==null?void 0:a.definition.overridePermissions)??{}});return d.jsx(Wi,{className:"tl-embed-container",id:t.id,children:a!=null&&a.definition?d.jsx("iframe",{className:"tl-embed",sandbox:p,src:a.embedUrl,width:N(r),height:N(s),draggable:!1,frameBorder:"0",referrerPolicy:"no-referrer-when-downgrade",style:{border:0,pointerEvents:u?"auto":"none",zIndex:u?"":"-1",boxShadow:bw(c),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:a==null?void 0:a.definition.backgroundColor}}):null})}indicator(t){const r=P.useMemo(()=>Do(t.props.url),[t.props.url]);return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:(r==null?void 0:r.definition.overrideOutlineRadius)??8,ry:(r==null?void 0:r.definition.overrideOutlineRadius)??8})}}g(rp,"type","embed"),g(rp,"props",LT),g(rp,"migrations",$T);function pq({id:e,file:n,isInteractive:t,width:r,height:s,style:o,pageRotation:i}){return d.jsx("iframe",{className:"tl-embed",draggable:!1,width:N(r),height:N(s),frameBorder:"0",scrolling:"no",seamless:!0,referrerPolicy:"no-referrer-when-downgrade",style:{...o,pointerEvents:t?"all":"none",zIndex:t?"":"-1",boxShadow:bw(i)},srcDoc:` + a ${r},${r} 0 1,0 -${r*2},0 `}function zX({point:e,int:n}){const t=b.Lrp(e,n,.75),r=b.RotWith(t,e,Me/4),s=b.RotWith(t,e,-Me/4),o=b.Lrp(r,s,.5);return o.add(b.Sub(o,e)),`M ${o.x} ${o.y} L ${r.x} ${r.y} ${e.x} ${e.y} L ${s.x} ${s.y} Z`}function BX({int:e,point:n}){const t=b.Lrp(n,e,.85),r=b.Sub(t,n).div(2),s=b.Add(n,b.Rot(r,Ve)),o=b.Sub(n,b.Rot(r,Ve)),i=b.Add(t,b.Rot(r,Ve)),a=b.Sub(t,b.Rot(r,Ve));return`M ${s.x} ${s.y} L ${i.x} ${i.y} L ${a.x} ${a.y} L ${o.x} ${o.y} Z`}function UX({int:e,point:n}){const t=b.Sub(e,n).div(2),r=b.Add(n,b.Rot(t,Ve)),s=b.Sub(n,b.Rot(t,Ve));return`M ${r.x} ${r.y} L ${s.x} ${s.y}`}function wf(e,n,t){const r=n==="end"?e.end.arrowhead:e.start.arrowhead;if(r==="none")return;const s=RX(e,n,t);if(s){switch(r){case"bar":return UX(s);case"square":return BX(s);case"diamond":return zX(s);case"dot":return FX(s);case"inverted":return NX(s);case"arrow":return LX(s);case"triangle":return $X(s)}return""}}function HX(e){const{start:n,end:t,handleArc:{radius:r,largeArcFlag:s,sweepFlag:o}}=e;return`M${n.handle.x},${n.handle.y} A${r} ${r} 0 ${s} ${o} ${t.handle.x},${t.handle.y}`}function DA(e){const{start:n,end:t,bodyArc:{radius:r,largeArcFlag:s,sweepFlag:o}}=e;return`M${n.point.x},${n.point.y} A${r} ${r} 0 ${s} ${o} ${t.point.x},${t.point.y}`}function RA(e,n){return`M${e.x},${e.y}L${n.x},${n.y}`}function KX(e){return RA(e.start.handle,e.end.handle)}function LA(e){return RA(e.start.point,e.end.point)}let WX=0;class ep extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"canSnap",()=>!1);g(this,"hideResizeHandles",()=>!0);g(this,"hideRotateHandle",()=>!0);g(this,"hideSelectionBoundsBg",()=>!0);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"canBeLaidOut",t=>{const r=Rn(this.editor,t);return!r.start&&!r.end});g(this,"onHandleDrag",(t,{handle:r,isPrecise:s})=>{const o=r.id,i=Rn(this.editor,t);if(o==="middle"){const{start:k,end:I}=Ha(this.editor,t,i),_=b.Sub(I,k),T=b.Per(_),M=b.Med(I,k),D=b.Sub(M,T),$=b.Add(M,T),j=b.NearestPointOnLineSegment(D,$,r,!1);let O=b.Dist(j,M);return b.Clockwise(j,I,M)&&(O*=-1),{id:t.id,type:t.type,props:{bend:O}}}const a={id:t.id,type:"arrow",props:{}},l=i[o],u=i[o==="start"?"end":"start"];if(this.editor.inputs.ctrlKey)return Vh(this.editor,t,o),a.props[o]={x:r.x,y:r.y},a;const h=this.editor.getShapePageTransform(t.id).applyToPoint(r),p=this.editor.getShapeAtPoint(h,{hitInside:!0,hitFrameInside:!0,margin:0,filter:k=>!k.isLocked&&this.editor.canBindShapes({fromShape:t,toShape:k,binding:"arrow"})});if(!p)return Vh(this.editor,t,o),a.props[o]={x:r.x,y:r.y},a;const f=this.editor.getShapeGeometry(p),S=Q.ZeroFix(f.bounds),x=this.editor.getShapePageTransform(a.id).applyToPoint(r),m=this.editor.getPointInShapeSpace(p,x);let v=s;v||(!l||l&&p.id!==l.toId)&&(v=this.editor.inputs.pointerVelocity.len()<.5),s||(f.isClosed||(v=!0),u&&p.id===u.toId&&u.props.isPrecise&&(v=!0));const w={x:(m.x-S.minX)/S.width,y:(m.y-S.minY)/S.height};v&&b.Dist(m,S.center){const r=Rn(this.editor,t),s=Ha(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)))){bI.set(t,{pagePosition:o.applyToPoint(t),terminalBindings:Hu(s,(a,l)=>{const c=r[a];return c?{binding:c,shapePosition:l,pagePosition:o.applyToPoint(l)}:null})}),r.start&&(Sf({editor:this.editor,arrow:t,terminal:"start",useHandle:!0}),t=this.editor.getShape(t.id)),r.end&&Sf({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}})}}});g(this,"onTranslate",(t,r)=>{const s=bI.get(t);if(!s)return;const o=this.editor.getShapePageTransform(r.id),i=b.Sub(o.applyToPoint(r),s.pagePosition);for(const a of Object.values(s.terminalBindings)){if(!a)continue;const l=b.Add(a.pagePosition,b.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=Q.ZeroFix(this.editor.getShapeGeometry(c).bounds),h=this.editor.getPointInShapeSpace(c,l),p={x:(h.x-u.minX)/u.width,y:(h.y-u.minY)/u.height};ac(this.editor,r,c.id,{...a.binding.props,normalizedAnchor:p,isPrecise:!0})}else Vh(this.editor,r,a.binding.props.terminal)}});g(this,"_resizeInitialBindings",new eo);g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=this._resizeInitialBindings.get(t,()=>Rn(this.editor,t)),a=Ha(this.editor,t,i),{start:l,end:c}=Be(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 h=Math.abs(s),p=Math.abs(o),f=i!=null&&i.start?b.From(i.start.props.normalizedAnchor):null,S=i!=null&&i.end?b.From(i.end.props.normalizedAnchor):null;return s<0&&o>=0?(u!==0&&(u*=-1,u*=Math.max(h,p)),f&&(f.x=1-f.x),S&&(S.x=1-S.x)):s>=0&&o<0?(u!==0&&(u*=-1,u*=Math.max(h,p)),f&&(f.y=1-f.y),S&&(S.y=1-S.y)):s>=0&&o>=0?u!==0&&(u*=Math.max(h,p)):s<0&&o<0&&(u!==0&&(u*=Math.max(h,p)),f&&(f.x=1-f.x,f.y=1-f.y),S&&(S.x=1-S.x,S.y=1-S.y)),i.start&&f&&ac(this.editor,t,i.start.toId,{...i.start.props,normalizedAnchor:f.toJson()}),i.end&&S&&ac(this.editor,t,i.end.toId,{...i.end.props,normalizedAnchor:S.toJson()}),{props:{start:l,end:c,bend:u}}});g(this,"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"}}}});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])})}canBind({toShapeType:t}){return t!=="arrow"}getDefaultProps(){return{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",text:"",labelPosition:.5,font:"draw",scale:1}}getGeometry(t){const r=ds(this.editor,t),s=[],o=r.isStraight?new Hs({start:b.From(r.start.point),end:b.From(r.end.point)}):new Ua({center:b.Cast(r.handleArc.center),start:b.Cast(r.start.point),end:b.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});let i;if(t.props.text.trim()){const a=Jh(this.editor,t);s.push(...a.debugGeom),i=new no({x:a.box.x,y:a.box.y,width:a.box.w,height:a.box.h,isFilled:!0,isLabel:!0})}return new Wr({children:[...i?[o,i]:[o],...s]})}getHandles(t){const r=ds(this.editor,t);return[{id:"start",type:"vertex",index:"a0",x:r.start.handle.x,y:r.start.handle.y},{id:"middle",type:"virtual",index:"a2",x:r.middle.x,y:r.middle.y},{id:"end",type:"vertex",index:"a3",x:r.end.handle.x,y:r.end.handle.y}].filter(Boolean)}component(t){const r=Ar(),s=this.editor.getOnlySelectedShape(),o=this.editor.isInAny("select.idle","select.pointing_handle","select.dragging_handle","select.translating","arrow.dragging")&&!this.editor.getInstanceState().isReadonly,i=ds(this.editor,t);if(!(i!=null&&i.isValid))return null;const a=Jh(this.editor,t),l=t.id===this.editor.getOnlySelectedShapeId(),u=this.editor.getEditingShapeId()===t.id||t.props.text;return d.jsxs(d.Fragment,{children:[d.jsx(bs,{id:t.id,style:{minWidth:50,minHeight:50},children:d.jsx(wI,{shape:t,shouldDisplayHandles:o&&(s==null?void 0:s.id)===t.id})}),u&&d.jsx(bg,{id:t.id,classNamePrefix:"tl-arrow",type:"arrow",font:t.props.font,fontSize:$v(t),lineHeight:Gt.lineHeight,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:r[t.props.labelColor].solid,textWidth:a.box.w,isSelected:l,padding:0,style:{transform:`translate(${a.box.center.x}px, ${a.box.center.y}px)`}})]})}indicator(t){const r=mg(t.id),s=ds(this.editor,t);if(!s)return null;const{start:o,end:i}=Ha(this.editor,t,s==null?void 0:s.bindings),a=this.editor.getShapeGeometry(t),l=a.bounds,c=t.props.text.trim()?a.children[1]:null;if(b.Equals(o,i))return null;const u=jt[t.props.size]*t.props.scale,h=s.start.arrowhead&&wf(s,"start",u),p=s.end.arrowhead&&wf(s,"end",u),f=s.isStraight?LA(s):DA(s),S=h&&s.start.arrowhead!=="arrow"||p&&s.end.arrowhead!=="arrow"||!!c,y=(t.id+"_clip").replace(":","_");return r&&c?d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5*t.props.scale,ry:3.5*t.props.scale}):d.jsxs("g",{children:[S&&d.jsx("defs",{children:d.jsxs("mask",{id:y,children:[d.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.w+200,height:l.h+200,fill:"white"}),c&&d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,fill:"black",rx:3.5*t.props.scale,ry:3.5*t.props.scale}),h&&d.jsx("path",{d:h,fill:s.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),p&&d.jsx("path",{d:p,fill:s.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),d.jsxs("g",{...S?{mask:`url(#${y})`}:void 0,children:[S&&d.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.width+200,height:l.height+200,opacity:0}),d.jsx("path",{d:f})]}),h&&d.jsx("path",{d:h}),p&&d.jsx("path",{d:p}),c&&d.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5,ry:3.5})]})}toSvg(t,r){r.addExportDef(vw(t.props.fill)),t.props.text&&r.addExportDef(xg(t.props.font));const s=lo(r),o=1/t.props.scale;return d.jsxs("g",{transform:`scale(${o})`,children:[d.jsx(wI,{shape:t,shouldDisplayHandles:!1}),d.jsx(wg,{fontSize:$v(t),font:t.props.font,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:s[t.props.labelColor].solid,bounds:Jh(this.editor,t).box,padding:4*t.props.scale})]})}getCanvasSvgDefs(){return[xw(),{key:"arrow:dot",component:VX},{key:"arrow:cross",component:YX}]}getInterpolatedProps(t,r,s){return{...r.props,start:{x:On(t.props.start.x,r.props.start.x,s),y:On(t.props.start.y,r.props.start.y,s)},end:{x:On(t.props.end.x,r.props.end.x,s),y:On(t.props.end.y,r.props.end.y,s)},bend:On(t.props.bend,r.props.bend,s),labelPosition:On(t.props.labelPosition,r.props.labelPosition,s)}}}g(ep,"type","arrow"),g(ep,"props",CT),g(ep,"migrations",IT);function GX(e,n){const t=ds(e,n);return t.isStraight?b.Dist(t.start.handle,t.end.handle):Math.abs(t.handleArc.length)}const wI=Lt(function({shape:n,shouldDisplayHandles:t}){const r=F(),s=Ar(),o=ds(r,n),i=Q.ZeroFix(r.getShapeGeometry(n).bounds),a=Rn(r,n),l=Ce.useMemo(()=>r.environment.isSafari?WX+=1:0,[n]);if(!(o!=null&&o.isValid))return null;const c=jt[n.props.size]*n.props.scale,u=o.start.arrowhead&&wf(o,"start",c),h=o.end.arrowhead&&wf(o,"end",c),p=o.isStraight?LA(o):DA(o);let f=null;if(t){const C=2/r.getZoomLevel(),{strokeDasharray:E,strokeDashoffset:k}=os(GX(r,n),C,{end:"skip",start:"skip",lengthRatio:2.5});f=a.start||a.end?d.jsx("path",{className:"tl-arrow-hint",d:o.isStraight?KX(o):HX(o),strokeDasharray:E,strokeDashoffset:k,strokeWidth:C,markerStart:a.start?a.start.props.isExact?"":a.start.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",markerEnd:a.end?a.end.props.isExact?"":a.end.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",opacity:.16}):null}const{strokeDasharray:S,strokeDashoffset:y}=os(o.isStraight?o.length:Math.abs(o.bodyArc.length),c,{style:n.props.dash}),x=Jh(r,n),m=!(o.start.arrowhead==="none"||o.start.arrowhead==="arrow"),v=!(o.end.arrowhead==="none"||o.end.arrowhead==="arrow"),w=(n.id+"_clip_"+l).replace(":","_");return d.jsxs(d.Fragment,{children:[d.jsx("defs",{children:d.jsxs("mask",{id:w,children:[d.jsx("rect",{x:N(-100+i.minX),y:N(-100+i.minY),width:N(i.width+200),height:N(i.height+200),fill:"white"}),n.props.text.trim()&&d.jsx("rect",{x:x.box.x,y:x.box.y,width:x.box.w,height:x.box.h,fill:"black",rx:4,ry:4}),u&&m&&d.jsx("path",{d:u,fill:o.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),h&&v&&d.jsx("path",{d:h,fill:o.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),d.jsxs("g",{fill:"none",stroke:s[n.props.color].solid,strokeWidth:c,strokeLinejoin:"round",strokeLinecap:"round",pointerEvents:"none",children:[f,d.jsxs("g",{mask:`url(#${w})`,children:[d.jsx("rect",{x:N(i.minX-100),y:N(i.minY-100),width:N(i.width+200),height:N(i.height+200),opacity:0}),d.jsx("path",{d:p,strokeDasharray:S,strokeDashoffset:y})]}),u&&m&&n.props.fill!=="none"&&d.jsx(nn,{theme:s,d:u,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),h&&v&&n.props.fill!=="none"&&d.jsx(nn,{theme:s,d:h,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),u&&d.jsx("path",{d:u}),h&&d.jsx("path",{d:h})]})]})}),bI=new WeakMap;function VX(){return d.jsx("marker",{id:"arrowhead-dot",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"0",children:d.jsx("circle",{cx:"3",cy:"3",r:"2",strokeDasharray:"100%"})})}function YX(){return d.jsxs("marker",{id:"arrowhead-cross",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"auto",children:[d.jsx("line",{x1:"1.5",y1:"1.5",x2:"4.5",y2:"4.5",strokeDasharray:"100%"}),d.jsx("line",{x1:"1.5",y1:"4.5",x2:"4.5",y2:"1.5",strokeDasharray:"100%"})]})}const PI="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 yl({url:e,zoomLevel:n}){return d.jsx("a",{className:le("tl-hyperlink-button",{"tl-hyperlink-button__hidden":n<.32}),href:e,target:"_blank",rel:"noopener noreferrer",onPointerDown:Dt,onPointerUp:Dt,title:e,draggable:!1,children:d.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${PI}") center 100% / 100% no-repeat`,WebkitMask:`url("${PI}") center 100% / 100% no-repeat`}})})}const CI="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",XX=[{offsetX:0,offsetY:2,blur:4,spread:0,color:"#00000029"},{offsetX:0,offsetY:3,blur:6,spread:0,color:"#0000001f"}];function bw(e){return XX.map(t=>{const{offsetX:r,offsetY:s,blur:o,spread:i,color:a}=t,l=new b(r,s),{x:c,y:u}=l.rot(-e);return`${c}px ${u}px ${o}px ${i}px ${a}`}).join(", ")}const qX=300,$A=320,ZX=46,QX=101;class tp extends Ol{constructor(){super(...arguments);g(this,"canResize",()=>!1);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"onBeforeCreate",t=>II(this.editor,t));g(this,"onBeforeUpdate",(t,r)=>{if(t.props.url!==r.props.url)if(ar.isValid(r.props.url))eq(this.editor,r);else return{...r,props:{...r.props,url:t.props.url}};if(t.props.assetId!==r.props.assetId)return II(this.editor,r)})}getDefaultProps(){return{url:"",w:qX,h:$A,assetId:null}}component(t){const r=t.props.assetId?this.editor.getAsset(t.props.assetId):null,s=this.editor.getShapePageTransform(t).rotation(),o=JX(t);return d.jsx(Wi,{children:d.jsxs("div",{className:"tl-bookmark__container",style:{boxShadow:bw(s),maxHeight:t.props.h},children:[(!r||r.props.image)&&d.jsxs("div",{className:"tl-bookmark__image_container",children:[r?d.jsx("img",{className:"tl-bookmark__image",draggable:!1,referrerPolicy:"strict-origin-when-cross-origin",src:r==null?void 0:r.props.image,alt:(r==null?void 0:r.props.title)||""}):d.jsx("div",{className:"tl-bookmark__placeholder"}),(r==null?void 0:r.props.image)&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]}),d.jsxs("div",{className:"tl-bookmark__copy_container",children:[r!=null&&r.props.title?d.jsx("h2",{className:"tl-bookmark__heading",children:r.props.title}):null,r!=null&&r.props.description&&(r!=null&&r.props.image)?d.jsx("p",{className:"tl-bookmark__description",children:r.props.description}):null,d.jsxs("a",{className:"tl-bookmark__link",href:t.props.url||"",target:"_blank",rel:"noopener noreferrer",onPointerDown:Dt,onPointerUp:Dt,onClick:Dt,children:[r!=null&&r.props.favicon?d.jsx("img",{className:"tl-bookmark__favicon",src:r==null?void 0:r.props.favicon,referrerPolicy:"strict-origin-when-cross-origin",alt:`favicon of ${o}`}):d.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${CI}") center 100% / 100% no-repeat`,WebkitMask:`url("${CI}") center 100% / 100% no-repeat`}}),d.jsx("span",{children:o})]})]})]})})}indicator(t){return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:"6",ry:"6"})}}g(tp,"type","bookmark"),g(tp,"props",AT),g(tp,"migrations",jT);function II(e,n){const t=n.props.assetId?e.getAsset(n.props.assetId):null;let r=$A;return t&&(t.props.image||(t.props.title?r=QX:r=ZX)),{...n,props:{...n.props,h:r}}}const JX=e=>{try{return new URL(e.props.url).hostname.replace(/^www\./,"")}catch{return e.props.url}};function eq(e,n){const{url:t}=n.props,r=_i.createId(fv(t));e.getAsset(r)?n.props.assetId!==r&&e.updateShapes([{id:n.id,type:n.type,props:{assetId:r}}]):(e.updateShapes([{id:n.id,type:n.type,props:{assetId:null}}]),tq(e,n))}const tq=Y2(async(e,n)=>{if(e.isDisposed)return;const{url:t}=n.props,r=await e.getAssetForExternalContent({type:"url",url:t});r&&e.run(()=>{e.createAssets([r]),e.updateShapes([{id:n.id,type:n.type,props:{assetId:r.id}}])})},500);function Gi(e,n=!1){const t=e.length;if(t<2)return"";let r=e[0].point,s=e[1].point;if(t===2)return`M${ke(r)}L${ke(s)}`;let o="";for(let i=2,a=t-1;i3?"T":""}${o}L${ke(e[t-1].point)}`}function nq(e,n={}){const{start:t={},end:r={}}=n,{cap:s=!0}=t,{cap:o=!0}=r;Ye(!t.taper&&!r.taper,"cap taper not supported here"),Ye(!t.easing&&!r.easing,"cap easing not supported here"),Ye(s&&o,"cap must be true");const i=Ps(e,n);Sg(i,n);const a=rq(i);let l="";for(const c of a)l+=oq(c,n);return l}function rq(e){if(e.length<=2)return[e];const n=[];let t=[e[0]],r=b.Sub(e[1].point,e[0].point).uni(),s,o,i,a,l;for(let c=1,u=e.length;c.7)&&(b.Dist2(i.point,a.point)+b.Dist2(a.point,l.point))/((i.radius+a.radius+l.radius)/3)**2<1.5){t.push(a),n.push(xy(t)),t=[a];continue}}return t.push(e[e.length-1]),n.push(xy(t)),n}function xy(e){const n=e[0];let t;for(;e.length>2&&(t=e[1],b.Dist2(n.point,t.point)<((n.radius+t.radius)/2*.5)**2);)e.splice(1,1);const r=e[e.length-1];let s;for(;e.length>2&&(s=e[e.length-2],b.Dist2(r.point,s.point)<((r.radius+s.radius)/2*.5)**2);)e.splice(e.length-2,1);return e.length>1&&(e[0]={...e[0],vector:b.Sub(e[0].point,e[1].point).uni()},e[e.length-1]={...e[e.length-1],vector:b.Sub(e[e.length-2].point,e[e.length-1].point).uni()}),e}function sq(e,n,t){return"M "+e+" "+n+" m -"+t+", 0 a "+t+","+t+" 0 1,1 "+t*2+",0 a "+t+","+t+" 0 1,1 -"+t*2+",0"}function oq(e,n={}){if(e.length===0)return"";if(e.length===1)return sq(e[0].point.x,e[0].point.y,e[0].radius);const{left:t,right:r}=gA(e,n);r.reverse();let s=`M${ke(t[0])}T`;for(let o=1;oe*.65+EH(e*Me/2)*.35,aq=e=>({size:e,thinning:.5,streamline:pl(e,[9,16],[.64,.74],!0),smoothing:.62,easing:At.easeOutSine,simulatePressure:!0}),lq=e=>({size:1+e*1.2,thinning:.62,streamline:.62,smoothing:.62,simulatePressure:!1,easing:iq}),EI=e=>({size:e,thinning:0,streamline:pl(e,[9,16],[.64,.74],!0),smoothing:.62,simulatePressure:!1,easing:At.linear}),cq=e=>({size:e,thinning:0,streamline:.62,smoothing:.62,simulatePressure:!1,easing:At.linear});function Pw({strokeWidth:e,showAsComplete:n}){return{size:1+e,thinning:0,streamline:.5,smoothing:.5,simulatePressure:!1,easing:At.easeOutSine,last:n}}function Nv(e,n,t,r){const s=e.isComplete||t;return r?e.isPen?{...cq(n),last:s}:{...EI(n),last:s}:e.dash==="draw"?e.isPen?{...lq(n),last:s}:{...aq(n),last:s}:{...EI(n),last:s}}function Sl(e){const n=[];for(const t of e)if(t.type==="free"||t.points.length<2)n.push(...t.points.map(b.Cast));else{const r=Math.max(4,Math.floor(b.Dist(t.points[0],t.points[1])/16));n.push(...b.PointsBetween(t.points[0],t.points[1],r))}return n}function uq(e,n){return{draw:"none",solid:"none",dotted:`0.1 ${n*2}`,dashed:`${n*2} ${n*2}`}[e.props.dash]}class np extends Ir{constructor(){super(...arguments);g(this,"hideResizeHandles",t=>wy(t));g(this,"hideRotateHandle",t=>wy(t));g(this,"hideSelectionBoundsFg",t=>wy(t));g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=[];for(const a of t.props.segments)i.push({...a,points:a.points.map(({x:l,y:c,z:u})=>({x:zs(s*l),y:zs(o*c),z:u}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",fill:"none",dash:"draw",size:"m",isComplete:!1,isClosed:!1,isPen:!1,scale:1}}getGeometry(t){const r=Sl(t.props.segments),s=(jt[t.props.size]+1)*t.props.scale;if(t.props.segments.length===1){const i=Q.FromPoints(r);if(i.widthi.point);return t.props.isClosed?new at({points:o,isFilled:t.props.fill!=="none"}):new ia({points:o})}component(t){return d.jsx(bs,{id:t.id,children:d.jsx(_I,{shape:t,zoomLevel:this.editor.getZoomLevel()})})}indicator(t){var h;const r=Sl(t.props.segments);let s=(jt[t.props.size]+1)*t.props.scale;const o=this.editor.getZoomLevel();!(o<.5&&o<1.5/s)&&!t.props.isPen&&t.props.dash==="draw"&&r.length===1&&(s+=Yr(t.id)()*(s/6));const a=t.props.isComplete||((h=Ut(t.props.segments))==null?void 0:h.type)==="straight",l=Nv(t.props,s,a,!0),c=Ps(r,l),u=c.length>1?Gi(c,t.props.isClosed):NA(r[0],s);return d.jsx("path",{d:u})}toSvg(t,r){r.addExportDef(vw(t.props.fill));const s=1/t.props.scale;return d.jsx("g",{transform:`scale(${s})`,children:d.jsx(_I,{shape:t,zoomLevel:1})})}getCanvasSvgDefs(){return[xw()]}expandSelectionOutlinePx(t){const r=t.props.dash==="draw"?1.6:1;return jt[t.props.size]*r/2*t.props.scale}}g(np,"type","draw"),g(np,"props",DT),g(np,"migrations",RT);function NA(e,n){const t=(n+1)*.5;return`M ${e.x} ${e.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function wy(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function _I({shape:e,zoomLevel:n}){var h;const t=Ar(),r=Sl(e.props.segments),s=e.props.isComplete||((h=Ut(e.props.segments))==null?void 0:h.type)==="straight";let o=(jt[e.props.size]+1)*e.props.scale;const i=n<.5&&n<1.5/o;!i&&!e.props.isPen&&e.props.dash==="draw"&&r.length===1&&(o+=Yr(e.id)()*(o/6));const a=Nv(e.props,o,s,i);if(!i&&e.props.dash==="draw")return d.jsxs(d.Fragment,{children:[e.props.isClosed&&e.props.fill&&r.length>1?d.jsx(nn,{d:Gi(Ps(r,a),e.props.isClosed),theme:t,color:e.props.color,fill:e.props.isClosed?e.props.fill:"none",scale:e.props.scale}):null,d.jsx("path",{d:nq(r,a),strokeLinecap:"round",fill:t[e.props.color].solid})]});const l=Ps(r,a),c=l.length<2,u=c?NA(r[0],0):Gi(l,e.props.isClosed);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{d:u,theme:t,color:e.props.color,fill:c||e.props.isClosed?e.props.fill:"none",scale:e.props.scale}),d.jsx("path",{d:u,strokeLinecap:"round",fill:c?t[e.props.color].solid:"none",stroke:t[e.props.color].solid,strokeWidth:o,strokeDasharray:c?"none":uq(e,o),strokeDashoffset:"0"})]})}function dq(e,n,t={}){const{newPoint:r,handle:s,scaleX:o,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=t;let h=e.props.w*o,p=e.props.h*i;const f=new b(0,0);if(h>0){if(h0){if(pObject.entries(e).filter(([n,t])=>t).map(([n])=>n).join(" ");class rp extends Ol{constructor(){super(...arguments);g(this,"hideSelectionBoundsFg",t=>!this.canResize(t));g(this,"canEdit",()=>!0);g(this,"canResize",t=>{var r,s;return!!((s=(r=Do(t.props.url))==null?void 0:r.definition)!=null&&s.doesResize)});g(this,"canEditInReadOnly",()=>!0);g(this,"isAspectRatioLocked",t=>{const r=Do(t.props.url);return(r==null?void 0:r.definition.isAspectRatioLocked)??!1});g(this,"onResize",(t,r)=>{const s=this.isAspectRatioLocked(t),o=Do(t.props.url);let i=(o==null?void 0:o.definition.minWidth)??200,a=(o==null?void 0:o.definition.minHeight)??200;if(s){const l=t.props.w/t.props.h;l>1?i*=l:a/=l}return dq(t,r,{minWidth:i,minHeight:a})})}getDefaultProps(){return{w:300,h:300,url:""}}component(t){const{w:r,h:s,url:o}=t.props,i=mg(t.id),a=P.useMemo(()=>xA(o),[o]),l=H("is hovering",()=>{const{editingShapeId:f,hoveredShapeId:S}=this.editor.getCurrentPageState();if(f&&S!==f){const y=this.editor.getShape(f);if(y&&this.editor.isShapeOfType(y,"embed"))return!0}return!1},[]),c=this.editor.getShapePageTransform(t).rotation(),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 d.jsx(Wi,{className:"tl-embed-container",id:t.id,children:d.jsx(pq,{id:f,width:N(r),height:N(s),isInteractive:u,pageRotation:c})})}const p=hq({...lH,...(a==null?void 0:a.definition.overridePermissions)??{}});return d.jsx(Wi,{className:"tl-embed-container",id:t.id,children:a!=null&&a.definition?d.jsx("iframe",{className:"tl-embed",sandbox:p,src:a.embedUrl,width:N(r),height:N(s),draggable:!1,frameBorder:"0",referrerPolicy:"no-referrer-when-downgrade",style:{border:0,pointerEvents:u?"auto":"none",zIndex:u?"":"-1",boxShadow:bw(c),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:a==null?void 0:a.definition.backgroundColor}}):null})}indicator(t){const r=P.useMemo(()=>Do(t.props.url),[t.props.url]);return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:(r==null?void 0:r.definition.overrideOutlineRadius)??8,ry:(r==null?void 0:r.definition.overrideOutlineRadius)??8})}}g(rp,"type","embed"),g(rp,"props",LT),g(rp,"migrations",$T);function pq({id:e,file:n,isInteractive:t,width:r,height:s,style:o,pageRotation:i}){return d.jsx("iframe",{className:"tl-embed",draggable:!1,width:N(r),height:N(s),frameBorder:"0",scrolling:"no",seamless:!0,referrerPolicy:"no-referrer-when-downgrade",style:{...o,pointerEvents:t?"all":"none",zIndex:t?"":"-1",boxShadow:bw(i)},srcDoc:` @@ -215,9 +215,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho .gist .gist-file { height: calc(100vh - 2px); padding: 0px; display: grid; grid-template-rows: 1fr auto; } - `})}const fq=P.forwardRef(({id:e,name:n,isEditing:t},r)=>{const s=F(),o=P.useCallback(l=>{l.key==="Enter"&&!l.nativeEvent.isComposing&&(Dt(l),l.currentTarget.blur(),s.setEditingShape(null))},[s]),i=P.useCallback(l=>{const c=s.getShape(e);if(!c)return;const u=c.props.name,h=l.currentTarget.value.trim();u!==h&&s.updateShapes([{id:e,type:"frame",props:{name:h}}])},[e,s]),a=P.useCallback(l=>{const c=s.getShape(e);if(!c)return;const u=c.props.name,h=l.currentTarget.value;u!==h&&s.updateShapes([{id:e,type:"frame",props:{name:h}}])},[e,s]);return d.jsxs("div",{className:`tl-frame-label ${t?"tl-frame-label__editing":""}`,children:[d.jsx("input",{className:"tl-frame-name-input",ref:r,style:{display:t?void 0:"none"},value:n,autoFocus:!0,onKeyDown:o,onBlur:i,onChange:a}),FA(n,"Frame")+"​"]})}),gq=function({id:n,name:t,width:r,height:s}){const o=F(),i=H("shape rotation",()=>Go(o.getShapePageTransform(n).rotation()),[o,n]),a=mg(n),l=P.useRef(null),c=P.useCallback(S=>{const m=Nn(S);S.preventDefault(),o.getEditingShapeId()!==n&&o.dispatch({type:"pointer",name:"pointer_down",target:"shape",shape:o.getShape(n),...m})},[o,n]);P.useEffect(()=>{const S=l.current;S&&a&&(S.focus(),S.select())},[l,a]);const h=((i+Math.PI/4)*(2/Math.PI)+4)%4,p=["top","left","bottom","right"][Math.floor(h)];let f;switch(p){case"top":f="";break;case"right":f=`translate(${N(r)}px, 0px) rotate(90deg)`;break;case"bottom":f=`translate(${N(r)}px, ${N(s)}px) rotate(180deg)`;break;case"left":f=`translate(0px, ${N(s)}px) rotate(270deg)`;break}return d.jsx("div",{className:"tl-frame-heading",style:{overflow:a?"visible":"hidden",maxWidth:`calc(var(--tl-zoom) * ${Math.ceil(p==="top"||p==="bottom"?r:s)}px + var(--space-5))`,bottom:"100%",transform:`${f} scale(var(--tl-scale)) translateX(calc(-1 * var(--space-3))`},onPointerDown:c,children:d.jsx("div",{className:"tl-frame-heading-hit-area",children:d.jsx(fq,{ref:l,id:n,name:t,isEditing:a})})})};function FA(e,n){return e.match(/^\s*$/)?n:e}class sp extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"canReceiveNewChildrenOfType",(t,r)=>!t.isLocked);g(this,"canDropShapes",(t,r)=>!t.isLocked);g(this,"onDragShapesOver",(t,r)=>{r.every(s=>s.parentId===t.id)||this.editor.reparentShapes(r,t.id)});g(this,"onDragShapesOut",(t,r)=>{const s=this.editor.getShape(t.parentId);s&&this.editor.isShapeOfType(s,"group")?this.editor.reparentShapes(r,s.id):this.editor.reparentShapes(r,this.editor.getCurrentPageId())});g(this,"onResize",(t,r)=>fw(t,r))}getDefaultProps(){return{w:160*2,h:90*2,name:""}}getGeometry(t){return new no({width:t.props.w,height:t.props.h,isFilled:!1})}component(t){const r=this.editor.getShapeGeometry(t).bounds,s=Ar(),o=H("is creating this shape",()=>{const i=this.editor.getStateDescendant("select.resizing");if(!i||!i.getIsActive())return!1;const a=i==null?void 0:i.info;return a?a.isCreating&&this.editor.getOnlySelectedShapeId()===t.id:!1},[t.id]);return d.jsxs(d.Fragment,{children:[d.jsx(bs,{children:d.jsx("rect",{className:le("tl-frame__body",{"tl-frame__creating":o}),width:r.width,height:r.height,fill:s.solid,stroke:s.text})}),o?null:d.jsx(gq,{id:t.id,name:t.props.name,width:r.width,height:r.height})]})}toSvg(t,r){const s=lo({isDarkMode:r.isDarkMode}),a=((Go(this.editor.getShapePageTransform(t.id).rotation())+Math.PI/4)*(2/Math.PI)+4)%4,l=Math.floor(a);let c;switch(l){case 0:c="";break;case 3:c=`translate(${N(t.props.w)}, 0) rotate(90)`;break;case 2:c=`translate(${N(t.props.w)}, ${N(t.props.h)}) rotate(180)`;break;case 1:c=`translate(0, ${N(t.props.h)}) rotate(270)`;break;default:throw Error("labelSide out of bounds")}const u={fontSize:12,fontFamily:"Inter, sans-serif",textAlign:"start",width:t.props.w,height:32,padding:0,lineHeight:1,fontStyle:"normal",fontWeight:"normal",overflow:"truncate-ellipsis",verticalTextAlign:"middle"},h=this.editor.textMeasure.measureTextSpans(FA(t.props.name,"Frame")+"​",u),p=h[0],f=Ut(h),S=f.box.w+f.box.x-p.box.x,m=Lv(this.editor,h,{offsetY:-u.height-2,...u});return d.jsxs(d.Fragment,{children:[d.jsx("rect",{width:t.props.w,height:t.props.h,fill:s.solid,stroke:s.black.solid,strokeWidth:1,rx:1,ry:1}),d.jsxs("g",{transform:c,children:[d.jsx("rect",{x:-8,y:-u.height-4,width:S+16,height:u.height,fill:s.background,rx:4,ry:4}),m]})]})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds;return d.jsx("rect",{width:N(r.width),height:N(r.height),className:"tl-frame-indicator"})}providesBackgroundForChildren(){return!0}}g(sp,"type","frame"),g(sp,"props",NT),g(sp,"migrations",FT);function kI(e,n){return e>n?(Me*(n/2)+(e-n))*2:(Me*(e/2)+(n-e))*2}function zA(e,n){return Cw(e,n).map((t,r)=>t.getSvgPathData(r===0)).join(" ")+" Z"}function mq(e,n,t,r){const s=e/4,o=n/4,i=Yr(r),a=t*.75,l=v=>v.addXY(i()*a,i()*a),c=new b(e/2,n),u=new b(0,o*1.2),h=new b(e/2,o*.9),p=new b(e,o*1.2),f=l(new b(e/2,n)),S=l(new b(0,o*1.2)),m=l(new b(e/2,o*.9)),x=l(new b(e,o*1.2));return[new sn({start:c,cp1:new b(s*1.5,o*3),cp2:new b(0,o*2.5),end:u}),new sn({start:u,cp1:new b(0,-o*.32),cp2:new b(s*1.85,-o*.32),end:h}),new sn({start:h,cp1:new b(s*2.15,-o*.32),cp2:new b(e,-o*.32),end:p}),new sn({start:p,cp1:new b(e,o*2.5),cp2:new b(s*2.5,o*3),end:f}),new sn({start:f,cp1:new b(s*1.5,o*3),cp2:new b(0,o*2.5),end:S}),new sn({start:S,cp1:new b(0,-o*.32),cp2:new b(s*1.85,-o*.32),end:m}),new sn({start:m,cp1:new b(s*2.15,-o*.32),cp2:new b(e,-o*.32),end:x}),new sn({start:x,cp1:new b(e,o*2.5),cp2:new b(s*2.5,o*3),end:c})].map((v,w)=>v.getSvgPathData(w===0)).join(" ")+" Z"}function Cw(e,n){const t=e/4,r=n/4;return[new sn({start:new b(e/2,n),cp1:new b(t*1.5,r*3),cp2:new b(0,r*2.5),end:new b(0,r*1.2)}),new sn({start:new b(0,r*1.2),cp1:new b(0,-r*.32),cp2:new b(t*1.85,-r*.32),end:new b(e/2,r*.9)}),new sn({start:new b(e/2,r*.9),cp1:new b(t*2.15,-r*.32),cp2:new b(e,-r*.32),end:new b(e,r*1.2)}),new sn({start:new b(e,r*1.2),cp1:new b(e,r*2.5),cp2:new b(t*2.5,r*3),end:new b(e/2,n)})]}function yq(e){return{size:1+e,thinning:.25,end:{taper:e},start:{taper:e},streamline:0,smoothing:1,simulatePressure:!1}}function Sq(e,n,t,r){const s=Yr(e),o=n/2,i=t/2,a=oM(o,i),l=[],c=Le*s(),u=Le+Ve/2+Math.abs(s())*Ve,h=Math.max(16,a/10);for(let p=0;p0?At.easeInOutSine(f):At.easeInExpo(f)))/2)))}return Ps(l,yq(r))}function vq(e,n,t,r){return Gi(Sq(e,n,t,r))}function Fv(e){let n="M";const t=e.length;let r,s,o;for(let i=0,a=t;in?[{type:"straight",start:new b(r,0),delta:new b(1,0)},{type:"arc",center:new b(e-r,r),startAngle:-Me/2},{type:"straight",start:new b(e-r,n),delta:new b(-1,0)},{type:"arc",center:new b(r,r),startAngle:Me/2}]:[{type:"straight",start:new b(e,r),delta:new b(0,1)},{type:"arc",center:new b(r,n-r),startAngle:0},{type:"straight",start:new b(0,n-r),delta:new b(0,-1)},{type:"arc",center:new b(r,r),startAngle:Me}];let l=0;const c=[];for(let u=0;up;)l-=p,a.push(a.shift()),p=a[0].type==="straight"?s:Me*r}return c}const wq={s:50,m:70,l:100,xl:130},bq=.2;function Pg(e,n,t,r){const s=Yr(t),o=kI(e,n),i=Math.max(Math.ceil(o/wq[r]),6,Math.ceil(o/Math.min(e,n))),a=o/i*bq,l=Math.max(e-a*2,1),c=Math.max(n-a*2,1),h=kI(l,c)/i,p=(e-l)/2,f=(n-c)/2,S=xq(l,c,i).map(w=>w.addXY(p,f)),m=e<20?0:a*.3,x=n<20?0:a*.3,y=S.slice(0);for(let w=0;we&&(O.x=e),O.y<0?O.y=0:O.y>n&&(O.y=n);const R=Q0(E,k,O),K=b.Dist(R||b.Average([E,k]),E);v.push({leftPoint:E,rightPoint:k,arcPoint:O,center:R,radius:K})}return v}function Pq(e,n,t,r){const s=[],o=Pg(e,n,t,r);for(const{center:i,radius:a,leftPoint:l,rightPoint:c}of o)s.push(...MH(l,c,i,a,10));return s}function Bv(e,n,t,r){const s=Pg(e,n,t,r);let o=`M${s[0].leftPoint.toFixed()}`;for(const{leftPoint:i,rightPoint:a,radius:l,center:c}of s){if(c===null){o+=` L${a.toFixed()}`;continue}const u=b.Clockwise(i,a,c)?"0":"1";o+=` A${N(l)},${N(l)} 0 ${u},1 ${a.toFixed()}`}return o+=" Z",o}const Cq={s:.5,m:.7,l:.9,xl:1.6};function Iq(e,n,t,r){const s=Yr(t),o=Cq[r],i=Pg(e,n,t,r),c=i.reduce((f,S)=>f+b.Dist2(S.leftPoint,S.rightPoint),0)/i.length>(o*15)**2?f=>f.addXY(s()*o*2,s()*o*2):f=>f;let u=`M${i[0].leftPoint.toFixed()}`,h=c(i[0].leftPoint),p=`M${h.toFixed()}`;for(const{leftPoint:f,center:S,rightPoint:m,radius:x,arcPoint:y}of i){if(S===null){u+=` L${m.toFixed()}`;const I=c(m);p+=` L${I.toFixed()}`,h=I;continue}const v=b.Clockwise(f,m,S)?"0":"1";u+=` A${N(x)},${N(x)} 0 ${v},1 ${m.toFixed()}`;const w=c(m),C=c(y),E=Q0(h,w,C);if(!Number.isFinite(E.x)||!Number.isFinite(E.y)){p+=` L${w.toFixed()}`,h=w;continue}const k=Math.abs(b.Dist(E,h));p+=` A${N(k)},${N(k)} 0 ${v},1 ${w.toFixed()}`,h=w}return u+p+" Z"}function Uv(e,n){switch(e.geo){case"x-box":return Eq(e.w,e.h,n,e.dash);case"check-box":return _q(e.w,e.h);default:return}}function Eq(e,n,t,r){const s=r==="draw"?.62:0;if(r==="dashed")return[[new b(0,0),new b(e/2,n/2)],[new b(e,n),new b(e/2,n/2)],[new b(0,n),new b(e/2,n/2)],[new b(e,0),new b(e/2,n/2)]];const o=a=>Math.max(0,Math.min(e,a)),i=a=>Math.max(0,Math.min(n,a));return[[new b(o(t*s),i(t*s)),new b(o(e-t*s),i(n-t*s))],[new b(o(t*s),i(n-t*s)),new b(o(e-t*s),i(t*s))]]}function _q(e,n){const t=Math.min(e,n)*.82,r=(e-t)/2,s=(n-t)/2,o=a=>Math.max(0,Math.min(e,a)),i=a=>Math.max(0,Math.min(n,a));return[[new b(o(r+t*.25),i(s+t*.52)),new b(o(r+t*.45),i(s+t*.82))],[new b(o(r+t*.45),i(s+t*.82)),new b(o(r+t*.82),i(s+t*.22))]]}function TI({shape:e,shouldScale:n}){const t=n?e.props.scale:1,r=F(),s=Ar(),{id:o,props:i}=e,{w:a,color:l,fill:c,dash:u,growY:h,size:p}=i,f=jt[p]*t,S=i.h+h;switch(i.geo){case"cloud":if(u==="solid"){const m=Bv(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:m,color:l,fill:c,scale:t}),d.jsx("path",{d:m,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else if(u==="draw"){const m=Iq(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:m,color:l,fill:c,scale:t}),d.jsx("path",{d:m,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else{const m=Bv(a,S,o,p),x=Pg(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:m,color:l,fill:c,scale:t}),d.jsx("g",{strokeWidth:f,stroke:s[l].solid,fill:"none",pointerEvents:"all",children:x.map(({leftPoint:y,rightPoint:v,center:w,radius:C},E)=>{const k=w?C*Go(Go(b.Angle(w,v))-Go(b.Angle(w,y))):b.Dist(y,v),{strokeDasharray:I,strokeDashoffset:_}=os(k,f,{style:u,start:"outset",end:"outset"});return d.jsx("path",{d:w?`M${y.x},${y.y}A${C},${C},0,0,1,${v.x},${v.y}`:`M${y.x},${y.y}L${v.x},${v.y}`,strokeDasharray:I,strokeDashoffset:_},E)})})]})}case"ellipse":{const m=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=m.getSvgPathData(!0);if(u==="dashed"||u==="dotted"){const y=m.length,{strokeDasharray:v,strokeDashoffset:w}=os(y<64?y*2:y,f,{style:u,snap:4,closed:!0});return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:v,strokeDashoffset:w})]})}else{const v=(n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e)).getSvgPathData(!0);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}}case"oval":{const m=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=m.getSvgPathData(!0);if(u==="dashed"||u==="dotted"){const y=m.getLength(),{strokeDasharray:v,strokeDashoffset:w}=os(y<64?y*2:y,f,{style:u,snap:4,start:"outset",end:"outset",closed:!0});return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:v,strokeDashoffset:w})]})}else return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}case"heart":if(u==="dashed"||u==="dotted"||u==="solid"){const m=zA(a,S),x=Cw(a,S);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:m,color:l,fill:c,scale:t}),x.map((y,v)=>{const{strokeDasharray:w,strokeDashoffset:C}=os(y.length,f,{style:u,snap:1,start:"outset",end:"outset",closed:!0});return d.jsx("path",{d:y.getSvgPathData(),strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:w,strokeDashoffset:C,pointerEvents:"all"},`curve_${v}`)})]})}else{const m=mq(a,S,f,e.id);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:m,color:l,fill:c,scale:t}),d.jsx("path",{d:m,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}default:{const m=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=m instanceof Wr?m.children[0].vertices:m.vertices,y=Uv(e.props,f);if(u==="solid"){let v="M"+x[0]+"L"+x.slice(1)+"Z";if(y)for(const[w,C]of y)v+=`M${w.x},${w.y}L${C.x},${C.y}`;return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else if(u==="dashed"||u==="dotted"){const v="M"+x[0]+"L"+x.slice(1)+"Z";return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsxs("g",{strokeWidth:f,stroke:s[l].solid,fill:"none",pointerEvents:"all",children:[Array.from(Array(x.length)).map((w,C)=>{const E=b.ToFixed(x[C]),k=b.ToFixed(x[(C+1)%x.length]),I=b.Dist(E,k),{strokeDasharray:_,strokeDashoffset:T}=os(I,f,{style:u,start:"outset",end:"outset"});return d.jsx("line",{x1:E.x,y1:E.y,x2:k.x,y2:k.y,strokeDasharray:_,strokeDashoffset:T},C)}),y&&y.map(([w,C],E)=>{const k=b.Dist(w,C),{strokeDasharray:I,strokeDashoffset:_}=os(k,f,{style:u,start:"skip",end:"skip",snap:u==="dotted"?4:void 0});return d.jsx("path",{d:`M${w.x},${w.y}L${C.x},${C.y}`,stroke:s[l].solid,strokeWidth:f,fill:"none",strokeDasharray:I,strokeDashoffset:_},`line_fg_${E}`)})]})]})}else if(u==="draw"){let v=Fv(zv(o,x,f/3,f*2,2));if(y)for(const[C,E]of y)v+=`M${C.toFixed()}L${E.toFixed()}`;const w=Fv(zv(o,x,0,f*2,1));return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:w,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}}}}const MI=17*3;class op extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])});g(this,"onResize",(t,{handle:r,newPoint:s,scaleX:o,scaleY:i,initialShape:a})=>{const l=a.props.w/a.props.scale,c=a.props.h/a.props.scale,u=a.props.growY/a.props.scale;let h=l*o,p=(c+u)*i,f=0,S=0;const m=MI;if(t.props.text.trim()){let E=Math.max(Math.abs(h),m),k=Math.max(Math.abs(p),m);E{if(!t.props.text)return t.props.growY?{...t,props:{...t.props,growY:0}}:void 0;const r=t.props.h/t.props.scale,s=sh(this.editor,t).h;let o=null;if(s>r?o=s-r:t.props.growY&&(o=0),o!==null)return{...t,props:{...t.props,growY:o*t.props.scale}}});g(this,"onBeforeUpdate",(t,r)=>{const s=t.props.text,o=r.props.text;if(s===o&&t.props.font===r.props.font&&t.props.size===r.props.size)return;if(s&&!o)return{...r,props:{...r.props,growY:0}};const i=t.props.w/t.props.scale,a=t.props.h/t.props.scale,l=t.props.growY/t.props.scale,c=sh(this.editor,r);if(!s&&o&&o.length===1){let h=Math.max(i,c.w),p=Math.max(a,c.h);const f=MI;return ia?u=c.h-a:l&&(u=0),u!==null){const h=r.props.w/r.props.scale;return{...r,props:{...r.props,growY:u*r.props.scale,w:Math.max(h,c.w)*r.props.scale}}}if(c.w>i)return{...r,props:{...r.props,w:c.w*r.props.scale}}});g(this,"onDoubleClick",t=>{if(this.editor.inputs.altKey)switch(t.props.geo){case"rectangle":return{...t,props:{geo:"check-box"}};case"check-box":return{...t,props:{geo:"rectangle"}}}})}getDefaultProps(){return{w:100,h:100,geo:"rectangle",color:"black",labelColor:"black",fill:"none",dash:"draw",size:"m",font:"draw",text:"",align:"middle",verticalAlign:"middle",growY:0,url:"",scale:1}}getGeometry(t){const r=Math.max(1,t.props.w),s=Math.max(1,t.props.h+t.props.growY),o=r/2,i=s/2,a=t.props.fill!=="none";let l;switch(t.props.geo){case"cloud":{l=new at({points:Pq(r,s,t.id,t.props.size),isFilled:a});break}case"triangle":{l=new at({points:[new b(o,0),new b(r,s),new b(0,s)],isFilled:a});break}case"diamond":{l=new at({points:[new b(o,0),new b(r,i),new b(o,s),new b(0,i)],isFilled:a});break}case"pentagon":{l=new at({points:ey(r,s,5),isFilled:a});break}case"hexagon":{l=new at({points:ey(r,s,6),isFilled:a});break}case"octagon":{l=new at({points:ey(r,s,8),isFilled:a});break}case"ellipse":{l=new oY({width:r,height:s,isFilled:a});break}case"oval":{l=new iY({width:r,height:s,isFilled:a});break}case"star":{const w=Le/5/2,C=Math.floor(5/4)*2,E=5*2-C,k=0,I=Math.floor(5/2)*2,_=Math.cos(-Ve+C*w)*r/2,T=Math.cos(-Ve+E*w)*r/2,M=Math.sin(-Ve+k*w)*s/2,D=Math.sin(-Ve+I*w)*s/2,$=r-Math.abs(_-T),j=s-Math.abs(D-M),O=r/2+T-(r/2-_),R=s/2+M-(s/2-D),K=1,B=(r-O)/2,z=(s-R)/2,W=(r+$)/2,Y=(s+j)/2,q=W*K/2,ae=Y*K/2;l=new at({points:Array.from(Array(5*2)).map((fe,we)=>{const J=-Ve+we*w;return new b(B+(we%2?q:W)*Math.cos(J),z+(we%2?ae:Y)*Math.sin(J))}),isFilled:a});break}case"rhombus":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(v,0),new b(r,0),new b(r-v,s),new b(0,s)],isFilled:a});break}case"rhombus-2":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(0,0),new b(r-v,0),new b(r,s),new b(v,s)],isFilled:a});break}case"trapezoid":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(v,0),new b(r-v,0),new b(r,s),new b(0,s)],isFilled:a});break}case"arrow-right":{const v=Math.min(r,s)*.38,w=s*.16;l=new at({points:[new b(0,w),new b(r-v,w),new b(r-v,0),new b(r,s/2),new b(r-v,s),new b(r-v,s-w),new b(0,s-w)],isFilled:a});break}case"arrow-left":{const v=Math.min(r,s)*.38,w=s*.16;l=new at({points:[new b(v,0),new b(v,w),new b(r,w),new b(r,s-w),new b(v,s-w),new b(v,s),new b(0,s/2)],isFilled:a});break}case"arrow-up":{const v=r*.16,w=Math.min(r,s)*.38;l=new at({points:[new b(r/2,0),new b(r,w),new b(r-v,w),new b(r-v,s),new b(v,s),new b(v,w),new b(0,w)],isFilled:a});break}case"arrow-down":{const v=r*.16,w=Math.min(r,s)*.38;l=new at({points:[new b(v,0),new b(r-v,0),new b(r-v,s-w),new b(r,s-w),new b(r/2,s),new b(0,s-w),new b(v,s-w)],isFilled:a});break}case"check-box":case"x-box":case"rectangle":{l=new no({width:r,height:s,isFilled:a});break}case"heart":{const w=Cw(r,s).reduce((C,E)=>(C.push(...E.vertices),C),[]);l=new at({points:w,isFilled:a});break}default:cn(t.props.geo)}const c=sh(this.editor,t),u=r/t.props.scale,h=s/t.props.scale,p=Math.min(100,u/2),f=Math.min(Ys[t.props.size]*Gt.lineHeight+yr*2,h/2),S=Math.min(u,Math.max(c.w,Math.min(p,Math.max(1,u-8)))),m=Math.min(h,Math.max(c.h,Math.min(f,Math.max(1,h-8)))),x=Uv(t.props,jt[t.props.size]*t.props.scale),y=x?x.map(v=>new ia({points:v})):[];return new Wr({children:[l,new no({x:t.props.align==="start"?0:t.props.align==="end"?(u-S)*t.props.scale:(u-S)/2*t.props.scale,y:t.props.verticalAlign==="start"?0:t.props.verticalAlign==="end"?(h-m)*t.props.scale:(h-m)/2*t.props.scale,width:S*t.props.scale,height:m*t.props.scale,isFilled:!0,isLabel:!0}),...y]})}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.getVertices(),r.bounds.center]};case"cloud":case"ellipse":case"heart":case"oval":return{outline:s,points:[r.bounds.center]};default:cn(t.props.geo)}}component(t){const{id:r,type:s,props:o}=t,{fill:i,font:a,align:l,verticalAlign:c,size:u,text:h}=o,p=Ar(),f=this.editor.getEditingShapeId()!==null,S=H("isGeoOnlySelected",()=>t.id===this.editor.getOnlySelectedShapeId(),[]),m=f||t.props.text;return d.jsxs(d.Fragment,{children:[d.jsx(bs,{id:r,children:d.jsx(TI,{shape:t,shouldScale:!0})}),m&&d.jsx(Wi,{style:{overflow:"hidden",width:t.props.w,height:t.props.h+o.growY},children:d.jsx(bg,{id:r,type:s,font:a,fontSize:Ys[u]*t.props.scale,lineHeight:Gt.lineHeight,padding:yr*t.props.scale,fill:i,align:l,verticalAlign:c,text:h,isSelected:S,labelColor:p[o.labelColor].solid,wrap:!0})}),t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){const{id:r,props:s}=t,{w:o,size:i}=s,a=s.h+s.growY,l=jt[i],c=this.editor.getShapeGeometry(t);switch(s.geo){case"ellipse":return s.dash==="draw"?d.jsx("path",{d:vq(r,o,a,l)}):d.jsx("path",{d:c.getSvgPathData(!0)});case"heart":return d.jsx("path",{d:zA(o,a)});case"oval":return d.jsx("path",{d:c.getSvgPathData(!0)});case"cloud":return d.jsx("path",{d:Bv(o,a,r,i)});default:{const u=this.editor.getShapeGeometry(t),h=u instanceof Wr?u.children[0].vertices:u.vertices;let p;if(s.dash==="draw"){const S=zv(r,h,0,l*2*t.props.scale,1);p=Fv(S)}else p="M"+h[0]+"L"+h.slice(1)+"Z";const f=Uv(t.props,l);if(f)for(const[S,m]of f)p+=`M${S.x},${S.y}L${m.x},${m.y}`;return d.jsx("path",{d:p})}}}toSvg(t,r){const s={...t,props:{...t.props,w:t.props.w/t.props.scale,h:t.props.h/t.props.scale}},o=s.props;r.addExportDef(vw(o.fill));let i;if(o.text){r.addExportDef(xg(o.font));const a=lo(r),l=new Q(0,0,o.w,o.h+o.growY);i=d.jsx(wg,{fontSize:Ys[o.size],font:o.font,align:o.align,verticalAlign:o.verticalAlign,text:o.text,labelColor:a[o.labelColor].solid,bounds:l,padding:16})}return d.jsxs(d.Fragment,{children:[d.jsx(TI,{shouldScale:!1,shape:s}),i]})}getCanvasSvgDefs(){return[xw()]}}g(op,"type","geo"),g(op,"props",zT),g(op,"migrations",BT);function sh(e,n){const{text:t,font:r,size:s,w:o}=n.props;if(!t)return{w:0,h:0};const i=e.textMeasure.measureText("w",{...Gt,fontFamily:Ss[r],fontSize:Ys[s],maxWidth:100}),a={s:2,m:3.5,l:5,xl:10},l=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[r],fontSize:Ys[s],minWidth:i.w,maxWidth:Math.max(0,Math.ceil(i.w+a[s]),Math.ceil(o/n.props.scale-yr*2))});return{w:l.w+yr*2,h:l.h+yr*2}}function kq(){const[e,n]=P.useState(!1);return P.useEffect(()=>{const r=CSS.supports("color","color(display-p3 1 1 1)"),s=matchMedia("(color-gamut: p3)");n(r&&s.matches);const o=()=>n(r&&s.matches);return s.addEventListener("change",o),()=>s.removeEventListener("change",o)},[]),H(xt.forceSrgb)||!e?"srgb":"p3"}const AI=.35,jI=.82;class ip extends Ir{constructor(){super(...arguments);g(this,"hideResizeHandles",t=>oh(t));g(this,"hideRotateHandle",t=>oh(t));g(this,"hideSelectionBoundsFg",t=>oh(t));g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=[];for(const a of t.props.segments)i.push({...a,points:a.points.map(({x:l,y:c,z:u})=>({x:s*l,y:o*c,z:u}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",size:"m",isComplete:!1,isPen:!1,scale:1}}getGeometry(t){const r=Pi(t);if(oh(t))return new yg({x:-r/2,y:-r/2,radius:r/2,isFilled:!0});const{strokePoints:s,sw:o}=OI(t,r,!0),i=Pw({strokeWidth:o,showAsComplete:!0});return Sg(s,i),new at({points:mw(s,i),isFilled:!0})}component(t){const r=by(this.editor,t),s=Pi(t);return d.jsx(bs,{id:t.id,children:d.jsx(ih,{shape:t,forceSolid:r,strokeWidth:s,opacity:AI})})}backgroundComponent(t){const r=by(this.editor,t),s=Pi(t);return d.jsx(bs,{id:t.id,children:d.jsx(ih,{shape:t,forceSolid:r,strokeWidth:s,opacity:jI})})}indicator(t){const r=by(this.editor,t),s=Pi(t),{strokePoints:o,sw:i}=OI(t,s,r),a=Sl(t.props.segments);let l;return o.length<2?l=Mq(a[0],i):l=Gi(o,!1),d.jsx("path",{d:l})}toSvg(t){const r=Pi(t),s=r<1.5,o=1/t.props.scale;return d.jsx("g",{transform:`scale(${o})`,children:d.jsx(ih,{forceSolid:s,strokeWidth:r,shape:t,opacity:AI})})}toBackgroundSvg(t){const r=Pi(t),s=r<1.5,o=1/t.props.scale;return d.jsx("g",{transform:`scale(${o})`,children:d.jsx(ih,{forceSolid:s,strokeWidth:r,shape:t,opacity:jI})})}}g(ip,"type","highlight"),g(ip,"props",KT),g(ip,"migrations",WT);function Tq(e){return`M ${e.x} ${e.y} m -${.1}, 0 a ${.1},${.1} 0 1,0 ${.1*2},0 a ${.1},${.1} 0 1,0 -${.1*2},0`}function Mq(e,n){const t=n/2;return`M ${e.x} ${e.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function OI(e,n,t){var l;const r=Sl(e.props.segments),s=e.props.isComplete||((l=Ut(e.props.segments))==null?void 0:l.type)==="straight";let o=n;!t&&!e.props.isPen&&r.length===1&&(o+=Yr(e.id)()*(n/6));const i=Pw({strokeWidth:o,showAsComplete:s});return{strokePoints:Ps(r,i),sw:o}}function Pi(e){return gl[e.props.size]*1.12*e.props.scale}function oh(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function ih({strokeWidth:e,forceSolid:n,shape:t,opacity:r}){var p;const s=Ar(),o=Sl(t.props.segments);let i=e;!n&&!t.props.isPen&&o.length===1&&(i+=Yr(t.id)()*(i/6));const a=Pw({strokeWidth:i,showAsComplete:t.props.isComplete||((p=Ut(t.props.segments))==null?void 0:p.type)==="straight"}),l=Ps(o,a),c=l.length>1?Gi(l,!1):Tq(t.props.segments[0].points[0]),u=kq(),h=s[t.props.color].highlight[u];return d.jsx("path",{d:c,strokeLinecap:"round",fill:"none",pointerEvents:"all",stroke:h,strokeWidth:i,opacity:r})}function by(e,n){return H("forceSolid",()=>{const t=Pi(n),r=e.getZoomLevel();return t/r<1.5},[e])}function BA(){return d.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:[d.jsx("path",{d:"M3,11 L3,3 11,3",strokeWidth:"2"}),d.jsx("path",{d:"M19,27 L27,27 L27,19",strokeWidth:"2"}),d.jsx("path",{d:"M27,3 L3,27",strokeWidth:"2"})]})}function UA(e,n,t){const r=F(),[s,o]=P.useState(null),i=n?r.getAsset(n):null,l=r.getCulledShapes().has(e),c=P.useRef(!1);P.useEffect(()=>{s&&(c.current=!0)},[s]);const u=i&&"w"in i.props?t/i.props.w:1,h=H("zoom level",()=>r.getZoomLevel()*u,[r,u]);return P.useEffect(()=>{if(l)return;let p=!1;const f=r.timers.setTimeout(async()=>{const S=await r.resolveAssetUrl(n,{screenScale:h});p||o(S)},c.current?500:0);return()=>{clearTimeout(f),p=!0}},[n,i==null?void 0:i.props.src,l,h,r]),{asset:i,url:s}}function HA(){const[e,n]=P.useState(!1);return P.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const t=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{n(t.matches)};return r(),t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[]),e}async function Aq(e){const t=await(await vs(e)).blob();return ji.blobToDataUrl(t)}class ap extends Ol{constructor(){super(...arguments);g(this,"isAspectRatioLocked",()=>!0);g(this,"canCrop",()=>!0);g(this,"onResize",(t,r)=>{let s=fw(t,r);const{flipX:o,flipY:i}=r.initialShape.props;return s={...s,props:{...s.props,flipX:r.scaleX<0!==o,flipY:r.scaleY<0!==i}},s});g(this,"onDoubleClick",t=>{const r=t.props.assetId?this.editor.getAsset(t.props.assetId):void 0;!r||!(r.props.src&&this.isAnimated(t))||this.editor.updateShapes([{type:"image",id:t.id,props:{playing:!t.props.playing}}])});g(this,"onDoubleClickEdge",t=>{const r=t.props;if(!r||this.editor.getCroppingShapeId()!==t.id)return;const s=Be(r.crop)||{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},o=1/(s.bottomRight.x-s.topLeft.x)*t.props.w,i=1/(s.bottomRight.y-s.topLeft.y)*t.props.h,a=new b(s.topLeft.x*o,s.topLeft.y*i).rot(t.rotation),l={id:t.id,type:t.type,x:t.x-a.x,y:t.y-a.y,props:{crop:{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},w:o,h:i}};this.editor.updateShapes([l])})}getDefaultProps(){return{w:100,h:100,assetId:null,playing:!0,url:"",crop:null,flipX:!1,flipY:!1}}isAnimated(t){const r=t.props.assetId?this.editor.getAsset(t.props.assetId):void 0;return r?"mimeType"in r.props&&cs.isAnimatedImageType(r==null?void 0:r.props.mimeType)||"isAnimated"in r.props&&r.props.isAnimated:!1}component(t){var m;const r=this.editor.getCroppingShapeId()===t.id,s=HA(),[o,i]=P.useState(""),[a,l]=P.useState(""),c=t.id===this.editor.getOnlySelectedShapeId(),{asset:u,url:h}=UA(t.id,t.props.assetId,t.props.w);if(P.useEffect(()=>{if(h){let x=!1;const y=hl();return y.onload=()=>{x||l(h)},y.src=h,()=>{x=!0}}},[h,t]),P.useEffect(()=>{if(h&&this.isAnimated(t)){let x=!1;const y=hl();return y.onload=()=>{if(x)return;const v=document.createElement("canvas");v.width=y.width,v.height=y.height;const w=v.getContext("2d");w&&(w.drawImage(y,0,0),i(v.toDataURL()),l(h))},y.crossOrigin="anonymous",y.src=h,()=>{x=!0}}},[s,h,t]),(u==null?void 0:u.type)==="bookmark")throw Error("Bookmark assets can't be rendered as images");const p=c&&r&&this.editor.isIn("select.crop"),f=s&&(((m=u==null?void 0:u.props.mimeType)==null?void 0:m.includes("video"))||this.isAnimated(t)),S=DI(t);return u!=null&&u.props.src?a?d.jsxs(d.Fragment,{children:[p&&d.jsx("div",{style:S,children:d.jsx("img",{className:"tl-image",crossOrigin:this.isAnimated(t)?"anonymous":void 0,src:!t.props.playing||f?o:a,referrerPolicy:"strict-origin-when-cross-origin",style:{opacity:.1},draggable:!1})}),d.jsxs(Wi,{id:t.id,style:{overflow:"hidden",width:t.props.w,height:t.props.h},children:[d.jsxs("div",{className:"tl-image-container",style:S,children:[d.jsx("img",{className:le("tl-image",{"tl-flip-x":t.props.flipX&&!t.props.flipY,"tl-flip-y":t.props.flipY&&!t.props.flipX,"tl-flip-xy":t.props.flipY&&t.props.flipX}),crossOrigin:this.isAnimated(t)?"anonymous":void 0,src:!t.props.playing||f?o:a,referrerPolicy:"strict-origin-when-cross-origin",draggable:!1}),this.isAnimated(t)&&!t.props.playing&&d.jsx("div",{className:"tl-image__tg",children:"GIF"})]}),t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})]}):null:d.jsxs(Wi,{id:t.id,style:{overflow:"hidden",width:t.props.w,height:t.props.h,color:"var(--color-text-3)",backgroundColor:u?"transparent":"var(--color-low)",border:u?"none":"1px solid var(--color-low-border)"},children:[d.jsx("div",{className:"tl-image-container",style:S,children:u?null:d.jsx(BA,{})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){return this.editor.getCroppingShapeId()===t.id?null:d.jsx("rect",{width:N(t.props.w),height:N(t.props.h)})}async toSvg(t){if(!t.props.assetId||!this.editor.getAsset(t.props.assetId))return null;let s=await this.editor.resolveAssetUrl(t.props.assetId,{shouldResolveToOriginal:!0});if(!s)return null;(s.startsWith("blob:")||s.startsWith("http")||s.startsWith("/")||s.startsWith("./"))&&(s=await Aq(s)||"");const o=DI(t),i=t.props.crop;if(o.transform&&i){const{transform:a,width:l,height:c}=o,u=(i.bottomRight.x-i.topLeft.x)*l,h=(i.bottomRight.y-i.topLeft.y)*c,p=[new b(0,0),new b(u,0),new b(u,h),new b(0,h)],f=`cropClipPath_${t.id.replace(":","_")}`;return d.jsxs(d.Fragment,{children:[d.jsx("defs",{children:d.jsx("clipPath",{id:f,children:d.jsx("polygon",{points:p.map(S=>`${S.x},${S.y}`).join(" ")})})}),d.jsx("g",{clipPath:`url(#${f})`,children:d.jsx("image",{href:s,width:l,height:c,style:{transform:a}})})]})}else return d.jsx("image",{href:s,width:t.props.w,height:t.props.h})}}g(ap,"type","image"),g(ap,"props",GT),g(ap,"migrations",VT);function DI(e){const n=e.props.crop,t=n==null?void 0:n.topLeft;if(!t)return{width:e.props.w,height:e.props.h};const r=1/(n.bottomRight.x-n.topLeft.x)*e.props.w,s=1/(n.bottomRight.y-n.topLeft.y)*e.props.h,o=-t.x*r,i=-t.y*s;return{transform:`translate(${o}px, ${i}px)`,width:r,height:s}}function KA(e){return{size:e,thinning:.4,streamline:0,smoothing:.5,simulatePressure:!0,last:!0}}function WA(e,n,t){const r=n.vertices,s=KA(t);return Ps(r,s)}function jq(e,n,t){const r=KA(t);return mw(Sg(WA(e,n,t),r),r)}function Oq(e,n,t){const r=jq(e,n,t);return tw(r)}function Dq(e,n,t){if(e.props.dash==="draw"){const r=WA(e,n,t);return Gi(r)}return n.getSvgPathData()}function GA(e,n,t){let r=`M ${ke(n[0])}L`,s=`M ${ke(n[0])}L`;const o=t/3,i=t*2,a=Yr(e);let l=n[0],c,u=n[0],h;const p=n.length;for(let f=0,S=p-1;f!0);g(this,"hideRotateHandle",()=>!0);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"hideSelectionBoundsBg",()=>!0);g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r;return{props:{points:Hu(t.props.points,(i,{id:a,index:l,x:c,y:u})=>({id:a,index:l,x:c*s,y:u*o}))}}});g(this,"onHandleDrag",(t,{handle:r})=>{if(r.type==="vertex")return{...t,props:{...t.props,points:{...t.props.points,[r.id]:{id:r.id,index:r.index,x:r.x,y:r.y}}}}})}getDefaultProps(){const[t,r]=xu(2);return{dash:"draw",size:"m",color:"black",spline:"line",points:{[t]:{id:t,index:t,x:0,y:0},[r]:{id:r,index:r,x:.1,y:.1}},scale:1}}getGeometry(t){return kc(t)}getHandles(t){return Rq.get(t.props,()=>{const r=kc(t),s=_c(t),o=s.map(i=>({...i,id:i.index,type:"vertex",canSnap:!0}));for(let i=0;i{const o=this.getHandles(t).filter(i=>i.type==="vertex").findIndex(i=>i.id===s.id);return r.filter((i,a)=>Math.abs(a-o)>1).map(b.From)},getSelfSnapOutline:s=>{const o=this.getHandles(t).filter(a=>a.type==="vertex").findIndex(a=>a.id===s.id),i=kc(t).segments.filter((a,l)=>l!==o-1&&l!==o);return i.length?new Wr({children:i}):null}}}getInterpolatedProps(t,r,s){const o=_c(t),i=_c(r),a=[],l=[];let c=oT;if(o.length>i.length)for(let u=0;uo.length)for(let u=0;u{const p=l[h];return[u.id,{...u,x:On(u.x,p.x,s),y:On(u.y,p.y,s)}]}))}}}g(lp,"type","line"),g(lp,"props",YT),g(lp,"migrations",XT);function _c(e){return Object.values(e.props.points).sort(an)}function kc(e){const n=_c(e).map(b.From);switch(e.props.spline){case"cubic":return new sY({points:n});case"line":return new ia({points:n})}}function RI({shape:e,shouldScale:n=!1}){const t=Ar(),r=kc(e),{dash:s,color:o,size:i}=e.props,a=1/e.props.scale,l=n?a:1,c=jt[i]*e.props.scale;if(e.props.spline==="line"){if(s==="solid"){const u=r.points,h="M"+u[0]+"L"+u.slice(1);return d.jsx("path",{d:h,stroke:t[o].solid,strokeWidth:c,fill:"none",transform:`scale(${l})`})}if(s==="dashed"||s==="dotted")return d.jsx("g",{stroke:t[o].solid,strokeWidth:c,transform:`scale(${l})`,children:r.segments.map((u,h)=>{const{strokeDasharray:p,strokeDashoffset:f}=os(u.length,c,{style:s,start:h>0?"outset":"none",end:h{const{strokeDasharray:f,strokeDashoffset:S}=os(h.length,c,{style:s,start:p>0?"outset":"none",end:p{for(const t of Object.values(e.icons)){const r=hl();r.src=t,r.decode()}for(const t of Object.values(e.embedIcons)){const r=hl();r.src=t,r.decode()}},[e]),d.jsx(VA.Provider,{value:e,children:n})}function Iw(){const e=P.useContext(VA);if(!e)throw new Error("useAssetUrls must be used within an AssetUrlsProvider");return e}const Hv={"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-json.short":"JSON","action.copy-as-json":"Copy as JSON","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.duplicate":"Duplicate","action.edit-link":"Edit link","action.exit-pen-mode":"Exit pen mode","action.export-as-json.short":"JSON","action.export-as-json":"Export as JSON","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-json.short":"JSON","action.export-all-as-json":"Export as JSON","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-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-edge-scrolling.menu":"Edge scrolling","action.toggle-edge-scrolling":"Toggle edge scrolling","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","assets.files.size-too-big":"File size is too big","assets.files.type-not-allowed":"File type is not allowed","assets.files.upload-failed":"Upload failed","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","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.diamond":"Diamond","geo-style.ellipse":"Ellipse","geo-style.hexagon":"Hexagon","geo-style.octagon":"Octagon","geo-style.oval":"Oval","geo-style.cloud":"Cloud","geo-style.pentagon":"Pentagon","geo-style.rectangle":"Rectangle","geo-style.rhombus-2":"Rhombus 2","geo-style.rhombus":"Rhombus","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","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.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.asset":"Asset","tool.frame":"Frame","tool.note":"Note","tool.laser":"Laser","tool.embed":"Embed","tool.text":"Text","menu.title":"Menu","menu.theme":"Theme","menu.copy-as":"Copy as","menu.edit":"Edit","menu.export-as":"Export as","menu.file":"File","menu.language":"Language","menu.preferences":"Preferences","menu.help":"Help","menu.view":"View","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.default-project-name":"Shared Project","share-menu.copy-link":"Copy editor link","share-menu.readonly-link":"Read-only","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","status.offline":"Offline","status.online":"Online","people-menu.title":"People","people-menu.change-name":"Change name","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","help-menu.title":"Help and resources","help-menu.about":"About","help-menu.docs":"Documentation & API","help-menu.discord":"Discord","help-menu.github":"GitHub","help-menu.keyboard-shortcuts":"Keyboard shortcuts","help-menu.twitter":"Twitter","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","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.","edit-pages-dialog.move-down":"Move down","edit-pages-dialog.move-up":"Move up","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","home-project-dialog.title":"Home project","home-project-dialog.description":"This is your local home project. It's just for you!","rename-project-dialog.title":"Rename project","rename-project-dialog.cancel":"Cancel","rename-project-dialog.rename":"Rename","home-project-dialog.ok":"Ok","style-panel.title":"Styles","style-panel.align":"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.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","tool-panel.drawing":"Drawing","tool-panel.shapes":"Shapes","tool-panel.more":"More","debug-panel.more":"More","navigation-zone.toggle-minimap":"Toggle minimap","navigation-zone.zoom":"Zoom","focus-mode.toggle-focus-mode":"Toggle focus mode","toast.close":"Close","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..."},$q=new Set(["ar","fa","he","ur","ku"]),ya={locale:"en",label:"English",messages:Hv,dir:"ltr"};async function Nq(e,n){if(!(await vs(n.translations.en)).ok)return console.warn("No main translations found."),ya;if(e==="en")return ya;const r=bu.find(a=>a.locale===e);if(!r)return console.warn(`No translation found for locale ${e}`),ya;const o=await(await vs(n.translations[r.locale])).json();if(!o)return console.warn(`No messages found for locale ${e}`),ya;const i=[];for(const a in ya.messages)o[a]||i.push(a);return i.length>0,{locale:e,label:r.label,dir:$q.has(r.locale)?"rtl":"ltr",messages:{...ya.messages,...o}}}const YA=P.createContext(null);function XA(){const e=P.useContext(YA);if(!e)throw new Error("useCurrentTranslation must be used inside of ");return e}const Fq=Lt(function({overrides:n,children:t}){const s=F().user.getLocale(),o=Iw(),[i,a]=P.useState(()=>n&&n.en?{locale:"en",label:"English",dir:"ltr",messages:{...Hv,...n.en}}:{locale:"en",label:"English",dir:"ltr",messages:Hv});return P.useEffect(()=>{let l=!1;async function c(){const u=await Nq(s,o);u&&!l&&(n&&n[s]?a({...u,messages:{...u.messages,...n[s]}}):a(u))}return c(),()=>{l=!0}},[o,s,n]),d.jsx(YA.Provider,{value:i,children:t})});function xe(){const e=XA();return P.useCallback(function(t){return e.messages[t]??t},[e])}class cp extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"hideResizeHandles",()=>!0);g(this,"hideSelectionBoundsFg",()=>!1);g(this,"onBeforeCreate",t=>LI(this.editor,t));g(this,"onBeforeUpdate",(t,r)=>{if(!(t.props.text===r.props.text&&t.props.font===r.props.font&&t.props.size===r.props.size))return LI(this.editor,r)});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])})}getDefaultProps(){return{color:"black",size:"m",text:"",font:"draw",align:"middle",verticalAlign:"middle",growY:0,fontSizeAdjustment:0,url:"",scale:1}}getGeometry(t){const{labelHeight:r,labelWidth:s}=qA(this.editor,t),{scale:o}=t.props,i=r*o,a=s*o,l=ze*o,c=ah(t);return new Wr({children:[new no({width:l,height:c,isFilled:!0}),new no({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})]})}getHandles(t){const{scale:r}=t.props;if(this.editor.getInstanceState().isCoarsePointer)return[];const o=this.editor.getZoomLevel();if(o*r<.25)return[];const i=ah(t),a=ze*r,l=hX/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}]}component(t){const{id:r,type:s,props:{scale:o,color:i,font:a,size:l,align:c,text:u,verticalAlign:h,fontSizeAdjustment:p}}=t,f=Uq(r),S=Ar(),m=ze*o,x=ah(t),y=H("shape rotation",()=>{var C;return((C=this.editor.getShapePageTransform(r))==null?void 0:C.rotation())??0},[this.editor]),v=H("zoom",()=>this.editor.getZoomLevel()<.35/o,[o,this.editor]),w=t.id===this.editor.getOnlySelectedShapeId();return d.jsxs(d.Fragment,{children:[d.jsx("div",{id:r,className:"tl-note__container",style:{width:m,height:x,backgroundColor:S[i].note.fill,borderBottom:v?`${3*o}px solid rgb(15, 23, 31, .2)`:"none",boxShadow:v?"none":Hq(t.id,y,o)},children:d.jsx(bg,{id:r,type:s,font:a,fontSize:(p||Ys[l])*o,lineHeight:Gt.lineHeight,align:c,verticalAlign:h,text:u,isNote:!0,isSelected:w,labelColor:S[i].note.text,wrap:!0,padding:16*o,onKeyDown:f})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){const{scale:r}=t.props;return d.jsx("rect",{rx:r,width:N(ze*r),height:N(ah(t))})}toSvg(t,r){t.props.text&&r.addExportDef(xg(t.props.font));const s=lo({isDarkMode:r.isDarkMode}),o=Kq(t);return d.jsxs(d.Fragment,{children:[d.jsx("rect",{x:5,y:5,rx:1,width:ze-10,height:o.h,fill:"rgba(0,0,0,.1)"}),d.jsx("rect",{rx:1,width:ze,height:o.h,fill:s[t.props.color].note.fill}),d.jsx(wg,{fontSize:t.props.fontSizeAdjustment||Ys[t.props.size],font:t.props.font,align:t.props.align,verticalAlign:t.props.verticalAlign,text:t.props.text,labelColor:s[t.props.color].note.text,bounds:o,stroke:!1})]})}}g(cp,"type","note"),g(cp,"props",qT),g(cp,"migrations",ZT);function LI(e,n){const{labelHeight:t,fontSizeAdjustment:r}=qA(e,n),s=Math.max(0,t-ze);if(s!==n.props.growY||r!==n.props.fontSizeAdjustment)return{...n,props:{...n.props,growY:s,fontSizeAdjustment:r}}}function zq(e,n){const{text:t}=n.props;if(!t)return{labelHeight:Ys[n.props.size]*Gt.lineHeight+yr*2,labelWidth:100,fontSizeAdjustment:0};const r=Ys[n.props.size];let s=0,o=0,i=ze,a=ze;const l=1;do{s=Math.min(r,r-o);const c=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[n.props.font],fontSize:s,maxWidth:ze-yr*2-l,disableOverflowWrapBreaking:!0});if(i=c.h+yr*2,a=c.w+yr*2,s<=14){const u=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[n.props.font],fontSize:s,maxWidth:ze-yr*2-l});i=u.h+yr*2,a=u.w+yr*2;break}if(c.scrollWidth.toFixed(0)===c.w.toFixed(0))break}while(o++<50);return{labelHeight:i,labelWidth:a,fontSizeAdjustment:s}}const Bq=new eo;function qA(e,n){return Bq.get(n,()=>zq(e,n))}function Uq(e){const n=F(),t=XA();return P.useCallback(r=>{const s=n.getShape(e);if(!s)return;const o=r.key==="Tab",i=(r.metaKey||r.ctrlKey)&&r.key==="Enter";if(o||i){r.preventDefault();const a=n.getShapePageTransform(e),l=a.rotation(),c=!!(t.dir==="rtl"||wA(s.props.text)),u=(ze+n.options.adjacentShapeMargin+(i&&!r.shiftKey?s.props.growY:0))*s.props.scale,h=new b(o?r.shiftKey!=c?-1:1:0,i?r.shiftKey?-1:1:0).mul(u).add(vg.clone().mul(s.props.scale)).rot(l).add(a.point()),p=TA(n,s,h,l);p&&(n.mark("editing adjacent shape"),vf(n,p,!0))}},[e,n,t.dir])}function ah(e){return(ze+e.props.growY)*e.props.scale}function Hq(e,n,t){const r=Yr(e),s=Math.abs(r())+.5,o=Math.cos(n),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), + `})}const fq=P.forwardRef(({id:e,name:n,isEditing:t},r)=>{const s=F(),o=P.useCallback(l=>{l.key==="Enter"&&!l.nativeEvent.isComposing&&(Dt(l),l.currentTarget.blur(),s.setEditingShape(null))},[s]),i=P.useCallback(l=>{const c=s.getShape(e);if(!c)return;const u=c.props.name,h=l.currentTarget.value.trim();u!==h&&s.updateShapes([{id:e,type:"frame",props:{name:h}}])},[e,s]),a=P.useCallback(l=>{const c=s.getShape(e);if(!c)return;const u=c.props.name,h=l.currentTarget.value;u!==h&&s.updateShapes([{id:e,type:"frame",props:{name:h}}])},[e,s]);return d.jsxs("div",{className:`tl-frame-label ${t?"tl-frame-label__editing":""}`,children:[d.jsx("input",{className:"tl-frame-name-input",ref:r,style:{display:t?void 0:"none"},value:n,autoFocus:!0,onKeyDown:o,onBlur:i,onChange:a}),FA(n,"Frame")+"​"]})}),gq=function({id:n,name:t,width:r,height:s}){const o=F(),i=H("shape rotation",()=>Go(o.getShapePageTransform(n).rotation()),[o,n]),a=mg(n),l=P.useRef(null),c=P.useCallback(S=>{const y=Nn(S);S.preventDefault(),o.getEditingShapeId()!==n&&o.dispatch({type:"pointer",name:"pointer_down",target:"shape",shape:o.getShape(n),...y})},[o,n]);P.useEffect(()=>{const S=l.current;S&&a&&(S.focus(),S.select())},[l,a]);const h=((i+Math.PI/4)*(2/Math.PI)+4)%4,p=["top","left","bottom","right"][Math.floor(h)];let f;switch(p){case"top":f="";break;case"right":f=`translate(${N(r)}px, 0px) rotate(90deg)`;break;case"bottom":f=`translate(${N(r)}px, ${N(s)}px) rotate(180deg)`;break;case"left":f=`translate(0px, ${N(s)}px) rotate(270deg)`;break}return d.jsx("div",{className:"tl-frame-heading",style:{overflow:a?"visible":"hidden",maxWidth:`calc(var(--tl-zoom) * ${Math.ceil(p==="top"||p==="bottom"?r:s)}px + var(--space-5))`,bottom:"100%",transform:`${f} scale(var(--tl-scale)) translateX(calc(-1 * var(--space-3))`},onPointerDown:c,children:d.jsx("div",{className:"tl-frame-heading-hit-area",children:d.jsx(fq,{ref:l,id:n,name:t,isEditing:a})})})};function FA(e,n){return e.match(/^\s*$/)?n:e}class sp extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"canReceiveNewChildrenOfType",(t,r)=>!t.isLocked);g(this,"canDropShapes",(t,r)=>!t.isLocked);g(this,"onDragShapesOver",(t,r)=>{r.every(s=>s.parentId===t.id)||this.editor.reparentShapes(r,t.id)});g(this,"onDragShapesOut",(t,r)=>{const s=this.editor.getShape(t.parentId);s&&this.editor.isShapeOfType(s,"group")?this.editor.reparentShapes(r,s.id):this.editor.reparentShapes(r,this.editor.getCurrentPageId())});g(this,"onResize",(t,r)=>fw(t,r))}getDefaultProps(){return{w:160*2,h:90*2,name:""}}getGeometry(t){return new no({width:t.props.w,height:t.props.h,isFilled:!1})}component(t){const r=this.editor.getShapeGeometry(t).bounds,s=Ar(),o=H("is creating this shape",()=>{const i=this.editor.getStateDescendant("select.resizing");if(!i||!i.getIsActive())return!1;const a=i==null?void 0:i.info;return a?a.isCreating&&this.editor.getOnlySelectedShapeId()===t.id:!1},[t.id]);return d.jsxs(d.Fragment,{children:[d.jsx(bs,{children:d.jsx("rect",{className:le("tl-frame__body",{"tl-frame__creating":o}),width:r.width,height:r.height,fill:s.solid,stroke:s.text})}),o?null:d.jsx(gq,{id:t.id,name:t.props.name,width:r.width,height:r.height})]})}toSvg(t,r){const s=lo({isDarkMode:r.isDarkMode}),a=((Go(this.editor.getShapePageTransform(t.id).rotation())+Math.PI/4)*(2/Math.PI)+4)%4,l=Math.floor(a);let c;switch(l){case 0:c="";break;case 3:c=`translate(${N(t.props.w)}, 0) rotate(90)`;break;case 2:c=`translate(${N(t.props.w)}, ${N(t.props.h)}) rotate(180)`;break;case 1:c=`translate(0, ${N(t.props.h)}) rotate(270)`;break;default:throw Error("labelSide out of bounds")}const u={fontSize:12,fontFamily:"Inter, sans-serif",textAlign:"start",width:t.props.w,height:32,padding:0,lineHeight:1,fontStyle:"normal",fontWeight:"normal",overflow:"truncate-ellipsis",verticalTextAlign:"middle"},h=this.editor.textMeasure.measureTextSpans(FA(t.props.name,"Frame")+"​",u),p=h[0],f=Ut(h),S=f.box.w+f.box.x-p.box.x,y=Lv(this.editor,h,{offsetY:-u.height-2,...u});return d.jsxs(d.Fragment,{children:[d.jsx("rect",{width:t.props.w,height:t.props.h,fill:s.solid,stroke:s.black.solid,strokeWidth:1,rx:1,ry:1}),d.jsxs("g",{transform:c,children:[d.jsx("rect",{x:-8,y:-u.height-4,width:S+16,height:u.height,fill:s.background,rx:4,ry:4}),y]})]})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds;return d.jsx("rect",{width:N(r.width),height:N(r.height),className:"tl-frame-indicator"})}providesBackgroundForChildren(){return!0}}g(sp,"type","frame"),g(sp,"props",NT),g(sp,"migrations",FT);function kI(e,n){return e>n?(Me*(n/2)+(e-n))*2:(Me*(e/2)+(n-e))*2}function zA(e,n){return Cw(e,n).map((t,r)=>t.getSvgPathData(r===0)).join(" ")+" Z"}function mq(e,n,t,r){const s=e/4,o=n/4,i=Yr(r),a=t*.75,l=v=>v.addXY(i()*a,i()*a),c=new b(e/2,n),u=new b(0,o*1.2),h=new b(e/2,o*.9),p=new b(e,o*1.2),f=l(new b(e/2,n)),S=l(new b(0,o*1.2)),y=l(new b(e/2,o*.9)),x=l(new b(e,o*1.2));return[new sn({start:c,cp1:new b(s*1.5,o*3),cp2:new b(0,o*2.5),end:u}),new sn({start:u,cp1:new b(0,-o*.32),cp2:new b(s*1.85,-o*.32),end:h}),new sn({start:h,cp1:new b(s*2.15,-o*.32),cp2:new b(e,-o*.32),end:p}),new sn({start:p,cp1:new b(e,o*2.5),cp2:new b(s*2.5,o*3),end:f}),new sn({start:f,cp1:new b(s*1.5,o*3),cp2:new b(0,o*2.5),end:S}),new sn({start:S,cp1:new b(0,-o*.32),cp2:new b(s*1.85,-o*.32),end:y}),new sn({start:y,cp1:new b(s*2.15,-o*.32),cp2:new b(e,-o*.32),end:x}),new sn({start:x,cp1:new b(e,o*2.5),cp2:new b(s*2.5,o*3),end:c})].map((v,w)=>v.getSvgPathData(w===0)).join(" ")+" Z"}function Cw(e,n){const t=e/4,r=n/4;return[new sn({start:new b(e/2,n),cp1:new b(t*1.5,r*3),cp2:new b(0,r*2.5),end:new b(0,r*1.2)}),new sn({start:new b(0,r*1.2),cp1:new b(0,-r*.32),cp2:new b(t*1.85,-r*.32),end:new b(e/2,r*.9)}),new sn({start:new b(e/2,r*.9),cp1:new b(t*2.15,-r*.32),cp2:new b(e,-r*.32),end:new b(e,r*1.2)}),new sn({start:new b(e,r*1.2),cp1:new b(e,r*2.5),cp2:new b(t*2.5,r*3),end:new b(e/2,n)})]}function yq(e){return{size:1+e,thinning:.25,end:{taper:e},start:{taper:e},streamline:0,smoothing:1,simulatePressure:!1}}function Sq(e,n,t,r){const s=Yr(e),o=n/2,i=t/2,a=oM(o,i),l=[],c=Le*s(),u=Le+Ve/2+Math.abs(s())*Ve,h=Math.max(16,a/10);for(let p=0;p0?At.easeInOutSine(f):At.easeInExpo(f)))/2)))}return Ps(l,yq(r))}function vq(e,n,t,r){return Gi(Sq(e,n,t,r))}function Fv(e){let n="M";const t=e.length;let r,s,o;for(let i=0,a=t;in?[{type:"straight",start:new b(r,0),delta:new b(1,0)},{type:"arc",center:new b(e-r,r),startAngle:-Me/2},{type:"straight",start:new b(e-r,n),delta:new b(-1,0)},{type:"arc",center:new b(r,r),startAngle:Me/2}]:[{type:"straight",start:new b(e,r),delta:new b(0,1)},{type:"arc",center:new b(r,n-r),startAngle:0},{type:"straight",start:new b(0,n-r),delta:new b(0,-1)},{type:"arc",center:new b(r,r),startAngle:Me}];let l=0;const c=[];for(let u=0;up;)l-=p,a.push(a.shift()),p=a[0].type==="straight"?s:Me*r}return c}const wq={s:50,m:70,l:100,xl:130},bq=.2;function Pg(e,n,t,r){const s=Yr(t),o=kI(e,n),i=Math.max(Math.ceil(o/wq[r]),6,Math.ceil(o/Math.min(e,n))),a=o/i*bq,l=Math.max(e-a*2,1),c=Math.max(n-a*2,1),h=kI(l,c)/i,p=(e-l)/2,f=(n-c)/2,S=xq(l,c,i).map(w=>w.addXY(p,f)),y=e<20?0:a*.3,x=n<20?0:a*.3,m=S.slice(0);for(let w=0;we&&(O.x=e),O.y<0?O.y=0:O.y>n&&(O.y=n);const R=Q0(E,k,O),K=b.Dist(R||b.Average([E,k]),E);v.push({leftPoint:E,rightPoint:k,arcPoint:O,center:R,radius:K})}return v}function Pq(e,n,t,r){const s=[],o=Pg(e,n,t,r);for(const{center:i,radius:a,leftPoint:l,rightPoint:c}of o)s.push(...MH(l,c,i,a,10));return s}function Bv(e,n,t,r){const s=Pg(e,n,t,r);let o=`M${s[0].leftPoint.toFixed()}`;for(const{leftPoint:i,rightPoint:a,radius:l,center:c}of s){if(c===null){o+=` L${a.toFixed()}`;continue}const u=b.Clockwise(i,a,c)?"0":"1";o+=` A${N(l)},${N(l)} 0 ${u},1 ${a.toFixed()}`}return o+=" Z",o}const Cq={s:.5,m:.7,l:.9,xl:1.6};function Iq(e,n,t,r){const s=Yr(t),o=Cq[r],i=Pg(e,n,t,r),c=i.reduce((f,S)=>f+b.Dist2(S.leftPoint,S.rightPoint),0)/i.length>(o*15)**2?f=>f.addXY(s()*o*2,s()*o*2):f=>f;let u=`M${i[0].leftPoint.toFixed()}`,h=c(i[0].leftPoint),p=`M${h.toFixed()}`;for(const{leftPoint:f,center:S,rightPoint:y,radius:x,arcPoint:m}of i){if(S===null){u+=` L${y.toFixed()}`;const I=c(y);p+=` L${I.toFixed()}`,h=I;continue}const v=b.Clockwise(f,y,S)?"0":"1";u+=` A${N(x)},${N(x)} 0 ${v},1 ${y.toFixed()}`;const w=c(y),C=c(m),E=Q0(h,w,C);if(!Number.isFinite(E.x)||!Number.isFinite(E.y)){p+=` L${w.toFixed()}`,h=w;continue}const k=Math.abs(b.Dist(E,h));p+=` A${N(k)},${N(k)} 0 ${v},1 ${w.toFixed()}`,h=w}return u+p+" Z"}function Uv(e,n){switch(e.geo){case"x-box":return Eq(e.w,e.h,n,e.dash);case"check-box":return _q(e.w,e.h);default:return}}function Eq(e,n,t,r){const s=r==="draw"?.62:0;if(r==="dashed")return[[new b(0,0),new b(e/2,n/2)],[new b(e,n),new b(e/2,n/2)],[new b(0,n),new b(e/2,n/2)],[new b(e,0),new b(e/2,n/2)]];const o=a=>Math.max(0,Math.min(e,a)),i=a=>Math.max(0,Math.min(n,a));return[[new b(o(t*s),i(t*s)),new b(o(e-t*s),i(n-t*s))],[new b(o(t*s),i(n-t*s)),new b(o(e-t*s),i(t*s))]]}function _q(e,n){const t=Math.min(e,n)*.82,r=(e-t)/2,s=(n-t)/2,o=a=>Math.max(0,Math.min(e,a)),i=a=>Math.max(0,Math.min(n,a));return[[new b(o(r+t*.25),i(s+t*.52)),new b(o(r+t*.45),i(s+t*.82))],[new b(o(r+t*.45),i(s+t*.82)),new b(o(r+t*.82),i(s+t*.22))]]}function TI({shape:e,shouldScale:n}){const t=n?e.props.scale:1,r=F(),s=Ar(),{id:o,props:i}=e,{w:a,color:l,fill:c,dash:u,growY:h,size:p}=i,f=jt[p]*t,S=i.h+h;switch(i.geo){case"cloud":if(u==="solid"){const y=Bv(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:y,color:l,fill:c,scale:t}),d.jsx("path",{d:y,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else if(u==="draw"){const y=Iq(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:y,color:l,fill:c,scale:t}),d.jsx("path",{d:y,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else{const y=Bv(a,S,o,p),x=Pg(a,S,o,p);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:y,color:l,fill:c,scale:t}),d.jsx("g",{strokeWidth:f,stroke:s[l].solid,fill:"none",pointerEvents:"all",children:x.map(({leftPoint:m,rightPoint:v,center:w,radius:C},E)=>{const k=w?C*Go(Go(b.Angle(w,v))-Go(b.Angle(w,m))):b.Dist(m,v),{strokeDasharray:I,strokeDashoffset:_}=os(k,f,{style:u,start:"outset",end:"outset"});return d.jsx("path",{d:w?`M${m.x},${m.y}A${C},${C},0,0,1,${v.x},${v.y}`:`M${m.x},${m.y}L${v.x},${v.y}`,strokeDasharray:I,strokeDashoffset:_},E)})})]})}case"ellipse":{const y=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=y.getSvgPathData(!0);if(u==="dashed"||u==="dotted"){const m=y.length,{strokeDasharray:v,strokeDashoffset:w}=os(m<64?m*2:m,f,{style:u,snap:4,closed:!0});return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:v,strokeDashoffset:w})]})}else{const v=(n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e)).getSvgPathData(!0);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}}case"oval":{const y=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=y.getSvgPathData(!0);if(u==="dashed"||u==="dotted"){const m=y.getLength(),{strokeDasharray:v,strokeDashoffset:w}=os(m<64?m*2:m,f,{style:u,snap:4,start:"outset",end:"outset",closed:!0});return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:v,strokeDashoffset:w})]})}else return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:x,color:l,fill:c,scale:t}),d.jsx("path",{d:x,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}case"heart":if(u==="dashed"||u==="dotted"||u==="solid"){const y=zA(a,S),x=Cw(a,S);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:y,color:l,fill:c,scale:t}),x.map((m,v)=>{const{strokeDasharray:w,strokeDashoffset:C}=os(m.length,f,{style:u,snap:1,start:"outset",end:"outset",closed:!0});return d.jsx("path",{d:m.getSvgPathData(),strokeWidth:f,fill:"none",stroke:s[l].solid,strokeDasharray:w,strokeDashoffset:C,pointerEvents:"all"},`curve_${v}`)})]})}else{const y=mq(a,S,f,e.id);return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:y,color:l,fill:c,scale:t}),d.jsx("path",{d:y,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}default:{const y=n?r.getShapeGeometry(e):r.getShapeUtil(e).getGeometry(e),x=y instanceof Wr?y.children[0].vertices:y.vertices,m=Uv(e.props,f);if(u==="solid"){let v="M"+x[0]+"L"+x.slice(1)+"Z";if(m)for(const[w,C]of m)v+=`M${w.x},${w.y}L${C.x},${C.y}`;return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}else if(u==="dashed"||u==="dotted"){const v="M"+x[0]+"L"+x.slice(1)+"Z";return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:v,color:l,fill:c,scale:t}),d.jsxs("g",{strokeWidth:f,stroke:s[l].solid,fill:"none",pointerEvents:"all",children:[Array.from(Array(x.length)).map((w,C)=>{const E=b.ToFixed(x[C]),k=b.ToFixed(x[(C+1)%x.length]),I=b.Dist(E,k),{strokeDasharray:_,strokeDashoffset:T}=os(I,f,{style:u,start:"outset",end:"outset"});return d.jsx("line",{x1:E.x,y1:E.y,x2:k.x,y2:k.y,strokeDasharray:_,strokeDashoffset:T},C)}),m&&m.map(([w,C],E)=>{const k=b.Dist(w,C),{strokeDasharray:I,strokeDashoffset:_}=os(k,f,{style:u,start:"skip",end:"skip",snap:u==="dotted"?4:void 0});return d.jsx("path",{d:`M${w.x},${w.y}L${C.x},${C.y}`,stroke:s[l].solid,strokeWidth:f,fill:"none",strokeDasharray:I,strokeDashoffset:_},`line_fg_${E}`)})]})]})}else if(u==="draw"){let v=Fv(zv(o,x,f/3,f*2,2));if(m)for(const[C,E]of m)v+=`M${C.toFixed()}L${E.toFixed()}`;const w=Fv(zv(o,x,0,f*2,1));return d.jsxs(d.Fragment,{children:[d.jsx(nn,{theme:s,d:w,color:l,fill:c,scale:t}),d.jsx("path",{d:v,stroke:s[l].solid,strokeWidth:f,fill:"none"})]})}}}}const MI=17*3;class op extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])});g(this,"onResize",(t,{handle:r,newPoint:s,scaleX:o,scaleY:i,initialShape:a})=>{const l=a.props.w/a.props.scale,c=a.props.h/a.props.scale,u=a.props.growY/a.props.scale;let h=l*o,p=(c+u)*i,f=0,S=0;const y=MI;if(t.props.text.trim()){let E=Math.max(Math.abs(h),y),k=Math.max(Math.abs(p),y);E{if(!t.props.text)return t.props.growY?{...t,props:{...t.props,growY:0}}:void 0;const r=t.props.h/t.props.scale,s=sh(this.editor,t).h;let o=null;if(s>r?o=s-r:t.props.growY&&(o=0),o!==null)return{...t,props:{...t.props,growY:o*t.props.scale}}});g(this,"onBeforeUpdate",(t,r)=>{const s=t.props.text,o=r.props.text;if(s===o&&t.props.font===r.props.font&&t.props.size===r.props.size)return;if(s&&!o)return{...r,props:{...r.props,growY:0}};const i=t.props.w/t.props.scale,a=t.props.h/t.props.scale,l=t.props.growY/t.props.scale,c=sh(this.editor,r);if(!s&&o&&o.length===1){let h=Math.max(i,c.w),p=Math.max(a,c.h);const f=MI;return ia?u=c.h-a:l&&(u=0),u!==null){const h=r.props.w/r.props.scale;return{...r,props:{...r.props,growY:u*r.props.scale,w:Math.max(h,c.w)*r.props.scale}}}if(c.w>i)return{...r,props:{...r.props,w:c.w*r.props.scale}}});g(this,"onDoubleClick",t=>{if(this.editor.inputs.altKey)switch(t.props.geo){case"rectangle":return{...t,props:{geo:"check-box"}};case"check-box":return{...t,props:{geo:"rectangle"}}}})}getDefaultProps(){return{w:100,h:100,geo:"rectangle",color:"black",labelColor:"black",fill:"none",dash:"draw",size:"m",font:"draw",text:"",align:"middle",verticalAlign:"middle",growY:0,url:"",scale:1}}getGeometry(t){const r=Math.max(1,t.props.w),s=Math.max(1,t.props.h+t.props.growY),o=r/2,i=s/2,a=t.props.fill!=="none";let l;switch(t.props.geo){case"cloud":{l=new at({points:Pq(r,s,t.id,t.props.size),isFilled:a});break}case"triangle":{l=new at({points:[new b(o,0),new b(r,s),new b(0,s)],isFilled:a});break}case"diamond":{l=new at({points:[new b(o,0),new b(r,i),new b(o,s),new b(0,i)],isFilled:a});break}case"pentagon":{l=new at({points:ey(r,s,5),isFilled:a});break}case"hexagon":{l=new at({points:ey(r,s,6),isFilled:a});break}case"octagon":{l=new at({points:ey(r,s,8),isFilled:a});break}case"ellipse":{l=new oY({width:r,height:s,isFilled:a});break}case"oval":{l=new iY({width:r,height:s,isFilled:a});break}case"star":{const w=Le/5/2,C=Math.floor(5/4)*2,E=5*2-C,k=0,I=Math.floor(5/2)*2,_=Math.cos(-Ve+C*w)*r/2,T=Math.cos(-Ve+E*w)*r/2,M=Math.sin(-Ve+k*w)*s/2,D=Math.sin(-Ve+I*w)*s/2,$=r-Math.abs(_-T),j=s-Math.abs(D-M),O=r/2+T-(r/2-_),R=s/2+M-(s/2-D),K=1,B=(r-O)/2,z=(s-R)/2,W=(r+$)/2,Y=(s+j)/2,q=W*K/2,ae=Y*K/2;l=new at({points:Array.from(Array(5*2)).map((fe,we)=>{const J=-Ve+we*w;return new b(B+(we%2?q:W)*Math.cos(J),z+(we%2?ae:Y)*Math.sin(J))}),isFilled:a});break}case"rhombus":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(v,0),new b(r,0),new b(r-v,s),new b(0,s)],isFilled:a});break}case"rhombus-2":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(0,0),new b(r-v,0),new b(r,s),new b(v,s)],isFilled:a});break}case"trapezoid":{const v=Math.min(r*.38,s*.38);l=new at({points:[new b(v,0),new b(r-v,0),new b(r,s),new b(0,s)],isFilled:a});break}case"arrow-right":{const v=Math.min(r,s)*.38,w=s*.16;l=new at({points:[new b(0,w),new b(r-v,w),new b(r-v,0),new b(r,s/2),new b(r-v,s),new b(r-v,s-w),new b(0,s-w)],isFilled:a});break}case"arrow-left":{const v=Math.min(r,s)*.38,w=s*.16;l=new at({points:[new b(v,0),new b(v,w),new b(r,w),new b(r,s-w),new b(v,s-w),new b(v,s),new b(0,s/2)],isFilled:a});break}case"arrow-up":{const v=r*.16,w=Math.min(r,s)*.38;l=new at({points:[new b(r/2,0),new b(r,w),new b(r-v,w),new b(r-v,s),new b(v,s),new b(v,w),new b(0,w)],isFilled:a});break}case"arrow-down":{const v=r*.16,w=Math.min(r,s)*.38;l=new at({points:[new b(v,0),new b(r-v,0),new b(r-v,s-w),new b(r,s-w),new b(r/2,s),new b(0,s-w),new b(v,s-w)],isFilled:a});break}case"check-box":case"x-box":case"rectangle":{l=new no({width:r,height:s,isFilled:a});break}case"heart":{const w=Cw(r,s).reduce((C,E)=>(C.push(...E.vertices),C),[]);l=new at({points:w,isFilled:a});break}default:cn(t.props.geo)}const c=sh(this.editor,t),u=r/t.props.scale,h=s/t.props.scale,p=Math.min(100,u/2),f=Math.min(Ys[t.props.size]*Gt.lineHeight+yr*2,h/2),S=Math.min(u,Math.max(c.w,Math.min(p,Math.max(1,u-8)))),y=Math.min(h,Math.max(c.h,Math.min(f,Math.max(1,h-8)))),x=Uv(t.props,jt[t.props.size]*t.props.scale),m=x?x.map(v=>new ia({points:v})):[];return new Wr({children:[l,new no({x:t.props.align==="start"?0:t.props.align==="end"?(u-S)*t.props.scale:(u-S)/2*t.props.scale,y:t.props.verticalAlign==="start"?0:t.props.verticalAlign==="end"?(h-y)*t.props.scale:(h-y)/2*t.props.scale,width:S*t.props.scale,height:y*t.props.scale,isFilled:!0,isLabel:!0}),...m]})}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.getVertices(),r.bounds.center]};case"cloud":case"ellipse":case"heart":case"oval":return{outline:s,points:[r.bounds.center]};default:cn(t.props.geo)}}component(t){const{id:r,type:s,props:o}=t,{fill:i,font:a,align:l,verticalAlign:c,size:u,text:h}=o,p=Ar(),f=this.editor.getEditingShapeId()!==null,S=H("isGeoOnlySelected",()=>t.id===this.editor.getOnlySelectedShapeId(),[]),y=f||t.props.text;return d.jsxs(d.Fragment,{children:[d.jsx(bs,{id:r,children:d.jsx(TI,{shape:t,shouldScale:!0})}),y&&d.jsx(Wi,{style:{overflow:"hidden",width:t.props.w,height:t.props.h+o.growY},children:d.jsx(bg,{id:r,type:s,font:a,fontSize:Ys[u]*t.props.scale,lineHeight:Gt.lineHeight,padding:yr*t.props.scale,fill:i,align:l,verticalAlign:c,text:h,isSelected:S,labelColor:p[o.labelColor].solid,wrap:!0})}),t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){const{id:r,props:s}=t,{w:o,size:i}=s,a=s.h+s.growY,l=jt[i],c=this.editor.getShapeGeometry(t);switch(s.geo){case"ellipse":return s.dash==="draw"?d.jsx("path",{d:vq(r,o,a,l)}):d.jsx("path",{d:c.getSvgPathData(!0)});case"heart":return d.jsx("path",{d:zA(o,a)});case"oval":return d.jsx("path",{d:c.getSvgPathData(!0)});case"cloud":return d.jsx("path",{d:Bv(o,a,r,i)});default:{const u=this.editor.getShapeGeometry(t),h=u instanceof Wr?u.children[0].vertices:u.vertices;let p;if(s.dash==="draw"){const S=zv(r,h,0,l*2*t.props.scale,1);p=Fv(S)}else p="M"+h[0]+"L"+h.slice(1)+"Z";const f=Uv(t.props,l);if(f)for(const[S,y]of f)p+=`M${S.x},${S.y}L${y.x},${y.y}`;return d.jsx("path",{d:p})}}}toSvg(t,r){const s={...t,props:{...t.props,w:t.props.w/t.props.scale,h:t.props.h/t.props.scale}},o=s.props;r.addExportDef(vw(o.fill));let i;if(o.text){r.addExportDef(xg(o.font));const a=lo(r),l=new Q(0,0,o.w,o.h+o.growY);i=d.jsx(wg,{fontSize:Ys[o.size],font:o.font,align:o.align,verticalAlign:o.verticalAlign,text:o.text,labelColor:a[o.labelColor].solid,bounds:l,padding:16})}return d.jsxs(d.Fragment,{children:[d.jsx(TI,{shouldScale:!1,shape:s}),i]})}getCanvasSvgDefs(){return[xw()]}}g(op,"type","geo"),g(op,"props",zT),g(op,"migrations",BT);function sh(e,n){const{text:t,font:r,size:s,w:o}=n.props;if(!t)return{w:0,h:0};const i=e.textMeasure.measureText("w",{...Gt,fontFamily:Ss[r],fontSize:Ys[s],maxWidth:100}),a={s:2,m:3.5,l:5,xl:10},l=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[r],fontSize:Ys[s],minWidth:i.w,maxWidth:Math.max(0,Math.ceil(i.w+a[s]),Math.ceil(o/n.props.scale-yr*2))});return{w:l.w+yr*2,h:l.h+yr*2}}function kq(){const[e,n]=P.useState(!1);return P.useEffect(()=>{const r=CSS.supports("color","color(display-p3 1 1 1)"),s=matchMedia("(color-gamut: p3)");n(r&&s.matches);const o=()=>n(r&&s.matches);return s.addEventListener("change",o),()=>s.removeEventListener("change",o)},[]),H(xt.forceSrgb)||!e?"srgb":"p3"}const AI=.35,jI=.82;class ip extends Ir{constructor(){super(...arguments);g(this,"hideResizeHandles",t=>oh(t));g(this,"hideRotateHandle",t=>oh(t));g(this,"hideSelectionBoundsFg",t=>oh(t));g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r,i=[];for(const a of t.props.segments)i.push({...a,points:a.points.map(({x:l,y:c,z:u})=>({x:s*l,y:o*c,z:u}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",size:"m",isComplete:!1,isPen:!1,scale:1}}getGeometry(t){const r=Pi(t);if(oh(t))return new yg({x:-r/2,y:-r/2,radius:r/2,isFilled:!0});const{strokePoints:s,sw:o}=OI(t,r,!0),i=Pw({strokeWidth:o,showAsComplete:!0});return Sg(s,i),new at({points:mw(s,i),isFilled:!0})}component(t){const r=by(this.editor,t),s=Pi(t);return d.jsx(bs,{id:t.id,children:d.jsx(ih,{shape:t,forceSolid:r,strokeWidth:s,opacity:AI})})}backgroundComponent(t){const r=by(this.editor,t),s=Pi(t);return d.jsx(bs,{id:t.id,children:d.jsx(ih,{shape:t,forceSolid:r,strokeWidth:s,opacity:jI})})}indicator(t){const r=by(this.editor,t),s=Pi(t),{strokePoints:o,sw:i}=OI(t,s,r),a=Sl(t.props.segments);let l;return o.length<2?l=Mq(a[0],i):l=Gi(o,!1),d.jsx("path",{d:l})}toSvg(t){const r=Pi(t),s=r<1.5,o=1/t.props.scale;return d.jsx("g",{transform:`scale(${o})`,children:d.jsx(ih,{forceSolid:s,strokeWidth:r,shape:t,opacity:AI})})}toBackgroundSvg(t){const r=Pi(t),s=r<1.5,o=1/t.props.scale;return d.jsx("g",{transform:`scale(${o})`,children:d.jsx(ih,{forceSolid:s,strokeWidth:r,shape:t,opacity:jI})})}}g(ip,"type","highlight"),g(ip,"props",KT),g(ip,"migrations",WT);function Tq(e){return`M ${e.x} ${e.y} m -${.1}, 0 a ${.1},${.1} 0 1,0 ${.1*2},0 a ${.1},${.1} 0 1,0 -${.1*2},0`}function Mq(e,n){const t=n/2;return`M ${e.x} ${e.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function OI(e,n,t){var l;const r=Sl(e.props.segments),s=e.props.isComplete||((l=Ut(e.props.segments))==null?void 0:l.type)==="straight";let o=n;!t&&!e.props.isPen&&r.length===1&&(o+=Yr(e.id)()*(n/6));const i=Pw({strokeWidth:o,showAsComplete:s});return{strokePoints:Ps(r,i),sw:o}}function Pi(e){return gl[e.props.size]*1.12*e.props.scale}function oh(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function ih({strokeWidth:e,forceSolid:n,shape:t,opacity:r}){var p;const s=Ar(),o=Sl(t.props.segments);let i=e;!n&&!t.props.isPen&&o.length===1&&(i+=Yr(t.id)()*(i/6));const a=Pw({strokeWidth:i,showAsComplete:t.props.isComplete||((p=Ut(t.props.segments))==null?void 0:p.type)==="straight"}),l=Ps(o,a),c=l.length>1?Gi(l,!1):Tq(t.props.segments[0].points[0]),u=kq(),h=s[t.props.color].highlight[u];return d.jsx("path",{d:c,strokeLinecap:"round",fill:"none",pointerEvents:"all",stroke:h,strokeWidth:i,opacity:r})}function by(e,n){return H("forceSolid",()=>{const t=Pi(n),r=e.getZoomLevel();return t/r<1.5},[e])}function BA(){return d.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:[d.jsx("path",{d:"M3,11 L3,3 11,3",strokeWidth:"2"}),d.jsx("path",{d:"M19,27 L27,27 L27,19",strokeWidth:"2"}),d.jsx("path",{d:"M27,3 L3,27",strokeWidth:"2"})]})}function UA(e,n,t){const r=F(),[s,o]=P.useState(null),i=n?r.getAsset(n):null,l=r.getCulledShapes().has(e),c=P.useRef(!1);P.useEffect(()=>{s&&(c.current=!0)},[s]);const u=i&&"w"in i.props?t/i.props.w:1,h=H("zoom level",()=>r.getZoomLevel()*u,[r,u]);return P.useEffect(()=>{if(l)return;let p=!1;const f=r.timers.setTimeout(async()=>{const S=await r.resolveAssetUrl(n,{screenScale:h});p||o(S)},c.current?500:0);return()=>{clearTimeout(f),p=!0}},[n,i==null?void 0:i.props.src,l,h,r]),{asset:i,url:s}}function HA(){const[e,n]=P.useState(!1);return P.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const t=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{n(t.matches)};return r(),t.addEventListener("change",r),()=>t.removeEventListener("change",r)},[]),e}async function Aq(e){const t=await(await vs(e)).blob();return ji.blobToDataUrl(t)}class ap extends Ol{constructor(){super(...arguments);g(this,"isAspectRatioLocked",()=>!0);g(this,"canCrop",()=>!0);g(this,"onResize",(t,r)=>{let s=fw(t,r);const{flipX:o,flipY:i}=r.initialShape.props;return s={...s,props:{...s.props,flipX:r.scaleX<0!==o,flipY:r.scaleY<0!==i}},s});g(this,"onDoubleClick",t=>{const r=t.props.assetId?this.editor.getAsset(t.props.assetId):void 0;!r||!(r.props.src&&this.isAnimated(t))||this.editor.updateShapes([{type:"image",id:t.id,props:{playing:!t.props.playing}}])});g(this,"onDoubleClickEdge",t=>{const r=t.props;if(!r||this.editor.getCroppingShapeId()!==t.id)return;const s=Be(r.crop)||{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},o=1/(s.bottomRight.x-s.topLeft.x)*t.props.w,i=1/(s.bottomRight.y-s.topLeft.y)*t.props.h,a=new b(s.topLeft.x*o,s.topLeft.y*i).rot(t.rotation),l={id:t.id,type:t.type,x:t.x-a.x,y:t.y-a.y,props:{crop:{topLeft:{x:0,y:0},bottomRight:{x:1,y:1}},w:o,h:i}};this.editor.updateShapes([l])})}getDefaultProps(){return{w:100,h:100,assetId:null,playing:!0,url:"",crop:null,flipX:!1,flipY:!1}}isAnimated(t){const r=t.props.assetId?this.editor.getAsset(t.props.assetId):void 0;return r?"mimeType"in r.props&&cs.isAnimatedImageType(r==null?void 0:r.props.mimeType)||"isAnimated"in r.props&&r.props.isAnimated:!1}component(t){var y;const r=this.editor.getCroppingShapeId()===t.id,s=HA(),[o,i]=P.useState(""),[a,l]=P.useState(""),c=t.id===this.editor.getOnlySelectedShapeId(),{asset:u,url:h}=UA(t.id,t.props.assetId,t.props.w);if(P.useEffect(()=>{if(h){let x=!1;const m=hl();return m.onload=()=>{x||l(h)},m.src=h,()=>{x=!0}}},[h,t]),P.useEffect(()=>{if(h&&this.isAnimated(t)){let x=!1;const m=hl();return m.onload=()=>{if(x)return;const v=document.createElement("canvas");v.width=m.width,v.height=m.height;const w=v.getContext("2d");w&&(w.drawImage(m,0,0),i(v.toDataURL()),l(h))},m.crossOrigin="anonymous",m.src=h,()=>{x=!0}}},[s,h,t]),(u==null?void 0:u.type)==="bookmark")throw Error("Bookmark assets can't be rendered as images");const p=c&&r&&this.editor.isIn("select.crop"),f=s&&(((y=u==null?void 0:u.props.mimeType)==null?void 0:y.includes("video"))||this.isAnimated(t)),S=DI(t);return u!=null&&u.props.src?a?d.jsxs(d.Fragment,{children:[p&&d.jsx("div",{style:S,children:d.jsx("img",{className:"tl-image",crossOrigin:this.isAnimated(t)?"anonymous":void 0,src:!t.props.playing||f?o:a,referrerPolicy:"strict-origin-when-cross-origin",style:{opacity:.1},draggable:!1})}),d.jsxs(Wi,{id:t.id,style:{overflow:"hidden",width:t.props.w,height:t.props.h},children:[d.jsxs("div",{className:"tl-image-container",style:S,children:[d.jsx("img",{className:le("tl-image",{"tl-flip-x":t.props.flipX&&!t.props.flipY,"tl-flip-y":t.props.flipY&&!t.props.flipX,"tl-flip-xy":t.props.flipY&&t.props.flipX}),crossOrigin:this.isAnimated(t)?"anonymous":void 0,src:!t.props.playing||f?o:a,referrerPolicy:"strict-origin-when-cross-origin",draggable:!1}),this.isAnimated(t)&&!t.props.playing&&d.jsx("div",{className:"tl-image__tg",children:"GIF"})]}),t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})]}):null:d.jsxs(Wi,{id:t.id,style:{overflow:"hidden",width:t.props.w,height:t.props.h,color:"var(--color-text-3)",backgroundColor:u?"transparent":"var(--color-low)",border:u?"none":"1px solid var(--color-low-border)"},children:[d.jsx("div",{className:"tl-image-container",style:S,children:u?null:d.jsx(BA,{})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){return this.editor.getCroppingShapeId()===t.id?null:d.jsx("rect",{width:N(t.props.w),height:N(t.props.h)})}async toSvg(t){if(!t.props.assetId||!this.editor.getAsset(t.props.assetId))return null;let s=await this.editor.resolveAssetUrl(t.props.assetId,{shouldResolveToOriginal:!0});if(!s)return null;(s.startsWith("blob:")||s.startsWith("http")||s.startsWith("/")||s.startsWith("./"))&&(s=await Aq(s)||"");const o=DI(t),i=t.props.crop;if(o.transform&&i){const{transform:a,width:l,height:c}=o,u=(i.bottomRight.x-i.topLeft.x)*l,h=(i.bottomRight.y-i.topLeft.y)*c,p=[new b(0,0),new b(u,0),new b(u,h),new b(0,h)],f=`cropClipPath_${t.id.replace(":","_")}`;return d.jsxs(d.Fragment,{children:[d.jsx("defs",{children:d.jsx("clipPath",{id:f,children:d.jsx("polygon",{points:p.map(S=>`${S.x},${S.y}`).join(" ")})})}),d.jsx("g",{clipPath:`url(#${f})`,children:d.jsx("image",{href:s,width:l,height:c,style:{transform:a}})})]})}else return d.jsx("image",{href:s,width:t.props.w,height:t.props.h})}}g(ap,"type","image"),g(ap,"props",GT),g(ap,"migrations",VT);function DI(e){const n=e.props.crop,t=n==null?void 0:n.topLeft;if(!t)return{width:e.props.w,height:e.props.h};const r=1/(n.bottomRight.x-n.topLeft.x)*e.props.w,s=1/(n.bottomRight.y-n.topLeft.y)*e.props.h,o=-t.x*r,i=-t.y*s;return{transform:`translate(${o}px, ${i}px)`,width:r,height:s}}function KA(e){return{size:e,thinning:.4,streamline:0,smoothing:.5,simulatePressure:!0,last:!0}}function WA(e,n,t){const r=n.vertices,s=KA(t);return Ps(r,s)}function jq(e,n,t){const r=KA(t);return mw(Sg(WA(e,n,t),r),r)}function Oq(e,n,t){const r=jq(e,n,t);return tw(r)}function Dq(e,n,t){if(e.props.dash==="draw"){const r=WA(e,n,t);return Gi(r)}return n.getSvgPathData()}function GA(e,n,t){let r=`M ${ke(n[0])}L`,s=`M ${ke(n[0])}L`;const o=t/3,i=t*2,a=Yr(e);let l=n[0],c,u=n[0],h;const p=n.length;for(let f=0,S=p-1;f!0);g(this,"hideRotateHandle",()=>!0);g(this,"hideSelectionBoundsFg",()=>!0);g(this,"hideSelectionBoundsBg",()=>!0);g(this,"onResize",(t,r)=>{const{scaleX:s,scaleY:o}=r;return{props:{points:Hu(t.props.points,(i,{id:a,index:l,x:c,y:u})=>({id:a,index:l,x:c*s,y:u*o}))}}});g(this,"onHandleDrag",(t,{handle:r})=>{if(r.type==="vertex")return{...t,props:{...t.props,points:{...t.props.points,[r.id]:{id:r.id,index:r.index,x:r.x,y:r.y}}}}})}getDefaultProps(){const[t,r]=xu(2);return{dash:"draw",size:"m",color:"black",spline:"line",points:{[t]:{id:t,index:t,x:0,y:0},[r]:{id:r,index:r,x:.1,y:.1}},scale:1}}getGeometry(t){return kc(t)}getHandles(t){return Rq.get(t.props,()=>{const r=kc(t),s=_c(t),o=s.map(i=>({...i,id:i.index,type:"vertex",canSnap:!0}));for(let i=0;i{const o=this.getHandles(t).filter(i=>i.type==="vertex").findIndex(i=>i.id===s.id);return r.filter((i,a)=>Math.abs(a-o)>1).map(b.From)},getSelfSnapOutline:s=>{const o=this.getHandles(t).filter(a=>a.type==="vertex").findIndex(a=>a.id===s.id),i=kc(t).segments.filter((a,l)=>l!==o-1&&l!==o);return i.length?new Wr({children:i}):null}}}getInterpolatedProps(t,r,s){const o=_c(t),i=_c(r),a=[],l=[];let c=oT;if(o.length>i.length)for(let u=0;uo.length)for(let u=0;u{const p=l[h];return[u.id,{...u,x:On(u.x,p.x,s),y:On(u.y,p.y,s)}]}))}}}g(lp,"type","line"),g(lp,"props",YT),g(lp,"migrations",XT);function _c(e){return Object.values(e.props.points).sort(an)}function kc(e){const n=_c(e).map(b.From);switch(e.props.spline){case"cubic":return new sY({points:n});case"line":return new ia({points:n})}}function RI({shape:e,shouldScale:n=!1}){const t=Ar(),r=kc(e),{dash:s,color:o,size:i}=e.props,a=1/e.props.scale,l=n?a:1,c=jt[i]*e.props.scale;if(e.props.spline==="line"){if(s==="solid"){const u=r.points,h="M"+u[0]+"L"+u.slice(1);return d.jsx("path",{d:h,stroke:t[o].solid,strokeWidth:c,fill:"none",transform:`scale(${l})`})}if(s==="dashed"||s==="dotted")return d.jsx("g",{stroke:t[o].solid,strokeWidth:c,transform:`scale(${l})`,children:r.segments.map((u,h)=>{const{strokeDasharray:p,strokeDashoffset:f}=os(u.length,c,{style:s,start:h>0?"outset":"none",end:h{const{strokeDasharray:f,strokeDashoffset:S}=os(h.length,c,{style:s,start:p>0?"outset":"none",end:p{for(const t of Object.values(e.icons)){const r=hl();r.src=t,r.decode()}for(const t of Object.values(e.embedIcons)){const r=hl();r.src=t,r.decode()}},[e]),d.jsx(VA.Provider,{value:e,children:n})}function Iw(){const e=P.useContext(VA);if(!e)throw new Error("useAssetUrls must be used within an AssetUrlsProvider");return e}const Hv={"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-json.short":"JSON","action.copy-as-json":"Copy as JSON","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.duplicate":"Duplicate","action.edit-link":"Edit link","action.exit-pen-mode":"Exit pen mode","action.export-as-json.short":"JSON","action.export-as-json":"Export as JSON","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-json.short":"JSON","action.export-all-as-json":"Export as JSON","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-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-edge-scrolling.menu":"Edge scrolling","action.toggle-edge-scrolling":"Toggle edge scrolling","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","assets.files.size-too-big":"File size is too big","assets.files.type-not-allowed":"File type is not allowed","assets.files.upload-failed":"Upload failed","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","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.diamond":"Diamond","geo-style.ellipse":"Ellipse","geo-style.hexagon":"Hexagon","geo-style.octagon":"Octagon","geo-style.oval":"Oval","geo-style.cloud":"Cloud","geo-style.pentagon":"Pentagon","geo-style.rectangle":"Rectangle","geo-style.rhombus-2":"Rhombus 2","geo-style.rhombus":"Rhombus","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","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.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.asset":"Asset","tool.frame":"Frame","tool.note":"Note","tool.laser":"Laser","tool.embed":"Embed","tool.text":"Text","menu.title":"Menu","menu.theme":"Theme","menu.copy-as":"Copy as","menu.edit":"Edit","menu.export-as":"Export as","menu.file":"File","menu.language":"Language","menu.preferences":"Preferences","menu.help":"Help","menu.view":"View","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.default-project-name":"Shared Project","share-menu.copy-link":"Copy editor link","share-menu.readonly-link":"Read-only","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","status.offline":"Offline","status.online":"Online","people-menu.title":"People","people-menu.change-name":"Change name","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","help-menu.title":"Help and resources","help-menu.about":"About","help-menu.docs":"Documentation & API","help-menu.discord":"Discord","help-menu.github":"GitHub","help-menu.keyboard-shortcuts":"Keyboard shortcuts","help-menu.twitter":"Twitter","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","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.","edit-pages-dialog.move-down":"Move down","edit-pages-dialog.move-up":"Move up","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","home-project-dialog.title":"Home project","home-project-dialog.description":"This is your local home project. It's just for you!","rename-project-dialog.title":"Rename project","rename-project-dialog.cancel":"Cancel","rename-project-dialog.rename":"Rename","home-project-dialog.ok":"Ok","style-panel.title":"Styles","style-panel.align":"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.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","tool-panel.drawing":"Drawing","tool-panel.shapes":"Shapes","tool-panel.more":"More","debug-panel.more":"More","navigation-zone.toggle-minimap":"Toggle minimap","navigation-zone.zoom":"Zoom","focus-mode.toggle-focus-mode":"Toggle focus mode","toast.close":"Close","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..."},$q=new Set(["ar","fa","he","ur","ku"]),ya={locale:"en",label:"English",messages:Hv,dir:"ltr"};async function Nq(e,n){if(!(await vs(n.translations.en)).ok)return console.warn("No main translations found."),ya;if(e==="en")return ya;const r=bu.find(a=>a.locale===e);if(!r)return console.warn(`No translation found for locale ${e}`),ya;const o=await(await vs(n.translations[r.locale])).json();if(!o)return console.warn(`No messages found for locale ${e}`),ya;const i=[];for(const a in ya.messages)o[a]||i.push(a);return i.length>0,{locale:e,label:r.label,dir:$q.has(r.locale)?"rtl":"ltr",messages:{...ya.messages,...o}}}const YA=P.createContext(null);function XA(){const e=P.useContext(YA);if(!e)throw new Error("useCurrentTranslation must be used inside of ");return e}const Fq=Lt(function({overrides:n,children:t}){const s=F().user.getLocale(),o=Iw(),[i,a]=P.useState(()=>n&&n.en?{locale:"en",label:"English",dir:"ltr",messages:{...Hv,...n.en}}:{locale:"en",label:"English",dir:"ltr",messages:Hv});return P.useEffect(()=>{let l=!1;async function c(){const u=await Nq(s,o);u&&!l&&(n&&n[s]?a({...u,messages:{...u.messages,...n[s]}}):a(u))}return c(),()=>{l=!0}},[o,s,n]),d.jsx(YA.Provider,{value:i,children:t})});function xe(){const e=XA();return P.useCallback(function(t){return e.messages[t]??t},[e])}class cp extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"hideResizeHandles",()=>!0);g(this,"hideSelectionBoundsFg",()=>!1);g(this,"onBeforeCreate",t=>LI(this.editor,t));g(this,"onBeforeUpdate",(t,r)=>{if(!(t.props.text===r.props.text&&t.props.font===r.props.font&&t.props.size===r.props.size))return LI(this.editor,r)});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t;o.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])})}getDefaultProps(){return{color:"black",size:"m",text:"",font:"draw",align:"middle",verticalAlign:"middle",growY:0,fontSizeAdjustment:0,url:"",scale:1}}getGeometry(t){const{labelHeight:r,labelWidth:s}=qA(this.editor,t),{scale:o}=t.props,i=r*o,a=s*o,l=ze*o,c=ah(t);return new Wr({children:[new no({width:l,height:c,isFilled:!0}),new no({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})]})}getHandles(t){const{scale:r}=t.props;if(this.editor.getInstanceState().isCoarsePointer)return[];const o=this.editor.getZoomLevel();if(o*r<.25)return[];const i=ah(t),a=ze*r,l=hX/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}]}component(t){const{id:r,type:s,props:{scale:o,color:i,font:a,size:l,align:c,text:u,verticalAlign:h,fontSizeAdjustment:p}}=t,f=Uq(r),S=Ar(),y=ze*o,x=ah(t),m=H("shape rotation",()=>{var C;return((C=this.editor.getShapePageTransform(r))==null?void 0:C.rotation())??0},[this.editor]),v=H("zoom",()=>this.editor.getZoomLevel()<.35/o,[o,this.editor]),w=t.id===this.editor.getOnlySelectedShapeId();return d.jsxs(d.Fragment,{children:[d.jsx("div",{id:r,className:"tl-note__container",style:{width:y,height:x,backgroundColor:S[i].note.fill,borderBottom:v?`${3*o}px solid rgb(15, 23, 31, .2)`:"none",boxShadow:v?"none":Hq(t.id,m,o)},children:d.jsx(bg,{id:r,type:s,font:a,fontSize:(p||Ys[l])*o,lineHeight:Gt.lineHeight,align:c,verticalAlign:h,text:u,isNote:!0,isSelected:w,labelColor:S[i].note.text,wrap:!0,padding:16*o,onKeyDown:f})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]})}indicator(t){const{scale:r}=t.props;return d.jsx("rect",{rx:r,width:N(ze*r),height:N(ah(t))})}toSvg(t,r){t.props.text&&r.addExportDef(xg(t.props.font));const s=lo({isDarkMode:r.isDarkMode}),o=Kq(t);return d.jsxs(d.Fragment,{children:[d.jsx("rect",{x:5,y:5,rx:1,width:ze-10,height:o.h,fill:"rgba(0,0,0,.1)"}),d.jsx("rect",{rx:1,width:ze,height:o.h,fill:s[t.props.color].note.fill}),d.jsx(wg,{fontSize:t.props.fontSizeAdjustment||Ys[t.props.size],font:t.props.font,align:t.props.align,verticalAlign:t.props.verticalAlign,text:t.props.text,labelColor:s[t.props.color].note.text,bounds:o,stroke:!1})]})}}g(cp,"type","note"),g(cp,"props",qT),g(cp,"migrations",ZT);function LI(e,n){const{labelHeight:t,fontSizeAdjustment:r}=qA(e,n),s=Math.max(0,t-ze);if(s!==n.props.growY||r!==n.props.fontSizeAdjustment)return{...n,props:{...n.props,growY:s,fontSizeAdjustment:r}}}function zq(e,n){const{text:t}=n.props;if(!t)return{labelHeight:Ys[n.props.size]*Gt.lineHeight+yr*2,labelWidth:100,fontSizeAdjustment:0};const r=Ys[n.props.size];let s=0,o=0,i=ze,a=ze;const l=1;do{s=Math.min(r,r-o);const c=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[n.props.font],fontSize:s,maxWidth:ze-yr*2-l,disableOverflowWrapBreaking:!0});if(i=c.h+yr*2,a=c.w+yr*2,s<=14){const u=e.textMeasure.measureText(t,{...Gt,fontFamily:Ss[n.props.font],fontSize:s,maxWidth:ze-yr*2-l});i=u.h+yr*2,a=u.w+yr*2;break}if(c.scrollWidth.toFixed(0)===c.w.toFixed(0))break}while(o++<50);return{labelHeight:i,labelWidth:a,fontSizeAdjustment:s}}const Bq=new eo;function qA(e,n){return Bq.get(n,()=>zq(e,n))}function Uq(e){const n=F(),t=XA();return P.useCallback(r=>{const s=n.getShape(e);if(!s)return;const o=r.key==="Tab",i=(r.metaKey||r.ctrlKey)&&r.key==="Enter";if(o||i){r.preventDefault();const a=n.getShapePageTransform(e),l=a.rotation(),c=!!(t.dir==="rtl"||wA(s.props.text)),u=(ze+n.options.adjacentShapeMargin+(i&&!r.shiftKey?s.props.growY:0))*s.props.scale,h=new b(o?r.shiftKey!=c?-1:1:0,i?r.shiftKey?-1:1:0).mul(u).add(vg.clone().mul(s.props.scale)).rot(l).add(a.point()),p=TA(n,s,h,l);p&&(n.mark("editing adjacent shape"),vf(n,p,!0))}},[e,n,t.dir])}function ah(e){return(ze+e.props.growY)*e.props.scale}function Hq(e,n,t){const r=Yr(e),s=Math.abs(r())+.5,o=Math.cos(n),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), 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)}), - 0px ${48*t}px ${10*t}px -${10*t}px inset rgba(15, 23, 44, ${((.022+r()*.005)*((1+o)/2)).toFixed(2)})`}function Kq(e){return new Q(0,0,ze,ze+e.props.growY)}function Wq(e,{initialBounds:n,scaleX:t,scaleY:r,newPoint:s}){const o=Math.max(.01,Math.min(Math.abs(t),Math.abs(r))),i=new b(0,0);t<0&&(i.x=-(n.width*o)),r<0&&(i.y=-(n.height*o));const{x:a,y:l}=b.Add(s,i.rot(e.rotation));return{x:a,y:l,props:{scale:o*e.props.scale}}}const Gq=new eo;class up extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"isAspectRatioLocked",()=>!0);g(this,"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,...Wq(t,r)};{const c=Math.max(1,Math.abs(o.width*a)),{x:u,y:h}=a<0?b.Sub(s,b.FromAngle(t.rotation).mul(c)):s;return{id:t.id,type:t.type,x:u,y:h,props:{w:c/i.props.scale,autoSize:!1}}}});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t,i=t.props.text.trimEnd();i.length===0?this.editor.deleteShapes([t.id]):i!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])});g(this,"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=t.props.text!==r.props.text;if(!s&&!o)return;const i=this.getMinDimensions(t),a=$I(this.editor,r.props),l=i.width*t.props.scale,c=i.height*t.props.scale,u=a.width*r.props.scale,h=a.height*r.props.scale;let p;switch(r.props.textAlign){case"middle":{p=new b((u-l)/2,o?0:(h-c)/2);break}case"end":{p=new b(u-l,o?0:(h-c)/2);break}default:{if(o)break;p=new b(0,(h-c)/2);break}}if(p){p.rot(r.rotation);const{x:f,y:S}=r;return{...r,x:f-p.x,y:S-p.y,props:{...r.props,w:u}}}else return{...r,props:{...r.props,w:u}}})}getDefaultProps(){return{color:"black",size:"m",w:8,text:"",font:"draw",textAlign:"start",autoSize:!0,scale:1}}getMinDimensions(t){return Gq.get(t.props,r=>$I(this.editor,r))}getGeometry(t){const{scale:r}=t.props,{width:s,height:o}=this.getMinDimensions(t);return new no({width:s*r,height:o*r,isFilled:!0,isLabel:!0})}component(t){const{id:r,props:{font:s,size:o,text:i,color:a,scale:l,textAlign:c}}=t,{width:u,height:h}=this.getMinDimensions(t),p=t.id===this.editor.getOnlySelectedShapeId(),f=Ar(),S=Vq(r);return d.jsx(bg,{id:r,classNamePrefix:"tl-text-shape",type:"text",font:s,fontSize:gl[o],lineHeight:Gt.lineHeight,align:c,verticalAlign:"middle",text:i,labelColor:f[a].solid,isSelected:p,textWidth:u,textHeight:h,style:{transform:`scale(${l})`,transformOrigin:"top left"},wrap:!0,onKeyDown:S})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds,s=F();return t.props.autoSize&&s.getEditingShapeId()===t.id?null:d.jsx("rect",{width:N(r.width),height:N(r.height)})}toSvg(t,r){t.props.text&&r.addExportDef(xg(t.props.font));const s=this.editor.getShapeGeometry(t).bounds,o=s.width/(t.props.scale??1),i=s.height/(t.props.scale??1),a=lo(r);return d.jsx(wg,{fontSize:gl[t.props.size],font:t.props.font,align:t.props.textAlign,verticalAlign:"middle",text:t.props.text,labelColor:a[t.props.color].solid,bounds:new Q(0,0,o,i),padding:0})}}g(up,"type","text"),g(up,"props",QT),g(up,"migrations",JT);function $I(e,n){const{font:t,text:r,autoSize:s,size:o,w:i}=n,a=s?16:Math.max(16,i),l=gl[o],c=s?null:Math.floor(Math.max(a,i)),u=e.textMeasure.measureText(r,{...Gt,fontFamily:Ss[t],fontSize:l,maxWidth:c});return s&&(u.w+=1),{width:Math.max(a,u.w),height:Math.max(l,u.h)}}function Vq(e){const n=F();return P.useCallback(t=>{if(n.getEditingShapeId()===e)switch(t.key){case"Enter":{(t.ctrlKey||t.metaKey)&&n.complete();break}case"Tab":{Ie(t),t.shiftKey?ml.unindent(t.currentTarget):ml.indent(t.currentTarget);break}}},[n,e])}class dp extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"isAspectRatioLocked",()=>!0)}getDefaultProps(){return{w:100,h:100,assetId:null,time:0,playing:!0,url:""}}component(t){const{editor:r}=this,s=r.getShapeGeometry(t).bounds.w*r.getZoomLevel()>=110,{asset:o,url:i}=UA(t.id,t.props.assetId,t.props.w),{time:a,playing:l}=t.props,c=mg(t.id),u=HA(),h=P.useRef(null),p=P.useCallback(v=>{const w=v.currentTarget;w&&r.updateShapes([{type:"video",id:t.id,props:{playing:!0,time:w.currentTime}}])},[t.id,r]),f=P.useCallback(v=>{const w=v.currentTarget;w&&r.updateShapes([{type:"video",id:t.id,props:{playing:!1,time:w.currentTime}}])},[t.id,r]),S=P.useCallback(v=>{const w=v.currentTarget;w&&c&&r.updateShapes([{type:"video",id:t.id,props:{time:w.currentTime}}])},[c,t.id,r]),[m,x]=P.useState(!1),y=P.useCallback(v=>{const w=v.currentTarget;w&&(a!==w.currentTime&&(w.currentTime=a),l||w.pause(),x(!0))},[l,a]);return P.useEffect(()=>{const v=h.current;v&&(m&&!c&&a!==v.currentTime&&(v.currentTime=a),c&&document.activeElement!==v&&v.focus())},[c,m,a]),P.useEffect(()=>{if(u){const v=h.current;if(!v)return;v.pause(),v.currentTime=0}},[h,u]),d.jsxs(d.Fragment,{children:[d.jsx(Wi,{id:t.id,style:{color:"var(--color-text-3)",backgroundColor:o?"transparent":"var(--color-low)",border:o?"none":"1px solid var(--color-low-border)"},children:d.jsx("div",{className:"tl-counter-scaled",children:d.jsx("div",{className:"tl-video-container",children:o!=null&&o.props.src?i?d.jsx("video",{ref:h,style:c?{pointerEvents:"all"}:void 0,className:`tl-video tl-video-shape-${t.id.split(":")[1]}`,width:"100%",height:"100%",draggable:!1,playsInline:!0,autoPlay:!0,muted:!0,loop:!0,disableRemotePlayback:!0,disablePictureInPicture:!0,controls:c&&s,onPlay:p,onPause:f,onTimeUpdate:S,onLoadedData:y,hidden:!m,children:d.jsx("source",{src:i})}):null:d.jsx(BA,{})})})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:r.getZoomLevel()})]})}indicator(t){return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h)})}toSvg(t){return d.jsx("image",{href:Yq(t.id),width:t.props.w,height:t.props.h})}}g(dp,"type","video"),g(dp,"props",eM),g(dp,"migrations",tM);function Yq(e){const n=e.split(":")[1],t=document.querySelector(`.tl-video-shape-${n}`);if(t){const r=document.createElement("canvas");return r.width=t.videoWidth,r.height=t.videoHeight,r.getContext("2d").drawImage(t,0,0),r.toDataURL("image/png")}else throw new Error("Video with not found when attempting serialization.")}const ZA=[up,tp,np,op,cp,lp,sp,ep,ip,rp,ap,dp];function Xq(e){return e.sideEffects.register({instance_page_state:{afterChange:(n,t)=>{if(n.croppingShapeId!==t.croppingShapeId){const r=e.isIn("select.crop");!n.croppingShapeId&&t.croppingShapeId?r||e.setCurrentTool("select.crop.idle"):n.croppingShapeId&&!t.croppingShapeId&&r&&e.setCurrentTool("select.idle")}n.editingShapeId!==t.editingShapeId&&(!n.editingShapeId&&t.editingShapeId?e.isIn("select.editing_shape")||e.setCurrentTool("select.editing_shape"):n.editingShapeId&&!t.editingShapeId&&e.isIn("select.editing_shape")&&e.setCurrentTool("select.idle"))}}})}class QA extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"scribbleId","id");g(this,"markId","");g(this,"excludedShapeIds",new Set);g(this,"onEnter",t=>{this.markId="erase scribble begin",this.editor.mark(this.markId),this.info=t;const{originPagePoint:r}=this.editor.inputs;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()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()})}update(){const{editor:t,excludedShapeIds:r}=this,s=t.getErasingShapeIds(),o=t.getZoomLevel(),i=t.getCurrentPageShapes(),{inputs:{currentPagePoint:a,previousPagePoint:l}}=t;this.pushPointToScribble();const c=new Set(s),u=this.editor.options.hitTestMargin/o;for(const h of i){if(t.isShapeOfType(h,"group"))continue;const p=t.getShapeMask(h.id);if(p&&!sr(a,p))continue;const f=t.getShapeGeometry(h),S=t.getShapePageTransform(h);if(!f||!S)continue;const m=S.clone().invert(),x=m.applyToPoint(l),y=m.applyToPoint(a),{bounds:v}=f;v.minX-u>Math.max(x.x,y.x)||v.minY-u>Math.max(x.y,y.y)||v.maxX+u!r.has(h)))}complete(){const{editor:t}=this;t.deleteShapes(t.getCurrentPageState().erasingShapeIds),t.setErasingShapes([]),this.parent.transition("idle")}cancel(){const{editor:t}=this;t.setErasingShapes([]),t.bailToMark(this.markId),this.parent.transition("idle",this.info)}}g(QA,"id","erasing");var eS;let qq=(eS=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(eS,"id","idle"),eS);var tS;let Zq=(tS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{const t=this.editor.getZoomLevel(),r=this.editor.getCurrentPageShapesSorted(),{inputs:{currentPagePoint:s}}=this.editor,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)break;o.add(u.id)}}this.editor.setErasingShapes([...o])});g(this,"onLongPress",t=>{this.startErasing(t)});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startErasing(t)});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}startErasing(t){this.parent.transition("erasing",t)}complete(){const t=this.editor.getErasingShapeIds();t.length&&(this.editor.mark("erase end"),this.editor.deleteShapes(t)),this.editor.setErasingShapes([]),this.parent.transition("idle")}cancel(){this.editor.setErasingShapes([]),this.parent.transition("idle")}},g(tS,"id","pointing"),tS);class Tc extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})})}}g(Tc,"id","eraser"),g(Tc,"initial","idle"),g(Tc,"isLockable",!1),g(Tc,"children",()=>[qq,Zq,QA]);class JA extends se{constructor(){super(...arguments);g(this,"initialCamera",new b);g(this,"onEnter",()=>{this.initialCamera=b.From(this.editor.getCamera()),this.update()});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.parent.transition("idle")});g(this,"onComplete",()=>{this.complete()})}update(){const{initialCamera:t,editor:r}=this,{currentScreenPoint:s,originScreenPoint:o}=r.inputs,i=b.Sub(s,o).div(r.getZoomLevel());i.len2()!==0&&r.setCamera(t.clone().add(i))}complete(){const{editor:t}=this,{pointerVelocity:r}=t.inputs,s=Math.min(r.len(),2);s>.1&&this.editor.slideCamera({speed:s,direction:r}),this.parent.transition("idle")}}g(JA,"id","dragging");var nS;let Qq=(nS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"grab",rotation:0})});g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(nS,"id","idle"),nS);var rS;let Jq=(rS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.stopCameraAnimation(),this.editor.setCursor({type:"grabbing",rotation:0})});g(this,"onLongPress",()=>{this.startDragging()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startDragging()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.complete()})}startDragging(){this.parent.transition("dragging")}complete(){this.parent.transition("idle")}},g(rS,"id","pointing"),rS);class Mc extends se{constructor(){super(...arguments);g(this,"onDoubleClick",t=>{if(t.phase==="settle"){const{currentScreenPoint:r}=this.editor.inputs;this.editor.zoomIn(r,{animation:{duration:220,easing:At.easeOutQuint}})}});g(this,"onTripleClick",t=>{if(t.phase==="settle"){const{currentScreenPoint:r}=this.editor.inputs;this.editor.zoomOut(r,{animation:{duration:320,easing:At.easeOutQuint}})}});g(this,"onQuadrupleClick",t=>{if(t.phase==="settle"){const r=this.editor.getZoomLevel(),{inputs:{currentScreenPoint:s}}=this.editor;r===1?this.editor.zoomToFit({animation:{duration:400,easing:At.easeOutQuint}}):this.editor.resetZoom(s,{animation:{duration:320,easing:At.easeOutQuint}})}})}}g(Mc,"id","hand"),g(Mc,"initial","idle"),g(Mc,"isLockable",!1),g(Mc,"children",()=>[Qq,Jq,JA]);var sS;let eZ=(sS=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("lasering",t)})}},g(sS,"id","idle"),sS);class ej extends se{constructor(){super(...arguments);g(this,"scribbleId","id");g(this,"onEnter",()=>{const t=this.editor.scribbles.addScribble({color:"laser",opacity:.7,size:4,delay:1200,shrink:.05,taper:!0});this.scribbleId=t.id,this.pushPointToScribble()});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.pushPointToScribble()});g(this,"onPointerUp",()=>{this.complete()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()})}complete(){this.parent.transition("idle")}cancel(){this.parent.transition("idle")}}g(ej,"id","lasering");class Ac extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})})}}g(Ac,"id","laser"),g(Ac,"initial","idle"),g(Ac,"children",()=>[eZ,ej]),g(Ac,"isLockable",!1);class tj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"initialSelectedShapeIds",[]);g(this,"excludedShapeIds",new Set);g(this,"isWrapMode",!1);g(this,"initialStartShape",null);g(this,"onEnter",t=>{const{altKey:r,currentPagePoint:s}=this.editor.inputs;if(this.isWrapMode=this.editor.user.getIsWrapMode(),r){this.parent.transition("scribble_brushing",t);return}this.excludedShapeIds=new Set(this.editor.getCurrentPageShapes().filter(o=>this.editor.isShapeOfType(o,"group")||this.editor.isShapeOrAncestorLocked(o)).map(o=>o.id)),this.info=t,this.initialSelectedShapeIds=this.editor.getSelectedShapeIds().slice(),this.initialStartShape=this.editor.getShapesAtPoint(s)[0],this.hitTestShapes()});g(this,"onExit",()=>{this.initialSelectedShapeIds=[],this.editor.updateInstanceState({brush:null})});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.hitTestShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",t=>{this.editor.setSelectedShapes(this.initialSelectedShapeIds),this.parent.transition("idle",t)});g(this,"onKeyDown",t=>{this.editor.inputs.altKey?this.parent.transition("scribble_brushing",t):this.hitTestShapes()});g(this,"onKeyUp",()=>{this.hitTestShapes()});g(this,"onInterrupt",()=>{this.editor.updateInstanceState({brush:null})})}complete(){this.hitTestShapes(),this.parent.transition("idle")}hitTestShapes(){const{editor:t,excludedShapeIds:r,isWrapMode:s}=this,{inputs:{originPagePoint:o,currentPagePoint:i,shiftKey:a,ctrlKey:l}}=t,c=new Set(a?this.initialSelectedShapeIds:[]),u=s?!l:l,h=Q.FromPoints([o,i]),{corners:p}=h;let f,S,m,x,y,v;const w=t.getCurrentPageShapes(),C=t.getCurrentPageId();e:for(let I=0,_=w.length;I<_;I++){if(m=w[I],r.has(m.id)||c.has(m.id)||(x=t.getShapePageBounds(m),!x))continue e;if(h.contains(x)){this.handleHit(m,i,C,c,p);continue e}if(u||t.isShapeOfType(m,"frame"))continue e;if(h.collides(x)){if(y=t.getShapePageTransform(m),!y)continue e;v=y.clone().invert().applyToPoints(p);const T=t.getShapeGeometry(m);t:for(let M=0;M<4;M++)if(f=v[M],S=v[(M+1)%4],T.hitTestLineSegment(f,S,0)){this.handleHit(m,i,C,c,p);break t}}}t.getInstanceState().isCoarsePointer;const E=t.getInstanceState().brush;(!E||!h.equals(E))&&t.updateInstanceState({brush:{...h.toJson()}});const k=t.getSelectedShapeIds();(k.length!==c.size||k.some(I=>!c.has(I)))&&t.setSelectedShapes(Array.from(c))}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&&!YM(l,i)&&!sr(r,l)||o.add(a.id)}}g(tj,"id","brushing");const vl={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 nj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t,this.updateCursor()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startResizing()});g(this,"onLongPress",()=>{this.startResizing()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){const t=this.editor.getSelectedShapes(),r=vl[this.info.handle];this.editor.setCursor({type:r,rotation:t.length===1?this.editor.getSelectionRotation():0})}startResizing(){this.editor.getInstanceState().isReadonly||this.parent.transition("resizing",this.info)}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(nj,"id","pointing_resize_handle");const gr=8;class Ew extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","");g(this,"snapshot",{});g(this,"onEnter",t=>{this.info=t,this.markId="cropping",this.editor.mark(this.markId),this.snapshot=this.createSnapshot(),this.updateShapes()});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"getDefaultCrop",()=>({topLeft:{x:0,y:0},bottomRight:{x:1,y:1}}))}updateCursor(){if(!this.editor.getSelectedShapes()[0])return;const r=vl[this.info.handle];this.editor.setCursor({type:r,rotation:this.editor.getSelectionRotation()})}updateShapes(){const{shape:t,cursorHandleOffset:r}=this.snapshot;if(!t||!this.editor.getShapeUtil("image"))return;const o=t.props,i=this.editor.inputs.currentPagePoint.clone().sub(r),a=this.editor.inputs.originPagePoint.clone().sub(r),l=i.clone().sub(a).rot(-t.rotation),c=o.crop??this.getDefaultCrop(),u=Be(c),h=new b(t.x,t.y),p=new b(0,0),f=1/(c.bottomRight.x-c.topLeft.x)*o.w,S=1/(c.bottomRight.y-c.topLeft.y)*o.h;let m=!1;switch(this.info.handle){case"top":case"top_left":case"top_right":{if(S{this.editor.setCursor({type:"default",rotation:0});const t=this.editor.getOnlySelectedShape();t&&this.editor.setCroppingShape(t.id)});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0})});g(this,"onCancel",()=>{this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})});g(this,"onPointerDown",t=>{var r;if(!this.editor.getIsMenuOpen()){if(t.ctrlKey){this.cancel(),this.editor.root.handleEvent(t);return}switch(t.target){case"canvas":{const s=rj(this.editor);if(s&&!this.editor.isShapeOfType(s,"group")){this.onPointerDown({...t,shape:s,target:"shape"});return}this.cancel(),this.editor.root.handleEvent(t);break}case"shape":{if(t.shape.id===this.editor.getCroppingShapeId()){this.editor.setCurrentTool("select.crop.pointing_crop",t);return}else(r=this.editor.getShapeUtil(t.shape))!=null&&r.canCrop(t.shape)?(this.editor.setCroppingShape(t.shape.id),this.editor.setSelectedShapes([t.shape.id]),this.editor.setCurrentTool("select.crop.pointing_crop",t)):(this.cancel(),this.editor.root.handleEvent(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":{this.editor.setCurrentTool("select.pointing_rotate_handle",{...t,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",{...t,onInteractionEnd:"select.crop.idle"});break}default:this.cancel()}break}}}});g(this,"onDoubleClick",t=>{var i;if(this.editor.inputs.shiftKey||t.phase!=="up")return;const r=this.editor.getCroppingShapeId();if(!r)return;const s=this.editor.getShape(r);if(!s)return;const o=this.editor.getShapeUtil(s);if(o){if(t.target==="selection"){(i=o.onDoubleClickEdge)==null||i.call(o,s);return}this.cancel(),this.editor.root.handleEvent(t)}});g(this,"onKeyDown",()=>{this.nudgeCroppingImage(!1)});g(this,"onKeyRepeat",()=>{this.nudgeCroppingImage(!0)});g(this,"onKeyUp",t=>{switch(t.code){case"Enter":{this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{});break}}})}cancel(){this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})}nudgeCroppingImage(t=!1){const{editor:{inputs:{keys:r}}}=this,s=r.has("ShiftLeft"),o=new b(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 b(0,0)))return;s&&o.mul(10);const i=this.editor.getShape(this.editor.getCroppingShapeId());if(!i)return;const a=sj(this.editor,i,o);a&&(t||this.editor.mark("translate crop"),this.editor.updateShapes([a]))}},g(oS,"id","idle"),oS);class oj extends se{constructor(){super(...arguments);g(this,"onCancel",()=>{this.editor.setCurrentTool("select.crop.idle",{})});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.editor.setCurrentTool("select.crop.translating_crop",t)});g(this,"onPointerUp",t=>{this.editor.setCurrentTool("select.crop.idle",t)})}}g(oj,"id","pointing_crop");class _w extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd);const r=this.editor.getSelectedShapes()[0];if(!r)return;const s=vl[this.info.handle];this.editor.setCursor({type:s,rotation:this.editor.getSelectionRotation()}),this.editor.setCroppingShape(r.id)});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0)});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startCropping()});g(this,"onLongPress",()=>{this.startCropping()});g(this,"onPointerUp",()=>{this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startCropping(){this.editor.getInstanceState().isReadonly||this.parent.transition("cropping",{...this.info,onInteractionEnd:this.info.onInteractionEnd})}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))}}g(_w,"id","pointing_crop_handle");class ij extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","translating crop");g(this,"snapshot",{});g(this,"onEnter",t=>{this.info=t,this.snapshot=this.createSnapshot(),this.editor.mark(this.markId),this.editor.setCursor({type:"move",rotation:0}),this.updateShapes()});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onKeyDown",t=>{switch(t.key){case"Alt":case"Shift":{this.updateShapes();return}}});g(this,"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{originPagePoint:r,currentPagePoint:s}=this.editor.inputs,o=s.clone().sub(r),i=sj(this.editor,t,o);i&&this.editor.updateShapes([i])}}g(ij,"id","translating_crop");class hp extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"onEnter",()=>{this.didCancel=!1,this.markId="crop",this.editor.mark(this.markId)});g(this,"didCancel",!1);g(this,"onExit",()=>{this.didCancel?this.editor.bailToMark(this.markId):this.editor.squashToMark(this.markId)});g(this,"onCancel",()=>{this.didCancel=!0})}}g(hp,"id","crop"),g(hp,"initial","idle"),g(hp,"children",()=>[tZ,ij,oj,_w,Ew]);class aj extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"initialHandle",{});g(this,"initialAdjacentHandle",null);g(this,"initialPagePoint",{});g(this,"markId","");g(this,"initialPageTransform");g(this,"initialPageRotation");g(this,"info",{});g(this,"isPrecise",!1);g(this,"isPreciseId",null);g(this,"pointingId",null);g(this,"onEnter",t=>{const{shape:r,isCreating:s,handle:o}=t;if(this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.shapeId=r.id,this.markId=s?`creating:${r.id}`:"dragging handle",s||this.editor.mark(this.markId),this.initialHandle=Be(o),this.editor.isShapeOfType(r,"line")&&this.initialHandle.type==="create"){this.editor.updateShape({...r,props:{points:{...r.props.points,[o.index]:{id:o.index,index:o.index,x:o.x,y:o.y}}}});const c=this.editor.getShapeHandles(r).find(u=>u.index===o.index);this.initialHandle=Be(c)}this.initialPageTransform=this.editor.getShapePageTransform(r),this.initialPageRotation=this.initialPageTransform.rotation(),this.initialPagePoint=this.editor.inputs.originPagePoint.clone(),this.editor.setCursor({type:s?"cross":"grabbing",rotation:0});const i=this.editor.getShapeHandles(r).sort(an),a=i.findIndex(l=>l.id===t.handle.id);this.initialAdjacentHandle=null;for(let l=a+1;l=0;l--){const c=i[l];if(c.type==="vertex"&&c.id!=="middle"&&c.id!==t.handle.id){this.initialAdjacentHandle=c;break}}if(this.editor.isShapeOfType(r,"arrow")){const l=Rn(this.editor,r)[t.handle.id];this.isPrecise=!1,l?(this.editor.setHintingShapes([l.toId]),this.isPrecise=l.props.isPrecise,this.isPrecise?this.isPreciseId=l.toId:this.resetExactTimeout()):this.editor.setHintingShapes([])}this.update(),this.editor.select(this.shapeId)});g(this,"exactTimeout",-1);g(this,"onPointerMove",()=>{this.update()});g(this,"onKeyDown",()=>{this.update()});g(this,"onKeyUp",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.update(),this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setHintingShapes([]),this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0})})}resetExactTimeout(){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},750)}clearExactTimeout(){this.exactTimeout!==-1&&(clearTimeout(this.exactTimeout),this.exactTimeout=-1)}complete(){this.editor.snaps.clearIndicators(),Ke(this.editor,[this.shapeId]);const{onInteractionEnd:t}=this.info;if(this.editor.getInstanceState().isToolLocked&&t){this.editor.setCurrentTool(t,{shapeId:this.shapeId});return}this.parent.transition("idle")}cancel(){this.editor.bailToMark(this.markId),this.editor.snaps.clearIndicators();const{onInteractionEnd:t}=this.info;if(t){this.editor.setCurrentTool(t,{shapeId:this.shapeId});return}this.parent.transition("idle")}update(){var I;const{editor:t,shapeId:r,initialPagePoint:s}=this,{initialHandle:o,initialPageRotation:i,initialAdjacentHandle:a}=this,l=this.editor.getHintingShapeIds(),c=this.editor.user.getIsSnapMode(),{snaps:u,inputs:{currentPagePoint:h,shiftKey:p,ctrlKey:f,altKey:S,pointerVelocity:m}}=t,x=this.info.shape,y=t.getShape(r);if(!y)return;const v=t.getShapeUtil(y);let w=h.clone().sub(s).rot(-i).add(o);if(p&&a&&o.id!=="middle"){const _=b.Angle(a,w),M=uf(_,24)-_;w=b.RotWith(w,a,M)}t.snaps.clearIndicators();let C={...o,x:w.x,y:w.y};if(o.canSnap&&(c?!f:f)){if(!t.getShapePageTransform(y.id))throw Error("Expected a page transform");const T=u.handles.snapHandle({currentShapeId:r,handle:C});T&&(T.nudge.rot(-t.getShapeParentTransform(y).rotation()),w.add(T.nudge),C={...o,x:w.x,y:w.y})}const E=(I=v.onHandleDrag)==null?void 0:I.call(v,y,{handle:C,isPrecise:this.isPrecise||S,initial:x}),k={id:y.id,type:y.type,...E};if(o.type==="vertex"&&this.editor.isShapeOfType(y,"arrow")){const _=Rn(t,y)[o.id];_?l[0]!==_.toId&&(t.setHintingShapes([_.toId]),this.pointingId=_.toId,this.isPrecise=m.len()<.5||S,this.isPreciseId=this.isPrecise?_.toId:null,this.resetExactTimeout()):l.length>0&&(t.setHintingShapes([]),this.pointingId=null,this.isPrecise=!1,this.isPreciseId=null,this.resetExactTimeout())}E&&t.updateShapes([k])}}g(aj,"id","dragging_handle");function lj(e){return e.isLabel?[e]:e instanceof Wr?e.children.filter(n=>n.isLabel):[]}class cj extends se{constructor(){super(...arguments);g(this,"hitShapeForPointerUp",null);g(this,"onEnter",()=>{const t=this.editor.getEditingShape();if(!t)throw Error("Entered editing state without an editing shape");this.hitShapeForPointerUp=null,Ks(this.editor),this.editor.select(t)});g(this,"onExit",()=>{var o;const{editingShapeId:t}=this.editor.getCurrentPageState();if(!t)return;this.editor.setEditingShape(null),Ks.cancel();const r=this.editor.getShape(t),s=this.editor.getShapeUtil(r);(o=s.onEditEnd)==null||o.call(s,r)});g(this,"onPointerMove",t=>{if(this.hitShapeForPointerUp&&this.editor.inputs.isDragging){if(this.editor.getInstanceState().isReadonly||this.hitShapeForPointerUp.isLocked)return;this.editor.select(this.hitShapeForPointerUp),this.parent.transition("translating",t),this.hitShapeForPointerUp=null;return}switch(t.target){case"shape":case"canvas":{Ks(this.editor);return}}});g(this,"onPointerDown",t=>{switch(this.hitShapeForPointerUp=null,t.target){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=lj(o),a=i.length===1?i[0]:void 0,l=this.editor.isShapeOfType(s,"text")&&s.props.text.trim()==="";if(a&&!l){const c=this.editor.getPointInShapeSpace(r,this.editor.inputs.currentPagePoint);if(a.bounds.containsPoint(c,0)&&a.hitTestPoint(c)){if(r.id===s.id)return;this.hitShapeForPointerUp=r,this.editor.mark("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)});g(this,"onPointerUp",t=>{const r=this.hitShapeForPointerUp;if(!r)return;this.hitShapeForPointerUp=null;const s=this.editor.getShapeUtil(r);if(!r.isLocked){if(this.editor.getInstanceState().isReadonly&&!s.canEditInReadOnly(r)){this.parent.transition("pointing_shape",t);return}this.editor.select(r.id),this.editor.setEditingShape(r.id),Ks(this.editor)}});g(this,"onComplete",t=>{this.parent.transition("idle",t)});g(this,"onCancel",t=>{this.parent.transition("idle",t)})}}g(cj,"id","editing_shape");function NI(e){const n=e.getOnlySelectedShape();return!!(n&&!e.isShapeOrAncestorLocked(n)&&e.getShapeUtil(n).canCrop(n))}function bf(e){const n=e.getSelectedShapeIds(),{shiftKey:t,altKey:r,currentPagePoint:s}=e.inputs,o=e.getShapeAtPoint(s,{hitInside:!1,margin:e.options.hitTestMargin/e.getZoomLevel(),hitLabels:!0,renderingOnly:!0,filter:i=>!i.isLocked});if(o){const i=e.getOutermostSelectableShape(o);if(t&&!r)e.cancelDoubleClick(),n.includes(i.id)?(e.mark("deselecting shape"),e.deselect(i)):(e.mark("shift selecting shape"),e.setSelectedShapes([...n,i.id]));else{let a;i===o||i.id===e.getFocusedGroupId()||n.includes(i.id)?a=o:a=i,a&&!n.includes(a.id)&&(e.mark("selecting shape"),e.select(a.id))}}else{if(t)return;{n.length>0&&(e.mark("selecting none"),e.selectNone());const i=e.getFocusedGroupId();if(An(i)){const a=e.getShape(i);e.isPointInShape(a,s,{margin:0,hitInside:!0})||e.setFocusedGroup(null)}}}}const nZ=["Delete","Backspace","[","]","Enter"," ","Shift","Tab"];var iS;let rZ=(iS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.parent.setCurrentToolIdMask(void 0),Ks(this.editor),this.editor.setCursor({type:"default",rotation:0})});g(this,"onExit",()=>{Ks.cancel()});g(this,"onPointerMove",()=>{Ks(this.editor)});g(this,"onPointerDown",t=>{if(this.editor.getIsMenuOpen())return;const r=t.ctrlKey&&NI(this.editor);if(t.ctrlKey&&!r){if(t.target==="shape"&&this.isDarwin&&this.editor.inputs.keys.has("ControlLeft")&&!this.editor.isShapeOrAncestorLocked(t.shape)){this.parent.transition("pointing_shape",t);return}this.parent.transition("brushing",t);return}switch(t.target){case"canvas":{const s=rj(this.editor);if(s&&!s.isLocked){this.onPointerDown({...t,shape:s,target:"shape"});return}const o=this.editor.getSelectedShapeIds(),i=this.editor.getOnlySelectedShape(),{inputs:{currentPagePoint:a}}=this.editor;if((o.length>1||i&&!this.editor.getShapeUtil(i).hideSelectionBoundsBg(i))&&FI(this.editor,a)){this.onPointerDown({...t,target:"selection"});return}this.parent.transition("pointing_canvas",t);break}case"shape":{const{shape:s}=t;if(this.isOverArrowLabelTest(s)){this.parent.transition("pointing_arrow_label",t);break}if(this.editor.isShapeOrAncestorLocked(s)){this.parent.transition("pointing_canvas",t);break}this.parent.transition("pointing_shape",t);break}case"handle":{if(this.editor.getInstanceState().isReadonly)break;this.editor.inputs.altKey?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":{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":{r?this.parent.transition("crop.pointing_crop_handle",t):this.parent.transition("pointing_resize_handle",t);break}default:{const s=this.editor.getHoveredShape();if(s&&!this.editor.getSelectedShapeIds().includes(s.id)&&!s.isLocked){this.onPointerDown({...t,shape:s,target:"shape"});return}this.parent.transition("pointing_selection",t)}}break}}});g(this,"onDoubleClick",t=>{var r,s,o,i;if(!(this.editor.inputs.shiftKey||t.phase!=="up"))switch(t.target){case"canvas":{const a=this.editor.getHoveredShape(),l=a&&!this.editor.isShapeOfType(a,"group")?a:this.editor.getSelectedShapeAtPoint(this.editor.inputs.currentPagePoint)??this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1}),c=this.editor.getFocusedGroupId();if(l){if(this.editor.isShapeOfType(l,"group")){bf(this.editor);return}else{const u=this.editor.getShape(l.parentId);if(u&&this.editor.isShapeOfType(u,"group")&&!(c&&u.id===c)){bf(this.editor);return}}this.onDoubleClick({...t,shape:l,target:"shape"});return}this.editor.inputs.shiftKey||this.handleDoubleClickOnCanvas(t);break}case"selection":{if(this.editor.getInstanceState().isReadonly)break;const a=this.editor.getOnlySelectedShape();if(a){const l=this.editor.getShapeUtil(a);if(!this.canInteractWithShapeInReadOnly(a))return;if(t.handle==="right"||t.handle==="left"||t.handle==="top"||t.handle==="bottom"){const c=(r=l.onDoubleClickEdge)==null?void 0:r.call(l,a);if(c){this.editor.mark("double click edge"),this.editor.updateShapes([c]),Ke(this.editor,[a.id]);return}}if(l.canCrop(a)&&!this.editor.isShapeOrAncestorLocked(a)){this.parent.transition("crop",t);return}this.shouldStartEditingShape(a)&&this.startEditingShape(a,t,!0)}break}case"shape":{const{shape:a}=t,l=this.editor.getShapeUtil(a);if(a.type!=="video"&&a.type!=="embed"&&this.editor.getInstanceState().isReadonly)break;if(l.onDoubleClick){const c=(s=l.onDoubleClick)==null?void 0:s.call(l,a);if(c){this.editor.updateShapes([c]);return}else if(l.canCrop(a)&&!this.editor.isShapeOrAncestorLocked(a)){this.editor.mark("select and crop"),this.editor.select((o=t.shape)==null?void 0:o.id),this.parent.transition("crop",t);return}}this.shouldStartEditingShape(a)?this.startEditingShape(a,t,!0):this.handleDoubleClickOnCanvas(t);break}case"handle":{if(this.editor.getInstanceState().isReadonly)break;const{shape:a,handle:l}=t,c=this.editor.getShapeUtil(a),u=(i=c.onDoubleClickHandle)==null?void 0:i.call(c,a,l);u?this.editor.updateShapes([u]):this.shouldStartEditingShape(a)&&this.startEditingShape(a,t,!0)}}});g(this,"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.currentPagePoint,{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1,hitLabels:!0,hitLocked:!0,hitFrameInside:!1,renderingOnly:!0});if(s){this.onRightClick({...t,shape:s,target:"shape"});return}const o=this.editor.getSelectedShapeIds(),i=this.editor.getOnlySelectedShape(),{inputs:{currentPagePoint:a}}=this.editor;if((o.length>1||i&&!this.editor.getShapeUtil(i).hideSelectionBoundsBg(i))&&FI(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.mark("selecting shape"),this.editor.setSelectedShapes([o.id]));break}}});g(this,"onCancel",()=>{this.editor.getFocusedGroupId()!==this.editor.getCurrentPageId()&&this.editor.getSelectedShapeIds().length>0?this.editor.popFocusedGroupId():(this.editor.mark("clearing selection"),this.editor.selectNone())});g(this,"onKeyDown",t=>{switch(t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{this.nudgeSelectedShapes(!1);return}}if(xt.editOnType.get()&&!nZ.includes(t.key)&&!t.altKey&&!t.ctrlKey){const r=this.editor.getOnlySelectedShape();if(r&&this.editor.isShapeOfType(r,"note")&&this.shouldStartEditingShape(r)){this.startEditingShape(r,{...t,target:"shape",shape:r},!0);return}}});g(this,"onKeyRepeat",t=>{switch(t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{this.nudgeSelectedShapes(!0);break}}});g(this,"onKeyUp",t=>{switch(t.code){case"Enter":{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.shouldStartEditingShape(s)){this.startEditingShape(s,{...t,target:"shape",shape:s},!0);return}NI(this.editor)&&this.parent.transition("crop",t);break}}});g(this,"isDarwin",window.navigator.userAgent.toLowerCase().indexOf("mac")>-1)}shouldStartEditingShape(t=this.editor.getOnlySelectedShape()){return!t||this.editor.isShapeOrAncestorLocked(t)&&t.type!=="embed"||!this.canInteractWithShapeInReadOnly(t)?!1:this.editor.getShapeUtil(t).canEdit(t)}startEditingShape(t,r,s){this.editor.isShapeOrAncestorLocked(t)&&t.type!=="embed"||(this.editor.mark("editing shape"),vf(this.editor,t,s),this.parent.transition("editing_shape",r))}isOverArrowLabelTest(t){if(!t)return!1;const r=this.editor.getPointInShapeSpace(t,this.editor.inputs.currentPagePoint);if(this.editor.isShapeOfType(t,"arrow")){const s=this.editor.getShapeGeometry(t).children[1];if(s&&sr(r,s.vertices))return!0}return!1}handleDoubleClickOnCanvas(t){if(this.editor.getInstanceState().isReadonly)return;this.editor.mark("creating text shape");const r=je(),{x:s,y:o}=this.editor.inputs.currentPagePoint;this.editor.createShapes([{id:r,type:"text",x:s,y:o,props:{text:"",autoSize:!0}}]);const i=this.editor.getShape(r);if(!i)return;const a=this.editor.getShapeUtil(i);this.editor.getInstanceState().isReadonly&&!a.canEditInReadOnly(i)||(this.editor.setEditingShape(r),this.editor.select(r),this.parent.transition("editing_shape",t))}nudgeSelectedShapes(t=!1){const{editor:{inputs:{keys:r}}}=this,s=r.has("ShiftLeft"),o=new b(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 b(0,0)))return;t||this.editor.mark("nudge shapes");const{gridSize:i}=this.editor.getDocumentSettings(),a=this.editor.getInstanceState().isGridMode?s?i*iZ:i:s?sZ:oZ,l=this.editor.getSelectedShapeIds();this.editor.nudgeShapes(l,o.mul(a)),Ke(this.editor,l)}canInteractWithShapeInReadOnly(t){return!!(!this.editor.getInstanceState().isReadonly||this.editor.getShapeUtil(t).canEditInReadOnly(t))}},g(iS,"id","idle"),iS);const sZ=10,oZ=1,iZ=5;function FI(e,n){const t=e.getSelectionRotatedPageBounds();if(!t)return!1;const r=e.getSelectionRotation();return r?sr(n,t.corners.map(s=>b.RotWith(s,t.point,r))):t.containsPoint(n)}class uj extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"markId","");g(this,"wasAlreadySelected",!1);g(this,"didDrag",!1);g(this,"info",{});g(this,"onEnter",t=>{const{shape:r}=t;this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.info=t,this.shapeId=r.id,this.didDrag=!1,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{currentPagePoint:i}=this.editor.inputs,a=this.editor.getPointInShapeSpace(r,i);this._labelDragOffset=b.Sub(o.center,a),this.markId="label-drag start",this.editor.mark(this.markId),this.editor.setSelectedShapes([this.shapeId])});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})});g(this,"_labelDragOffset",new b(0,0));g(this,"onPointerMove",()=>{const{isDragging:t}=this.editor.inputs;if(!t)return;const r=this.editor.getShape(this.shapeId);if(!r)return;const s=ds(this.editor,r),o=this.editor.getShapeGeometry(r),i=o.children[0],a=this.editor.getPointInShapeSpace(r,this.editor.inputs.currentPagePoint),l=i.nearestPoint(b.Add(a,this._labelDragOffset));let c;if(s.isStraight){const u=b.Dist(s.start.point,s.end.point);c=1-b.Dist(s.end.point,l)/u}else{const{_center:u,measure:h,angleEnd:p,angleStart:f}=o.children[0];c=Cv(h,f,p,u.angle(l))}isNaN(c)&&(c=.5),this.didDrag=!0,this.editor.updateShape({id:r.id,type:r.type,props:{labelPosition:c}})});g(this,"onPointerUp",()=>{const t=this.editor.getShape(this.shapeId);t&&(this.didDrag||!this.wasAlreadySelected?this.complete():(this.editor.setEditingShape(t.id),this.editor.setCurrentTool("select.editing_shape")))});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){this.editor.setCursor({type:"grabbing",rotation:0})}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(uj,"id","pointing_arrow_label");class dj extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{const{inputs:t}=this.editor;t.shiftKey||this.editor.getSelectedShapeIds().length>0&&(this.editor.mark("selecting none"),this.editor.selectNone())});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.parent.transition("brushing",t)});g(this,"onPointerUp",()=>{bf(this.editor),this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.parent.transition("idle")})}complete(){this.parent.transition("idle")}}g(dj,"id","pointing_canvas");class hj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t;const{shape:r}=t;if(this.editor.isShapeOfType(r,"arrow")){const s=Rn(this.editor,r)[t.handle.id];s&&this.editor.setHintingShapes([s.toId])}this.editor.setCursor({type:"grabbing",rotation:0})});g(this,"onExit",()=>{this.editor.setHintingShapes([]),this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerUp",()=>{const{shape:t,handle:r}=this.info;if(this.editor.isShapeOfType(t,"note")){const{editor:s}=this,o=zI(s,t,r,!1);if(o){vf(s,o,!0);return}}this.parent.transition("idle",this.info)});g(this,"onPointerMove",()=>{const{editor:t}=this;t.inputs.isDragging&&this.startDraggingHandle()});g(this,"onLongPress",()=>{this.startDraggingHandle()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startDraggingHandle(){const{editor:t}=this;if(t.getInstanceState().isReadonly)return;const{shape:r,handle:s}=this.info;if(t.isShapeOfType(r,"note")){const o=zI(t,r,s,!0);if(o){const i=t.getPointInParentSpace(o,t.inputs.originPagePoint).sub(b.Rot(vg.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:()=>{vf(t,o,!0)}});return}}this.parent.transition("dragging_handle",this.info)}cancel(){this.parent.transition("idle")}}g(hj,"id","pointing_handle");function zI(e,n,t,r){const s=e.getShapePageTransform(n.id),o=s.point(),i=s.rotation(),l=_A(e,o,i,n.props.growY,0,n.props.scale)[t.index];if(l)return TA(e,n,l,i,r)}class pj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.info=t,this.updateCursor()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startRotating()});g(this,"onLongPress",()=>{this.startRotating()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){this.editor.setCursor({type:vl[this.info.handle],rotation:this.editor.getSelectionRotation()})}startRotating(){this.editor.getInstanceState().isReadonly||this.parent.transition("rotating",this.info)}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(pj,"id","pointing_rotate_handle");class fj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerUp",t=>{bf(this.editor),this.parent.transition("idle",t)});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startTranslating(t)});g(this,"onLongPress",t=>{this.startTranslating(t)});g(this,"onDoubleClick",t=>{var o,i;const r=this.editor.getHoveredShape(),s=r&&!this.editor.isShapeOfType(r,"group")?r:this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{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}});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startTranslating(t){this.editor.getInstanceState().isReadonly||this.parent.transition("translating",t)}cancel(){this.parent.transition("idle")}}g(fj,"id","pointing_selection");class gj extends se{constructor(){super(...arguments);g(this,"hitShape",{});g(this,"hitShapeForPointerUp",{});g(this,"isDoubleClick",!1);g(this,"didSelectOnEnter",!1);g(this,"onEnter",t=>{const r=this.editor.getSelectedShapeIds(),s=this.editor.getSelectionRotatedPageBounds(),o=this.editor.getFocusedGroupId(),{inputs:{currentPagePoint:i,shiftKey:a,altKey:l}}=this.editor;this.hitShape=t.shape,this.isDoubleClick=!1;const c=this.editor.getOutermostSelectableShape(t.shape),u=this.editor.findShapeAncestor(c,h=>r.includes(h.id));if(this.editor.getShapeUtil(t.shape).onClick||c.id===o||r.includes(c.id)||u||r.length>1&&(s!=null&&s.containsPoint(i))){this.didSelectOnEnter=!1,this.hitShapeForPointerUp=c;return}this.didSelectOnEnter=!0,a&&!l?(this.editor.cancelDoubleClick(),r.includes(c.id)||(this.editor.mark("shift selecting shape"),this.editor.setSelectedShapes([...r,c.id]))):(this.editor.mark("selecting shape"),this.editor.setSelectedShapes([c.id]))});g(this,"onPointerUp",t=>{var u;const r=this.editor.getSelectedShapeIds(),s=this.editor.getFocusedGroupId(),o=this.editor.getZoomLevel(),{inputs:{currentPagePoint:i,shiftKey:a}}=this.editor,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 h=this.editor.getShapeUtil(c);if(h.onClick){const p=(u=h.onClick)==null?void 0:u.call(h,c);if(p){this.editor.mark("shape on click"),this.editor.updateShapes([p]),this.parent.transition("idle",t);return}}if(c.id===s){r.length>0?(this.editor.mark("clearing shape ids"),this.editor.setSelectedShapes([])):this.editor.popFocusedGroupId(),this.parent.transition("idle",t);return}}if(!this.didSelectOnEnter){const h=this.editor.getOutermostSelectableShape(l,p=>!r.includes(p.id));if(r.includes(h.id))if(a)this.editor.mark("deselecting on pointer up"),this.editor.deselect(c);else if(r.includes(c.id)){if(r.length===1){const p=this.editor.getShapeUtil(c).getGeometry(c),f=lj(p),S=f.length===1?f[0]:void 0;if(S){const m=this.editor.getPointInShapeSpace(c,i);if(S.bounds.containsPoint(m,0)&&S.hitTestPoint(m)){this.editor.run(()=>{this.editor.mark("editing on pointer up"),this.editor.select(c.id);const x=this.editor.getShapeUtil(c);this.editor.getInstanceState().isReadonly&&!x.canEditInReadOnly(c)||(this.editor.setEditingShape(c.id),this.editor.setCurrentTool("select.editing_shape"),this.isDoubleClick&&this.editor.emit("select-all-text",{shapeId:c.id}))});return}}}this.editor.mark("selecting on pointer up"),this.editor.select(c.id)}else this.editor.mark("selecting on pointer up"),this.editor.select(c);else if(a){const p=this.editor.getShapeAncestors(h);this.editor.mark("shift deselecting on pointer up"),this.editor.setSelectedShapes([...this.editor.getSelectedShapeIds().filter(f=>!p.find(S=>S.id===f)),h.id])}else this.editor.mark("selecting on pointer up"),this.editor.setSelectedShapes([h.id])}this.parent.transition("idle",t)});g(this,"onDoubleClick",()=>{this.isDoubleClick=!0});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startTranslating(t)});g(this,"onLongPress",t=>{this.startTranslating(t)});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startTranslating(t){this.editor.getInstanceState().isReadonly||(this.editor.focus(),this.parent.transition("translating",t))}cancel(){this.parent.transition("idle")}}g(gj,"id","pointing_shape");class mj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","");g(this,"didHoldCommand",!1);g(this,"creationCursorOffset",{x:0,y:0});g(this,"snapshot",{});g(this,"onEnter",t=>{const{isCreating:r=!1,creationCursorOffset:s={x:0,y:0}}=t;this.info=t,this.didHoldCommand=!1,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.creationCursorOffset=s,this.snapshot=this._createSnapshot(),r?(this.markId=`creating:${this.editor.getOnlySelectedShape().id}`,this.editor.setCursor({type:"cross",rotation:0})):(this.markId="starting resizing",this.editor.mark(this.markId)),this.handleResizeStart(),this.updateShapes()});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onKeyDown",()=>{this.updateShapes()});g(this,"onKeyUp",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0}),this.editor.snaps.clearIndicators()});g(this,"_createSnapshot",()=>{const t=this.editor.getSelectedShapeIds(),r=this.editor.getSelectionRotation(),{inputs:{originPagePoint:s}}=this.editor,o=this.editor.getSelectionRotatedPageBounds(),i=b.RotWith(o.getHandlePoint(this.info.handle),o.point,r),a=b.Sub(s,i),l=new Map,c=[];t.forEach(h=>{const p=this.editor.getShape(h);if(p){if(p.type==="frame"&&c.push({id:h,children:me(this.editor.getSortedChildIdsForParent(p).map(f=>this.editor.getShape(f)))}),l.set(p.id,this._createShapeSnapshot(p)),this.editor.isShapeOfType(p,"frame")&&t.length===1)return;this.editor.visitDescendants(p.id,f=>{const S=this.editor.getShape(f);if(S&&(l.set(S.id,this._createShapeSnapshot(S)),this.editor.isShapeOfType(S,"frame")))return!1})}});const u=![...l.values()].some(h=>!aM(h.pageRotation,r)||h.isAspectRatioLocked);return{shapeSnapshots:l,selectionBounds:o,cursorHandleOffset:a,selectionRotation:r,selectedShapeIds:t,canShapesDeform:u,initialSelectionPageBounds:this.editor.getSelectionPageBounds(),frames:c}});g(this,"_createShapeSnapshot",t=>{const r=this.editor.getShapePageTransform(t),s=this.editor.getShapeUtil(t);return{shape:t,bounds:this.editor.getShapeGeometry(t).bounds,pageTransform:r,pageRotation:oe.Decompose(r).rotation,isAspectRatioLocked:s.isAspectRatioLocked(t)}})}cancel(){this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}complete(){var t,r;if(Ke(this.editor,this.snapshot.selectedShapeIds),this.handleResizeEnd(),this.info.isCreating&&this.info.onCreate){(r=(t=this.info).onCreate)==null||r.call(t,this.editor.getOnlySelectedShape());return}if(this.editor.getInstanceState().isToolLocked&&this.info.onInteractionEnd){this.editor.setCurrentTool(this.info.onInteractionEnd,{});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{altKey:t,shiftKey:r}=this.editor.inputs,{frames:s,shapeSnapshots:o,selectionBounds:i,cursorHandleOffset:a,selectedShapeIds:l,selectionRotation:c,canShapesDeform:u}=this.snapshot;let h=r||!u;if(o.size===1){const _=[...o.values()][0];this.editor.isShapeOfType(_.shape,"text")&&(h=!(this.info.handle==="left"||this.info.handle==="right"))}const{ctrlKey:p}=this.editor.inputs,f=this.editor.inputs.currentPagePoint.clone().sub(a).sub(this.creationCursorOffset),S=this.editor.inputs.originPagePoint.clone().sub(a);if(this.editor.getInstanceState().isGridMode&&!p){const{gridSize:_}=this.editor.getDocumentSettings();f.snapToGrid(_)}const m=this.info.handle,x=BI(m,Math.PI);if(this.editor.snaps.clearIndicators(),(this.editor.user.getIsSnapMode()?!p:p)&&c%Ve===0){const{nudge:_}=this.editor.snaps.shapeBounds.snapResizeShapes({dragDelta:b.Sub(f,S),initialSelectionPageBounds:this.snapshot.initialSelectionPageBounds,handle:BI(m,c),isAspectRatioLocked:h,isResizingFromCenter:t});f.add(_)}const v=b.RotWith(t?i.center:i.getHandlePoint(x),i.point,c),w=b.Sub(f,v).rot(-c),C=b.Sub(S,v).rot(-c),E=b.DivV(w,C);Number.isFinite(E.x)||(E.x=1),Number.isFinite(E.y)||(E.y=1);const k=m==="top"||m==="bottom",I=m==="left"||m==="right";h?I?E.y=Math.abs(E.x):k?E.x=Math.abs(E.y):Math.abs(E.x)>Math.abs(E.y)?E.y=Math.abs(E.x)*(E.y<0?-1:1):E.x=Math.abs(E.y)*(E.x<0?-1:1):(k&&(E.x=1),I&&(E.y=1)),this.info.isCreating||this.updateCursor({dragHandle:m,isFlippedX:E.x<0,isFlippedY:E.y<0,rotation:c});for(const _ of o.keys()){const T=o.get(_);this.editor.resizeShape(_,E,{initialShape:T.shape,initialBounds:T.bounds,initialPageTransform:T.pageTransform,dragHandle:m,mode:l.length===1&&_===l[0]?"resize_bounds":"scale_shape",scaleOrigin:v,isAspectRatioLocked:h,scaleAxisRotation:c,skipStartAndEndCallbacks:!0})}if(this.editor.inputs.ctrlKey){this.didHoldCommand=!0;for(const{id:_,children:T}of s){if(!T.length)continue;const M=o.get(_).shape,D=this.editor.getShape(_);if(!(M&&D))continue;const $=D.x-M.x,j=D.y-M.y,O=new b($,j).rot(-M.rotation);if(O.x!==0||O.y!==0)for(const R of T)this.editor.updateShape({id:R.id,type:R.type,x:R.x-O.x,y:R.y-O.y})}}else if(this.didHoldCommand){this.didHoldCommand=!1;for(const{children:_}of s)if(_.length)for(const T of _)this.editor.updateShape({id:T.id,type:T.type,x:T.x,y:T.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)}}g(mj,"id","resizing");const Py=["top","top_right","right","bottom_right","bottom","bottom_left","left","top_left"];function BI(e,n){n=n%Le;const t=Math.round(n/(Me/4)),r=Py.indexOf(e);return Py[(r+t)%Py.length]}const UI=Math.PI/180;class yj extends se{constructor(){super(...arguments);g(this,"snapshot",{});g(this,"info",{});g(this,"markId","");g(this,"onEnter",t=>{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.markId="rotate start",this.editor.mark(this.markId);const r=ZM({editor:this.editor});if(!r)return this.parent.transition("idle",this.info);this.snapshot=r;const s=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Uh({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!1}),snapshot:this.snapshot,stage:"start"}),this.editor.setCursor({type:vl[this.info.handle],rotation:s+this.snapshot.initialSelectionRotation})});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0),this.snapshot={}});g(this,"onPointerMove",()=>{this.update()});g(this,"onKeyDown",()=>{this.update()});g(this,"onKeyUp",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"update",()=>{const t=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Uh({editor:this.editor,delta:t,snapshot:this.snapshot,stage:"update"}),this.editor.setCursor({type:vl[this.info.handle],rotation:t+this.snapshot.initialSelectionRotation})});g(this,"cancel",()=>{this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("idle",this.info)});g(this,"complete",()=>{Uh({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!0}),snapshot:this.snapshot,stage:"end"}),Ke(this.editor,this.snapshot.shapeSnapshots.map(t=>t.shape.id)),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("idle",this.info)})}_getRotationFromPointerPosition({snapToNearestDegree:t}){const r=this.editor.getSelectionRotation(),s=this.editor.getSelectionRotatedPageBounds(),{inputs:{shiftKey:o,currentPagePoint:i}}=this.editor,{initialCursorAngle:a,initialSelectionRotation:l}=this.snapshot;if(!s)return l;const u=s.center.clone().rotWith(s.point,r).angle(i)-a;let h=l+u;if(o)h=uf(h,24);else if(t&&(h=Math.round(h/UI)*UI,this.editor.getInstanceState().isCoarsePointer)){const p=uf(h,4),f=Fh(h,p);Math.abs(f)<_H(5)&&(h=p)}return h-l}}g(yj,"id","rotating");class Sj extends se{constructor(){super(...arguments);g(this,"hits",new Set);g(this,"size",0);g(this,"scribbleId","id");g(this,"initialSelectedShapeIds",new Set);g(this,"newlySelectedShapeIds",new Set);g(this,"onEnter",()=>{this.initialSelectedShapeIds=new Set(this.editor.inputs.shiftKey?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})});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.updateScribbleSelection(!0)});g(this,"onPointerUp",()=>{this.complete()});g(this,"onKeyDown",()=>{this.updateScribbleSelection(!1)});g(this,"onKeyUp",()=>{this.editor.inputs.altKey?this.updateScribbleSelection(!1):this.parent.transition("brushing")});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)})}updateScribbleSelection(t){const{editor:r}=this,s=this.editor.getCurrentPageShapes(),{inputs:{shiftKey:o,originPagePoint:i,previousPagePoint:a,currentPagePoint:l}}=this.editor,{newlySelectedShapeIds:c,initialSelectedShapeIds:u}=this;t&&this.pushPointToScribble();const h=s;let p,f,S,m;const x=0;for(let w=0,C=h.length;wMath.max(S.x,m.x)||I.minY-x>Math.max(S.y,m.y)||I.maxX+x!v.has(w)))&&this.editor.setSelectedShapes(Array.from(v))}complete(){this.updateScribbleSelection(!0),this.parent.transition("idle")}cancel(){this.editor.setSelectedShapes([...this.initialSelectedShapeIds]),this.parent.transition("idle")}}g(Sj,"id","scribble_brushing");const aZ=20,lZ=100;class cZ{constructor(n){g(this,"prevDroppingShapeId",null);g(this,"droppingNodeTimer",null);g(this,"first",!0);g(this,"dispose",()=>{this.clear()});this.editor=n,n.disposables.add(this.dispose)}updateDroppingNode(n,t){var r;this.first&&(this.editor.setHintingShapes(n.map(s=>this.editor.findShapeAncestor(s,o=>o.type!=="group")).filter(s=>s)),this.prevDroppingShapeId=((r=this.editor.getDroppingOverShape(this.editor.inputs.originPagePoint,n))==null?void 0:r.id)??null,this.first=!1),this.droppingNodeTimer===null?this.setDragTimer(n,aZ,t):this.editor.inputs.pointerVelocity.len()>.5&&(clearTimeout(this.droppingNodeTimer),this.setDragTimer(n,lZ,t))}setDragTimer(n,t,r){this.droppingNodeTimer=this.editor.timers.setTimeout(()=>{this.editor.run(()=>{this.handleDrag(this.editor.inputs.currentPagePoint,n,r)}),this.droppingNodeTimer=null},t)}handleDrag(n,t,r){var l,c,u,h,p;t=me(t.map(f=>this.editor.getShape(f.id)));const s=((l=this.editor.getDroppingOverShape(n,t))==null?void 0:l.id)??null;if(s===this.prevDroppingShapeId){this.hintParents(t);return}const{prevDroppingShapeId:o}=this,i=o&&this.editor.getShape(o),a=s&&this.editor.getShape(s);i&&((u=(c=this.editor.getShapeUtil(i)).onDragShapesOut)==null||u.call(c,i,t)),a&&((p=(h=this.editor.getShapeUtil(a)).onDragShapesOver)==null||p.call(h,a,t)),this.hintParents(t),r==null||r(),this.prevDroppingShapeId=s}hintParents(n){const t=new Map;for(const s of n){const o=this.editor.findShapeAncestor(s,i=>i.type!=="group");o&&(t.has(o.id)||t.set(o.id,[]),t.get(o.id).push(s.id))}const r=[];for(const[s,o]of t){const i=this.editor.getShape(s);i&&CA(this.editor,i).length{});g(this,"dragAndDropManager",new cZ(this.editor));g(this,"onEnter",t=>{var o;const{isCreating:r=!1,onCreate:s=()=>{}}=t;if(!((o=this.editor.getSelectedShapeIds())!=null&&o.length)){this.parent.transition("idle");return}if(this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.isCreating=r,this.onCreate=s,r?this.markId=`creating:${this.editor.getOnlySelectedShape().id}`:(this.markId="translating",this.editor.mark(this.markId)),this.isCloning=!1,this.info=t,this.editor.setCursor({type:"move",rotation:0}),this.selectionSnapshot=HI(this.editor),!this.isCreating&&this.editor.inputs.altKey){this.startCloning();return}this.snapshot=this.selectionSnapshot,this.handleStart(),this.updateShapes()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.selectionSnapshot={},this.snapshot={},this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0}),this.dragAndDropManager.clear()});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;this.dragAndDropManager.updateDroppingNode(this.snapshot.movingShapes,this.updateParentTransforms),r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onKeyDown",()=>{if(this.editor.inputs.altKey&&!this.isCloning){this.startCloning();return}this.updateShapes()});g(this,"onKeyUp",()=>{if(!this.editor.inputs.altKey&&this.isCloning){this.stopCloning();return}this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"updateParentTransforms",()=>{const{editor:t,snapshot:{shapeSnapshots:r}}=this;r.forEach(s=>{const o=t.getShape(s.shape.id);if(!o)return null;const i=Tn(o.parentId)?null:oe.Inverse(t.getShapePageTransform(o.parentId));s.parentTransform=i})})}startCloning(){this.isCreating||(this.isCloning=!0,this.reset(),this.markId="translating",this.editor.mark(this.markId),this.editor.duplicateShapes(Array.from(this.editor.getSelectedShapeIds())),this.snapshot=HI(this.editor),this.handleStart(),this.updateShapes())}stopCloning(){this.isCloning=!1,this.snapshot=this.selectionSnapshot,this.reset(),this.markId="translating",this.editor.mark(this.markId),this.updateShapes()}reset(){this.editor.bailToMark(this.markId)}complete(){var t;this.updateShapes(),this.dragAndDropManager.dropShapes(this.snapshot.movingShapes),Ke(this.editor,this.snapshot.movingShapes.map(r=>r.id)),this.handleEnd(),this.editor.getInstanceState().isToolLocked&&this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd):this.isCreating?(t=this.onCreate)==null||t.call(this,this.editor.getOnlySelectedShape()):this.parent.transition("idle")}cancel(){this.reset(),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd):this.parent.transition("idle",this.info)}handleStart(){const{movingShapes:t}=this.snapshot,r=[];t.forEach(s=>{var a;const o=this.editor.getShapeUtil(s),i=(a=o.onTranslateStart)==null?void 0:a.call(o,s);i&&r.push(i)}),r.length>0&&this.editor.updateShapes(r),this.editor.setHoveredShape(null)}handleEnd(){const{movingShapes:t}=this.snapshot;if(this.isCloning&&t.length>0){const s=b.Average(t.map(i=>this.editor.getShapePageTransform(i.id).point())),o=b.Sub(s,this.selectionSnapshot.averagePagePoint);b.IsNaN(o)||this.editor.updateInstanceState({duplicateProps:{shapeIds:t.map(i=>i.id),offset:{x:o.x,y:o.y}}})}const r=[];t.forEach(s=>{var l;const o=this.editor.getShape(s.id),i=this.editor.getShapeUtil(s),a=(l=i.onTranslateEnd)==null?void 0:l.call(i,s,o);a&&r.push(a)}),r.length>0&&this.editor.updateShapes(r)}updateShapes(){const{snapshot:t}=this;this.dragAndDropManager.updateDroppingNode(t.movingShapes,this.updateParentTransforms),uZ({editor:this.editor,snapshot:t});const{movingShapes:r}=t,s=[];r.forEach(o=>{var c;const i=this.editor.getShape(o.id),a=this.editor.getShapeUtil(o),l=(c=a.onTranslate)==null?void 0:c.call(a,o,i);l&&s.push(l)}),s.length>0&&this.editor.updateShapes(s)}}g(vj,"id","translating");function HI(e){var h;const n=[],t=[],r=e.getSelectedShapeIds(),s=me(r.map(p=>{const f=e.getShape(p);if(!f)return null;n.push(f);const S=e.getShapePageTransform(p),m=S.point(),x=S.rotation();t.push(m);const y=to.isId(f.parentId)?null:oe.Inverse(e.getShapePageTransform(f.parentId));return{shape:f,pagePoint:m,pageRotation:x,parentTransform:y}})),o=e.getOnlySelectedShape();let i=[];if(o)i=e.snaps.shapeBounds.getSnapPoints(o.id);else{const p=e.getSelectionPageBounds();p&&(i=p.cornersAndCenter.map((f,S)=>({id:"selection:"+S,x:f.x,y:f.y})))}let a,l;const{originPagePoint:c}=e.inputs,u=s.filter(p=>e.isShapeOfType(p.shape,"note")&&e.isPointInShape(p.shape,c));if(u.length!==0)if(u.length===1)l=u[0];else{const p=e.getCurrentPageShapesSorted();l=(h=u.map(f=>({snapshot:f,index:p.findIndex(S=>S.id===f.shape.id)})).sort((f,S)=>S.index-f.index)[0])==null?void 0:h.snapshot}return l&&(a=kA(e,l.pageRotation,l.shape.props.scale,l.shape.props.growY??0)),{averagePagePoint:b.Average(t),movingShapes:n,shapeSnapshots:s,initialPageBounds:e.getSelectionPageBounds(),initialSnapPoints:i,noteAdjacentPositions:a,noteSnapshot:l}}function uZ({editor:e,snapshot:n}){const{inputs:t}=e,{noteSnapshot:r,noteAdjacentPositions:s,initialPageBounds:o,initialSnapPoints:i,shapeSnapshots:a,averagePagePoint:l}=n,c=e.getInstanceState().isGridMode,u=e.getDocumentSettings().gridSize,h=b.Sub(t.currentPagePoint,t.originPagePoint),p=e.inputs.shiftKey?Math.abs(h.x){const w=b.Add(y,m),C=v?oe.applyToPoint(v,w):w;return{id:x.id,type:x.type,x:C.x,y:C.y}})))}class jc extends se{constructor(){super(...arguments);g(this,"reactor");g(this,"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})});g(this,"onEnter",()=>{this.reactor=oa("clean duplicate props",()=>{try{this.cleanUpDuplicateProps()}catch(t){typeof process<"u",console.error(t)}})});g(this,"onExit",()=>{var t;(t=this.reactor)==null||t.call(this),this.editor.getCurrentPageState().editingShapeId&&this.editor.setEditingShape(null)})}}g(jc,"id","select"),g(jc,"initial","idle"),g(jc,"isLockable",!1),g(jc,"children",()=>[hp,Ew,rZ,dj,gj,vj,tj,Sj,_w,fj,nj,cj,mj,yj,pj,uj,hj,aj]);class xj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerDown",()=>{this.parent.transition("pointing",this.info)})}}g(xj,"id","idle");class wj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerUp",()=>{this.complete()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.parent.transition("zoom_brushing",this.info)});g(this,"onCancel",()=>{this.cancel()})}complete(){const{currentScreenPoint:t}=this.editor.inputs;this.editor.inputs.altKey?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)}}g(wj,"id","pointing");class bj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"zoomBrush",new Q);g(this,"onEnter",t=>{this.info=t,this.update()});g(this,"onExit",()=>{this.editor.updateInstanceState({zoomBrush:null})});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()})}update(){const{inputs:{originPagePoint:t,currentPagePoint:r}}=this.editor;this.zoomBrush.setTo(Q.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{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.updateCursor()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.updateInstanceState({zoomBrush:null,cursor:{type:"default",rotation:0}}),this.parent.setCurrentToolIdMask(void 0)});g(this,"onKeyDown",()=>{this.updateCursor()});g(this,"onKeyUp",t=>{this.updateCursor(),t.code==="KeyZ"&&this.complete()});g(this,"onInterrupt",()=>{this.complete()})}complete(){this.info.onInteractionEnd&&this.info.onInteractionEnd!=="select"?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("select")}updateCursor(){this.editor.inputs.altKey?this.editor.setCursor({type:"zoom-out",rotation:0}):this.editor.setCursor({type:"zoom-in",rotation:0})}}g(Oc,"id","zoom"),g(Oc,"initial","idle"),g(Oc,"children",()=>[xj,bj,wj]),g(Oc,"isLockable",!1);const dZ=[Tc,Mc,Ac,Oc,jc];function re(e,n,{checkForDefaultPrevented:t=!0}={}){return function(s){if(e==null||e(s),t===!1||!s.defaultPrevented)return n==null?void 0:n(s)}}function hZ(e,n){typeof e=="function"?e(n):e!=null&&(e.current=n)}function Cg(...e){return n=>e.forEach(t=>hZ(t,n))}function Xe(...e){return P.useCallback(Cg(...e),e)}function pZ(e,n){const t=P.createContext(n);function r(o){const{children:i,...a}=o,l=P.useMemo(()=>a,Object.values(a));return d.jsx(t.Provider,{value:l,children:i})}function s(o){const i=P.useContext(t);if(i)return i;if(n!==void 0)return n;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function Ts(e,n=[]){let t=[];function r(o,i){const a=P.createContext(i),l=t.length;t=[...t,i];function c(h){const{scope:p,children:f,...S}=h,m=(p==null?void 0:p[e][l])||a,x=P.useMemo(()=>S,Object.values(S));return d.jsx(m.Provider,{value:x,children:f})}function u(h,p){const f=(p==null?void 0:p[e][l])||a,S=P.useContext(f);if(S)return S;if(i!==void 0)return i;throw new Error(`\`${h}\` must be used within \`${o}\``)}return c.displayName=o+"Provider",[c,u]}const s=()=>{const o=t.map(i=>P.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return P.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,fZ(s,...n)]}function fZ(...e){const n=e[0];if(e.length===1)return n;const t=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const h=l(o)[`__scope${c}`];return{...a,...h}},{});return P.useMemo(()=>({[`__scope${n.scopeName}`]:i}),[i])}};return t.scopeName=n.scopeName,t}var Zo=globalThis!=null&&globalThis.document?P.useLayoutEffect:()=>{},gZ=B3.useId||(()=>{}),mZ=0;function Xs(e){const[n,t]=P.useState(gZ());return Zo(()=>{e||t(r=>r??String(mZ++))},[e]),e||(n?`radix-${n}`:"")}function Yt(e){const n=P.useRef(e);return P.useEffect(()=>{n.current=e}),P.useMemo(()=>(...t)=>{var r;return(r=n.current)==null?void 0:r.call(n,...t)},[])}function ci({prop:e,defaultProp:n,onChange:t=()=>{}}){const[r,s]=yZ({defaultProp:n,onChange:t}),o=e!==void 0,i=o?e:r,a=Yt(t),l=P.useCallback(c=>{if(o){const h=typeof c=="function"?c(e):c;h!==e&&a(h)}else s(c)},[o,e,s,a]);return[i,l]}function yZ({defaultProp:e,onChange:n}){const t=P.useState(e),[r]=t,s=P.useRef(r),o=Yt(n);return P.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),t}var Vi=P.forwardRef((e,n)=>{const{children:t,...r}=e,s=P.Children.toArray(t),o=s.find(vZ);if(o){const i=o.props.children,a=s.map(l=>l===o?P.Children.count(i)>1?P.Children.only(null):P.isValidElement(i)?i.props.children:null:l);return d.jsx(Kv,{...r,ref:n,children:P.isValidElement(i)?P.cloneElement(i,void 0,a):null})}return d.jsx(Kv,{...r,ref:n,children:t})});Vi.displayName="Slot";var Kv=P.forwardRef((e,n)=>{const{children:t,...r}=e;if(P.isValidElement(t)){const s=wZ(t);return P.cloneElement(t,{...xZ(r,t.props),ref:n?Cg(n,s):s})}return P.Children.count(t)>1?P.Children.only(null):null});Kv.displayName="SlotClone";var SZ=({children:e})=>d.jsx(d.Fragment,{children:e});function vZ(e){return P.isValidElement(e)&&e.type===SZ}function xZ(e,n){const t={...n};for(const r in n){const s=e[r],o=n[r];/^on[A-Z]/.test(r)?s&&o?t[r]=(...a)=>{o(...a),s(...a)}:s&&(t[r]=s):r==="style"?t[r]={...s,...o}:r==="className"&&(t[r]=[s,o].filter(Boolean).join(" "))}return{...e,...t}}function wZ(e){var r,s;let n=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var bZ=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],_e=bZ.reduce((e,n)=>{const t=P.forwardRef((r,s)=>{const{asChild:o,...i}=r,a=o?Vi:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(a,{...i,ref:s})});return t.displayName=`Primitive.${n}`,{...e,[n]:t}},{});function kw(e,n){e&&ta.flushSync(()=>e.dispatchEvent(n))}function PZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e);P.useEffect(()=>{const r=s=>{s.key==="Escape"&&t(s)};return n.addEventListener("keydown",r,{capture:!0}),()=>n.removeEventListener("keydown",r,{capture:!0})},[t,n])}var CZ="DismissableLayer",Wv="dismissableLayer.update",IZ="dismissableLayer.pointerDownOutside",EZ="dismissableLayer.focusOutside",KI,Pj=P.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ed=P.forwardRef((e,n)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,onDismiss:a,...l}=e,c=P.useContext(Pj),[u,h]=P.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=P.useState({}),S=Xe(n,I=>h(I)),m=Array.from(c.layers),[x]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(x),v=u?m.indexOf(u):-1,w=c.layersWithOutsidePointerEventsDisabled.size>0,C=v>=y,E=kZ(I=>{const _=I.target,T=[...c.branches].some(M=>M.contains(_));!C||T||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},p),k=TZ(I=>{const _=I.target;[...c.branches].some(M=>M.contains(_))||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},p);return PZ(I=>{v===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},p),P.useEffect(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(KI=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),WI(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=KI)}},[u,p,t,c]),P.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),WI())},[u,c]),P.useEffect(()=>{const I=()=>f({});return document.addEventListener(Wv,I),()=>document.removeEventListener(Wv,I)},[]),d.jsx(_e.div,{...l,ref:S,style:{pointerEvents:w?C?"auto":"none":void 0,...e.style},onFocusCapture:re(e.onFocusCapture,k.onFocusCapture),onBlurCapture:re(e.onBlurCapture,k.onBlurCapture),onPointerDownCapture:re(e.onPointerDownCapture,E.onPointerDownCapture)})});ed.displayName=CZ;var _Z="DismissableLayerBranch",Cj=P.forwardRef((e,n)=>{const t=P.useContext(Pj),r=P.useRef(null),s=Xe(n,r);return P.useEffect(()=>{const o=r.current;if(o)return t.branches.add(o),()=>{t.branches.delete(o)}},[t.branches]),d.jsx(_e.div,{...e,ref:s})});Cj.displayName=_Z;function kZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e),r=P.useRef(!1),s=P.useRef(()=>{});return P.useEffect(()=>{const o=a=>{if(a.target&&!r.current){let l=function(){Ij(IZ,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(n.removeEventListener("click",s.current),s.current=l,n.addEventListener("click",s.current,{once:!0})):l()}else n.removeEventListener("click",s.current);r.current=!1},i=window.setTimeout(()=>{n.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(i),n.removeEventListener("pointerdown",o),n.removeEventListener("click",s.current)}},[n,t]),{onPointerDownCapture:()=>r.current=!0}}function TZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e),r=P.useRef(!1);return P.useEffect(()=>{const s=o=>{o.target&&!r.current&&Ij(EZ,t,{originalEvent:o},{discrete:!1})};return n.addEventListener("focusin",s),()=>n.removeEventListener("focusin",s)},[n,t]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function WI(){const e=new CustomEvent(Wv);document.dispatchEvent(e)}function Ij(e,n,t,{discrete:r}){const s=t.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:t});n&&s.addEventListener(e,n,{once:!0}),r?kw(s,o):s.dispatchEvent(o)}var MZ=ed,AZ=Cj,Cy="focusScope.autoFocusOnMount",Iy="focusScope.autoFocusOnUnmount",GI={bubbles:!1,cancelable:!0},jZ="FocusScope",Ig=P.forwardRef((e,n)=>{const{loop:t=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...i}=e,[a,l]=P.useState(null),c=Yt(s),u=Yt(o),h=P.useRef(null),p=Xe(n,m=>l(m)),f=P.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;P.useEffect(()=>{if(r){let m=function(w){if(f.paused||!a)return;const C=w.target;a.contains(C)?h.current=C:Po(h.current,{select:!0})},x=function(w){if(f.paused||!a)return;const C=w.relatedTarget;C!==null&&(a.contains(C)||Po(h.current,{select:!0}))},y=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Po(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",x);const v=new MutationObserver(y);return a&&v.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",x),v.disconnect()}}},[r,a,f.paused]),P.useEffect(()=>{if(a){YI.add(f);const m=document.activeElement;if(!a.contains(m)){const y=new CustomEvent(Cy,GI);a.addEventListener(Cy,c),a.dispatchEvent(y),y.defaultPrevented||(OZ(NZ(Ej(a)),{select:!0}),document.activeElement===m&&Po(a))}return()=>{a.removeEventListener(Cy,c),setTimeout(()=>{const y=new CustomEvent(Iy,GI);a.addEventListener(Iy,u),a.dispatchEvent(y),y.defaultPrevented||Po(m??document.body,{select:!0}),a.removeEventListener(Iy,u),YI.remove(f)},0)}}},[a,c,u,f]);const S=P.useCallback(m=>{if(!t&&!r||f.paused)return;const x=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,y=document.activeElement;if(x&&y){const v=m.currentTarget,[w,C]=DZ(v);w&&C?!m.shiftKey&&y===C?(m.preventDefault(),t&&Po(w,{select:!0})):m.shiftKey&&y===w&&(m.preventDefault(),t&&Po(C,{select:!0})):y===v&&m.preventDefault()}},[t,r,f.paused]);return d.jsx(_e.div,{tabIndex:-1,...i,ref:p,onKeyDown:S})});Ig.displayName=jZ;function OZ(e,{select:n=!1}={}){const t=document.activeElement;for(const r of e)if(Po(r,{select:n}),document.activeElement!==t)return}function DZ(e){const n=Ej(e),t=VI(n,e),r=VI(n.reverse(),e);return[t,r]}function Ej(e){const n=[],t=document.createTreeWalker(e,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();)n.push(t.currentNode);return n}function VI(e,n){for(const t of e)if(!RZ(t,{upTo:n}))return t}function RZ(e,{upTo:n}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(n!==void 0&&e===n)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function LZ(e){return e instanceof HTMLInputElement&&"select"in e}function Po(e,{select:n=!1}={}){if(e&&e.focus){const t=document.activeElement;e.focus({preventScroll:!0}),e!==t&&LZ(e)&&n&&e.select()}}var YI=$Z();function $Z(){let e=[];return{add(n){const t=e[0];n!==t&&(t==null||t.pause()),e=XI(e,n),e.unshift(n)},remove(n){var t;e=XI(e,n),(t=e[0])==null||t.resume()}}}function XI(e,n){const t=[...e],r=t.indexOf(n);return r!==-1&&t.splice(r,1),t}function NZ(e){return e.filter(n=>n.tagName!=="A")}var FZ="Portal",td=P.forwardRef((e,n)=>{var a;const{container:t,...r}=e,[s,o]=P.useState(!1);Zo(()=>o(!0),[]);const i=t||s&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Q$.createPortal(d.jsx(_e.div,{...r,ref:n}),i):null});td.displayName=FZ;function zZ(e,n){return P.useReducer((t,r)=>n[t][r]??t,e)}var qr=e=>{const{present:n,children:t}=e,r=BZ(n),s=typeof t=="function"?t({present:r.isPresent}):P.Children.only(t),o=Xe(r.ref,UZ(s));return typeof t=="function"||r.isPresent?P.cloneElement(s,{ref:o}):null};qr.displayName="Presence";function BZ(e){const[n,t]=P.useState(),r=P.useRef({}),s=P.useRef(e),o=P.useRef("none"),i=e?"mounted":"unmounted",[a,l]=zZ(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return P.useEffect(()=>{const c=lh(r.current);o.current=a==="mounted"?c:"none"},[a]),Zo(()=>{const c=r.current,u=s.current;if(u!==e){const p=o.current,f=lh(c);e?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,l]),Zo(()=>{if(n){const c=h=>{const f=lh(r.current).includes(h.animationName);h.target===n&&f&&ta.flushSync(()=>l("ANIMATION_END"))},u=h=>{h.target===n&&(o.current=lh(r.current))};return n.addEventListener("animationstart",u),n.addEventListener("animationcancel",c),n.addEventListener("animationend",c),()=>{n.removeEventListener("animationstart",u),n.removeEventListener("animationcancel",c),n.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[n,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:P.useCallback(c=>{c&&(r.current=getComputedStyle(c)),t(c)},[])}}function lh(e){return(e==null?void 0:e.animationName)||"none"}function UZ(e){var r,s;let n=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Ey=0;function Tw(){P.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??qI()),document.body.insertAdjacentElement("beforeend",e[1]??qI()),Ey++,()=>{Ey===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(n=>n.remove()),Ey--}},[])}function qI(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var ls=function(){return ls=Object.assign||function(n){for(var t,r=1,s=arguments.length;r"u")return oQ;var n=iQ(e),t=document.documentElement.clientWidth,r=window.innerWidth;return{left:n[0],top:n[1],right:n[2],gap:Math.max(0,r-t+n[2]-n[0])}},lQ=Mj(),rl="data-scroll-locked",cQ=function(e,n,t,r){var s=e.left,o=e.top,i=e.right,a=e.gap;return t===void 0&&(t="margin"),` + 0px ${48*t}px ${10*t}px -${10*t}px inset rgba(15, 23, 44, ${((.022+r()*.005)*((1+o)/2)).toFixed(2)})`}function Kq(e){return new Q(0,0,ze,ze+e.props.growY)}function Wq(e,{initialBounds:n,scaleX:t,scaleY:r,newPoint:s}){const o=Math.max(.01,Math.min(Math.abs(t),Math.abs(r))),i=new b(0,0);t<0&&(i.x=-(n.width*o)),r<0&&(i.y=-(n.height*o));const{x:a,y:l}=b.Add(s,i.rot(e.rotation));return{x:a,y:l,props:{scale:o*e.props.scale}}}const Gq=new eo;class up extends Ir{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"isAspectRatioLocked",()=>!0);g(this,"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,...Wq(t,r)};{const c=Math.max(1,Math.abs(o.width*a)),{x:u,y:h}=a<0?b.Sub(s,b.FromAngle(t.rotation).mul(c)):s;return{id:t.id,type:t.type,x:u,y:h,props:{w:c/i.props.scale,autoSize:!1}}}});g(this,"onEditEnd",t=>{const{id:r,type:s,props:{text:o}}=t,i=t.props.text.trimEnd();i.length===0?this.editor.deleteShapes([t.id]):i!==t.props.text&&this.editor.updateShapes([{id:r,type:s,props:{text:o.trimEnd()}}])});g(this,"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=t.props.text!==r.props.text;if(!s&&!o)return;const i=this.getMinDimensions(t),a=$I(this.editor,r.props),l=i.width*t.props.scale,c=i.height*t.props.scale,u=a.width*r.props.scale,h=a.height*r.props.scale;let p;switch(r.props.textAlign){case"middle":{p=new b((u-l)/2,o?0:(h-c)/2);break}case"end":{p=new b(u-l,o?0:(h-c)/2);break}default:{if(o)break;p=new b(0,(h-c)/2);break}}if(p){p.rot(r.rotation);const{x:f,y:S}=r;return{...r,x:f-p.x,y:S-p.y,props:{...r.props,w:u}}}else return{...r,props:{...r.props,w:u}}})}getDefaultProps(){return{color:"black",size:"m",w:8,text:"",font:"draw",textAlign:"start",autoSize:!0,scale:1}}getMinDimensions(t){return Gq.get(t.props,r=>$I(this.editor,r))}getGeometry(t){const{scale:r}=t.props,{width:s,height:o}=this.getMinDimensions(t);return new no({width:s*r,height:o*r,isFilled:!0,isLabel:!0})}component(t){const{id:r,props:{font:s,size:o,text:i,color:a,scale:l,textAlign:c}}=t,{width:u,height:h}=this.getMinDimensions(t),p=t.id===this.editor.getOnlySelectedShapeId(),f=Ar(),S=Vq(r);return d.jsx(bg,{id:r,classNamePrefix:"tl-text-shape",type:"text",font:s,fontSize:gl[o],lineHeight:Gt.lineHeight,align:c,verticalAlign:"middle",text:i,labelColor:f[a].solid,isSelected:p,textWidth:u,textHeight:h,style:{transform:`scale(${l})`,transformOrigin:"top left"},wrap:!0,onKeyDown:S})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds,s=F();return t.props.autoSize&&s.getEditingShapeId()===t.id?null:d.jsx("rect",{width:N(r.width),height:N(r.height)})}toSvg(t,r){t.props.text&&r.addExportDef(xg(t.props.font));const s=this.editor.getShapeGeometry(t).bounds,o=s.width/(t.props.scale??1),i=s.height/(t.props.scale??1),a=lo(r);return d.jsx(wg,{fontSize:gl[t.props.size],font:t.props.font,align:t.props.textAlign,verticalAlign:"middle",text:t.props.text,labelColor:a[t.props.color].solid,bounds:new Q(0,0,o,i),padding:0})}}g(up,"type","text"),g(up,"props",QT),g(up,"migrations",JT);function $I(e,n){const{font:t,text:r,autoSize:s,size:o,w:i}=n,a=s?16:Math.max(16,i),l=gl[o],c=s?null:Math.floor(Math.max(a,i)),u=e.textMeasure.measureText(r,{...Gt,fontFamily:Ss[t],fontSize:l,maxWidth:c});return s&&(u.w+=1),{width:Math.max(a,u.w),height:Math.max(l,u.h)}}function Vq(e){const n=F();return P.useCallback(t=>{if(n.getEditingShapeId()===e)switch(t.key){case"Enter":{(t.ctrlKey||t.metaKey)&&n.complete();break}case"Tab":{Ie(t),t.shiftKey?ml.unindent(t.currentTarget):ml.indent(t.currentTarget);break}}},[n,e])}class dp extends Ol{constructor(){super(...arguments);g(this,"canEdit",()=>!0);g(this,"isAspectRatioLocked",()=>!0)}getDefaultProps(){return{w:100,h:100,assetId:null,time:0,playing:!0,url:""}}component(t){const{editor:r}=this,s=r.getShapeGeometry(t).bounds.w*r.getZoomLevel()>=110,{asset:o,url:i}=UA(t.id,t.props.assetId,t.props.w),{time:a,playing:l}=t.props,c=mg(t.id),u=HA(),h=P.useRef(null),p=P.useCallback(v=>{const w=v.currentTarget;w&&r.updateShapes([{type:"video",id:t.id,props:{playing:!0,time:w.currentTime}}])},[t.id,r]),f=P.useCallback(v=>{const w=v.currentTarget;w&&r.updateShapes([{type:"video",id:t.id,props:{playing:!1,time:w.currentTime}}])},[t.id,r]),S=P.useCallback(v=>{const w=v.currentTarget;w&&c&&r.updateShapes([{type:"video",id:t.id,props:{time:w.currentTime}}])},[c,t.id,r]),[y,x]=P.useState(!1),m=P.useCallback(v=>{const w=v.currentTarget;w&&(a!==w.currentTime&&(w.currentTime=a),l||w.pause(),x(!0))},[l,a]);return P.useEffect(()=>{const v=h.current;v&&(y&&!c&&a!==v.currentTime&&(v.currentTime=a),c&&document.activeElement!==v&&v.focus())},[c,y,a]),P.useEffect(()=>{if(u){const v=h.current;if(!v)return;v.pause(),v.currentTime=0}},[h,u]),d.jsxs(d.Fragment,{children:[d.jsx(Wi,{id:t.id,style:{color:"var(--color-text-3)",backgroundColor:o?"transparent":"var(--color-low)",border:o?"none":"1px solid var(--color-low-border)"},children:d.jsx("div",{className:"tl-counter-scaled",children:d.jsx("div",{className:"tl-video-container",children:o!=null&&o.props.src?i?d.jsx("video",{ref:h,style:c?{pointerEvents:"all"}:void 0,className:`tl-video tl-video-shape-${t.id.split(":")[1]}`,width:"100%",height:"100%",draggable:!1,playsInline:!0,autoPlay:!0,muted:!0,loop:!0,disableRemotePlayback:!0,disablePictureInPicture:!0,controls:c&&s,onPlay:p,onPause:f,onTimeUpdate:S,onLoadedData:m,hidden:!y,children:d.jsx("source",{src:i})}):null:d.jsx(BA,{})})})}),"url"in t.props&&t.props.url&&d.jsx(yl,{url:t.props.url,zoomLevel:r.getZoomLevel()})]})}indicator(t){return d.jsx("rect",{width:N(t.props.w),height:N(t.props.h)})}toSvg(t){return d.jsx("image",{href:Yq(t.id),width:t.props.w,height:t.props.h})}}g(dp,"type","video"),g(dp,"props",eM),g(dp,"migrations",tM);function Yq(e){const n=e.split(":")[1],t=document.querySelector(`.tl-video-shape-${n}`);if(t){const r=document.createElement("canvas");return r.width=t.videoWidth,r.height=t.videoHeight,r.getContext("2d").drawImage(t,0,0),r.toDataURL("image/png")}else throw new Error("Video with not found when attempting serialization.")}const ZA=[up,tp,np,op,cp,lp,sp,ep,ip,rp,ap,dp];function Xq(e){return e.sideEffects.register({instance_page_state:{afterChange:(n,t)=>{if(n.croppingShapeId!==t.croppingShapeId){const r=e.isIn("select.crop");!n.croppingShapeId&&t.croppingShapeId?r||e.setCurrentTool("select.crop.idle"):n.croppingShapeId&&!t.croppingShapeId&&r&&e.setCurrentTool("select.idle")}n.editingShapeId!==t.editingShapeId&&(!n.editingShapeId&&t.editingShapeId?e.isIn("select.editing_shape")||e.setCurrentTool("select.editing_shape"):n.editingShapeId&&!t.editingShapeId&&e.isIn("select.editing_shape")&&e.setCurrentTool("select.idle"))}}})}class QA extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"scribbleId","id");g(this,"markId","");g(this,"excludedShapeIds",new Set);g(this,"onEnter",t=>{this.markId="erase scribble begin",this.editor.mark(this.markId),this.info=t;const{originPagePoint:r}=this.editor.inputs;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()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()})}update(){const{editor:t,excludedShapeIds:r}=this,s=t.getErasingShapeIds(),o=t.getZoomLevel(),i=t.getCurrentPageShapes(),{inputs:{currentPagePoint:a,previousPagePoint:l}}=t;this.pushPointToScribble();const c=new Set(s),u=this.editor.options.hitTestMargin/o;for(const h of i){if(t.isShapeOfType(h,"group"))continue;const p=t.getShapeMask(h.id);if(p&&!sr(a,p))continue;const f=t.getShapeGeometry(h),S=t.getShapePageTransform(h);if(!f||!S)continue;const y=S.clone().invert(),x=y.applyToPoint(l),m=y.applyToPoint(a),{bounds:v}=f;v.minX-u>Math.max(x.x,m.x)||v.minY-u>Math.max(x.y,m.y)||v.maxX+u!r.has(h)))}complete(){const{editor:t}=this;t.deleteShapes(t.getCurrentPageState().erasingShapeIds),t.setErasingShapes([]),this.parent.transition("idle")}cancel(){const{editor:t}=this;t.setErasingShapes([]),t.bailToMark(this.markId),this.parent.transition("idle",this.info)}}g(QA,"id","erasing");var eS;let qq=(eS=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(eS,"id","idle"),eS);var tS;let Zq=(tS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{const t=this.editor.getZoomLevel(),r=this.editor.getCurrentPageShapesSorted(),{inputs:{currentPagePoint:s}}=this.editor,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)break;o.add(u.id)}}this.editor.setErasingShapes([...o])});g(this,"onLongPress",t=>{this.startErasing(t)});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startErasing(t)});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.cancel()})}startErasing(t){this.parent.transition("erasing",t)}complete(){const t=this.editor.getErasingShapeIds();t.length&&(this.editor.mark("erase end"),this.editor.deleteShapes(t)),this.editor.setErasingShapes([]),this.parent.transition("idle")}cancel(){this.editor.setErasingShapes([]),this.parent.transition("idle")}},g(tS,"id","pointing"),tS);class Tc extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})})}}g(Tc,"id","eraser"),g(Tc,"initial","idle"),g(Tc,"isLockable",!1),g(Tc,"children",()=>[qq,Zq,QA]);class JA extends se{constructor(){super(...arguments);g(this,"initialCamera",new b);g(this,"onEnter",()=>{this.initialCamera=b.From(this.editor.getCamera()),this.update()});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.parent.transition("idle")});g(this,"onComplete",()=>{this.complete()})}update(){const{initialCamera:t,editor:r}=this,{currentScreenPoint:s,originScreenPoint:o}=r.inputs,i=b.Sub(s,o).div(r.getZoomLevel());i.len2()!==0&&r.setCamera(t.clone().add(i))}complete(){const{editor:t}=this,{pointerVelocity:r}=t.inputs,s=Math.min(r.len(),2);s>.1&&this.editor.slideCamera({speed:s,direction:r}),this.parent.transition("idle")}}g(JA,"id","dragging");var nS;let Qq=(nS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"grab",rotation:0})});g(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});g(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},g(nS,"id","idle"),nS);var rS;let Jq=(rS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.stopCameraAnimation(),this.editor.setCursor({type:"grabbing",rotation:0})});g(this,"onLongPress",()=>{this.startDragging()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startDragging()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.complete()})}startDragging(){this.parent.transition("dragging")}complete(){this.parent.transition("idle")}},g(rS,"id","pointing"),rS);class Mc extends se{constructor(){super(...arguments);g(this,"onDoubleClick",t=>{if(t.phase==="settle"){const{currentScreenPoint:r}=this.editor.inputs;this.editor.zoomIn(r,{animation:{duration:220,easing:At.easeOutQuint}})}});g(this,"onTripleClick",t=>{if(t.phase==="settle"){const{currentScreenPoint:r}=this.editor.inputs;this.editor.zoomOut(r,{animation:{duration:320,easing:At.easeOutQuint}})}});g(this,"onQuadrupleClick",t=>{if(t.phase==="settle"){const r=this.editor.getZoomLevel(),{inputs:{currentScreenPoint:s}}=this.editor;r===1?this.editor.zoomToFit({animation:{duration:400,easing:At.easeOutQuint}}):this.editor.resetZoom(s,{animation:{duration:320,easing:At.easeOutQuint}})}})}}g(Mc,"id","hand"),g(Mc,"initial","idle"),g(Mc,"isLockable",!1),g(Mc,"children",()=>[Qq,Jq,JA]);var sS;let eZ=(sS=class extends se{constructor(){super(...arguments);g(this,"onPointerDown",t=>{this.parent.transition("lasering",t)})}},g(sS,"id","idle"),sS);class ej extends se{constructor(){super(...arguments);g(this,"scribbleId","id");g(this,"onEnter",()=>{const t=this.editor.scribbles.addScribble({color:"laser",opacity:.7,size:4,delay:1200,shrink:.05,taper:!0});this.scribbleId=t.id,this.pushPointToScribble()});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.pushPointToScribble()});g(this,"onPointerUp",()=>{this.complete()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()})}complete(){this.parent.transition("idle")}cancel(){this.parent.transition("idle")}}g(ej,"id","lasering");class Ac extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})})}}g(Ac,"id","laser"),g(Ac,"initial","idle"),g(Ac,"children",()=>[eZ,ej]),g(Ac,"isLockable",!1);class tj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"initialSelectedShapeIds",[]);g(this,"excludedShapeIds",new Set);g(this,"isWrapMode",!1);g(this,"initialStartShape",null);g(this,"onEnter",t=>{const{altKey:r,currentPagePoint:s}=this.editor.inputs;if(this.isWrapMode=this.editor.user.getIsWrapMode(),r){this.parent.transition("scribble_brushing",t);return}this.excludedShapeIds=new Set(this.editor.getCurrentPageShapes().filter(o=>this.editor.isShapeOfType(o,"group")||this.editor.isShapeOrAncestorLocked(o)).map(o=>o.id)),this.info=t,this.initialSelectedShapeIds=this.editor.getSelectedShapeIds().slice(),this.initialStartShape=this.editor.getShapesAtPoint(s)[0],this.hitTestShapes()});g(this,"onExit",()=>{this.initialSelectedShapeIds=[],this.editor.updateInstanceState({brush:null})});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.hitTestShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",t=>{this.editor.setSelectedShapes(this.initialSelectedShapeIds),this.parent.transition("idle",t)});g(this,"onKeyDown",t=>{this.editor.inputs.altKey?this.parent.transition("scribble_brushing",t):this.hitTestShapes()});g(this,"onKeyUp",()=>{this.hitTestShapes()});g(this,"onInterrupt",()=>{this.editor.updateInstanceState({brush:null})})}complete(){this.hitTestShapes(),this.parent.transition("idle")}hitTestShapes(){const{editor:t,excludedShapeIds:r,isWrapMode:s}=this,{inputs:{originPagePoint:o,currentPagePoint:i,shiftKey:a,ctrlKey:l}}=t,c=new Set(a?this.initialSelectedShapeIds:[]),u=s?!l:l,h=Q.FromPoints([o,i]),{corners:p}=h;let f,S,y,x,m,v;const w=t.getCurrentPageShapes(),C=t.getCurrentPageId();e:for(let I=0,_=w.length;I<_;I++){if(y=w[I],r.has(y.id)||c.has(y.id)||(x=t.getShapePageBounds(y),!x))continue e;if(h.contains(x)){this.handleHit(y,i,C,c,p);continue e}if(u||t.isShapeOfType(y,"frame"))continue e;if(h.collides(x)){if(m=t.getShapePageTransform(y),!m)continue e;v=m.clone().invert().applyToPoints(p);const T=t.getShapeGeometry(y);t:for(let M=0;M<4;M++)if(f=v[M],S=v[(M+1)%4],T.hitTestLineSegment(f,S,0)){this.handleHit(y,i,C,c,p);break t}}}t.getInstanceState().isCoarsePointer;const E=t.getInstanceState().brush;(!E||!h.equals(E))&&t.updateInstanceState({brush:{...h.toJson()}});const k=t.getSelectedShapeIds();(k.length!==c.size||k.some(I=>!c.has(I)))&&t.setSelectedShapes(Array.from(c))}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&&!YM(l,i)&&!sr(r,l)||o.add(a.id)}}g(tj,"id","brushing");const vl={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 nj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t,this.updateCursor()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startResizing()});g(this,"onLongPress",()=>{this.startResizing()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){const t=this.editor.getSelectedShapes(),r=vl[this.info.handle];this.editor.setCursor({type:r,rotation:t.length===1?this.editor.getSelectionRotation():0})}startResizing(){this.editor.getInstanceState().isReadonly||this.parent.transition("resizing",this.info)}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(nj,"id","pointing_resize_handle");const gr=8;class Ew extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","");g(this,"snapshot",{});g(this,"onEnter",t=>{this.info=t,this.markId="cropping",this.editor.mark(this.markId),this.snapshot=this.createSnapshot(),this.updateShapes()});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"getDefaultCrop",()=>({topLeft:{x:0,y:0},bottomRight:{x:1,y:1}}))}updateCursor(){if(!this.editor.getSelectedShapes()[0])return;const r=vl[this.info.handle];this.editor.setCursor({type:r,rotation:this.editor.getSelectionRotation()})}updateShapes(){const{shape:t,cursorHandleOffset:r}=this.snapshot;if(!t||!this.editor.getShapeUtil("image"))return;const o=t.props,i=this.editor.inputs.currentPagePoint.clone().sub(r),a=this.editor.inputs.originPagePoint.clone().sub(r),l=i.clone().sub(a).rot(-t.rotation),c=o.crop??this.getDefaultCrop(),u=Be(c),h=new b(t.x,t.y),p=new b(0,0),f=1/(c.bottomRight.x-c.topLeft.x)*o.w,S=1/(c.bottomRight.y-c.topLeft.y)*o.h;let y=!1;switch(this.info.handle){case"top":case"top_left":case"top_right":{if(S{this.editor.setCursor({type:"default",rotation:0});const t=this.editor.getOnlySelectedShape();t&&this.editor.setCroppingShape(t.id)});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0})});g(this,"onCancel",()=>{this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})});g(this,"onPointerDown",t=>{var r;if(!this.editor.getIsMenuOpen()){if(t.ctrlKey){this.cancel(),this.editor.root.handleEvent(t);return}switch(t.target){case"canvas":{const s=rj(this.editor);if(s&&!this.editor.isShapeOfType(s,"group")){this.onPointerDown({...t,shape:s,target:"shape"});return}this.cancel(),this.editor.root.handleEvent(t);break}case"shape":{if(t.shape.id===this.editor.getCroppingShapeId()){this.editor.setCurrentTool("select.crop.pointing_crop",t);return}else(r=this.editor.getShapeUtil(t.shape))!=null&&r.canCrop(t.shape)?(this.editor.setCroppingShape(t.shape.id),this.editor.setSelectedShapes([t.shape.id]),this.editor.setCurrentTool("select.crop.pointing_crop",t)):(this.cancel(),this.editor.root.handleEvent(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":{this.editor.setCurrentTool("select.pointing_rotate_handle",{...t,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",{...t,onInteractionEnd:"select.crop.idle"});break}default:this.cancel()}break}}}});g(this,"onDoubleClick",t=>{var i;if(this.editor.inputs.shiftKey||t.phase!=="up")return;const r=this.editor.getCroppingShapeId();if(!r)return;const s=this.editor.getShape(r);if(!s)return;const o=this.editor.getShapeUtil(s);if(o){if(t.target==="selection"){(i=o.onDoubleClickEdge)==null||i.call(o,s);return}this.cancel(),this.editor.root.handleEvent(t)}});g(this,"onKeyDown",()=>{this.nudgeCroppingImage(!1)});g(this,"onKeyRepeat",()=>{this.nudgeCroppingImage(!0)});g(this,"onKeyUp",t=>{switch(t.code){case"Enter":{this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{});break}}})}cancel(){this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle",{})}nudgeCroppingImage(t=!1){const{editor:{inputs:{keys:r}}}=this,s=r.has("ShiftLeft"),o=new b(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 b(0,0)))return;s&&o.mul(10);const i=this.editor.getShape(this.editor.getCroppingShapeId());if(!i)return;const a=sj(this.editor,i,o);a&&(t||this.editor.mark("translate crop"),this.editor.updateShapes([a]))}},g(oS,"id","idle"),oS);class oj extends se{constructor(){super(...arguments);g(this,"onCancel",()=>{this.editor.setCurrentTool("select.crop.idle",{})});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.editor.setCurrentTool("select.crop.translating_crop",t)});g(this,"onPointerUp",t=>{this.editor.setCurrentTool("select.crop.idle",t)})}}g(oj,"id","pointing_crop");class _w extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd);const r=this.editor.getSelectedShapes()[0];if(!r)return;const s=vl[this.info.handle];this.editor.setCursor({type:s,rotation:this.editor.getSelectionRotation()}),this.editor.setCroppingShape(r.id)});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0)});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startCropping()});g(this,"onLongPress",()=>{this.startCropping()});g(this,"onPointerUp",()=>{this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startCropping(){this.editor.getInstanceState().isReadonly||this.parent.transition("cropping",{...this.info,onInteractionEnd:this.info.onInteractionEnd})}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):(this.editor.setCroppingShape(null),this.editor.setCurrentTool("select.idle"))}}g(_w,"id","pointing_crop_handle");class ij extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","translating crop");g(this,"snapshot",{});g(this,"onEnter",t=>{this.info=t,this.snapshot=this.createSnapshot(),this.editor.mark(this.markId),this.editor.setCursor({type:"move",rotation:0}),this.updateShapes()});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onKeyDown",t=>{switch(t.key){case"Alt":case"Shift":{this.updateShapes();return}}});g(this,"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{originPagePoint:r,currentPagePoint:s}=this.editor.inputs,o=s.clone().sub(r),i=sj(this.editor,t,o);i&&this.editor.updateShapes([i])}}g(ij,"id","translating_crop");class hp extends se{constructor(){super(...arguments);g(this,"markId","");g(this,"onEnter",()=>{this.didCancel=!1,this.markId="crop",this.editor.mark(this.markId)});g(this,"didCancel",!1);g(this,"onExit",()=>{this.didCancel?this.editor.bailToMark(this.markId):this.editor.squashToMark(this.markId)});g(this,"onCancel",()=>{this.didCancel=!0})}}g(hp,"id","crop"),g(hp,"initial","idle"),g(hp,"children",()=>[tZ,ij,oj,_w,Ew]);class aj extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"initialHandle",{});g(this,"initialAdjacentHandle",null);g(this,"initialPagePoint",{});g(this,"markId","");g(this,"initialPageTransform");g(this,"initialPageRotation");g(this,"info",{});g(this,"isPrecise",!1);g(this,"isPreciseId",null);g(this,"pointingId",null);g(this,"onEnter",t=>{const{shape:r,isCreating:s,handle:o}=t;if(this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.shapeId=r.id,this.markId=s?`creating:${r.id}`:"dragging handle",s||this.editor.mark(this.markId),this.initialHandle=Be(o),this.editor.isShapeOfType(r,"line")&&this.initialHandle.type==="create"){this.editor.updateShape({...r,props:{points:{...r.props.points,[o.index]:{id:o.index,index:o.index,x:o.x,y:o.y}}}});const c=this.editor.getShapeHandles(r).find(u=>u.index===o.index);this.initialHandle=Be(c)}this.initialPageTransform=this.editor.getShapePageTransform(r),this.initialPageRotation=this.initialPageTransform.rotation(),this.initialPagePoint=this.editor.inputs.originPagePoint.clone(),this.editor.setCursor({type:s?"cross":"grabbing",rotation:0});const i=this.editor.getShapeHandles(r).sort(an),a=i.findIndex(l=>l.id===t.handle.id);this.initialAdjacentHandle=null;for(let l=a+1;l=0;l--){const c=i[l];if(c.type==="vertex"&&c.id!=="middle"&&c.id!==t.handle.id){this.initialAdjacentHandle=c;break}}if(this.editor.isShapeOfType(r,"arrow")){const l=Rn(this.editor,r)[t.handle.id];this.isPrecise=!1,l?(this.editor.setHintingShapes([l.toId]),this.isPrecise=l.props.isPrecise,this.isPrecise?this.isPreciseId=l.toId:this.resetExactTimeout()):this.editor.setHintingShapes([])}this.update(),this.editor.select(this.shapeId)});g(this,"exactTimeout",-1);g(this,"onPointerMove",()=>{this.update()});g(this,"onKeyDown",()=>{this.update()});g(this,"onKeyUp",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.update(),this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setHintingShapes([]),this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0})})}resetExactTimeout(){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},750)}clearExactTimeout(){this.exactTimeout!==-1&&(clearTimeout(this.exactTimeout),this.exactTimeout=-1)}complete(){this.editor.snaps.clearIndicators(),Ke(this.editor,[this.shapeId]);const{onInteractionEnd:t}=this.info;if(this.editor.getInstanceState().isToolLocked&&t){this.editor.setCurrentTool(t,{shapeId:this.shapeId});return}this.parent.transition("idle")}cancel(){this.editor.bailToMark(this.markId),this.editor.snaps.clearIndicators();const{onInteractionEnd:t}=this.info;if(t){this.editor.setCurrentTool(t,{shapeId:this.shapeId});return}this.parent.transition("idle")}update(){var I;const{editor:t,shapeId:r,initialPagePoint:s}=this,{initialHandle:o,initialPageRotation:i,initialAdjacentHandle:a}=this,l=this.editor.getHintingShapeIds(),c=this.editor.user.getIsSnapMode(),{snaps:u,inputs:{currentPagePoint:h,shiftKey:p,ctrlKey:f,altKey:S,pointerVelocity:y}}=t,x=this.info.shape,m=t.getShape(r);if(!m)return;const v=t.getShapeUtil(m);let w=h.clone().sub(s).rot(-i).add(o);if(p&&a&&o.id!=="middle"){const _=b.Angle(a,w),M=uf(_,24)-_;w=b.RotWith(w,a,M)}t.snaps.clearIndicators();let C={...o,x:w.x,y:w.y};if(o.canSnap&&(c?!f:f)){if(!t.getShapePageTransform(m.id))throw Error("Expected a page transform");const T=u.handles.snapHandle({currentShapeId:r,handle:C});T&&(T.nudge.rot(-t.getShapeParentTransform(m).rotation()),w.add(T.nudge),C={...o,x:w.x,y:w.y})}const E=(I=v.onHandleDrag)==null?void 0:I.call(v,m,{handle:C,isPrecise:this.isPrecise||S,initial:x}),k={id:m.id,type:m.type,...E};if(o.type==="vertex"&&this.editor.isShapeOfType(m,"arrow")){const _=Rn(t,m)[o.id];_?l[0]!==_.toId&&(t.setHintingShapes([_.toId]),this.pointingId=_.toId,this.isPrecise=y.len()<.5||S,this.isPreciseId=this.isPrecise?_.toId:null,this.resetExactTimeout()):l.length>0&&(t.setHintingShapes([]),this.pointingId=null,this.isPrecise=!1,this.isPreciseId=null,this.resetExactTimeout())}E&&t.updateShapes([k])}}g(aj,"id","dragging_handle");function lj(e){return e.isLabel?[e]:e instanceof Wr?e.children.filter(n=>n.isLabel):[]}class cj extends se{constructor(){super(...arguments);g(this,"hitShapeForPointerUp",null);g(this,"onEnter",()=>{const t=this.editor.getEditingShape();if(!t)throw Error("Entered editing state without an editing shape");this.hitShapeForPointerUp=null,Ks(this.editor),this.editor.select(t)});g(this,"onExit",()=>{var o;const{editingShapeId:t}=this.editor.getCurrentPageState();if(!t)return;this.editor.setEditingShape(null),Ks.cancel();const r=this.editor.getShape(t),s=this.editor.getShapeUtil(r);(o=s.onEditEnd)==null||o.call(s,r)});g(this,"onPointerMove",t=>{if(this.hitShapeForPointerUp&&this.editor.inputs.isDragging){if(this.editor.getInstanceState().isReadonly||this.hitShapeForPointerUp.isLocked)return;this.editor.select(this.hitShapeForPointerUp),this.parent.transition("translating",t),this.hitShapeForPointerUp=null;return}switch(t.target){case"shape":case"canvas":{Ks(this.editor);return}}});g(this,"onPointerDown",t=>{switch(this.hitShapeForPointerUp=null,t.target){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=lj(o),a=i.length===1?i[0]:void 0,l=this.editor.isShapeOfType(s,"text")&&s.props.text.trim()==="";if(a&&!l){const c=this.editor.getPointInShapeSpace(r,this.editor.inputs.currentPagePoint);if(a.bounds.containsPoint(c,0)&&a.hitTestPoint(c)){if(r.id===s.id)return;this.hitShapeForPointerUp=r,this.editor.mark("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)});g(this,"onPointerUp",t=>{const r=this.hitShapeForPointerUp;if(!r)return;this.hitShapeForPointerUp=null;const s=this.editor.getShapeUtil(r);if(!r.isLocked){if(this.editor.getInstanceState().isReadonly&&!s.canEditInReadOnly(r)){this.parent.transition("pointing_shape",t);return}this.editor.select(r.id),this.editor.setEditingShape(r.id),Ks(this.editor)}});g(this,"onComplete",t=>{this.parent.transition("idle",t)});g(this,"onCancel",t=>{this.parent.transition("idle",t)})}}g(cj,"id","editing_shape");function NI(e){const n=e.getOnlySelectedShape();return!!(n&&!e.isShapeOrAncestorLocked(n)&&e.getShapeUtil(n).canCrop(n))}function bf(e){const n=e.getSelectedShapeIds(),{shiftKey:t,altKey:r,currentPagePoint:s}=e.inputs,o=e.getShapeAtPoint(s,{hitInside:!1,margin:e.options.hitTestMargin/e.getZoomLevel(),hitLabels:!0,renderingOnly:!0,filter:i=>!i.isLocked});if(o){const i=e.getOutermostSelectableShape(o);if(t&&!r)e.cancelDoubleClick(),n.includes(i.id)?(e.mark("deselecting shape"),e.deselect(i)):(e.mark("shift selecting shape"),e.setSelectedShapes([...n,i.id]));else{let a;i===o||i.id===e.getFocusedGroupId()||n.includes(i.id)?a=o:a=i,a&&!n.includes(a.id)&&(e.mark("selecting shape"),e.select(a.id))}}else{if(t)return;{n.length>0&&(e.mark("selecting none"),e.selectNone());const i=e.getFocusedGroupId();if(An(i)){const a=e.getShape(i);e.isPointInShape(a,s,{margin:0,hitInside:!0})||e.setFocusedGroup(null)}}}}const nZ=["Delete","Backspace","[","]","Enter"," ","Shift","Tab"];var iS;let rZ=(iS=class extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{this.parent.setCurrentToolIdMask(void 0),Ks(this.editor),this.editor.setCursor({type:"default",rotation:0})});g(this,"onExit",()=>{Ks.cancel()});g(this,"onPointerMove",()=>{Ks(this.editor)});g(this,"onPointerDown",t=>{if(this.editor.getIsMenuOpen())return;const r=t.ctrlKey&&NI(this.editor);if(t.ctrlKey&&!r){if(t.target==="shape"&&this.isDarwin&&this.editor.inputs.keys.has("ControlLeft")&&!this.editor.isShapeOrAncestorLocked(t.shape)){this.parent.transition("pointing_shape",t);return}this.parent.transition("brushing",t);return}switch(t.target){case"canvas":{const s=rj(this.editor);if(s&&!s.isLocked){this.onPointerDown({...t,shape:s,target:"shape"});return}const o=this.editor.getSelectedShapeIds(),i=this.editor.getOnlySelectedShape(),{inputs:{currentPagePoint:a}}=this.editor;if((o.length>1||i&&!this.editor.getShapeUtil(i).hideSelectionBoundsBg(i))&&FI(this.editor,a)){this.onPointerDown({...t,target:"selection"});return}this.parent.transition("pointing_canvas",t);break}case"shape":{const{shape:s}=t;if(this.isOverArrowLabelTest(s)){this.parent.transition("pointing_arrow_label",t);break}if(this.editor.isShapeOrAncestorLocked(s)){this.parent.transition("pointing_canvas",t);break}this.parent.transition("pointing_shape",t);break}case"handle":{if(this.editor.getInstanceState().isReadonly)break;this.editor.inputs.altKey?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":{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":{r?this.parent.transition("crop.pointing_crop_handle",t):this.parent.transition("pointing_resize_handle",t);break}default:{const s=this.editor.getHoveredShape();if(s&&!this.editor.getSelectedShapeIds().includes(s.id)&&!s.isLocked){this.onPointerDown({...t,shape:s,target:"shape"});return}this.parent.transition("pointing_selection",t)}}break}}});g(this,"onDoubleClick",t=>{var r,s,o,i;if(!(this.editor.inputs.shiftKey||t.phase!=="up"))switch(t.target){case"canvas":{const a=this.editor.getHoveredShape(),l=a&&!this.editor.isShapeOfType(a,"group")?a:this.editor.getSelectedShapeAtPoint(this.editor.inputs.currentPagePoint)??this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1}),c=this.editor.getFocusedGroupId();if(l){if(this.editor.isShapeOfType(l,"group")){bf(this.editor);return}else{const u=this.editor.getShape(l.parentId);if(u&&this.editor.isShapeOfType(u,"group")&&!(c&&u.id===c)){bf(this.editor);return}}this.onDoubleClick({...t,shape:l,target:"shape"});return}this.editor.inputs.shiftKey||this.handleDoubleClickOnCanvas(t);break}case"selection":{if(this.editor.getInstanceState().isReadonly)break;const a=this.editor.getOnlySelectedShape();if(a){const l=this.editor.getShapeUtil(a);if(!this.canInteractWithShapeInReadOnly(a))return;if(t.handle==="right"||t.handle==="left"||t.handle==="top"||t.handle==="bottom"){const c=(r=l.onDoubleClickEdge)==null?void 0:r.call(l,a);if(c){this.editor.mark("double click edge"),this.editor.updateShapes([c]),Ke(this.editor,[a.id]);return}}if(l.canCrop(a)&&!this.editor.isShapeOrAncestorLocked(a)){this.parent.transition("crop",t);return}this.shouldStartEditingShape(a)&&this.startEditingShape(a,t,!0)}break}case"shape":{const{shape:a}=t,l=this.editor.getShapeUtil(a);if(a.type!=="video"&&a.type!=="embed"&&this.editor.getInstanceState().isReadonly)break;if(l.onDoubleClick){const c=(s=l.onDoubleClick)==null?void 0:s.call(l,a);if(c){this.editor.updateShapes([c]);return}else if(l.canCrop(a)&&!this.editor.isShapeOrAncestorLocked(a)){this.editor.mark("select and crop"),this.editor.select((o=t.shape)==null?void 0:o.id),this.parent.transition("crop",t);return}}this.shouldStartEditingShape(a)?this.startEditingShape(a,t,!0):this.handleDoubleClickOnCanvas(t);break}case"handle":{if(this.editor.getInstanceState().isReadonly)break;const{shape:a,handle:l}=t,c=this.editor.getShapeUtil(a),u=(i=c.onDoubleClickHandle)==null?void 0:i.call(c,a,l);u?this.editor.updateShapes([u]):this.shouldStartEditingShape(a)&&this.startEditingShape(a,t,!0)}}});g(this,"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.currentPagePoint,{margin:this.editor.options.hitTestMargin/this.editor.getZoomLevel(),hitInside:!1,hitLabels:!0,hitLocked:!0,hitFrameInside:!1,renderingOnly:!0});if(s){this.onRightClick({...t,shape:s,target:"shape"});return}const o=this.editor.getSelectedShapeIds(),i=this.editor.getOnlySelectedShape(),{inputs:{currentPagePoint:a}}=this.editor;if((o.length>1||i&&!this.editor.getShapeUtil(i).hideSelectionBoundsBg(i))&&FI(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.mark("selecting shape"),this.editor.setSelectedShapes([o.id]));break}}});g(this,"onCancel",()=>{this.editor.getFocusedGroupId()!==this.editor.getCurrentPageId()&&this.editor.getSelectedShapeIds().length>0?this.editor.popFocusedGroupId():(this.editor.mark("clearing selection"),this.editor.selectNone())});g(this,"onKeyDown",t=>{switch(t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{this.nudgeSelectedShapes(!1);return}}if(xt.editOnType.get()&&!nZ.includes(t.key)&&!t.altKey&&!t.ctrlKey){const r=this.editor.getOnlySelectedShape();if(r&&this.editor.isShapeOfType(r,"note")&&this.shouldStartEditingShape(r)){this.startEditingShape(r,{...t,target:"shape",shape:r},!0);return}}});g(this,"onKeyRepeat",t=>{switch(t.code){case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":{this.nudgeSelectedShapes(!0);break}}});g(this,"onKeyUp",t=>{switch(t.code){case"Enter":{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.shouldStartEditingShape(s)){this.startEditingShape(s,{...t,target:"shape",shape:s},!0);return}NI(this.editor)&&this.parent.transition("crop",t);break}}});g(this,"isDarwin",window.navigator.userAgent.toLowerCase().indexOf("mac")>-1)}shouldStartEditingShape(t=this.editor.getOnlySelectedShape()){return!t||this.editor.isShapeOrAncestorLocked(t)&&t.type!=="embed"||!this.canInteractWithShapeInReadOnly(t)?!1:this.editor.getShapeUtil(t).canEdit(t)}startEditingShape(t,r,s){this.editor.isShapeOrAncestorLocked(t)&&t.type!=="embed"||(this.editor.mark("editing shape"),vf(this.editor,t,s),this.parent.transition("editing_shape",r))}isOverArrowLabelTest(t){if(!t)return!1;const r=this.editor.getPointInShapeSpace(t,this.editor.inputs.currentPagePoint);if(this.editor.isShapeOfType(t,"arrow")){const s=this.editor.getShapeGeometry(t).children[1];if(s&&sr(r,s.vertices))return!0}return!1}handleDoubleClickOnCanvas(t){if(this.editor.getInstanceState().isReadonly)return;this.editor.mark("creating text shape");const r=je(),{x:s,y:o}=this.editor.inputs.currentPagePoint;this.editor.createShapes([{id:r,type:"text",x:s,y:o,props:{text:"",autoSize:!0}}]);const i=this.editor.getShape(r);if(!i)return;const a=this.editor.getShapeUtil(i);this.editor.getInstanceState().isReadonly&&!a.canEditInReadOnly(i)||(this.editor.setEditingShape(r),this.editor.select(r),this.parent.transition("editing_shape",t))}nudgeSelectedShapes(t=!1){const{editor:{inputs:{keys:r}}}=this,s=r.has("ShiftLeft"),o=new b(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 b(0,0)))return;t||this.editor.mark("nudge shapes");const{gridSize:i}=this.editor.getDocumentSettings(),a=this.editor.getInstanceState().isGridMode?s?i*iZ:i:s?sZ:oZ,l=this.editor.getSelectedShapeIds();this.editor.nudgeShapes(l,o.mul(a)),Ke(this.editor,l)}canInteractWithShapeInReadOnly(t){return!!(!this.editor.getInstanceState().isReadonly||this.editor.getShapeUtil(t).canEditInReadOnly(t))}},g(iS,"id","idle"),iS);const sZ=10,oZ=1,iZ=5;function FI(e,n){const t=e.getSelectionRotatedPageBounds();if(!t)return!1;const r=e.getSelectionRotation();return r?sr(n,t.corners.map(s=>b.RotWith(s,t.point,r))):t.containsPoint(n)}class uj extends se{constructor(){super(...arguments);g(this,"shapeId","");g(this,"markId","");g(this,"wasAlreadySelected",!1);g(this,"didDrag",!1);g(this,"info",{});g(this,"onEnter",t=>{const{shape:r}=t;this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.info=t,this.shapeId=r.id,this.didDrag=!1,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{currentPagePoint:i}=this.editor.inputs,a=this.editor.getPointInShapeSpace(r,i);this._labelDragOffset=b.Sub(o.center,a),this.markId="label-drag start",this.editor.mark(this.markId),this.editor.setSelectedShapes([this.shapeId])});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})});g(this,"_labelDragOffset",new b(0,0));g(this,"onPointerMove",()=>{const{isDragging:t}=this.editor.inputs;if(!t)return;const r=this.editor.getShape(this.shapeId);if(!r)return;const s=ds(this.editor,r),o=this.editor.getShapeGeometry(r),i=o.children[0],a=this.editor.getPointInShapeSpace(r,this.editor.inputs.currentPagePoint),l=i.nearestPoint(b.Add(a,this._labelDragOffset));let c;if(s.isStraight){const u=b.Dist(s.start.point,s.end.point);c=1-b.Dist(s.end.point,l)/u}else{const{_center:u,measure:h,angleEnd:p,angleStart:f}=o.children[0];c=Cv(h,f,p,u.angle(l))}isNaN(c)&&(c=.5),this.didDrag=!0,this.editor.updateShape({id:r.id,type:r.type,props:{labelPosition:c}})});g(this,"onPointerUp",()=>{const t=this.editor.getShape(this.shapeId);t&&(this.didDrag||!this.wasAlreadySelected?this.complete():(this.editor.setEditingShape(t.id),this.editor.setCurrentTool("select.editing_shape")))});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){this.editor.setCursor({type:"grabbing",rotation:0})}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(uj,"id","pointing_arrow_label");class dj extends se{constructor(){super(...arguments);g(this,"onEnter",()=>{const{inputs:t}=this.editor;t.shiftKey||this.editor.getSelectedShapeIds().length>0&&(this.editor.mark("selecting none"),this.editor.selectNone())});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.parent.transition("brushing",t)});g(this,"onPointerUp",()=>{bf(this.editor),this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onInterrupt",()=>{this.parent.transition("idle")})}complete(){this.parent.transition("idle")}}g(dj,"id","pointing_canvas");class hj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t;const{shape:r}=t;if(this.editor.isShapeOfType(r,"arrow")){const s=Rn(this.editor,r)[t.handle.id];s&&this.editor.setHintingShapes([s.toId])}this.editor.setCursor({type:"grabbing",rotation:0})});g(this,"onExit",()=>{this.editor.setHintingShapes([]),this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerUp",()=>{const{shape:t,handle:r}=this.info;if(this.editor.isShapeOfType(t,"note")){const{editor:s}=this,o=zI(s,t,r,!1);if(o){vf(s,o,!0);return}}this.parent.transition("idle",this.info)});g(this,"onPointerMove",()=>{const{editor:t}=this;t.inputs.isDragging&&this.startDraggingHandle()});g(this,"onLongPress",()=>{this.startDraggingHandle()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startDraggingHandle(){const{editor:t}=this;if(t.getInstanceState().isReadonly)return;const{shape:r,handle:s}=this.info;if(t.isShapeOfType(r,"note")){const o=zI(t,r,s,!0);if(o){const i=t.getPointInParentSpace(o,t.inputs.originPagePoint).sub(b.Rot(vg.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:()=>{vf(t,o,!0)}});return}}this.parent.transition("dragging_handle",this.info)}cancel(){this.parent.transition("idle")}}g(hj,"id","pointing_handle");function zI(e,n,t,r){const s=e.getShapePageTransform(n.id),o=s.point(),i=s.rotation(),l=_A(e,o,i,n.props.growY,0,n.props.scale)[t.index];if(l)return TA(e,n,l,i,r)}class pj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.info=t,this.updateCursor()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0})});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.startRotating()});g(this,"onLongPress",()=>{this.startRotating()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}updateCursor(){this.editor.setCursor({type:vl[this.info.handle],rotation:this.editor.getSelectionRotation()})}startRotating(){this.editor.getInstanceState().isReadonly||this.parent.transition("rotating",this.info)}complete(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}cancel(){this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}}g(pj,"id","pointing_rotate_handle");class fj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerUp",t=>{bf(this.editor),this.parent.transition("idle",t)});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startTranslating(t)});g(this,"onLongPress",t=>{this.startTranslating(t)});g(this,"onDoubleClick",t=>{var o,i;const r=this.editor.getHoveredShape(),s=r&&!this.editor.isShapeOfType(r,"group")?r:this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{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}});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startTranslating(t){this.editor.getInstanceState().isReadonly||this.parent.transition("translating",t)}cancel(){this.parent.transition("idle")}}g(fj,"id","pointing_selection");class gj extends se{constructor(){super(...arguments);g(this,"hitShape",{});g(this,"hitShapeForPointerUp",{});g(this,"isDoubleClick",!1);g(this,"didSelectOnEnter",!1);g(this,"onEnter",t=>{const r=this.editor.getSelectedShapeIds(),s=this.editor.getSelectionRotatedPageBounds(),o=this.editor.getFocusedGroupId(),{inputs:{currentPagePoint:i,shiftKey:a,altKey:l}}=this.editor;this.hitShape=t.shape,this.isDoubleClick=!1;const c=this.editor.getOutermostSelectableShape(t.shape),u=this.editor.findShapeAncestor(c,h=>r.includes(h.id));if(this.editor.getShapeUtil(t.shape).onClick||c.id===o||r.includes(c.id)||u||r.length>1&&(s!=null&&s.containsPoint(i))){this.didSelectOnEnter=!1,this.hitShapeForPointerUp=c;return}this.didSelectOnEnter=!0,a&&!l?(this.editor.cancelDoubleClick(),r.includes(c.id)||(this.editor.mark("shift selecting shape"),this.editor.setSelectedShapes([...r,c.id]))):(this.editor.mark("selecting shape"),this.editor.setSelectedShapes([c.id]))});g(this,"onPointerUp",t=>{var u;const r=this.editor.getSelectedShapeIds(),s=this.editor.getFocusedGroupId(),o=this.editor.getZoomLevel(),{inputs:{currentPagePoint:i,shiftKey:a}}=this.editor,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 h=this.editor.getShapeUtil(c);if(h.onClick){const p=(u=h.onClick)==null?void 0:u.call(h,c);if(p){this.editor.mark("shape on click"),this.editor.updateShapes([p]),this.parent.transition("idle",t);return}}if(c.id===s){r.length>0?(this.editor.mark("clearing shape ids"),this.editor.setSelectedShapes([])):this.editor.popFocusedGroupId(),this.parent.transition("idle",t);return}}if(!this.didSelectOnEnter){const h=this.editor.getOutermostSelectableShape(l,p=>!r.includes(p.id));if(r.includes(h.id))if(a)this.editor.mark("deselecting on pointer up"),this.editor.deselect(c);else if(r.includes(c.id)){if(r.length===1){const p=this.editor.getShapeUtil(c).getGeometry(c),f=lj(p),S=f.length===1?f[0]:void 0;if(S){const y=this.editor.getPointInShapeSpace(c,i);if(S.bounds.containsPoint(y,0)&&S.hitTestPoint(y)){this.editor.run(()=>{this.editor.mark("editing on pointer up"),this.editor.select(c.id);const x=this.editor.getShapeUtil(c);this.editor.getInstanceState().isReadonly&&!x.canEditInReadOnly(c)||(this.editor.setEditingShape(c.id),this.editor.setCurrentTool("select.editing_shape"),this.isDoubleClick&&this.editor.emit("select-all-text",{shapeId:c.id}))});return}}}this.editor.mark("selecting on pointer up"),this.editor.select(c.id)}else this.editor.mark("selecting on pointer up"),this.editor.select(c);else if(a){const p=this.editor.getShapeAncestors(h);this.editor.mark("shift deselecting on pointer up"),this.editor.setSelectedShapes([...this.editor.getSelectedShapeIds().filter(f=>!p.find(S=>S.id===f)),h.id])}else this.editor.mark("selecting on pointer up"),this.editor.setSelectedShapes([h.id])}this.parent.transition("idle",t)});g(this,"onDoubleClick",()=>{this.isDoubleClick=!0});g(this,"onPointerMove",t=>{this.editor.inputs.isDragging&&this.startTranslating(t)});g(this,"onLongPress",t=>{this.startTranslating(t)});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.cancel()});g(this,"onInterrupt",()=>{this.cancel()})}startTranslating(t){this.editor.getInstanceState().isReadonly||(this.editor.focus(),this.parent.transition("translating",t))}cancel(){this.parent.transition("idle")}}g(gj,"id","pointing_shape");class mj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"markId","");g(this,"didHoldCommand",!1);g(this,"creationCursorOffset",{x:0,y:0});g(this,"snapshot",{});g(this,"onEnter",t=>{const{isCreating:r=!1,creationCursorOffset:s={x:0,y:0}}=t;this.info=t,this.didHoldCommand=!1,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.creationCursorOffset=s,this.snapshot=this._createSnapshot(),r?(this.markId=`creating:${this.editor.getOnlySelectedShape().id}`,this.editor.setCursor({type:"cross",rotation:0})):(this.markId="starting resizing",this.editor.mark(this.markId)),this.handleResizeStart(),this.updateShapes()});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onKeyDown",()=>{this.updateShapes()});g(this,"onKeyUp",()=>{this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.setCursor({type:"default",rotation:0}),this.editor.snaps.clearIndicators()});g(this,"_createSnapshot",()=>{const t=this.editor.getSelectedShapeIds(),r=this.editor.getSelectionRotation(),{inputs:{originPagePoint:s}}=this.editor,o=this.editor.getSelectionRotatedPageBounds(),i=b.RotWith(o.getHandlePoint(this.info.handle),o.point,r),a=b.Sub(s,i),l=new Map,c=[];t.forEach(h=>{const p=this.editor.getShape(h);if(p){if(p.type==="frame"&&c.push({id:h,children:me(this.editor.getSortedChildIdsForParent(p).map(f=>this.editor.getShape(f)))}),l.set(p.id,this._createShapeSnapshot(p)),this.editor.isShapeOfType(p,"frame")&&t.length===1)return;this.editor.visitDescendants(p.id,f=>{const S=this.editor.getShape(f);if(S&&(l.set(S.id,this._createShapeSnapshot(S)),this.editor.isShapeOfType(S,"frame")))return!1})}});const u=![...l.values()].some(h=>!aM(h.pageRotation,r)||h.isAspectRatioLocked);return{shapeSnapshots:l,selectionBounds:o,cursorHandleOffset:a,selectionRotation:r,selectedShapeIds:t,canShapesDeform:u,initialSelectionPageBounds:this.editor.getSelectionPageBounds(),frames:c}});g(this,"_createShapeSnapshot",t=>{const r=this.editor.getShapePageTransform(t),s=this.editor.getShapeUtil(t);return{shape:t,bounds:this.editor.getShapeGeometry(t).bounds,pageTransform:r,pageRotation:oe.Decompose(r).rotation,isAspectRatioLocked:s.isAspectRatioLocked(t)}})}cancel(){this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,{}):this.parent.transition("idle")}complete(){var t,r;if(Ke(this.editor,this.snapshot.selectedShapeIds),this.handleResizeEnd(),this.info.isCreating&&this.info.onCreate){(r=(t=this.info).onCreate)==null||r.call(t,this.editor.getOnlySelectedShape());return}if(this.editor.getInstanceState().isToolLocked&&this.info.onInteractionEnd){this.editor.setCurrentTool(this.info.onInteractionEnd,{});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{altKey:t,shiftKey:r}=this.editor.inputs,{frames:s,shapeSnapshots:o,selectionBounds:i,cursorHandleOffset:a,selectedShapeIds:l,selectionRotation:c,canShapesDeform:u}=this.snapshot;let h=r||!u;if(o.size===1){const _=[...o.values()][0];this.editor.isShapeOfType(_.shape,"text")&&(h=!(this.info.handle==="left"||this.info.handle==="right"))}const{ctrlKey:p}=this.editor.inputs,f=this.editor.inputs.currentPagePoint.clone().sub(a).sub(this.creationCursorOffset),S=this.editor.inputs.originPagePoint.clone().sub(a);if(this.editor.getInstanceState().isGridMode&&!p){const{gridSize:_}=this.editor.getDocumentSettings();f.snapToGrid(_)}const y=this.info.handle,x=BI(y,Math.PI);if(this.editor.snaps.clearIndicators(),(this.editor.user.getIsSnapMode()?!p:p)&&c%Ve===0){const{nudge:_}=this.editor.snaps.shapeBounds.snapResizeShapes({dragDelta:b.Sub(f,S),initialSelectionPageBounds:this.snapshot.initialSelectionPageBounds,handle:BI(y,c),isAspectRatioLocked:h,isResizingFromCenter:t});f.add(_)}const v=b.RotWith(t?i.center:i.getHandlePoint(x),i.point,c),w=b.Sub(f,v).rot(-c),C=b.Sub(S,v).rot(-c),E=b.DivV(w,C);Number.isFinite(E.x)||(E.x=1),Number.isFinite(E.y)||(E.y=1);const k=y==="top"||y==="bottom",I=y==="left"||y==="right";h?I?E.y=Math.abs(E.x):k?E.x=Math.abs(E.y):Math.abs(E.x)>Math.abs(E.y)?E.y=Math.abs(E.x)*(E.y<0?-1:1):E.x=Math.abs(E.y)*(E.x<0?-1:1):(k&&(E.x=1),I&&(E.y=1)),this.info.isCreating||this.updateCursor({dragHandle:y,isFlippedX:E.x<0,isFlippedY:E.y<0,rotation:c});for(const _ of o.keys()){const T=o.get(_);this.editor.resizeShape(_,E,{initialShape:T.shape,initialBounds:T.bounds,initialPageTransform:T.pageTransform,dragHandle:y,mode:l.length===1&&_===l[0]?"resize_bounds":"scale_shape",scaleOrigin:v,isAspectRatioLocked:h,scaleAxisRotation:c,skipStartAndEndCallbacks:!0})}if(this.editor.inputs.ctrlKey){this.didHoldCommand=!0;for(const{id:_,children:T}of s){if(!T.length)continue;const M=o.get(_).shape,D=this.editor.getShape(_);if(!(M&&D))continue;const $=D.x-M.x,j=D.y-M.y,O=new b($,j).rot(-M.rotation);if(O.x!==0||O.y!==0)for(const R of T)this.editor.updateShape({id:R.id,type:R.type,x:R.x-O.x,y:R.y-O.y})}}else if(this.didHoldCommand){this.didHoldCommand=!1;for(const{children:_}of s)if(_.length)for(const T of _)this.editor.updateShape({id:T.id,type:T.type,x:T.x,y:T.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)}}g(mj,"id","resizing");const Py=["top","top_right","right","bottom_right","bottom","bottom_left","left","top_left"];function BI(e,n){n=n%Le;const t=Math.round(n/(Me/4)),r=Py.indexOf(e);return Py[(r+t)%Py.length]}const UI=Math.PI/180;class yj extends se{constructor(){super(...arguments);g(this,"snapshot",{});g(this,"info",{});g(this,"markId","");g(this,"onEnter",t=>{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.markId="rotate start",this.editor.mark(this.markId);const r=ZM({editor:this.editor});if(!r)return this.parent.transition("idle",this.info);this.snapshot=r;const s=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Uh({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!1}),snapshot:this.snapshot,stage:"start"}),this.editor.setCursor({type:vl[this.info.handle],rotation:s+this.snapshot.initialSelectionRotation})});g(this,"onExit",()=>{this.editor.setCursor({type:"default",rotation:0}),this.parent.setCurrentToolIdMask(void 0),this.snapshot={}});g(this,"onPointerMove",()=>{this.update()});g(this,"onKeyDown",()=>{this.update()});g(this,"onKeyUp",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"update",()=>{const t=this._getRotationFromPointerPosition({snapToNearestDegree:!1});Uh({editor:this.editor,delta:t,snapshot:this.snapshot,stage:"update"}),this.editor.setCursor({type:vl[this.info.handle],rotation:t+this.snapshot.initialSelectionRotation})});g(this,"cancel",()=>{this.editor.bailToMark(this.markId),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("idle",this.info)});g(this,"complete",()=>{Uh({editor:this.editor,delta:this._getRotationFromPointerPosition({snapToNearestDegree:!0}),snapshot:this.snapshot,stage:"end"}),Ke(this.editor,this.snapshot.shapeSnapshots.map(t=>t.shape.id)),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("idle",this.info)})}_getRotationFromPointerPosition({snapToNearestDegree:t}){const r=this.editor.getSelectionRotation(),s=this.editor.getSelectionRotatedPageBounds(),{inputs:{shiftKey:o,currentPagePoint:i}}=this.editor,{initialCursorAngle:a,initialSelectionRotation:l}=this.snapshot;if(!s)return l;const u=s.center.clone().rotWith(s.point,r).angle(i)-a;let h=l+u;if(o)h=uf(h,24);else if(t&&(h=Math.round(h/UI)*UI,this.editor.getInstanceState().isCoarsePointer)){const p=uf(h,4),f=Fh(h,p);Math.abs(f)<_H(5)&&(h=p)}return h-l}}g(yj,"id","rotating");class Sj extends se{constructor(){super(...arguments);g(this,"hits",new Set);g(this,"size",0);g(this,"scribbleId","id");g(this,"initialSelectedShapeIds",new Set);g(this,"newlySelectedShapeIds",new Set);g(this,"onEnter",()=>{this.initialSelectedShapeIds=new Set(this.editor.inputs.shiftKey?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})});g(this,"onExit",()=>{this.editor.scribbles.stop(this.scribbleId)});g(this,"onPointerMove",()=>{this.updateScribbleSelection(!0)});g(this,"onPointerUp",()=>{this.complete()});g(this,"onKeyDown",()=>{this.updateScribbleSelection(!1)});g(this,"onKeyUp",()=>{this.editor.inputs.altKey?this.updateScribbleSelection(!1):this.parent.transition("brushing")});g(this,"onCancel",()=>{this.cancel()});g(this,"onComplete",()=>{this.complete()});g(this,"pushPointToScribble",()=>{const{x:t,y:r}=this.editor.inputs.currentPagePoint;this.editor.scribbles.addPoint(this.scribbleId,t,r)})}updateScribbleSelection(t){const{editor:r}=this,s=this.editor.getCurrentPageShapes(),{inputs:{shiftKey:o,originPagePoint:i,previousPagePoint:a,currentPagePoint:l}}=this.editor,{newlySelectedShapeIds:c,initialSelectedShapeIds:u}=this;t&&this.pushPointToScribble();const h=s;let p,f,S,y;const x=0;for(let w=0,C=h.length;wMath.max(S.x,y.x)||I.minY-x>Math.max(S.y,y.y)||I.maxX+x!v.has(w)))&&this.editor.setSelectedShapes(Array.from(v))}complete(){this.updateScribbleSelection(!0),this.parent.transition("idle")}cancel(){this.editor.setSelectedShapes([...this.initialSelectedShapeIds]),this.parent.transition("idle")}}g(Sj,"id","scribble_brushing");const aZ=20,lZ=100;class cZ{constructor(n){g(this,"prevDroppingShapeId",null);g(this,"droppingNodeTimer",null);g(this,"first",!0);g(this,"dispose",()=>{this.clear()});this.editor=n,n.disposables.add(this.dispose)}updateDroppingNode(n,t){var r;this.first&&(this.editor.setHintingShapes(n.map(s=>this.editor.findShapeAncestor(s,o=>o.type!=="group")).filter(s=>s)),this.prevDroppingShapeId=((r=this.editor.getDroppingOverShape(this.editor.inputs.originPagePoint,n))==null?void 0:r.id)??null,this.first=!1),this.droppingNodeTimer===null?this.setDragTimer(n,aZ,t):this.editor.inputs.pointerVelocity.len()>.5&&(clearTimeout(this.droppingNodeTimer),this.setDragTimer(n,lZ,t))}setDragTimer(n,t,r){this.droppingNodeTimer=this.editor.timers.setTimeout(()=>{this.editor.run(()=>{this.handleDrag(this.editor.inputs.currentPagePoint,n,r)}),this.droppingNodeTimer=null},t)}handleDrag(n,t,r){var l,c,u,h,p;t=me(t.map(f=>this.editor.getShape(f.id)));const s=((l=this.editor.getDroppingOverShape(n,t))==null?void 0:l.id)??null;if(s===this.prevDroppingShapeId){this.hintParents(t);return}const{prevDroppingShapeId:o}=this,i=o&&this.editor.getShape(o),a=s&&this.editor.getShape(s);i&&((u=(c=this.editor.getShapeUtil(i)).onDragShapesOut)==null||u.call(c,i,t)),a&&((p=(h=this.editor.getShapeUtil(a)).onDragShapesOver)==null||p.call(h,a,t)),this.hintParents(t),r==null||r(),this.prevDroppingShapeId=s}hintParents(n){const t=new Map;for(const s of n){const o=this.editor.findShapeAncestor(s,i=>i.type!=="group");o&&(t.has(o.id)||t.set(o.id,[]),t.get(o.id).push(s.id))}const r=[];for(const[s,o]of t){const i=this.editor.getShape(s);i&&CA(this.editor,i).length{});g(this,"dragAndDropManager",new cZ(this.editor));g(this,"onEnter",t=>{var o;const{isCreating:r=!1,onCreate:s=()=>{}}=t;if(!((o=this.editor.getSelectedShapeIds())!=null&&o.length)){this.parent.transition("idle");return}if(this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.isCreating=r,this.onCreate=s,r?this.markId=`creating:${this.editor.getOnlySelectedShape().id}`:(this.markId="translating",this.editor.mark(this.markId)),this.isCloning=!1,this.info=t,this.editor.setCursor({type:"move",rotation:0}),this.selectionSnapshot=HI(this.editor),!this.isCreating&&this.editor.inputs.altKey){this.startCloning();return}this.snapshot=this.selectionSnapshot,this.handleStart(),this.updateShapes()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.selectionSnapshot={},this.snapshot={},this.editor.snaps.clearIndicators(),this.editor.setCursor({type:"default",rotation:0}),this.dragAndDropManager.clear()});g(this,"onTick",({elapsed:t})=>{const{editor:r}=this;this.dragAndDropManager.updateDroppingNode(this.snapshot.movingShapes,this.updateParentTransforms),r.edgeScrollManager.updateEdgeScrolling(t)});g(this,"onPointerMove",()=>{this.updateShapes()});g(this,"onKeyDown",()=>{if(this.editor.inputs.altKey&&!this.isCloning){this.startCloning();return}this.updateShapes()});g(this,"onKeyUp",()=>{if(!this.editor.inputs.altKey&&this.isCloning){this.stopCloning();return}this.updateShapes()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onComplete",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()});g(this,"updateParentTransforms",()=>{const{editor:t,snapshot:{shapeSnapshots:r}}=this;r.forEach(s=>{const o=t.getShape(s.shape.id);if(!o)return null;const i=Tn(o.parentId)?null:oe.Inverse(t.getShapePageTransform(o.parentId));s.parentTransform=i})})}startCloning(){this.isCreating||(this.isCloning=!0,this.reset(),this.markId="translating",this.editor.mark(this.markId),this.editor.duplicateShapes(Array.from(this.editor.getSelectedShapeIds())),this.snapshot=HI(this.editor),this.handleStart(),this.updateShapes())}stopCloning(){this.isCloning=!1,this.snapshot=this.selectionSnapshot,this.reset(),this.markId="translating",this.editor.mark(this.markId),this.updateShapes()}reset(){this.editor.bailToMark(this.markId)}complete(){var t;this.updateShapes(),this.dragAndDropManager.dropShapes(this.snapshot.movingShapes),Ke(this.editor,this.snapshot.movingShapes.map(r=>r.id)),this.handleEnd(),this.editor.getInstanceState().isToolLocked&&this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd):this.isCreating?(t=this.onCreate)==null||t.call(this,this.editor.getOnlySelectedShape()):this.parent.transition("idle")}cancel(){this.reset(),this.info.onInteractionEnd?this.editor.setCurrentTool(this.info.onInteractionEnd):this.parent.transition("idle",this.info)}handleStart(){const{movingShapes:t}=this.snapshot,r=[];t.forEach(s=>{var a;const o=this.editor.getShapeUtil(s),i=(a=o.onTranslateStart)==null?void 0:a.call(o,s);i&&r.push(i)}),r.length>0&&this.editor.updateShapes(r),this.editor.setHoveredShape(null)}handleEnd(){const{movingShapes:t}=this.snapshot;if(this.isCloning&&t.length>0){const s=b.Average(t.map(i=>this.editor.getShapePageTransform(i.id).point())),o=b.Sub(s,this.selectionSnapshot.averagePagePoint);b.IsNaN(o)||this.editor.updateInstanceState({duplicateProps:{shapeIds:t.map(i=>i.id),offset:{x:o.x,y:o.y}}})}const r=[];t.forEach(s=>{var l;const o=this.editor.getShape(s.id),i=this.editor.getShapeUtil(s),a=(l=i.onTranslateEnd)==null?void 0:l.call(i,s,o);a&&r.push(a)}),r.length>0&&this.editor.updateShapes(r)}updateShapes(){const{snapshot:t}=this;this.dragAndDropManager.updateDroppingNode(t.movingShapes,this.updateParentTransforms),uZ({editor:this.editor,snapshot:t});const{movingShapes:r}=t,s=[];r.forEach(o=>{var c;const i=this.editor.getShape(o.id),a=this.editor.getShapeUtil(o),l=(c=a.onTranslate)==null?void 0:c.call(a,o,i);l&&s.push(l)}),s.length>0&&this.editor.updateShapes(s)}}g(vj,"id","translating");function HI(e){var h;const n=[],t=[],r=e.getSelectedShapeIds(),s=me(r.map(p=>{const f=e.getShape(p);if(!f)return null;n.push(f);const S=e.getShapePageTransform(p),y=S.point(),x=S.rotation();t.push(y);const m=to.isId(f.parentId)?null:oe.Inverse(e.getShapePageTransform(f.parentId));return{shape:f,pagePoint:y,pageRotation:x,parentTransform:m}})),o=e.getOnlySelectedShape();let i=[];if(o)i=e.snaps.shapeBounds.getSnapPoints(o.id);else{const p=e.getSelectionPageBounds();p&&(i=p.cornersAndCenter.map((f,S)=>({id:"selection:"+S,x:f.x,y:f.y})))}let a,l;const{originPagePoint:c}=e.inputs,u=s.filter(p=>e.isShapeOfType(p.shape,"note")&&e.isPointInShape(p.shape,c));if(u.length!==0)if(u.length===1)l=u[0];else{const p=e.getCurrentPageShapesSorted();l=(h=u.map(f=>({snapshot:f,index:p.findIndex(S=>S.id===f.shape.id)})).sort((f,S)=>S.index-f.index)[0])==null?void 0:h.snapshot}return l&&(a=kA(e,l.pageRotation,l.shape.props.scale,l.shape.props.growY??0)),{averagePagePoint:b.Average(t),movingShapes:n,shapeSnapshots:s,initialPageBounds:e.getSelectionPageBounds(),initialSnapPoints:i,noteAdjacentPositions:a,noteSnapshot:l}}function uZ({editor:e,snapshot:n}){const{inputs:t}=e,{noteSnapshot:r,noteAdjacentPositions:s,initialPageBounds:o,initialSnapPoints:i,shapeSnapshots:a,averagePagePoint:l}=n,c=e.getInstanceState().isGridMode,u=e.getDocumentSettings().gridSize,h=b.Sub(t.currentPagePoint,t.originPagePoint),p=e.inputs.shiftKey?Math.abs(h.x){const w=b.Add(m,y),C=v?oe.applyToPoint(v,w):w;return{id:x.id,type:x.type,x:C.x,y:C.y}})))}class jc extends se{constructor(){super(...arguments);g(this,"reactor");g(this,"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})});g(this,"onEnter",()=>{this.reactor=oa("clean duplicate props",()=>{try{this.cleanUpDuplicateProps()}catch(t){typeof process<"u",console.error(t)}})});g(this,"onExit",()=>{var t;(t=this.reactor)==null||t.call(this),this.editor.getCurrentPageState().editingShapeId&&this.editor.setEditingShape(null)})}}g(jc,"id","select"),g(jc,"initial","idle"),g(jc,"isLockable",!1),g(jc,"children",()=>[hp,Ew,rZ,dj,gj,vj,tj,Sj,_w,fj,nj,cj,mj,yj,pj,uj,hj,aj]);class xj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerDown",()=>{this.parent.transition("pointing",this.info)})}}g(xj,"id","idle");class wj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"onEnter",t=>{this.info=t});g(this,"onPointerUp",()=>{this.complete()});g(this,"onPointerMove",()=>{this.editor.inputs.isDragging&&this.parent.transition("zoom_brushing",this.info)});g(this,"onCancel",()=>{this.cancel()})}complete(){const{currentScreenPoint:t}=this.editor.inputs;this.editor.inputs.altKey?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)}}g(wj,"id","pointing");class bj extends se{constructor(){super(...arguments);g(this,"info",{});g(this,"zoomBrush",new Q);g(this,"onEnter",t=>{this.info=t,this.update()});g(this,"onExit",()=>{this.editor.updateInstanceState({zoomBrush:null})});g(this,"onPointerMove",()=>{this.update()});g(this,"onPointerUp",()=>{this.complete()});g(this,"onCancel",()=>{this.cancel()})}update(){const{inputs:{originPagePoint:t,currentPagePoint:r}}=this.editor;this.zoomBrush.setTo(Q.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{this.info=t,this.parent.setCurrentToolIdMask(t.onInteractionEnd),this.updateCursor()});g(this,"onExit",()=>{this.parent.setCurrentToolIdMask(void 0),this.editor.updateInstanceState({zoomBrush:null,cursor:{type:"default",rotation:0}}),this.parent.setCurrentToolIdMask(void 0)});g(this,"onKeyDown",()=>{this.updateCursor()});g(this,"onKeyUp",t=>{this.updateCursor(),t.code==="KeyZ"&&this.complete()});g(this,"onInterrupt",()=>{this.complete()})}complete(){this.info.onInteractionEnd&&this.info.onInteractionEnd!=="select"?this.editor.setCurrentTool(this.info.onInteractionEnd,this.info):this.parent.transition("select")}updateCursor(){this.editor.inputs.altKey?this.editor.setCursor({type:"zoom-out",rotation:0}):this.editor.setCursor({type:"zoom-in",rotation:0})}}g(Oc,"id","zoom"),g(Oc,"initial","idle"),g(Oc,"children",()=>[xj,bj,wj]),g(Oc,"isLockable",!1);const dZ=[Tc,Mc,Ac,Oc,jc];function re(e,n,{checkForDefaultPrevented:t=!0}={}){return function(s){if(e==null||e(s),t===!1||!s.defaultPrevented)return n==null?void 0:n(s)}}function hZ(e,n){typeof e=="function"?e(n):e!=null&&(e.current=n)}function Cg(...e){return n=>e.forEach(t=>hZ(t,n))}function Xe(...e){return P.useCallback(Cg(...e),e)}function pZ(e,n){const t=P.createContext(n);function r(o){const{children:i,...a}=o,l=P.useMemo(()=>a,Object.values(a));return d.jsx(t.Provider,{value:l,children:i})}function s(o){const i=P.useContext(t);if(i)return i;if(n!==void 0)return n;throw new Error(`\`${o}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,s]}function Ts(e,n=[]){let t=[];function r(o,i){const a=P.createContext(i),l=t.length;t=[...t,i];function c(h){const{scope:p,children:f,...S}=h,y=(p==null?void 0:p[e][l])||a,x=P.useMemo(()=>S,Object.values(S));return d.jsx(y.Provider,{value:x,children:f})}function u(h,p){const f=(p==null?void 0:p[e][l])||a,S=P.useContext(f);if(S)return S;if(i!==void 0)return i;throw new Error(`\`${h}\` must be used within \`${o}\``)}return c.displayName=o+"Provider",[c,u]}const s=()=>{const o=t.map(i=>P.createContext(i));return function(a){const l=(a==null?void 0:a[e])||o;return P.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return s.scopeName=e,[r,fZ(s,...n)]}function fZ(...e){const n=e[0];if(e.length===1)return n;const t=()=>{const r=e.map(s=>({useScope:s(),scopeName:s.scopeName}));return function(o){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const h=l(o)[`__scope${c}`];return{...a,...h}},{});return P.useMemo(()=>({[`__scope${n.scopeName}`]:i}),[i])}};return t.scopeName=n.scopeName,t}var Zo=globalThis!=null&&globalThis.document?P.useLayoutEffect:()=>{},gZ=B3.useId||(()=>{}),mZ=0;function Xs(e){const[n,t]=P.useState(gZ());return Zo(()=>{e||t(r=>r??String(mZ++))},[e]),e||(n?`radix-${n}`:"")}function Yt(e){const n=P.useRef(e);return P.useEffect(()=>{n.current=e}),P.useMemo(()=>(...t)=>{var r;return(r=n.current)==null?void 0:r.call(n,...t)},[])}function ci({prop:e,defaultProp:n,onChange:t=()=>{}}){const[r,s]=yZ({defaultProp:n,onChange:t}),o=e!==void 0,i=o?e:r,a=Yt(t),l=P.useCallback(c=>{if(o){const h=typeof c=="function"?c(e):c;h!==e&&a(h)}else s(c)},[o,e,s,a]);return[i,l]}function yZ({defaultProp:e,onChange:n}){const t=P.useState(e),[r]=t,s=P.useRef(r),o=Yt(n);return P.useEffect(()=>{s.current!==r&&(o(r),s.current=r)},[r,s,o]),t}var Vi=P.forwardRef((e,n)=>{const{children:t,...r}=e,s=P.Children.toArray(t),o=s.find(vZ);if(o){const i=o.props.children,a=s.map(l=>l===o?P.Children.count(i)>1?P.Children.only(null):P.isValidElement(i)?i.props.children:null:l);return d.jsx(Kv,{...r,ref:n,children:P.isValidElement(i)?P.cloneElement(i,void 0,a):null})}return d.jsx(Kv,{...r,ref:n,children:t})});Vi.displayName="Slot";var Kv=P.forwardRef((e,n)=>{const{children:t,...r}=e;if(P.isValidElement(t)){const s=wZ(t);return P.cloneElement(t,{...xZ(r,t.props),ref:n?Cg(n,s):s})}return P.Children.count(t)>1?P.Children.only(null):null});Kv.displayName="SlotClone";var SZ=({children:e})=>d.jsx(d.Fragment,{children:e});function vZ(e){return P.isValidElement(e)&&e.type===SZ}function xZ(e,n){const t={...n};for(const r in n){const s=e[r],o=n[r];/^on[A-Z]/.test(r)?s&&o?t[r]=(...a)=>{o(...a),s(...a)}:s&&(t[r]=s):r==="style"?t[r]={...s,...o}:r==="className"&&(t[r]=[s,o].filter(Boolean).join(" "))}return{...e,...t}}function wZ(e){var r,s;let n=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var bZ=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],_e=bZ.reduce((e,n)=>{const t=P.forwardRef((r,s)=>{const{asChild:o,...i}=r,a=o?Vi:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(a,{...i,ref:s})});return t.displayName=`Primitive.${n}`,{...e,[n]:t}},{});function kw(e,n){e&&ta.flushSync(()=>e.dispatchEvent(n))}function PZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e);P.useEffect(()=>{const r=s=>{s.key==="Escape"&&t(s)};return n.addEventListener("keydown",r,{capture:!0}),()=>n.removeEventListener("keydown",r,{capture:!0})},[t,n])}var CZ="DismissableLayer",Wv="dismissableLayer.update",IZ="dismissableLayer.pointerDownOutside",EZ="dismissableLayer.focusOutside",KI,Pj=P.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ed=P.forwardRef((e,n)=>{const{disableOutsidePointerEvents:t=!1,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,onDismiss:a,...l}=e,c=P.useContext(Pj),[u,h]=P.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=P.useState({}),S=Xe(n,I=>h(I)),y=Array.from(c.layers),[x]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),m=y.indexOf(x),v=u?y.indexOf(u):-1,w=c.layersWithOutsidePointerEventsDisabled.size>0,C=v>=m,E=kZ(I=>{const _=I.target,T=[...c.branches].some(M=>M.contains(_));!C||T||(s==null||s(I),i==null||i(I),I.defaultPrevented||a==null||a())},p),k=TZ(I=>{const _=I.target;[...c.branches].some(M=>M.contains(_))||(o==null||o(I),i==null||i(I),I.defaultPrevented||a==null||a())},p);return PZ(I=>{v===c.layers.size-1&&(r==null||r(I),!I.defaultPrevented&&a&&(I.preventDefault(),a()))},p),P.useEffect(()=>{if(u)return t&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(KI=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),WI(),()=>{t&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=KI)}},[u,p,t,c]),P.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),WI())},[u,c]),P.useEffect(()=>{const I=()=>f({});return document.addEventListener(Wv,I),()=>document.removeEventListener(Wv,I)},[]),d.jsx(_e.div,{...l,ref:S,style:{pointerEvents:w?C?"auto":"none":void 0,...e.style},onFocusCapture:re(e.onFocusCapture,k.onFocusCapture),onBlurCapture:re(e.onBlurCapture,k.onBlurCapture),onPointerDownCapture:re(e.onPointerDownCapture,E.onPointerDownCapture)})});ed.displayName=CZ;var _Z="DismissableLayerBranch",Cj=P.forwardRef((e,n)=>{const t=P.useContext(Pj),r=P.useRef(null),s=Xe(n,r);return P.useEffect(()=>{const o=r.current;if(o)return t.branches.add(o),()=>{t.branches.delete(o)}},[t.branches]),d.jsx(_e.div,{...e,ref:s})});Cj.displayName=_Z;function kZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e),r=P.useRef(!1),s=P.useRef(()=>{});return P.useEffect(()=>{const o=a=>{if(a.target&&!r.current){let l=function(){Ij(IZ,t,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(n.removeEventListener("click",s.current),s.current=l,n.addEventListener("click",s.current,{once:!0})):l()}else n.removeEventListener("click",s.current);r.current=!1},i=window.setTimeout(()=>{n.addEventListener("pointerdown",o)},0);return()=>{window.clearTimeout(i),n.removeEventListener("pointerdown",o),n.removeEventListener("click",s.current)}},[n,t]),{onPointerDownCapture:()=>r.current=!0}}function TZ(e,n=globalThis==null?void 0:globalThis.document){const t=Yt(e),r=P.useRef(!1);return P.useEffect(()=>{const s=o=>{o.target&&!r.current&&Ij(EZ,t,{originalEvent:o},{discrete:!1})};return n.addEventListener("focusin",s),()=>n.removeEventListener("focusin",s)},[n,t]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function WI(){const e=new CustomEvent(Wv);document.dispatchEvent(e)}function Ij(e,n,t,{discrete:r}){const s=t.originalEvent.target,o=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:t});n&&s.addEventListener(e,n,{once:!0}),r?kw(s,o):s.dispatchEvent(o)}var MZ=ed,AZ=Cj,Cy="focusScope.autoFocusOnMount",Iy="focusScope.autoFocusOnUnmount",GI={bubbles:!1,cancelable:!0},jZ="FocusScope",Ig=P.forwardRef((e,n)=>{const{loop:t=!1,trapped:r=!1,onMountAutoFocus:s,onUnmountAutoFocus:o,...i}=e,[a,l]=P.useState(null),c=Yt(s),u=Yt(o),h=P.useRef(null),p=Xe(n,y=>l(y)),f=P.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;P.useEffect(()=>{if(r){let y=function(w){if(f.paused||!a)return;const C=w.target;a.contains(C)?h.current=C:Po(h.current,{select:!0})},x=function(w){if(f.paused||!a)return;const C=w.relatedTarget;C!==null&&(a.contains(C)||Po(h.current,{select:!0}))},m=function(w){if(document.activeElement===document.body)for(const E of w)E.removedNodes.length>0&&Po(a)};document.addEventListener("focusin",y),document.addEventListener("focusout",x);const v=new MutationObserver(m);return a&&v.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",x),v.disconnect()}}},[r,a,f.paused]),P.useEffect(()=>{if(a){YI.add(f);const y=document.activeElement;if(!a.contains(y)){const m=new CustomEvent(Cy,GI);a.addEventListener(Cy,c),a.dispatchEvent(m),m.defaultPrevented||(OZ(NZ(Ej(a)),{select:!0}),document.activeElement===y&&Po(a))}return()=>{a.removeEventListener(Cy,c),setTimeout(()=>{const m=new CustomEvent(Iy,GI);a.addEventListener(Iy,u),a.dispatchEvent(m),m.defaultPrevented||Po(y??document.body,{select:!0}),a.removeEventListener(Iy,u),YI.remove(f)},0)}}},[a,c,u,f]);const S=P.useCallback(y=>{if(!t&&!r||f.paused)return;const x=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,m=document.activeElement;if(x&&m){const v=y.currentTarget,[w,C]=DZ(v);w&&C?!y.shiftKey&&m===C?(y.preventDefault(),t&&Po(w,{select:!0})):y.shiftKey&&m===w&&(y.preventDefault(),t&&Po(C,{select:!0})):m===v&&y.preventDefault()}},[t,r,f.paused]);return d.jsx(_e.div,{tabIndex:-1,...i,ref:p,onKeyDown:S})});Ig.displayName=jZ;function OZ(e,{select:n=!1}={}){const t=document.activeElement;for(const r of e)if(Po(r,{select:n}),document.activeElement!==t)return}function DZ(e){const n=Ej(e),t=VI(n,e),r=VI(n.reverse(),e);return[t,r]}function Ej(e){const n=[],t=document.createTreeWalker(e,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();)n.push(t.currentNode);return n}function VI(e,n){for(const t of e)if(!RZ(t,{upTo:n}))return t}function RZ(e,{upTo:n}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(n!==void 0&&e===n)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function LZ(e){return e instanceof HTMLInputElement&&"select"in e}function Po(e,{select:n=!1}={}){if(e&&e.focus){const t=document.activeElement;e.focus({preventScroll:!0}),e!==t&&LZ(e)&&n&&e.select()}}var YI=$Z();function $Z(){let e=[];return{add(n){const t=e[0];n!==t&&(t==null||t.pause()),e=XI(e,n),e.unshift(n)},remove(n){var t;e=XI(e,n),(t=e[0])==null||t.resume()}}}function XI(e,n){const t=[...e],r=t.indexOf(n);return r!==-1&&t.splice(r,1),t}function NZ(e){return e.filter(n=>n.tagName!=="A")}var FZ="Portal",td=P.forwardRef((e,n)=>{var a;const{container:t,...r}=e,[s,o]=P.useState(!1);Zo(()=>o(!0),[]);const i=t||s&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?Q$.createPortal(d.jsx(_e.div,{...r,ref:n}),i):null});td.displayName=FZ;function zZ(e,n){return P.useReducer((t,r)=>n[t][r]??t,e)}var qr=e=>{const{present:n,children:t}=e,r=BZ(n),s=typeof t=="function"?t({present:r.isPresent}):P.Children.only(t),o=Xe(r.ref,UZ(s));return typeof t=="function"||r.isPresent?P.cloneElement(s,{ref:o}):null};qr.displayName="Presence";function BZ(e){const[n,t]=P.useState(),r=P.useRef({}),s=P.useRef(e),o=P.useRef("none"),i=e?"mounted":"unmounted",[a,l]=zZ(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return P.useEffect(()=>{const c=lh(r.current);o.current=a==="mounted"?c:"none"},[a]),Zo(()=>{const c=r.current,u=s.current;if(u!==e){const p=o.current,f=lh(c);e?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),s.current=e}},[e,l]),Zo(()=>{if(n){const c=h=>{const f=lh(r.current).includes(h.animationName);h.target===n&&f&&ta.flushSync(()=>l("ANIMATION_END"))},u=h=>{h.target===n&&(o.current=lh(r.current))};return n.addEventListener("animationstart",u),n.addEventListener("animationcancel",c),n.addEventListener("animationend",c),()=>{n.removeEventListener("animationstart",u),n.removeEventListener("animationcancel",c),n.removeEventListener("animationend",c)}}else l("ANIMATION_END")},[n,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:P.useCallback(c=>{c&&(r.current=getComputedStyle(c)),t(c)},[])}}function lh(e){return(e==null?void 0:e.animationName)||"none"}function UZ(e){var r,s;let n=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Ey=0;function Tw(){P.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??qI()),document.body.insertAdjacentElement("beforeend",e[1]??qI()),Ey++,()=>{Ey===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(n=>n.remove()),Ey--}},[])}function qI(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var ls=function(){return ls=Object.assign||function(n){for(var t,r=1,s=arguments.length;r"u")return oQ;var n=iQ(e),t=document.documentElement.clientWidth,r=window.innerWidth;return{left:n[0],top:n[1],right:n[2],gap:Math.max(0,r-t+n[2]-n[0])}},lQ=Mj(),rl="data-scroll-locked",cQ=function(e,n,t,r){var s=e.left,o=e.top,i=e.right,a=e.gap;return t===void 0&&(t="margin"),` .`.concat(KZ,` { overflow: hidden `).concat(r,`; padding-right: `).concat(a,"px ").concat(r,`; @@ -254,14 +254,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho body[`).concat(rl,`] { `).concat(WZ,": ").concat(a,`px; } -`)},QI=function(){var e=parseInt(document.body.getAttribute(rl)||"0",10);return isFinite(e)?e:0},uQ=function(){P.useEffect(function(){return document.body.setAttribute(rl,(QI()+1).toString()),function(){var e=QI()-1;e<=0?document.body.removeAttribute(rl):document.body.setAttribute(rl,e.toString())}},[])},dQ=function(e){var n=e.noRelative,t=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;uQ();var o=P.useMemo(function(){return aQ(s)},[s]);return P.createElement(lQ,{styles:cQ(o,!n,s,t?"":"!important")})},Gv=!1;if(typeof window<"u")try{var ch=Object.defineProperty({},"passive",{get:function(){return Gv=!0,!0}});window.addEventListener("test",ch,ch),window.removeEventListener("test",ch,ch)}catch{Gv=!1}var Sa=Gv?{passive:!1}:!1,hQ=function(e){return e.tagName==="TEXTAREA"},Aj=function(e,n){var t=window.getComputedStyle(e);return t[n]!=="hidden"&&!(t.overflowY===t.overflowX&&!hQ(e)&&t[n]==="visible")},pQ=function(e){return Aj(e,"overflowY")},fQ=function(e){return Aj(e,"overflowX")},JI=function(e,n){var t=n.ownerDocument,r=n;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=jj(e,r);if(s){var o=Oj(e,r),i=o[1],a=o[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==t.body);return!1},gQ=function(e){var n=e.scrollTop,t=e.scrollHeight,r=e.clientHeight;return[n,t,r]},mQ=function(e){var n=e.scrollLeft,t=e.scrollWidth,r=e.clientWidth;return[n,t,r]},jj=function(e,n){return e==="v"?pQ(n):fQ(n)},Oj=function(e,n){return e==="v"?gQ(n):mQ(n)},yQ=function(e,n){return e==="h"&&n==="rtl"?-1:1},SQ=function(e,n,t,r,s){var o=yQ(e,window.getComputedStyle(n).direction),i=o*r,a=t.target,l=n.contains(a),c=!1,u=i>0,h=0,p=0;do{var f=Oj(e,a),S=f[0],m=f[1],x=f[2],y=m-x-o*S;(S||y)&&jj(e,a)&&(h+=y,p+=S),a instanceof ShadowRoot?a=a.host:a=a.parentNode}while(!l&&a!==document.body||l&&(n.contains(a)||n===a));return(u&&(Math.abs(h)<1||!s)||!u&&(Math.abs(p)<1||!s))&&(c=!0),c},uh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},eE=function(e){return[e.deltaX,e.deltaY]},tE=function(e){return e&&"current"in e?e.current:e},vQ=function(e,n){return e[0]===n[0]&&e[1]===n[1]},xQ=function(e){return` +`)},QI=function(){var e=parseInt(document.body.getAttribute(rl)||"0",10);return isFinite(e)?e:0},uQ=function(){P.useEffect(function(){return document.body.setAttribute(rl,(QI()+1).toString()),function(){var e=QI()-1;e<=0?document.body.removeAttribute(rl):document.body.setAttribute(rl,e.toString())}},[])},dQ=function(e){var n=e.noRelative,t=e.noImportant,r=e.gapMode,s=r===void 0?"margin":r;uQ();var o=P.useMemo(function(){return aQ(s)},[s]);return P.createElement(lQ,{styles:cQ(o,!n,s,t?"":"!important")})},Gv=!1;if(typeof window<"u")try{var ch=Object.defineProperty({},"passive",{get:function(){return Gv=!0,!0}});window.addEventListener("test",ch,ch),window.removeEventListener("test",ch,ch)}catch{Gv=!1}var Sa=Gv?{passive:!1}:!1,hQ=function(e){return e.tagName==="TEXTAREA"},Aj=function(e,n){var t=window.getComputedStyle(e);return t[n]!=="hidden"&&!(t.overflowY===t.overflowX&&!hQ(e)&&t[n]==="visible")},pQ=function(e){return Aj(e,"overflowY")},fQ=function(e){return Aj(e,"overflowX")},JI=function(e,n){var t=n.ownerDocument,r=n;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var s=jj(e,r);if(s){var o=Oj(e,r),i=o[1],a=o[2];if(i>a)return!0}r=r.parentNode}while(r&&r!==t.body);return!1},gQ=function(e){var n=e.scrollTop,t=e.scrollHeight,r=e.clientHeight;return[n,t,r]},mQ=function(e){var n=e.scrollLeft,t=e.scrollWidth,r=e.clientWidth;return[n,t,r]},jj=function(e,n){return e==="v"?pQ(n):fQ(n)},Oj=function(e,n){return e==="v"?gQ(n):mQ(n)},yQ=function(e,n){return e==="h"&&n==="rtl"?-1:1},SQ=function(e,n,t,r,s){var o=yQ(e,window.getComputedStyle(n).direction),i=o*r,a=t.target,l=n.contains(a),c=!1,u=i>0,h=0,p=0;do{var f=Oj(e,a),S=f[0],y=f[1],x=f[2],m=y-x-o*S;(S||m)&&jj(e,a)&&(h+=m,p+=S),a instanceof ShadowRoot?a=a.host:a=a.parentNode}while(!l&&a!==document.body||l&&(n.contains(a)||n===a));return(u&&(Math.abs(h)<1||!s)||!u&&(Math.abs(p)<1||!s))&&(c=!0),c},uh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},eE=function(e){return[e.deltaX,e.deltaY]},tE=function(e){return e&&"current"in e?e.current:e},vQ=function(e,n){return e[0]===n[0]&&e[1]===n[1]},xQ=function(e){return` .block-interactivity-`.concat(e,` {pointer-events: none;} .allow-interactivity-`).concat(e,` {pointer-events: all;} -`)},wQ=0,va=[];function bQ(e){var n=P.useRef([]),t=P.useRef([0,0]),r=P.useRef(),s=P.useState(wQ++)[0],o=P.useState(Mj)[0],i=P.useRef(e);P.useEffect(function(){i.current=e},[e]),P.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var m=HZ([e.lockRef.current],(e.shards||[]).map(tE),!0).filter(Boolean);return m.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),m.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var a=P.useCallback(function(m,x){if("touches"in m&&m.touches.length===2)return!i.current.allowPinchZoom;var y=uh(m),v=t.current,w="deltaX"in m?m.deltaX:v[0]-y[0],C="deltaY"in m?m.deltaY:v[1]-y[1],E,k=m.target,I=Math.abs(w)>Math.abs(C)?"h":"v";if("touches"in m&&I==="h"&&k.type==="range")return!1;var _=JI(I,k);if(!_)return!0;if(_?E=I:(E=I==="v"?"h":"v",_=JI(I,k)),!_)return!1;if(!r.current&&"changedTouches"in m&&(w||C)&&(r.current=E),!E)return!0;var T=r.current||E;return SQ(T,x,m,T==="h"?w:C,!0)},[]),l=P.useCallback(function(m){var x=m;if(!(!va.length||va[va.length-1]!==o)){var y="deltaY"in x?eE(x):uh(x),v=n.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&vQ(E.delta,y)})[0];if(v&&v.should){x.cancelable&&x.preventDefault();return}if(!v){var w=(i.current.shards||[]).map(tE).filter(Boolean).filter(function(E){return E.contains(x.target)}),C=w.length>0?a(x,w[0]):!i.current.noIsolation;C&&x.cancelable&&x.preventDefault()}}},[]),c=P.useCallback(function(m,x,y,v){var w={name:m,delta:x,target:y,should:v,shadowParent:PQ(y)};n.current.push(w),setTimeout(function(){n.current=n.current.filter(function(C){return C!==w})},1)},[]),u=P.useCallback(function(m){t.current=uh(m),r.current=void 0},[]),h=P.useCallback(function(m){c(m.type,eE(m),m.target,a(m,e.lockRef.current))},[]),p=P.useCallback(function(m){c(m.type,uh(m),m.target,a(m,e.lockRef.current))},[]);P.useEffect(function(){return va.push(o),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Sa),document.addEventListener("touchmove",l,Sa),document.addEventListener("touchstart",u,Sa),function(){va=va.filter(function(m){return m!==o}),document.removeEventListener("wheel",l,Sa),document.removeEventListener("touchmove",l,Sa),document.removeEventListener("touchstart",u,Sa)}},[]);var f=e.removeScrollBar,S=e.inert;return P.createElement(P.Fragment,null,S?P.createElement(o,{styles:xQ(s)}):null,f?P.createElement(dQ,{gapMode:e.gapMode}):null)}function PQ(e){for(var n=null;e!==null;)e instanceof ShadowRoot&&(n=e.host,e=e.host),e=e.parentNode;return n}const CQ=QZ(Tj,bQ);var _g=P.forwardRef(function(e,n){return P.createElement(Eg,ls({},e,{ref:n,sideCar:CQ}))});_g.classNames=Eg.classNames;var IQ=function(e){if(typeof document>"u")return null;var n=Array.isArray(e)?e[0]:e;return n.ownerDocument.body},xa=new WeakMap,dh=new WeakMap,hh={},My=0,Dj=function(e){return e&&(e.host||Dj(e.parentNode))},EQ=function(e,n){return n.map(function(t){if(e.contains(t))return t;var r=Dj(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(t){return!!t})},_Q=function(e,n,t,r){var s=EQ(n,Array.isArray(e)?e:[e]);hh[t]||(hh[t]=new WeakMap);var o=hh[t],i=[],a=new Set,l=new Set(s),c=function(h){!h||a.has(h)||(a.add(h),c(h.parentNode))};s.forEach(c);var u=function(h){!h||l.has(h)||Array.prototype.forEach.call(h.children,function(p){if(a.has(p))u(p);else try{var f=p.getAttribute(r),S=f!==null&&f!=="false",m=(xa.get(p)||0)+1,x=(o.get(p)||0)+1;xa.set(p,m),o.set(p,x),i.push(p),m===1&&S&&dh.set(p,!0),x===1&&p.setAttribute(t,"true"),S||p.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",p,y)}})};return u(n),a.clear(),My++,function(){i.forEach(function(h){var p=xa.get(h)-1,f=o.get(h)-1;xa.set(h,p),o.set(h,f),p||(dh.has(h)||h.removeAttribute(r),dh.delete(h)),f||h.removeAttribute(t)}),My--,My||(xa=new WeakMap,xa=new WeakMap,dh=new WeakMap,hh={})}},Mw=function(e,n,t){t===void 0&&(t="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=IQ(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),_Q(r,s,t,"aria-hidden")):function(){return null}},Aw="Dialog",[Rj,jae]=Ts(Aw),[kQ,Zr]=Rj(Aw),Lj=e=>{const{__scopeDialog:n,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!0}=e,a=P.useRef(null),l=P.useRef(null),[c=!1,u]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(kQ,{scope:n,triggerRef:a,contentRef:l,contentId:Xs(),titleId:Xs(),descriptionId:Xs(),open:c,onOpenChange:u,onOpenToggle:P.useCallback(()=>u(h=>!h),[u]),modal:i,children:t})};Lj.displayName=Aw;var $j="DialogTrigger",TQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr($j,t),o=Xe(n,s.triggerRef);return d.jsx(_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":Dw(s.open),...r,ref:o,onClick:re(e.onClick,s.onOpenToggle)})});TQ.displayName=$j;var jw="DialogPortal",[MQ,Nj]=Rj(jw,{forceMount:void 0}),Fj=e=>{const{__scopeDialog:n,forceMount:t,children:r,container:s}=e,o=Zr(jw,n);return d.jsx(MQ,{scope:n,forceMount:t,children:P.Children.map(r,i=>d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:i})}))})};Fj.displayName=jw;var Pf="DialogOverlay",zj=P.forwardRef((e,n)=>{const t=Nj(Pf,e.__scopeDialog),{forceMount:r=t.forceMount,...s}=e,o=Zr(Pf,e.__scopeDialog);return o.modal?d.jsx(qr,{present:r||o.open,children:d.jsx(AQ,{...s,ref:n})}):null});zj.displayName=Pf;var AQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Pf,t);return d.jsx(_g,{as:Vi,allowPinchZoom:!0,shards:[s.contentRef],children:d.jsx(_e.div,{"data-state":Dw(s.open),...r,ref:n,style:{pointerEvents:"auto",...r.style}})})}),Yi="DialogContent",Bj=P.forwardRef((e,n)=>{const t=Nj(Yi,e.__scopeDialog),{forceMount:r=t.forceMount,...s}=e,o=Zr(Yi,e.__scopeDialog);return d.jsx(qr,{present:r||o.open,children:o.modal?d.jsx(jQ,{...s,ref:n}):d.jsx(OQ,{...s,ref:n})})});Bj.displayName=Yi;var jQ=P.forwardRef((e,n)=>{const t=Zr(Yi,e.__scopeDialog),r=P.useRef(null),s=Xe(n,t.contentRef,r);return P.useEffect(()=>{const o=r.current;if(o)return Mw(o)},[]),d.jsx(Uj,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:re(e.onCloseAutoFocus,o=>{var i;o.preventDefault(),(i=t.triggerRef.current)==null||i.focus()}),onPointerDownOutside:re(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&o.preventDefault()}),onFocusOutside:re(e.onFocusOutside,o=>o.preventDefault())})}),OQ=P.forwardRef((e,n)=>{const t=Zr(Yi,e.__scopeDialog),r=P.useRef(!1),s=P.useRef(!1);return d.jsx(Uj,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,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=e.onInteractOutside)==null||l.call(e,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()}})}),Uj=P.forwardRef((e,n)=>{const{__scopeDialog:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...i}=e,a=Zr(Yi,t),l=P.useRef(null),c=Xe(n,l);return Tw(),d.jsxs(d.Fragment,{children:[d.jsx(Ig,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:d.jsx(ed,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Dw(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(RQ,{titleId:a.titleId}),d.jsx($Q,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Ow="DialogTitle",Hj=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Ow,t);return d.jsx(_e.h2,{id:s.titleId,...r,ref:n})});Hj.displayName=Ow;var Kj="DialogDescription",DQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Kj,t);return d.jsx(_e.p,{id:s.descriptionId,...r,ref:n})});DQ.displayName=Kj;var Wj="DialogClose",Gj=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Wj,t);return d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,()=>s.onOpenChange(!1))})});Gj.displayName=Wj;function Dw(e){return e?"open":"closed"}var Vj="DialogTitleWarning",[Oae,Yj]=pZ(Vj,{contentName:Yi,titleName:Ow,docsSlug:"dialog"}),RQ=({titleId:e})=>{const n=Yj(Vj),t=`\`${n.contentName}\` requires a \`${n.titleName}\` for the component to be accessible for screen reader users. +`)},wQ=0,va=[];function bQ(e){var n=P.useRef([]),t=P.useRef([0,0]),r=P.useRef(),s=P.useState(wQ++)[0],o=P.useState(Mj)[0],i=P.useRef(e);P.useEffect(function(){i.current=e},[e]),P.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(s));var y=HZ([e.lockRef.current],(e.shards||[]).map(tE),!0).filter(Boolean);return y.forEach(function(x){return x.classList.add("allow-interactivity-".concat(s))}),function(){document.body.classList.remove("block-interactivity-".concat(s)),y.forEach(function(x){return x.classList.remove("allow-interactivity-".concat(s))})}}},[e.inert,e.lockRef.current,e.shards]);var a=P.useCallback(function(y,x){if("touches"in y&&y.touches.length===2)return!i.current.allowPinchZoom;var m=uh(y),v=t.current,w="deltaX"in y?y.deltaX:v[0]-m[0],C="deltaY"in y?y.deltaY:v[1]-m[1],E,k=y.target,I=Math.abs(w)>Math.abs(C)?"h":"v";if("touches"in y&&I==="h"&&k.type==="range")return!1;var _=JI(I,k);if(!_)return!0;if(_?E=I:(E=I==="v"?"h":"v",_=JI(I,k)),!_)return!1;if(!r.current&&"changedTouches"in y&&(w||C)&&(r.current=E),!E)return!0;var T=r.current||E;return SQ(T,x,y,T==="h"?w:C,!0)},[]),l=P.useCallback(function(y){var x=y;if(!(!va.length||va[va.length-1]!==o)){var m="deltaY"in x?eE(x):uh(x),v=n.current.filter(function(E){return E.name===x.type&&(E.target===x.target||x.target===E.shadowParent)&&vQ(E.delta,m)})[0];if(v&&v.should){x.cancelable&&x.preventDefault();return}if(!v){var w=(i.current.shards||[]).map(tE).filter(Boolean).filter(function(E){return E.contains(x.target)}),C=w.length>0?a(x,w[0]):!i.current.noIsolation;C&&x.cancelable&&x.preventDefault()}}},[]),c=P.useCallback(function(y,x,m,v){var w={name:y,delta:x,target:m,should:v,shadowParent:PQ(m)};n.current.push(w),setTimeout(function(){n.current=n.current.filter(function(C){return C!==w})},1)},[]),u=P.useCallback(function(y){t.current=uh(y),r.current=void 0},[]),h=P.useCallback(function(y){c(y.type,eE(y),y.target,a(y,e.lockRef.current))},[]),p=P.useCallback(function(y){c(y.type,uh(y),y.target,a(y,e.lockRef.current))},[]);P.useEffect(function(){return va.push(o),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:p}),document.addEventListener("wheel",l,Sa),document.addEventListener("touchmove",l,Sa),document.addEventListener("touchstart",u,Sa),function(){va=va.filter(function(y){return y!==o}),document.removeEventListener("wheel",l,Sa),document.removeEventListener("touchmove",l,Sa),document.removeEventListener("touchstart",u,Sa)}},[]);var f=e.removeScrollBar,S=e.inert;return P.createElement(P.Fragment,null,S?P.createElement(o,{styles:xQ(s)}):null,f?P.createElement(dQ,{gapMode:e.gapMode}):null)}function PQ(e){for(var n=null;e!==null;)e instanceof ShadowRoot&&(n=e.host,e=e.host),e=e.parentNode;return n}const CQ=QZ(Tj,bQ);var _g=P.forwardRef(function(e,n){return P.createElement(Eg,ls({},e,{ref:n,sideCar:CQ}))});_g.classNames=Eg.classNames;var IQ=function(e){if(typeof document>"u")return null;var n=Array.isArray(e)?e[0]:e;return n.ownerDocument.body},xa=new WeakMap,dh=new WeakMap,hh={},My=0,Dj=function(e){return e&&(e.host||Dj(e.parentNode))},EQ=function(e,n){return n.map(function(t){if(e.contains(t))return t;var r=Dj(t);return r&&e.contains(r)?r:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(t){return!!t})},_Q=function(e,n,t,r){var s=EQ(n,Array.isArray(e)?e:[e]);hh[t]||(hh[t]=new WeakMap);var o=hh[t],i=[],a=new Set,l=new Set(s),c=function(h){!h||a.has(h)||(a.add(h),c(h.parentNode))};s.forEach(c);var u=function(h){!h||l.has(h)||Array.prototype.forEach.call(h.children,function(p){if(a.has(p))u(p);else try{var f=p.getAttribute(r),S=f!==null&&f!=="false",y=(xa.get(p)||0)+1,x=(o.get(p)||0)+1;xa.set(p,y),o.set(p,x),i.push(p),y===1&&S&&dh.set(p,!0),x===1&&p.setAttribute(t,"true"),S||p.setAttribute(r,"true")}catch(m){console.error("aria-hidden: cannot operate on ",p,m)}})};return u(n),a.clear(),My++,function(){i.forEach(function(h){var p=xa.get(h)-1,f=o.get(h)-1;xa.set(h,p),o.set(h,f),p||(dh.has(h)||h.removeAttribute(r),dh.delete(h)),f||h.removeAttribute(t)}),My--,My||(xa=new WeakMap,xa=new WeakMap,dh=new WeakMap,hh={})}},Mw=function(e,n,t){t===void 0&&(t="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),s=IQ(e);return s?(r.push.apply(r,Array.from(s.querySelectorAll("[aria-live]"))),_Q(r,s,t,"aria-hidden")):function(){return null}},Aw="Dialog",[Rj,jae]=Ts(Aw),[kQ,Zr]=Rj(Aw),Lj=e=>{const{__scopeDialog:n,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!0}=e,a=P.useRef(null),l=P.useRef(null),[c=!1,u]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(kQ,{scope:n,triggerRef:a,contentRef:l,contentId:Xs(),titleId:Xs(),descriptionId:Xs(),open:c,onOpenChange:u,onOpenToggle:P.useCallback(()=>u(h=>!h),[u]),modal:i,children:t})};Lj.displayName=Aw;var $j="DialogTrigger",TQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr($j,t),o=Xe(n,s.triggerRef);return d.jsx(_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":Dw(s.open),...r,ref:o,onClick:re(e.onClick,s.onOpenToggle)})});TQ.displayName=$j;var jw="DialogPortal",[MQ,Nj]=Rj(jw,{forceMount:void 0}),Fj=e=>{const{__scopeDialog:n,forceMount:t,children:r,container:s}=e,o=Zr(jw,n);return d.jsx(MQ,{scope:n,forceMount:t,children:P.Children.map(r,i=>d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:i})}))})};Fj.displayName=jw;var Pf="DialogOverlay",zj=P.forwardRef((e,n)=>{const t=Nj(Pf,e.__scopeDialog),{forceMount:r=t.forceMount,...s}=e,o=Zr(Pf,e.__scopeDialog);return o.modal?d.jsx(qr,{present:r||o.open,children:d.jsx(AQ,{...s,ref:n})}):null});zj.displayName=Pf;var AQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Pf,t);return d.jsx(_g,{as:Vi,allowPinchZoom:!0,shards:[s.contentRef],children:d.jsx(_e.div,{"data-state":Dw(s.open),...r,ref:n,style:{pointerEvents:"auto",...r.style}})})}),Yi="DialogContent",Bj=P.forwardRef((e,n)=>{const t=Nj(Yi,e.__scopeDialog),{forceMount:r=t.forceMount,...s}=e,o=Zr(Yi,e.__scopeDialog);return d.jsx(qr,{present:r||o.open,children:o.modal?d.jsx(jQ,{...s,ref:n}):d.jsx(OQ,{...s,ref:n})})});Bj.displayName=Yi;var jQ=P.forwardRef((e,n)=>{const t=Zr(Yi,e.__scopeDialog),r=P.useRef(null),s=Xe(n,t.contentRef,r);return P.useEffect(()=>{const o=r.current;if(o)return Mw(o)},[]),d.jsx(Uj,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:re(e.onCloseAutoFocus,o=>{var i;o.preventDefault(),(i=t.triggerRef.current)==null||i.focus()}),onPointerDownOutside:re(e.onPointerDownOutside,o=>{const i=o.detail.originalEvent,a=i.button===0&&i.ctrlKey===!0;(i.button===2||a)&&o.preventDefault()}),onFocusOutside:re(e.onFocusOutside,o=>o.preventDefault())})}),OQ=P.forwardRef((e,n)=>{const t=Zr(Yi,e.__scopeDialog),r=P.useRef(!1),s=P.useRef(!1);return d.jsx(Uj,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,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=e.onInteractOutside)==null||l.call(e,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()}})}),Uj=P.forwardRef((e,n)=>{const{__scopeDialog:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,...i}=e,a=Zr(Yi,t),l=P.useRef(null),c=Xe(n,l);return Tw(),d.jsxs(d.Fragment,{children:[d.jsx(Ig,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:d.jsx(ed,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":Dw(a.open),...i,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(RQ,{titleId:a.titleId}),d.jsx($Q,{contentRef:l,descriptionId:a.descriptionId})]})]})}),Ow="DialogTitle",Hj=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Ow,t);return d.jsx(_e.h2,{id:s.titleId,...r,ref:n})});Hj.displayName=Ow;var Kj="DialogDescription",DQ=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Kj,t);return d.jsx(_e.p,{id:s.descriptionId,...r,ref:n})});DQ.displayName=Kj;var Wj="DialogClose",Gj=P.forwardRef((e,n)=>{const{__scopeDialog:t,...r}=e,s=Zr(Wj,t);return d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,()=>s.onOpenChange(!1))})});Gj.displayName=Wj;function Dw(e){return e?"open":"closed"}var Vj="DialogTitleWarning",[Oae,Yj]=pZ(Vj,{contentName:Yi,titleName:Ow,docsSlug:"dialog"}),RQ=({titleId:e})=>{const n=Yj(Vj),t=`\`${n.contentName}\` requires a \`${n.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${n.titleName}\`, you can wrap it with our VisuallyHidden component. -For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return P.useEffect(()=>{e&&(document.getElementById(e)||console.error(t))},[t,e]),null},LQ="DialogDescriptionWarning",$Q=({contentRef:e,descriptionId:n})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Yj(LQ).contentName}}.`;return P.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");n&&s&&(document.getElementById(n)||console.warn(r))},[r,e,n]),null},NQ=Lj,FQ=Fj,zQ=zj,BQ=Bj;const Xj=()=>{},qj=P.createContext(null);function UQ({onEvent:e,children:n}){return d.jsx(qj.Provider,{value:e??Xj,children:n})}function qt(){return P.useContext(qj)??Xj}const Zj=P.createContext(null);function HQ({children:e}){const n=F(),t=qt(),[r,s]=P.useState([]),o=P.useCallback(c=>{const u=c.id??ct();return s(h=>[...h.filter(p=>p.id!==c.id),{...c,id:u}]),t("open-menu",{source:"dialog",id:u}),n.addOpenMenu(u),u},[n,t]),i=P.useCallback((c,u)=>(s(h=>h.map(p=>p.id===c?{...p,...u}:p)),t("open-menu",{source:"dialog",id:c}),n.addOpenMenu(c),c),[n,t]),a=P.useCallback(c=>(s(u=>u.filter(h=>{var p;return h.id===c?((p=h.onClose)==null||p.call(h),!1):!0})),t("close-menu",{source:"dialog",id:c}),n.deleteOpenMenu(c),c),[n,t]),l=P.useCallback(()=>{s(c=>(c.forEach(u=>{var h;(h=u.onClose)==null||h.call(u),t("close-menu",{source:"dialog",id:u.id}),n.deleteOpenMenu(u.id)}),[]))},[n,t]);return d.jsx(Zj.Provider,{value:{dialogs:r,addDialog:o,removeDialog:a,clearDialogs:l,updateDialog:i},children:e})}function aa(){const e=P.useContext(Zj);if(!e)throw new Error("useDialogs must be used within a DialogsProvider");return e}const KQ=({id:e,component:n,onClose:t})=>{const{removeDialog:r}=aa(),s=$t(),o=P.useCallback(i=>{if(!i){if(t)try{t()}catch(a){console.warn(a)}r(e)}},[e,t,r]);return d.jsx(NQ,{onOpenChange:o,defaultOpen:!0,children:d.jsx(FQ,{container:s,children:d.jsx(zQ,{dir:"ltr",className:"tlui-dialog__overlay",onClick:i=>{i.target===i.currentTarget&&o(!1)},children:d.jsx(BQ,{dir:"ltr",className:"tlui-dialog__content",children:d.jsx(n,{onClose:()=>o(!1)})})})})})};function WQ(){const{dialogs:e}=aa();return e.map(n=>d.jsx(KQ,{...n},n.id))}const GQ=Ce.memo(WQ);function VQ(){const e=F(),n=H("follow",()=>e.getInstanceState().followingUserId,[e]);return n?d.jsx(YQ,{userId:n}):null}function YQ({userId:e}){const n=ug(e);return n?d.jsx("div",{className:"tlui-following-indicator",style:{borderColor:n.color}}):null}function kg(e){const n=e+"CollectionProvider",[t,r]=Ts(n),[s,o]=t(n,{collectionRef:{current:null},itemMap:new Map}),i=f=>{const{scope:S,children:m}=f,x=Ce.useRef(null),y=Ce.useRef(new Map).current;return d.jsx(s,{scope:S,itemMap:y,collectionRef:x,children:m})};i.displayName=n;const a=e+"CollectionSlot",l=Ce.forwardRef((f,S)=>{const{scope:m,children:x}=f,y=o(a,m),v=Xe(S,y.collectionRef);return d.jsx(Vi,{ref:v,children:x})});l.displayName=a;const c=e+"CollectionItemSlot",u="data-radix-collection-item",h=Ce.forwardRef((f,S)=>{const{scope:m,children:x,...y}=f,v=Ce.useRef(null),w=Xe(S,v),C=o(c,m);return Ce.useEffect(()=>(C.itemMap.set(v,{ref:v,...y}),()=>void C.itemMap.delete(v))),d.jsx(Vi,{[u]:"",ref:w,children:x})});h.displayName=c;function p(f){const S=o(e+"CollectionConsumer",f);return Ce.useCallback(()=>{const x=S.collectionRef.current;if(!x)return[];const y=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(S.itemMap.values()).sort((C,E)=>y.indexOf(C.ref.current)-y.indexOf(E.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:i,Slot:l,ItemSlot:h},p,r]}var XQ="VisuallyHidden",Rw=P.forwardRef((e,n)=>d.jsx(_e.span,{...e,ref:n,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));Rw.displayName=XQ;var Lw="ToastProvider",[$w,qQ,ZQ]=kg("Toast"),[Qj,Dae]=Ts("Toast",[ZQ]),[QQ,Tg]=Qj(Lw),Jj=e=>{const{__scopeToast:n,label:t="Notification",duration:r=5e3,swipeDirection:s="right",swipeThreshold:o=50,children:i}=e,[a,l]=P.useState(null),[c,u]=P.useState(0),h=P.useRef(!1),p=P.useRef(!1);return t.trim()||console.error(`Invalid prop \`label\` supplied to \`${Lw}\`. Expected non-empty \`string\`.`),d.jsx($w.Provider,{scope:n,children:d.jsx(QQ,{scope:n,label:t,duration:r,swipeDirection:s,swipeThreshold:o,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:P.useCallback(()=>u(f=>f+1),[]),onToastRemove:P.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:i})})};Jj.displayName=Lw;var eO="ToastViewport",JQ=["F8"],Vv="toast.viewportPause",Yv="toast.viewportResume",tO=P.forwardRef((e,n)=>{const{__scopeToast:t,hotkey:r=JQ,label:s="Notifications ({hotkey})",...o}=e,i=Tg(eO,t),a=qQ(t),l=P.useRef(null),c=P.useRef(null),u=P.useRef(null),h=P.useRef(null),p=Xe(n,h,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),S=i.toastCount>0;P.useEffect(()=>{const x=y=>{var w;r.every(C=>y[C]||y.code===C)&&((w=h.current)==null||w.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[r]),P.useEffect(()=>{const x=l.current,y=h.current;if(S&&x&&y){const v=()=>{if(!i.isClosePausedRef.current){const k=new CustomEvent(Vv);y.dispatchEvent(k),i.isClosePausedRef.current=!0}},w=()=>{if(i.isClosePausedRef.current){const k=new CustomEvent(Yv);y.dispatchEvent(k),i.isClosePausedRef.current=!1}},C=k=>{!x.contains(k.relatedTarget)&&w()},E=()=>{x.contains(document.activeElement)||w()};return x.addEventListener("focusin",v),x.addEventListener("focusout",C),x.addEventListener("pointermove",v),x.addEventListener("pointerleave",E),window.addEventListener("blur",v),window.addEventListener("focus",w),()=>{x.removeEventListener("focusin",v),x.removeEventListener("focusout",C),x.removeEventListener("pointermove",v),x.removeEventListener("pointerleave",E),window.removeEventListener("blur",v),window.removeEventListener("focus",w)}}},[S,i.isClosePausedRef]);const m=P.useCallback(({tabbingDirection:x})=>{const v=a().map(w=>{const C=w.ref.current,E=[C,...hJ(C)];return x==="forwards"?E:E.reverse()});return(x==="forwards"?v.reverse():v).flat()},[a]);return P.useEffect(()=>{const x=h.current;if(x){const y=v=>{var E,k,I;const w=v.altKey||v.ctrlKey||v.metaKey;if(v.key==="Tab"&&!w){const _=document.activeElement,T=v.shiftKey;if(v.target===x&&T){(E=c.current)==null||E.focus();return}const $=m({tabbingDirection:T?"backwards":"forwards"}),j=$.findIndex(O=>O===_);Ay($.slice(j+1))?v.preventDefault():T?(k=c.current)==null||k.focus():(I=u.current)==null||I.focus()}};return x.addEventListener("keydown",y),()=>x.removeEventListener("keydown",y)}},[a,m]),d.jsxs(AZ,{ref:l,role:"region","aria-label":s.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:S?void 0:"none"},children:[S&&d.jsx(Xv,{ref:c,onFocusFromOutsideViewport:()=>{const x=m({tabbingDirection:"forwards"});Ay(x)}}),d.jsx($w.Slot,{scope:t,children:d.jsx(_e.ol,{tabIndex:-1,...o,ref:p})}),S&&d.jsx(Xv,{ref:u,onFocusFromOutsideViewport:()=>{const x=m({tabbingDirection:"backwards"});Ay(x)}})]})});tO.displayName=eO;var nO="ToastFocusProxy",Xv=P.forwardRef((e,n)=>{const{__scopeToast:t,onFocusFromOutsideViewport:r,...s}=e,o=Tg(nO,t);return d.jsx(Rw,{"aria-hidden":!0,tabIndex:0,...s,ref:n,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=o.viewport)!=null&&c.contains(a))&&r()}})});Xv.displayName=nO;var Mg="Toast",eJ="toast.swipeStart",tJ="toast.swipeMove",nJ="toast.swipeCancel",rJ="toast.swipeEnd",rO=P.forwardRef((e,n)=>{const{forceMount:t,open:r,defaultOpen:s,onOpenChange:o,...i}=e,[a=!0,l]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(qr,{present:t||a,children:d.jsx(iJ,{open:a,...i,ref:n,onClose:()=>l(!1),onPause:Yt(e.onPause),onResume:Yt(e.onResume),onSwipeStart:re(e.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:re(e.onSwipeMove,c=>{const{x:u,y:h}=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",`${h}px`)}),onSwipeCancel:re(e.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:re(e.onSwipeEnd,c=>{const{x:u,y:h}=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",`${h}px`),l(!1)})})})});rO.displayName=Mg;var[sJ,oJ]=Qj(Mg,{onClose(){}}),iJ=P.forwardRef((e,n)=>{const{__scopeToast:t,type:r="foreground",duration:s,open:o,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...S}=e,m=Tg(Mg,t),[x,y]=P.useState(null),v=Xe(n,O=>y(O)),w=P.useRef(null),C=P.useRef(null),E=s||m.duration,k=P.useRef(0),I=P.useRef(E),_=P.useRef(0),{onToastAdd:T,onToastRemove:M}=m,D=Yt(()=>{var R;(x==null?void 0:x.contains(document.activeElement))&&((R=m.viewport)==null||R.focus()),i()}),$=P.useCallback(O=>{!O||O===1/0||(window.clearTimeout(_.current),k.current=new Date().getTime(),_.current=window.setTimeout(D,O))},[D]);P.useEffect(()=>{const O=m.viewport;if(O){const R=()=>{$(I.current),c==null||c()},K=()=>{const B=new Date().getTime()-k.current;I.current=I.current-B,window.clearTimeout(_.current),l==null||l()};return O.addEventListener(Vv,K),O.addEventListener(Yv,R),()=>{O.removeEventListener(Vv,K),O.removeEventListener(Yv,R)}}},[m.viewport,E,l,c,$]),P.useEffect(()=>{o&&!m.isClosePausedRef.current&&$(E)},[o,E,m.isClosePausedRef,$]),P.useEffect(()=>(T(),()=>M()),[T,M]);const j=P.useMemo(()=>x?uO(x):null,[x]);return m.viewport?d.jsxs(d.Fragment,{children:[j&&d.jsx(aJ,{__scopeToast:t,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:j}),d.jsx(sJ,{scope:t,onClose:D,children:ta.createPortal(d.jsx($w.ItemSlot,{scope:t,children:d.jsx(MZ,{asChild:!0,onEscapeKeyDown:re(a,()=>{m.isFocusedToastEscapeKeyDownRef.current||D(),m.isFocusedToastEscapeKeyDownRef.current=!1}),children:d.jsx(_e.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":m.swipeDirection,...S,ref:v,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:re(e.onKeyDown,O=>{O.key==="Escape"&&(a==null||a(O.nativeEvent),O.nativeEvent.defaultPrevented||(m.isFocusedToastEscapeKeyDownRef.current=!0,D()))}),onPointerDown:re(e.onPointerDown,O=>{O.button===0&&(w.current={x:O.clientX,y:O.clientY})}),onPointerMove:re(e.onPointerMove,O=>{if(!w.current)return;const R=O.clientX-w.current.x,K=O.clientY-w.current.y,B=!!C.current,z=["left","right"].includes(m.swipeDirection),W=["left","up"].includes(m.swipeDirection)?Math.min:Math.max,Y=z?W(0,R):0,q=z?0:W(0,K),ae=O.pointerType==="touch"?10:2,fe={x:Y,y:q},we={originalEvent:O,delta:fe};B?(C.current=fe,ph(tJ,h,we,{discrete:!1})):nE(fe,m.swipeDirection,ae)?(C.current=fe,ph(eJ,u,we,{discrete:!1}),O.target.setPointerCapture(O.pointerId)):(Math.abs(R)>ae||Math.abs(K)>ae)&&(w.current=null)}),onPointerUp:re(e.onPointerUp,O=>{const R=C.current,K=O.target;if(K.hasPointerCapture(O.pointerId)&&K.releasePointerCapture(O.pointerId),C.current=null,w.current=null,R){const B=O.currentTarget,z={originalEvent:O,delta:R};nE(R,m.swipeDirection,m.swipeThreshold)?ph(rJ,f,z,{discrete:!0}):ph(nJ,p,z,{discrete:!0}),B.addEventListener("click",W=>W.preventDefault(),{once:!0})}})})})}),m.viewport)})]}):null}),aJ=e=>{const{__scopeToast:n,children:t,...r}=e,s=Tg(Mg,n),[o,i]=P.useState(!1),[a,l]=P.useState(!1);return uJ(()=>i(!0)),P.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:d.jsx(td,{asChild:!0,children:d.jsx(Rw,{...r,children:o&&d.jsxs(d.Fragment,{children:[s.label," ",t]})})})},lJ="ToastTitle",sO=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});sO.displayName=lJ;var cJ="ToastDescription",oO=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});oO.displayName=cJ;var iO="ToastAction",aO=P.forwardRef((e,n)=>{const{altText:t,...r}=e;return t.trim()?d.jsx(cO,{altText:t,asChild:!0,children:d.jsx(Nw,{...r,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${iO}\`. Expected non-empty \`string\`.`),null)});aO.displayName=iO;var lO="ToastClose",Nw=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e,s=oJ(lO,t);return d.jsx(cO,{asChild:!0,children:d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,s.onClose)})})});Nw.displayName=lO;var cO=P.forwardRef((e,n)=>{const{__scopeToast:t,altText:r,...s}=e;return d.jsx(_e.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...s,ref:n})});function uO(e){const n=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&n.push(r.textContent),dJ(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&&n.push(i)}else n.push(...uO(r))}}),n}function ph(e,n,t,{discrete:r}){const s=t.originalEvent.currentTarget,o=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:t});n&&s.addEventListener(e,n,{once:!0}),r?kw(s,o):s.dispatchEvent(o)}var nE=(e,n,t=0)=>{const r=Math.abs(e.x),s=Math.abs(e.y),o=r>s;return n==="left"||n==="right"?o&&r>t:!o&&s>t};function uJ(e=()=>{}){const n=Yt(e);Zo(()=>{let t=0,r=0;return t=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(n)),()=>{window.cancelAnimationFrame(t),window.cancelAnimationFrame(r)}},[n])}function dJ(e){return e.nodeType===e.ELEMENT_NODE}function hJ(e){const n=[],t=document.createTreeWalker(e,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();)n.push(t.currentNode);return n}function Ay(e){const n=document.activeElement;return e.some(t=>t===n?!0:(t.focus(),document.activeElement!==n))}var pJ=rO,fJ=sO,gJ=oO,mJ=aO,rE=Nw;const dO=P.createContext(null);function yJ({children:e}){const[n,t]=P.useState([]),r=P.useCallback(i=>{const a=i.id??ct();return t(l=>[...l.filter(c=>c.id!==i.id),{...i,id:a}]),a},[]),s=P.useCallback(i=>(t(a=>a.filter(l=>l.id!==i)),i),[]),o=P.useCallback(()=>{t(()=>[])},[]);return d.jsx(Jj,{children:d.jsx(dO.Provider,{value:{toasts:n,addToast:r,removeToast:s,clearToasts:o},children:e})})}function Qr(){const e=P.useContext(dO);if(!e)throw new Error("useToasts must be used within a ToastsProvider");return e}const ce=P.forwardRef(function({children:n,disabled:t,type:r,...s},o){return d.jsx("button",{ref:o,type:"button",draggable:!1,disabled:t,...s,className:le("tlui-button",`tlui-button__${r}`,s.className),children:n})});function wt({children:e}){return d.jsx("span",{className:"tlui-button__label",children:e})}const Cs=P.memo(function({small:n,invertIcon:t,icon:r,color:s,className:o,...i}){const a=Iw(),l=a.icons[r]??a.icons["question-mark-circle"],c=P.useRef(null);return P.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"?d.jsx("div",{className:le("tlui-icon tlui-icon__placeholder",{"tlui-icon__small":n},o)}):d.jsx("div",{...i,ref:c,className:le("tlui-icon",{"tlui-icon__small":n},o),style:{color:s,mask:`url(${l}) center 100% / 100% no-repeat`,transform:t?"scale(-1, 1)":void 0}})}),SJ={success:"check-circle",warning:"warning-triangle",error:"cross-circle",info:"info-circle"};function vJ({toast:e}){const{removeToast:n}=Qr(),t=xe(),r=i=>{i||n(e.id)},s=e.actions&&e.actions.length>0,o=e.icon||e.severity&&SJ[e.severity];return d.jsxs(pJ,{onOpenChange:r,className:"tlui-toast__container",duration:e.keepOpen?1/0:5e3,"data-severity":e.severity,children:[o&&d.jsx("div",{className:"tlui-toast__icon",children:d.jsx(Cs,{icon:o})}),d.jsxs("div",{className:"tlui-toast__main",children:[d.jsxs("div",{className:"tlui-toast__content",children:[e.title&&d.jsx(fJ,{className:"tlui-toast__title",children:e.title}),e.description&&d.jsx(gJ,{className:"tlui-toast__description",children:e.description})]}),e.actions&&d.jsxs("div",{className:"tlui-toast__actions",children:[e.actions.map((i,a)=>d.jsx(mJ,{altText:i.label,asChild:!0,onClick:i.onClick,children:d.jsx(ce,{type:i.type,children:d.jsx(wt,{children:i.label})})},a)),d.jsx(rE,{asChild:!0,children:d.jsx(ce,{type:"normal",className:"tlui-toast__close",style:{marginLeft:"auto"},children:d.jsx(wt,{children:e.closeLabel??t("toast.close")})})})]})]}),!s&&d.jsx(rE,{asChild:!0,children:d.jsx(ce,{type:"normal",className:"tlui-toast__close",children:d.jsx(wt,{children:e.closeLabel??t("toast.close")})})})]})}function xJ(){const{toasts:e}=Qr();return e.map(n=>d.jsx(vJ,{toast:n},n.id))}const wJ=P.memo(xJ);function bJ(){const e=F(),{toasts:n}=Qr(),[t,r]=P.useState(!1);return P.useEffect(()=>{let s=-1;return n.length?r(!0):s=e.timers.setTimeout(()=>{r(!1)},1e3),()=>{clearTimeout(s)}},[n.length,r,e]),t?d.jsx(tO,{className:"tlui-toast__viewport"}):null}function Se({icon:e,small:n,invertIcon:t}){return d.jsx(Cs,{className:"tlui-button__icon",icon:e,small:n,invertIcon:t})}const jy=[0,390,428,468,580,640,840,1023];var yt=(e=>(e[e.ZERO=0]="ZERO",e[e.MOBILE_XXS=1]="MOBILE_XXS",e[e.MOBILE_XS=2]="MOBILE_XS",e[e.MOBILE_SM=3]="MOBILE_SM",e[e.MOBILE=4]="MOBILE",e[e.TABLET_SM=5]="TABLET_SM",e[e.TABLET=6]="TABLET",e[e.DESKTOP=7]="DESKTOP",e))(yt||{});let qv={fonts:{draw:`${jo()}/fonts/Shantell_Sans-Tldrawish.woff2`,serif:`${jo()}/fonts/IBMPlexSerif-Medium.woff2`,sansSerif:`${jo()}/fonts/IBMPlexSans-Medium.woff2`,monospace:`${jo()}/fonts/IBMPlexMono-Medium.woff2`}};function hO(e){return P.useMemo(()=>e?{fonts:{...qv.fonts,...e==null?void 0:e.fonts}}:qv,[e])}const PJ=["align-bottom","align-center-horizontal","align-center-vertical","align-left","align-right","align-top","arrow-left","arrowhead-arrow","arrowhead-bar","arrowhead-diamond","arrowhead-dot","arrowhead-none","arrowhead-square","arrowhead-triangle-inverted","arrowhead-triangle","blob","bring-forward","bring-to-front","broken","check-circle","check","chevron-down","chevron-left","chevron-right","chevron-up","chevrons-ne","chevrons-sw","clipboard-copied","clipboard-copy","color","cross-2","cross-circle","dash-dashed","dash-dotted","dash-draw","dash-solid","disconnected","discord","distribute-horizontal","distribute-vertical","dot","dots-horizontal","dots-vertical","drag-handle-dots","duplicate","edit","external-link","fill-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","horizontal-align-end","horizontal-align-middle","horizontal-align-start","info-circle","leading","link","lock","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","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","undo","ungroup","unlock","vertical-align-end","vertical-align-middle","vertical-align-start","warning-triangle","zoom-in","zoom-out"];let cc={...qv,icons:Object.fromEntries(PJ.map(e=>[e,`${jo()}/icons/icon/${e}.svg`])),translations:Object.fromEntries(bu.map(e=>[e.locale,`${jo()}/translations/${e.locale}.json`])),embedIcons:Object.fromEntries(Wu.map(e=>[e.type,`${jo()}/embed-icons/${e.type}.png`]))};function CJ(e){return e?{fonts:Object.assign({...cc.fonts},{...e==null?void 0:e.fonts}),icons:Object.assign({...cc.icons},{...e==null?void 0:e.icons}),embedIcons:Object.assign({...cc.embedIcons},{...e==null?void 0:e.embedIcons}),translations:Object.assign({...cc.translations},{...e==null?void 0:e.translations})}:cc}function Ag({className:e,children:n}){return d.jsx("div",{className:le("tlui-dialog__header",e),children:n})}function jg({className:e,children:n}){return d.jsx(Hj,{dir:"ltr",className:le("tlui-dialog__header__title",e),children:n})}function Og(){return d.jsx("div",{className:"tlui-dialog__header__close",children:d.jsx(Gj,{"data-testid":"dialog.close",dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon","aria-label":"Close",onTouchEnd:e=>e.target.click(),children:d.jsx(Se,{small:!0,icon:"cross-2"})})})})}function Cu({className:e,children:n,style:t}){return d.jsx("div",{className:le("tlui-dialog__body",e),style:t,children:n})}function Fw({className:e,children:n}){return d.jsx("div",{className:le("tlui-dialog__footer",e),children:n})}const Dg=P.forwardRef(function({className:n,label:t,icon:r,iconLeft:s,autoSelect:o=!1,autoFocus:i=!1,defaultValue:a,placeholder:l,onComplete:c,onValueChange:u,onCancel:h,onFocus:p,onBlur:f,shouldManuallyMaintainScrollPositionWhenFocused:S=!1,children:m,value:x},y){const v=F(),w=P.useRef(null);P.useImperativeHandle(y,()=>w.current);const C=xe(),E=P.useRef(a??""),k=P.useRef(a??""),[I,_]=P.useState(!1),T=P.useCallback(j=>{_(!0);const O=j.currentTarget;k.current=O.value,v.timers.requestAnimationFrame(()=>{o&&O.select()}),p==null||p()},[o,p,v.timers]),M=P.useCallback(j=>{const O=j.currentTarget.value;k.current=O,u==null||u(O)},[u]),D=P.useCallback(j=>{switch(j.key){case"Enter":{j.currentTarget.blur(),Dt(j),c==null||c(j.currentTarget.value);break}case"Escape":{j.currentTarget.value=E.current,j.currentTarget.blur(),Dt(j),h==null||h(j.currentTarget.value);break}}},[c,h]),$=P.useCallback(j=>{_(!1);const O=j.currentTarget.value;f==null||f(O)},[f]);return P.useEffect(()=>{if(!v.environment.isIos)return;const j=window.visualViewport;if(I&&S&&j){const O=()=>{var R;(R=w.current)==null||R.scrollIntoView({block:"center"})};return j.addEventListener("resize",O),j.addEventListener("scroll",O),v.timers.requestAnimationFrame(()=>{var R;(R=w.current)==null||R.scrollIntoView({block:"center"})}),()=>{j.removeEventListener("resize",O),j.removeEventListener("scroll",O)}}},[v,I,S]),d.jsxs("div",{draggable:!1,className:"tlui-input__wrapper",children:[m,t&&d.jsx("label",{children:C(t)}),s&&d.jsx(Cs,{icon:s,className:"tlui-icon-left",small:!0}),d.jsx("input",{ref:w,className:le("tlui-input",n),type:"text",defaultValue:a,onKeyUp:D,onChange:M,onFocus:T,onBlur:$,autoFocus:i,placeholder:l,value:x}),r&&d.jsx(Cs,{icon:r,small:!!t})]})}),pO=Lt(function({onClose:n}){const t=F(),r=xe(),s=Iw(),[o,i]=P.useState(null),[a,l]=P.useState(""),[c,u]=P.useState(null),[h,p]=P.useState(!1),f=P.useRef(-1);return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:o?`${r("embed-dialog.title")} — ${o.title}`:r("embed-dialog.title")}),d.jsx(Og,{})]}),o?d.jsxs(d.Fragment,{children:[d.jsxs(Cu,{className:"tlui-embed-dialog__enter",children:[d.jsx(Dg,{className:"tlui-embed-dialog__input",label:"embed-dialog.url",placeholder:"http://example.com",autoFocus:!0,onValueChange:S=>{l(S);const m=Do(S);u(m&&m.definition.type===o.type?m:null),p(!1),clearTimeout(f.current),f.current=t.timers.setTimeout(()=>p(!m),320)}}),a===""?d.jsxs("div",{className:"tlui-embed-dialog__instruction",children:[d.jsx("span",{children:r("embed-dialog.instruction")})," ",o.instructionLink&&d.jsxs("a",{target:"_blank",rel:"noopener noreferrer",href:o.instructionLink,className:"tlui-embed-dialog__instruction__link",children:["Learn more.",d.jsx(Cs,{icon:"external-link",small:!0})]})]}):d.jsx("div",{className:"tlui-embed-dialog__warning",children:h?r("embed-dialog.invalid-url"):" "})]}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:()=>{i(null),u(null),l("")},children:d.jsx(wt,{children:r("embed-dialog.back")})}),d.jsx("div",{className:"tlui-embed__spacer"}),d.jsx(ce,{type:"normal",onClick:n,children:d.jsx(wt,{children:r("embed-dialog.cancel")})}),d.jsx(ce,{type:"primary",disabled:!c,onClick:()=>{c&&(t.putExternalContent({type:"embed",url:a,point:t.getViewportPageBounds().center,embed:c.definition}),n())},children:d.jsx(wt,{children:r("embed-dialog.create")})})]})]}):d.jsx(d.Fragment,{children:d.jsx(Cu,{className:"tlui-embed-dialog__list",children:Wu.map(S=>d.jsxs(ce,{type:"menu",onClick:()=>i(S),children:[d.jsx(wt,{children:S.title}),d.jsx("div",{className:"tlui-embed-dialog__item__image",style:{backgroundImage:`url(${s.embedIcons[S.type]})`}})]},S.type))})})]})});function fO(){const e=F(),n=P.useRef();return P.useEffect(()=>{const t=window.document.createElement("input");t.type="file",t.accept=j9,t.multiple=!0,n.current=t;async function r(s){const o=s.target.files;!o||o.length===0||(e.mark("insert media"),await e.putExternalContent({type:"files",files:Array.from(o),point:e.getViewportPageBounds().center,ignoreParent:!1}),t.value="")}return t.addEventListener("change",r),()=>{n.current=void 0,t.removeEventListener("change",r)}},[e]),P.useCallback(()=>{var t;(t=n.current)==null||t.click()},[n])}const gO=P.createContext(null);function IJ({overrides:e,children:n}){const t=F(),r=qt(),{addDialog:s}=aa(),o=fO(),i=P.useMemo(()=>{const a=[{id:"select",label:"tool.select",icon:"tool-pointer",kbd:"v",readonlyOk:!0,onSelect(c){t.setCurrentTool("select"),r("select-tool",{source:c,id:"select"})}},{id:"hand",label:"tool.hand",icon:"tool-hand",kbd:"h",readonlyOk:!0,onSelect(c){t.setCurrentTool("hand"),r("select-tool",{source:c,id:"hand"})}},{id:"eraser",label:"tool.eraser",icon:"tool-eraser",kbd:"e",onSelect(c){t.setCurrentTool("eraser"),r("select-tool",{source:c,id:"eraser"})}},{id:"draw",label:"tool.draw",icon:"tool-pencil",kbd:"d,b,x",onSelect(c){t.setCurrentTool("draw"),r("select-tool",{source:c,id:"draw"})}},...[...Br.values].map(c=>({id:c,label:`tool.${c}`,meta:{geo:c},kbd:c==="rectangle"?"r":c==="ellipse"?"o":void 0,icon:"geo-"+c,onSelect(u){t.run(()=>{t.setStyleForNextShapes(Br,c),t.setCurrentTool("geo"),r("select-tool",{source:u,id:`geo-${c}`})})}})),{id:"arrow",label:"tool.arrow",icon:"tool-arrow",kbd:"a",onSelect(c){t.setCurrentTool("arrow"),r("select-tool",{source:c,id:"arrow"})}},{id:"line",label:"tool.line",icon:"tool-line",kbd:"l",onSelect(c){t.setCurrentTool("line"),r("select-tool",{source:c,id:"line"})}},{id:"frame",label:"tool.frame",icon:"tool-frame",kbd:"f",onSelect(c){t.setCurrentTool("frame"),r("select-tool",{source:c,id:"frame"})}},{id:"text",label:"tool.text",icon:"tool-text",kbd:"t",onSelect(c){t.setCurrentTool("text"),r("select-tool",{source:c,id:"text"})}},{id:"asset",label:"tool.asset",icon:"tool-media",kbd:"$u",onSelect(c){o(),r("select-tool",{source:c,id:"media"})}},{id:"note",label:"tool.note",icon:"tool-note",kbd:"n",onSelect(c){t.setCurrentTool("note"),r("select-tool",{source:c,id:"note"})}},{id:"laser",label:"tool.laser",readonlyOk:!0,icon:"tool-laser",kbd:"k",onSelect(c){t.setCurrentTool("laser"),r("select-tool",{source:c,id:"laser"})}},{id:"embed",label:"tool.embed",icon:"dot",onSelect(c){s({component:pO}),r("select-tool",{source:c,id:"embed"})}},{id:"highlight",label:"tool.highlight",icon:"tool-highlight",kbd:"!d",onSelect(c){t.setCurrentTool("highlight"),r("select-tool",{source:c,id:"highlight"})}}];a.push();const l=Object.fromEntries(a.map(c=>[c.id,c]));return e?e(t,l,{insertMedia:o}):l},[e,t,r,o,s]);return d.jsx(gO.Provider,{value:i,children:n})}function Rg(){const e=P.useContext(gO);if(!e)throw new Error("useTools must be used within a ToolProvider");return e}const mO=Ce.createContext(null);function EJ({forceMobile:e=!1,children:n}){const t=F(),r=H("breakpoint",()=>{const{width:s}=t.getViewportScreenBounds(),o=e?yt.MOBILE_SM:jy.length-1;for(let i=0;ijy[i]&&s<=jy[i+1])return i;return o},[t]);return d.jsx(mO.Provider,{value:r,children:n})}function Cn(){const e=P.useContext(mO);if(e===null)throw new Error("useBreakpoint must be used inside of the component");return e}function _J(){const{addToast:e,removeToast:n,clearToasts:t}=Qr(),{addDialog:r,clearDialogs:s,removeDialog:o,updateDialog:i}=aa(),l=Cn()({addToast:e,removeToast:n,clearToasts:t,addDialog:r,clearDialogs:s,removeDialog:o,updateDialog:i,msg:c,isMobile:l}),[r,e,s,t,c,o,n,i,l])}function kJ(e,n){const t={};for(const r of e)if(r.translations)for(const[s,o]of Hn(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return{actions:(r,s)=>{for(const o of e)o.actions&&(s=o.actions(r,s,n));return s},tools:(r,s,o)=>{for(const i of e)i.tools&&(s=i.tools(r,s,{...n,...o}));return s},translations:t}}function yO(e){return P.useMemo(()=>e,e)}function TJ(e){const n=yO(e==null?[]:Array.isArray(e)?e:[e]);return P.useMemo(()=>{const t={};for(const r of n)if(r.translations)for(const[s,o]of Hn(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return t},[n])}function MJ(e){const n=_J(),t=yO(e==null?[]:Array.isArray(e)?e:[e]);return P.useMemo(()=>kJ(t,n),[t,n])}function AJ(e,n){const t=me(n.map(s=>e.getShape(s)).filter(s=>s&&e.isShapeOfType(s,"frame")));if(!t.length)return;const r=[];e.run(()=>{t.map(s=>{const o=e.getSortedChildIdsForParent(s.id);o.length&&(e.reparentShapes(o,s.parentId,s.index),r.push(...o))}),e.setSelectedShapes(r),e.deleteShapes(n)})}const jJ=50;function OJ(e,n,t={}){const r=e.getShape(n);if(!r)return;const s=e.getSortedChildIdsForParent(r.id),o=me(s.map(f=>e.getShape(f)));if(!o.length)return;const i=Q.FromPoints(o.flatMap(f=>{const S=e.getShapeGeometry(f.id);return e.getShapeLocalTransform(f).applyToPoints(S.vertices)})),{padding:a=jJ}=t,l=i.w+2*a,c=i.h+2*a,u=a-i.minX,h=a-i.minY;if(u===0&&h===0&&r.props.w===l&&r.props.h===c)return;const p=new b(u,h).rot(r.rotation);e.run(()=>{const f=s.map(S=>{const m=e.getShape(S);return{id:m.id,type:m.type,x:m.x+u,y:m.y+h}});f.push({id:r.id,type:r.type,x:r.x-p.x,y:r.y-p.y,props:{w:l,h:c}}),e.updateShapes(f)})}function sE(e){return ar.isValid(e)?{isValid:!0,hasProtocol:!0}:ar.isValid("https://"+e)?{isValid:!0,hasProtocol:!1}:{isValid:!1,hasProtocol:!1}}const DJ=Lt(function({onClose:n}){const r=F().getOnlySelectedShape();return r&&"url"in r.props&&typeof r.props.url=="string"?d.jsx(RJ,{onClose:n,selectedShape:r}):null}),RJ=Lt(function({onClose:n,selectedShape:t}){const r=F(),s=xe(),o=P.useRef(null);P.useEffect(()=>{r.timers.requestAnimationFrame(()=>{var S;return(S=o.current)==null?void 0:S.focus()})},[r]);const i=P.useRef(t.props.url),[a,l]=P.useState(()=>{const S=sE(t.props.url),m=S.isValid===!0?S.hasProtocol?t.props.url:"https://"+t.props.url:"https://";return{actual:m,safe:m,valid:!0}}),c=P.useCallback(S=>{const m=S.replace(/https?:\/\/(https?:\/\/)/,(v,w)=>w),x=sE(m),y=x.isValid===!0?x.hasProtocol?m:"https://"+m:"https://";l({actual:m,safe:y,valid:x.isValid})},[]),u=P.useCallback(()=>{const S=r.getOnlySelectedShape();S&&(r.updateShapes([{id:S.id,type:S.type,props:{url:""}}]),n())},[r,n]),h=P.useCallback(()=>{const S=r.getOnlySelectedShape();S&&(S&&"url"in S.props&&S.props.url!==a.safe&&r.updateShapes([{id:S.id,type:S.type,props:{url:a.safe}}]),n())},[r,n,a]),p=P.useCallback(()=>{n()},[n]);if(!t)return n(),null;const f=i.current&&!a.valid;return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:s("edit-link-dialog.title")}),d.jsx(Og,{})]}),d.jsx(Cu,{children:d.jsxs("div",{className:"tlui-edit-link-dialog",children:[d.jsx(Dg,{ref:o,className:"tlui-edit-link-dialog__input",label:"edit-link-dialog.url",autoFocus:!0,value:a.actual,onValueChange:c,onComplete:h,onCancel:p}),d.jsx("div",{children:a.valid?s("edit-link-dialog.detail"):s("edit-link-dialog.invalid-url")})]})}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:p,onTouchEnd:p,children:d.jsx(wt,{children:s("edit-link-dialog.cancel")})}),f?d.jsx(ce,{type:"danger",onTouchEnd:u,onClick:u,children:d.jsx(wt,{children:s("edit-link-dialog.clear")})}):d.jsx(ce,{type:"primary",disabled:!a.valid,onTouchEnd:h,onClick:h,children:d.jsx(wt,{children:s("edit-link-dialog.save")})})]})]})});var zw={exports:{}};zw.exports;(function(e){var n=function(){var t=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",o={};function i(l,c){if(!o[l]){o[l]={};for(var u=0;u>>8,u[h*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,h=c.length;u>1}else{for(p=1,h=0;h>1}v--,v==0&&(v=Math.pow(2,C),C++),delete S[y]}else for(p=f[y],h=0;h>1;v--,v==0&&(v=Math.pow(2,C),C++),f[x]=w++,y=String(m)}if(y!==""){if(Object.prototype.hasOwnProperty.call(S,y)){if(y.charCodeAt(0)<256){for(h=0;h>1}else{for(p=1,h=0;h>1}v--,v==0&&(v=Math.pow(2,C),C++),delete S[y]}else for(p=f[y],h=0;h>1;v--,v==0&&(v=Math.pow(2,C),C++)}for(p=2,h=0;h>1;for(;;)if(k=k<<1,I==c-1){E.push(u(k));break}else I++;return E.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 h=[],p=4,f=4,S=3,m="",x=[],y,v,w,C,E,k,I,_={val:u(0),position:c,index:1};for(y=0;y<3;y+=1)h[y]=y;for(w=0,E=Math.pow(2,2),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;switch(w){case 0:for(w=0,E=Math.pow(2,8),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;I=t(w);break;case 1:for(w=0,E=Math.pow(2,16),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;I=t(w);break;case 2:return""}for(h[3]=I,v=I,x.push(I);;){if(_.index>l)return"";for(w=0,E=Math.pow(2,S),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;switch(I=w){case 0:for(w=0,E=Math.pow(2,8),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;h[f++]=t(w),I=f-1,p--;break;case 1:for(w=0,E=Math.pow(2,16),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;h[f++]=t(w),I=f-1,p--;break;case 2:return x.join("")}if(p==0&&(p=Math.pow(2,S),S++),h[I])m=h[I];else if(I===f)m=v+v.charAt(0);else return null;x.push(m),h[f++]=v+m.charAt(0),p--,v=m,p==0&&(p=Math.pow(2,S),S++)}}};return a}();e!=null?e.exports=n:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return n})})(zw);var LJ=zw.exports;const SO=ti(LJ);async function $J(e,n,t){var y,v,w;const{elements:r,files:s}=n,o={shapes:[],bindings:[],rootShapeIds:[],assets:[],schema:e.store.schema.serialize()},i=new Map,a=new Map,l=e.getCurrentPageId(),c=new Map,u=[],h=new Set;r.forEach(C=>{if(c.set(C.id,je()),C.boundElements!==null)for(const E of C.boundElements)E.type==="text"&&h.add(E.id)});let p=oT;for(const C of r){if(h.has(C.id))continue;const E=c.get(C.id),k={id:E,typeName:"shape",parentId:l,index:p,x:C.x,y:C.y,rotation:0,isLocked:C.locked,opacity:NJ(C.opacity),meta:{}};switch(C.angle!==0&&a.set(E,C.angle),C.groupIds&&C.groupIds.length>0?i.has(C.groupIds[0])?(y=i.get(C.groupIds[0]))==null||y.push(E):i.set(C.groupIds[0],[E]):u.push(E),C.type){case"rectangle":case"ellipse":case"diamond":{let I="",_="middle";if(C.boundElements!==null){for(const M of C.boundElements)if(M.type==="text"){const D=r.find($=>$.id===M.id);D&&(I=D.text,_=KJ[D.textAlign])}}const T=C.backgroundColor==="transparent"?C.strokeColor:C.backgroundColor;o.shapes.push({...k,type:"geo",props:{geo:C.type,url:C.link??"",w:C.width,h:C.height,size:fh[C.strokeWidth]??"draw",color:uc[T]??"black",text:I,align:_,dash:gh(C),fill:VJ(C)}});break}case"freedraw":{o.shapes.push({...k,type:"draw",props:{dash:gh(C),size:fh[C.strokeWidth],color:uc[C.strokeColor]??"black",segments:[{type:"free",points:C.points.map(([I,_,T=.5])=>({x:I,y:_,z:T}))}]}});break}case"line":{if(C.points.slice().length<2)break;const _=xu(C.points.length);o.shapes.push({...k,type:"line",props:{dash:gh(C),size:fh[C.strokeWidth],color:uc[C.strokeColor]??"black",spline:C.roundness?"cubic":"line",points:{...Object.fromEntries(C.points.map(([T,M],D)=>{const $=_[D];return[$,{id:$,index:$,x:T,y:M}]}))}}});break}case"arrow":{let I="";if(C.boundElements!==null){for(const $ of C.boundElements)if($.type==="text"){const j=r.find(O=>O.id===$.id);j&&(I=j.text)}}const _=C.points[0],T=C.points[C.points.length-1],M=c.get((v=C.startBinding)==null?void 0:v.elementId),D=c.get((w=C.endBinding)==null?void 0:w.elementId);o.shapes.push({...k,type:"arrow",props:{text:I,bend:GJ(C,_,T),dash:gh(C),size:fh[C.strokeWidth]??"m",color:uc[C.strokeColor]??"black",start:{x:_[0],y:_[1]},end:{x:T[0],y:T[1]},arrowheadEnd:oE[C.endArrowhead]??"none",arrowheadStart:oE[C.startArrowhead]??"none"}}),M&&o.bindings.push({id:Oi(),typeName:"binding",type:"arrow",fromId:E,toId:M,props:{terminal:"start",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}}),D&&o.bindings.push({id:Oi(),typeName:"binding",type:"arrow",fromId:E,toId:D,props:{terminal:"end",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}});break}case"text":{const{size:I,scale:_}=zJ(C.fontSize);o.shapes.push({...k,type:"text",props:{size:I,scale:_,font:BJ[C.fontFamily]??"draw",color:uc[C.strokeColor]??"black",text:C.text,textAlign:WJ[C.textAlign]}});break}case"image":{const I=s[C.fileId];if(!I)break;const _=_i.createId();o.assets.push({id:_,typeName:"asset",type:"image",props:{w:C.width,h:C.height,fileSize:I.size,name:C.id??"Untitled",isAnimated:!1,mimeType:I.mimeType,src:I.dataURL},meta:{}}),o.shapes.push({...k,type:"image",props:{w:C.width,h:C.height,assetId:_}})}}p=Fr(p)}const f=t??(e.inputs.shiftKey?e.inputs.currentPagePoint:void 0);e.mark("paste"),e.putContentOntoCurrentPage(o,{point:f,select:!1,preserveIds:!0});for(const C of i.values())if(C.length>1){e.groupShapes(C);const E=e.getShape(C[0]);E!=null&&E.parentId&&An(E.parentId)&&u.push(E.parentId)}for(const[C,E]of a)e.select(C),e.rotateShapesBy([C],E);const S=me(u.map(C=>e.getShape(C))),m=Q.Common(S.map(C=>e.getShapePageBounds(C))),x=e.getViewportPageBounds().center;e.updateShapes(S.map(C=>{const E={x:(C.x??0)-(m.x+m.w/2),y:(C.y??0)-(m.y+m.h/2)};return{id:C.id,type:C.type,x:x.x+E.x,y:x.y+E.y}})),e.setSelectedShapes(u)}const NJ=e=>{const n=e/100;return n<.2?.1:n<.4?.25:n<.6?.5:n<.8?.75:1},fh={1:"s",2:"m",3:"l",4:"xl"},FJ={16:"s",20:"m",28:"l",36:"xl"};function zJ(e){const n=FJ[e];return n?{size:n,scale:1}:e<16?{size:"s",scale:e/16}:e>36?{size:"xl",scale:e/36}:{size:"m",scale:1}}const BJ={1:"draw",2:"sans",3:"mono"},uc={"#ffffff":"grey","#000000":"black","#343a40":"black","#495057":"grey","#c92a2a":"red","#a61e4d":"light-red","#862e9c":"violet","#5f3dc4":"light-violet","#364fc7":"blue","#1864ab":"light-blue","#0b7285":"light-green","#087f5b":"light-green","#2b8a3e":"green","#5c940d":"light-green","#e67700":"yellow","#d9480f":"orange","#ced4da":"grey","#868e96":"grey","#fa5252":"light-red","#e64980":"red","#be4bdb":"light-violet","#7950f2":"violet","#4c6ef5":"blue","#228be6":"light-blue","#15aabf":"light-green","#12b886":"green","#40c057":"green","#82c91e":"light-green","#fab005":"yellow","#fd7e14":"orange","#212529":"grey"},UJ={solid:"draw",dashed:"dashed",dotted:"dotted"},HJ={"cross-hatch":"pattern",hachure:"pattern",solid:"solid"},KJ={left:"start",center:"middle",right:"end"},WJ={left:"start",center:"middle",right:"end"},oE={arrow:"arrow",dot:"dot",triangle:"triangle",bar:"pipe"};function GJ(e,n,t){let r=0;if(e.points.length>2){const s=new b(n[0],n[1]),o=new b(t[0],t[1]),i=new b(e.points[1][0],e.points[1][1]),a=b.Sub(o,s),l=b.Per(a),c=b.Med(o,s),u=b.Sub(c,l),h=b.Add(c,l),p=b.NearestPointOnLineSegment(u,h,i,!1);r=b.Dist(p,c),b.Clockwise(p,o,c)&&(r*=-1)}return r}const gh=e=>{let n=UJ[e.strokeStyle]??"draw";return n==="draw"&&e.roughness===0&&(n="solid"),n},VJ=e=>e.backgroundColor==="transparent"?"none":HJ[e.fillStyle]??"solid";async function YJ(e,n,t,r){const o=(await Promise.all(n.map(async i=>await(await vs(i)).blob()))).map(i=>new File([i],"tldrawFile",{type:i.type}));e.mark("paste"),await e.putExternalContent({type:"files",files:o,point:t,ignoreParent:!1,sources:r}),n.forEach(i=>URL.revokeObjectURL(i))}function XJ(e,n,t){const r=e.getSelectionPageBounds();e.mark("paste"),e.putContentOntoCurrentPage(n,{point:t,select:!0});const s=e.getSelectionPageBounds();r&&s&&(r!=null&&r.collides(s))&&(e.updateInstanceState({isChangingStyle:!0}),e.timers.setTimeout(()=>{e.updateInstanceState({isChangingStyle:!1})},150))}async function Zv(e,n,t,r){return e.mark("paste"),await e.putExternalContent({type:"url",point:t,url:n,sources:r})}function qJ(e){const n=document.implementation.createHTMLDocument("");return n.documentElement.innerHTML=e.trim(),n.body.textContent||n.body.innerText||""}const ZJ=e=>{try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}},QJ=e=>{const n=e.split(/[\n\s]/);for(const t of n)try{const r=new URL(t);if(!(r.protocol==="http:"||r.protocol==="https:"))return}catch{return}return bM(n)},JJ=e=>/^-1)}const tee=e=>e.types.find(n=>n.match(/^image\//)),Dy=(e,n,t,r)=>{const s=QJ(n);if(s)for(const o of s)Zv(e,o,t);else ZJ(n)?Zv(e,n,t):JJ(n)?(e.mark("paste"),e.putExternalContent({type:"svg-text",text:n,point:t,sources:r})):(e.mark("paste"),e.putExternalContent({type:"text",text:n,point:t,sources:r}))},nee=async(e,n,t)=>{if(e.getEditingShapeId()!==null)return;if(!n)throw Error("No clipboard data");const r=[];for(const s of Object.values(n.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}}xO(e,r,t)},vO=async(e,n,t)=>{const r=[];for(const s of n){if(tee(s))for(const o of s.types)o.match(/^image\//)&&r.push({type:"blob",source:s.getType(o)});s.types.includes("text/html")&&r.push({type:"html",source:(async()=>{const o=await s.getType("text/html");return await ji.blobToText(o)})()}),s.types.includes("text/uri-list")&&r.push({type:"url",source:(async()=>{const o=await s.getType("text/uri-list");return await ji.blobToText(o)})()}),s.types.includes("text/plain")&&r.push({type:"text",source:(async()=>{const o=await s.getType("text/plain");return await ji.blobToText(o)})()})}return await xO(e,r,t)};async function xO(e,n,t){const r=n.filter(o=>(o.type==="file"||o.type==="blob")&&o.source!==null);if(r.length){const i=(await Promise.all(r.map(a=>a.source))).filter(Boolean).map(a=>URL.createObjectURL(a));return await YJ(e,i,t)}const s=await Promise.all(n.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>/))==null?void 0:u[1];if(c)try{const h=SO.decompressFromBase64(c);if(h===null){i({type:"error",data:h,reason:"found tldraw data comment but could not parse base64"});return}else{const p=JSON.parse(h);if(p.type!=="application/tldraw"&&i({type:"error",data:p,reason:`found tldraw data comment but JSON was of a different type: ${p.type}`}),typeof p.data=="string"){i({type:"error",data:p,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}i({type:"tldraw",data:p.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 h=JSON.parse(l);if(h.type==="excalidraw/clipboard"){i({type:"excalidraw",data:h});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"){XJ(e,o.data,t);return}for(const o of s)if(o.type==="excalidraw"){$J(e,o.data,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");Dy(e,c,t,s);return}if(!s.some(c=>c.type==="text"&&c.subtype!=="html")&&o.data.trim()){Dy(e,qJ(o.data),t,s);return}}for(const o of s)if(o.type==="text"&&o.subtype==="url"){Zv(e,o.data,t,s);return}for(const o of s)if(o.type==="text"&&o.subtype==="text"&&o.data.trim()){Dy(e,o.data,t,s);return}}const Cf=async e=>{var r;const n=await e.resolveAssetsInContent(e.getContentFromCurrentPage(e.getSelectedShapeIds()));if(!n){navigator&&navigator.clipboard&&navigator.clipboard.writeText("");return}const t=SO.compressToBase64(JSON.stringify({type:"application/tldraw",kind:"content",data:n}));if(!(typeof navigator>"u")){const s=n.shapes.map(o=>e.isShapeOfType(o,"text")||e.isShapeOfType(o,"geo")||e.isShapeOfType(o,"arrow")?o.props.text:e.isShapeOfType(o,"bookmark")||e.isShapeOfType(o,"embed")?o.props.url:null).filter(H9);if((r=navigator.clipboard)!=null&&r.write){const o=new Blob([`
${t}
`],{type:"text/html"});let i=s.join(" ");i===""&&(i=" "),navigator.clipboard.write([new ClipboardItem({"text/html":o,"text/plain":new Blob([i],{type:"text/plain"})})])}else navigator.clipboard.writeText&&navigator.clipboard.writeText(`
${t}
`)}};function ree(){const e=F(),n=qt(),t=P.useCallback(async function(i){e.getSelectedShapeIds().length!==0&&(await Cf(e),n("copy",{source:i}))},[e,n]),r=P.useCallback(async function(i){e.getSelectedShapeIds().length!==0&&(await Cf(e),e.deleteShapes(e.getSelectedShapeIds()),n("cut",{source:i}))},[e,n]),s=P.useCallback(async function(i,a,l){e.getEditingShapeId()===null&&(Array.isArray(i)&&i[0]instanceof ClipboardItem?(vO(e,i,l),n("paste",{source:"menu"})):navigator.clipboard.read().then(c=>{s(c,a,l)}))},[e,n]);return{copy:t,cut:r,paste:s}}function see(){const e=F(),n=qt(),t=H("editor.isFocused",()=>e.getInstanceState().isFocused,[e]);P.useEffect(()=>{if(!t)return;const r=async l=>{e.getSelectedShapeIds().length===0||e.getEditingShapeId()!==null||Oy(e)||(Ie(l),await Cf(e),n("copy",{source:"kbd"}))};async function s(l){e.getSelectedShapeIds().length===0||e.getEditingShapeId()!==null||Oy(e)||(Ie(l),await Cf(e),e.deleteShapes(e.getSelectedShapeIds()),n("cut",{source:"kbd"}))}let o=!1;const i=l=>{l.button===1&&(o=!0,e.timers.requestAnimationFrame(()=>{o=!1}))},a=l=>{if(o){Dt(l);return}if(e.getEditingShapeId()!==null||Oy(e))return;let c,u=!1;e.inputs.shiftKey&&(u=!0),e.user.getIsPasteAtCursorMode()&&(u=!u),u&&(c=e.inputs.currentPagePoint),l.clipboardData&&!e.inputs.shiftKey?nee(e,l.clipboardData,c):navigator.clipboard.read().then(h=>{Array.isArray(h)&&h[0]instanceof ClipboardItem&&vO(e,h,c)}),Ie(l),n("paste",{source:"kbd"})};return document.addEventListener("copy",r),document.addEventListener("cut",s),document.addEventListener("paste",a),document.addEventListener("pointerup",i),()=>{document.removeEventListener("copy",r),document.removeEventListener("cut",s),document.removeEventListener("paste",a),document.removeEventListener("pointerup",i)}},[e,n,t])}async function wO(e,n,t){const{type:r,quality:s,scale:o,width:i,height:a}=t;let[l,c]=await KY(i*o,a*o);l=Math.floor(l),c=Math.floor(c);const u=l/i,h=URL.createObjectURL(new Blob([n],{type:"image/svg+xml"})),p=await new Promise(S=>{const m=hl();m.crossOrigin="anonymous",m.onload=async()=>{e.environment.isSafari&&await new Promise(v=>e.timers.setTimeout(v,250));const x=document.createElement("canvas"),y=x.getContext("2d");x.width=l,x.height=c,y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="high",y.drawImage(m,0,0,l,c),URL.revokeObjectURL(h),S(x)},m.onerror=()=>{S(null)},m.src=h});if(!p)return null;const f=await new Promise(S=>p.toBlob(m=>{(!m||xt.throwToBlob.get())&&S(null),S(m)},"image/"+r,s));if(!f)return null;if(r==="png"){const S=new DataView(await f.arrayBuffer());return as.setPhysChunk(S,u,{type:"image/"+r})}else return f}async function bO(e,n,t){const r=await e.getSvgString(n!=null&&n.length?n:[...e.getCurrentPageShapeIds()],{scale:1,background:e.getInstanceState().exportBackground,...t});if(!r)throw new Error("Could not construct SVG.");return r}async function Qv(e,n,t,r={}){var s;switch(t){case"svg":return(s=await bO(e,n,r))==null?void 0:s.svg;case"json":{const o=await e.resolveAssetsInContent(e.getContentFromCurrentPage(n));return JSON.stringify(o)}default:cn(t)}}async function PO({editor:e,ids:n,format:t,opts:r={}}){switch(t){case"svg":return new Blob([await Qv(e,n,"svg",r)],{type:"text/plain"});case"json":return new Blob([await Qv(e,n,"json",r)],{type:"text/plain"});case"jpeg":case"png":case"webp":{const s=await bO(e,n,r);if(!s)throw new Error("Could not construct image.");const o=await wO(e,s.svg,{type:t,quality:1,scale:2,width:s.width,height:s.height});if(!o)throw new Error("Could not construct image.");return o}default:cn(t)}}const oee={jpeg:"image/jpeg",png:"image/png",webp:"image/webp",json:"text/plain",svg:"text/plain"};function iee(e,n,t,r={}){return{blobPromise:PO({editor:e,ids:n,format:t,opts:r}),mimeType:oee[t]}}function aee(e,n,t="svg",r={}){if(!window.navigator.clipboard)return Promise.reject(new Error("Copy not supported"));if(window.navigator.clipboard.write){const{blobPromise:s,mimeType:o}=iee(e,n,t,r);return window.navigator.clipboard.write([new ClipboardItem({[o]:s})]).catch(i=>(console.error(i),s.then(a=>window.navigator.clipboard.write([new ClipboardItem({[o]:a})]))))}switch(t){case"json":case"svg":return lee(async()=>Qv(e,n,t,r));case"jpeg":case"png":throw new Error("Copy not supported");default:cn(t)}}async function lee(e){var n,t;await((t=(n=navigator.clipboard)==null?void 0:n.writeText)==null?void 0:t.call(n,await e()))}function cee(){const e=F(),{addToast:n}=Qr(),t=xe();return P.useCallback((r,s="svg")=>{aee(e,r,s).catch(()=>{n({id:"copy-fail",severity:"warning",title:t("toast.error.copy-fail.title"),description:t("toast.error.copy-fail.desc")})})},[e,n,t])}async function uee(e,n,t="png",r,s={}){if(!r&&(r=`shapes at ${iE()}`,n.length===1)){const a=e.getShape(n[0]);e.isShapeOfType(a,"frame")?r=a.props.name??"frame":r=`${a.id.replace(/:/,"_")} at ${iE()}`}r+=`.${t}`;const o=await PO({editor:e,ids:n,format:t,opts:s}),i=new File([o],r,{type:o.type});dee(i)}function iE(){const e=new Date,n=String(e.getFullYear()).slice(2),t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),i=String(e.getSeconds()).padStart(2,"0");return`${n}-${t}-${r} ${s}.${o}.${i}`}function dee(e){const n=document.createElement("a"),t=URL.createObjectURL(e);n.href=t,n.download=e.name,n.click(),URL.revokeObjectURL(t)}function hee(){const e=F(),{addToast:n}=Qr(),t=xe();return P.useCallback((r,s="png",o)=>{uee(e,r,s,o,{scale:1,background:e.getInstanceState().exportBackground}).catch(i=>{console.error(i.message),n({id:"export-fail",title:t("toast.error.export-fail.title"),description:t("toast.error.export-fail.desc"),severity:"error"})})},[e,n,t])}async function pee(e,n,t){const r=me(n.map(a=>{const l=e.getShape(a);if(!(!l||e.getShapeUtil(l.type).toSvg===void 0))return l}));if(r.length===0)return;if(r.length===1){const a=r[0];if(!a||e.isShapeOfType(a,"image"))return}const s=[];if(t!==void 0){const a=r.map(l=>({shape:l,bounds:e.getShapeMaskedPageBounds(l).clone().expandBy(t)}));for(let l=0;le.getShapeMaskedPageBounds(l)));s.push({shapes:r,bounds:a})}const o=e.options.flattenImageBoundsPadding;for(const a of s){t!==void 0&&a.bounds.expandBy(-t);const l=await e.getSvgString(a.shapes,{padding:o});if(!(l!=null&&l.svg))continue;const c=new Blob([l.svg],{type:"image/svg+xml"}),u=await e.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});u&&(a.asset=u)}const i=[];return gs(()=>{for(const a of s){const{asset:l,bounds:c,shapes:u}=a;if(!l)continue;const h=e.findCommonAncestor(u)??e.getCurrentPageId();if(!h)continue;let p="a1";for(const y of u)if(y.parentId===h){y.index>p&&(p=y.index);break}let f,S,m;if(An(h)){const y=e.getShape(h);if(!y)continue;const v=e.getPointInShapeSpace(y,{x:c.x,y:c.y});m=e.getShapePageTransform(h).rotation(),v.sub(new b(o,o).rot(-m)),f=v.x,S=v.y}else f=c.x-o,S=c.y-o,m=0;e.deleteShapes(u),e.createAssets([{...l,id:l.id}]);const x=je();e.createShape({id:x,type:"image",index:p,parentId:h,x:f,y:S,rotation:-m,props:{assetId:l.id,w:c.w+o*2,h:c.h+o*2}}),i.push(x)}}),i}function Lg(){return F().store.props.collaboration!==void 0}function fee(){const e=F();return H("sync status",()=>{var n;return(n=e.store.props.collaboration)!=null&&n.status?e.store.props.collaboration.status.get():null},[e])}function gee(){const e=F(),n=P.useRef(null),t=P.useRef(null);return P.useCallback(async function(){const s=document.createElement("div"),o=document.createElement("style"),i=(y,v)=>{y&&(y.innerHTML=""),v&&document.head.contains(v)&&document.head.removeChild(v),y&&document.body.contains(y)&&document.body.removeChild(y)};i(n.current,t.current),n.current=s,t.current=o;const a=`tl-print-surface-${ct()}`;s.className=a,o.innerHTML=` +For more information, see https://radix-ui.com/primitives/docs/components/${n.docsSlug}`;return P.useEffect(()=>{e&&(document.getElementById(e)||console.error(t))},[t,e]),null},LQ="DialogDescriptionWarning",$Q=({contentRef:e,descriptionId:n})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Yj(LQ).contentName}}.`;return P.useEffect(()=>{var o;const s=(o=e.current)==null?void 0:o.getAttribute("aria-describedby");n&&s&&(document.getElementById(n)||console.warn(r))},[r,e,n]),null},NQ=Lj,FQ=Fj,zQ=zj,BQ=Bj;const Xj=()=>{},qj=P.createContext(null);function UQ({onEvent:e,children:n}){return d.jsx(qj.Provider,{value:e??Xj,children:n})}function qt(){return P.useContext(qj)??Xj}const Zj=P.createContext(null);function HQ({children:e}){const n=F(),t=qt(),[r,s]=P.useState([]),o=P.useCallback(c=>{const u=c.id??ct();return s(h=>[...h.filter(p=>p.id!==c.id),{...c,id:u}]),t("open-menu",{source:"dialog",id:u}),n.addOpenMenu(u),u},[n,t]),i=P.useCallback((c,u)=>(s(h=>h.map(p=>p.id===c?{...p,...u}:p)),t("open-menu",{source:"dialog",id:c}),n.addOpenMenu(c),c),[n,t]),a=P.useCallback(c=>(s(u=>u.filter(h=>{var p;return h.id===c?((p=h.onClose)==null||p.call(h),!1):!0})),t("close-menu",{source:"dialog",id:c}),n.deleteOpenMenu(c),c),[n,t]),l=P.useCallback(()=>{s(c=>(c.forEach(u=>{var h;(h=u.onClose)==null||h.call(u),t("close-menu",{source:"dialog",id:u.id}),n.deleteOpenMenu(u.id)}),[]))},[n,t]);return d.jsx(Zj.Provider,{value:{dialogs:r,addDialog:o,removeDialog:a,clearDialogs:l,updateDialog:i},children:e})}function aa(){const e=P.useContext(Zj);if(!e)throw new Error("useDialogs must be used within a DialogsProvider");return e}const KQ=({id:e,component:n,onClose:t})=>{const{removeDialog:r}=aa(),s=$t(),o=P.useCallback(i=>{if(!i){if(t)try{t()}catch(a){console.warn(a)}r(e)}},[e,t,r]);return d.jsx(NQ,{onOpenChange:o,defaultOpen:!0,children:d.jsx(FQ,{container:s,children:d.jsx(zQ,{dir:"ltr",className:"tlui-dialog__overlay",onClick:i=>{i.target===i.currentTarget&&o(!1)},children:d.jsx(BQ,{dir:"ltr",className:"tlui-dialog__content",children:d.jsx(n,{onClose:()=>o(!1)})})})})})};function WQ(){const{dialogs:e}=aa();return e.map(n=>d.jsx(KQ,{...n},n.id))}const GQ=Ce.memo(WQ);function VQ(){const e=F(),n=H("follow",()=>e.getInstanceState().followingUserId,[e]);return n?d.jsx(YQ,{userId:n}):null}function YQ({userId:e}){const n=ug(e);return n?d.jsx("div",{className:"tlui-following-indicator",style:{borderColor:n.color}}):null}function kg(e){const n=e+"CollectionProvider",[t,r]=Ts(n),[s,o]=t(n,{collectionRef:{current:null},itemMap:new Map}),i=f=>{const{scope:S,children:y}=f,x=Ce.useRef(null),m=Ce.useRef(new Map).current;return d.jsx(s,{scope:S,itemMap:m,collectionRef:x,children:y})};i.displayName=n;const a=e+"CollectionSlot",l=Ce.forwardRef((f,S)=>{const{scope:y,children:x}=f,m=o(a,y),v=Xe(S,m.collectionRef);return d.jsx(Vi,{ref:v,children:x})});l.displayName=a;const c=e+"CollectionItemSlot",u="data-radix-collection-item",h=Ce.forwardRef((f,S)=>{const{scope:y,children:x,...m}=f,v=Ce.useRef(null),w=Xe(S,v),C=o(c,y);return Ce.useEffect(()=>(C.itemMap.set(v,{ref:v,...m}),()=>void C.itemMap.delete(v))),d.jsx(Vi,{[u]:"",ref:w,children:x})});h.displayName=c;function p(f){const S=o(e+"CollectionConsumer",f);return Ce.useCallback(()=>{const x=S.collectionRef.current;if(!x)return[];const m=Array.from(x.querySelectorAll(`[${u}]`));return Array.from(S.itemMap.values()).sort((C,E)=>m.indexOf(C.ref.current)-m.indexOf(E.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:i,Slot:l,ItemSlot:h},p,r]}var XQ="VisuallyHidden",Rw=P.forwardRef((e,n)=>d.jsx(_e.span,{...e,ref:n,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}));Rw.displayName=XQ;var Lw="ToastProvider",[$w,qQ,ZQ]=kg("Toast"),[Qj,Dae]=Ts("Toast",[ZQ]),[QQ,Tg]=Qj(Lw),Jj=e=>{const{__scopeToast:n,label:t="Notification",duration:r=5e3,swipeDirection:s="right",swipeThreshold:o=50,children:i}=e,[a,l]=P.useState(null),[c,u]=P.useState(0),h=P.useRef(!1),p=P.useRef(!1);return t.trim()||console.error(`Invalid prop \`label\` supplied to \`${Lw}\`. Expected non-empty \`string\`.`),d.jsx($w.Provider,{scope:n,children:d.jsx(QQ,{scope:n,label:t,duration:r,swipeDirection:s,swipeThreshold:o,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:P.useCallback(()=>u(f=>f+1),[]),onToastRemove:P.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:i})})};Jj.displayName=Lw;var eO="ToastViewport",JQ=["F8"],Vv="toast.viewportPause",Yv="toast.viewportResume",tO=P.forwardRef((e,n)=>{const{__scopeToast:t,hotkey:r=JQ,label:s="Notifications ({hotkey})",...o}=e,i=Tg(eO,t),a=qQ(t),l=P.useRef(null),c=P.useRef(null),u=P.useRef(null),h=P.useRef(null),p=Xe(n,h,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),S=i.toastCount>0;P.useEffect(()=>{const x=m=>{var w;r.every(C=>m[C]||m.code===C)&&((w=h.current)==null||w.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[r]),P.useEffect(()=>{const x=l.current,m=h.current;if(S&&x&&m){const v=()=>{if(!i.isClosePausedRef.current){const k=new CustomEvent(Vv);m.dispatchEvent(k),i.isClosePausedRef.current=!0}},w=()=>{if(i.isClosePausedRef.current){const k=new CustomEvent(Yv);m.dispatchEvent(k),i.isClosePausedRef.current=!1}},C=k=>{!x.contains(k.relatedTarget)&&w()},E=()=>{x.contains(document.activeElement)||w()};return x.addEventListener("focusin",v),x.addEventListener("focusout",C),x.addEventListener("pointermove",v),x.addEventListener("pointerleave",E),window.addEventListener("blur",v),window.addEventListener("focus",w),()=>{x.removeEventListener("focusin",v),x.removeEventListener("focusout",C),x.removeEventListener("pointermove",v),x.removeEventListener("pointerleave",E),window.removeEventListener("blur",v),window.removeEventListener("focus",w)}}},[S,i.isClosePausedRef]);const y=P.useCallback(({tabbingDirection:x})=>{const v=a().map(w=>{const C=w.ref.current,E=[C,...hJ(C)];return x==="forwards"?E:E.reverse()});return(x==="forwards"?v.reverse():v).flat()},[a]);return P.useEffect(()=>{const x=h.current;if(x){const m=v=>{var E,k,I;const w=v.altKey||v.ctrlKey||v.metaKey;if(v.key==="Tab"&&!w){const _=document.activeElement,T=v.shiftKey;if(v.target===x&&T){(E=c.current)==null||E.focus();return}const $=y({tabbingDirection:T?"backwards":"forwards"}),j=$.findIndex(O=>O===_);Ay($.slice(j+1))?v.preventDefault():T?(k=c.current)==null||k.focus():(I=u.current)==null||I.focus()}};return x.addEventListener("keydown",m),()=>x.removeEventListener("keydown",m)}},[a,y]),d.jsxs(AZ,{ref:l,role:"region","aria-label":s.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:S?void 0:"none"},children:[S&&d.jsx(Xv,{ref:c,onFocusFromOutsideViewport:()=>{const x=y({tabbingDirection:"forwards"});Ay(x)}}),d.jsx($w.Slot,{scope:t,children:d.jsx(_e.ol,{tabIndex:-1,...o,ref:p})}),S&&d.jsx(Xv,{ref:u,onFocusFromOutsideViewport:()=>{const x=y({tabbingDirection:"backwards"});Ay(x)}})]})});tO.displayName=eO;var nO="ToastFocusProxy",Xv=P.forwardRef((e,n)=>{const{__scopeToast:t,onFocusFromOutsideViewport:r,...s}=e,o=Tg(nO,t);return d.jsx(Rw,{"aria-hidden":!0,tabIndex:0,...s,ref:n,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=o.viewport)!=null&&c.contains(a))&&r()}})});Xv.displayName=nO;var Mg="Toast",eJ="toast.swipeStart",tJ="toast.swipeMove",nJ="toast.swipeCancel",rJ="toast.swipeEnd",rO=P.forwardRef((e,n)=>{const{forceMount:t,open:r,defaultOpen:s,onOpenChange:o,...i}=e,[a=!0,l]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(qr,{present:t||a,children:d.jsx(iJ,{open:a,...i,ref:n,onClose:()=>l(!1),onPause:Yt(e.onPause),onResume:Yt(e.onResume),onSwipeStart:re(e.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:re(e.onSwipeMove,c=>{const{x:u,y:h}=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",`${h}px`)}),onSwipeCancel:re(e.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:re(e.onSwipeEnd,c=>{const{x:u,y:h}=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",`${h}px`),l(!1)})})})});rO.displayName=Mg;var[sJ,oJ]=Qj(Mg,{onClose(){}}),iJ=P.forwardRef((e,n)=>{const{__scopeToast:t,type:r="foreground",duration:s,open:o,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...S}=e,y=Tg(Mg,t),[x,m]=P.useState(null),v=Xe(n,O=>m(O)),w=P.useRef(null),C=P.useRef(null),E=s||y.duration,k=P.useRef(0),I=P.useRef(E),_=P.useRef(0),{onToastAdd:T,onToastRemove:M}=y,D=Yt(()=>{var R;(x==null?void 0:x.contains(document.activeElement))&&((R=y.viewport)==null||R.focus()),i()}),$=P.useCallback(O=>{!O||O===1/0||(window.clearTimeout(_.current),k.current=new Date().getTime(),_.current=window.setTimeout(D,O))},[D]);P.useEffect(()=>{const O=y.viewport;if(O){const R=()=>{$(I.current),c==null||c()},K=()=>{const B=new Date().getTime()-k.current;I.current=I.current-B,window.clearTimeout(_.current),l==null||l()};return O.addEventListener(Vv,K),O.addEventListener(Yv,R),()=>{O.removeEventListener(Vv,K),O.removeEventListener(Yv,R)}}},[y.viewport,E,l,c,$]),P.useEffect(()=>{o&&!y.isClosePausedRef.current&&$(E)},[o,E,y.isClosePausedRef,$]),P.useEffect(()=>(T(),()=>M()),[T,M]);const j=P.useMemo(()=>x?uO(x):null,[x]);return y.viewport?d.jsxs(d.Fragment,{children:[j&&d.jsx(aJ,{__scopeToast:t,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:j}),d.jsx(sJ,{scope:t,onClose:D,children:ta.createPortal(d.jsx($w.ItemSlot,{scope:t,children:d.jsx(MZ,{asChild:!0,onEscapeKeyDown:re(a,()=>{y.isFocusedToastEscapeKeyDownRef.current||D(),y.isFocusedToastEscapeKeyDownRef.current=!1}),children:d.jsx(_e.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":o?"open":"closed","data-swipe-direction":y.swipeDirection,...S,ref:v,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:re(e.onKeyDown,O=>{O.key==="Escape"&&(a==null||a(O.nativeEvent),O.nativeEvent.defaultPrevented||(y.isFocusedToastEscapeKeyDownRef.current=!0,D()))}),onPointerDown:re(e.onPointerDown,O=>{O.button===0&&(w.current={x:O.clientX,y:O.clientY})}),onPointerMove:re(e.onPointerMove,O=>{if(!w.current)return;const R=O.clientX-w.current.x,K=O.clientY-w.current.y,B=!!C.current,z=["left","right"].includes(y.swipeDirection),W=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,Y=z?W(0,R):0,q=z?0:W(0,K),ae=O.pointerType==="touch"?10:2,fe={x:Y,y:q},we={originalEvent:O,delta:fe};B?(C.current=fe,ph(tJ,h,we,{discrete:!1})):nE(fe,y.swipeDirection,ae)?(C.current=fe,ph(eJ,u,we,{discrete:!1}),O.target.setPointerCapture(O.pointerId)):(Math.abs(R)>ae||Math.abs(K)>ae)&&(w.current=null)}),onPointerUp:re(e.onPointerUp,O=>{const R=C.current,K=O.target;if(K.hasPointerCapture(O.pointerId)&&K.releasePointerCapture(O.pointerId),C.current=null,w.current=null,R){const B=O.currentTarget,z={originalEvent:O,delta:R};nE(R,y.swipeDirection,y.swipeThreshold)?ph(rJ,f,z,{discrete:!0}):ph(nJ,p,z,{discrete:!0}),B.addEventListener("click",W=>W.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null}),aJ=e=>{const{__scopeToast:n,children:t,...r}=e,s=Tg(Mg,n),[o,i]=P.useState(!1),[a,l]=P.useState(!1);return uJ(()=>i(!0)),P.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:d.jsx(td,{asChild:!0,children:d.jsx(Rw,{...r,children:o&&d.jsxs(d.Fragment,{children:[s.label," ",t]})})})},lJ="ToastTitle",sO=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});sO.displayName=lJ;var cJ="ToastDescription",oO=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});oO.displayName=cJ;var iO="ToastAction",aO=P.forwardRef((e,n)=>{const{altText:t,...r}=e;return t.trim()?d.jsx(cO,{altText:t,asChild:!0,children:d.jsx(Nw,{...r,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${iO}\`. Expected non-empty \`string\`.`),null)});aO.displayName=iO;var lO="ToastClose",Nw=P.forwardRef((e,n)=>{const{__scopeToast:t,...r}=e,s=oJ(lO,t);return d.jsx(cO,{asChild:!0,children:d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,s.onClose)})})});Nw.displayName=lO;var cO=P.forwardRef((e,n)=>{const{__scopeToast:t,altText:r,...s}=e;return d.jsx(_e.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...s,ref:n})});function uO(e){const n=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&n.push(r.textContent),dJ(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&&n.push(i)}else n.push(...uO(r))}}),n}function ph(e,n,t,{discrete:r}){const s=t.originalEvent.currentTarget,o=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:t});n&&s.addEventListener(e,n,{once:!0}),r?kw(s,o):s.dispatchEvent(o)}var nE=(e,n,t=0)=>{const r=Math.abs(e.x),s=Math.abs(e.y),o=r>s;return n==="left"||n==="right"?o&&r>t:!o&&s>t};function uJ(e=()=>{}){const n=Yt(e);Zo(()=>{let t=0,r=0;return t=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(n)),()=>{window.cancelAnimationFrame(t),window.cancelAnimationFrame(r)}},[n])}function dJ(e){return e.nodeType===e.ELEMENT_NODE}function hJ(e){const n=[],t=document.createTreeWalker(e,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();)n.push(t.currentNode);return n}function Ay(e){const n=document.activeElement;return e.some(t=>t===n?!0:(t.focus(),document.activeElement!==n))}var pJ=rO,fJ=sO,gJ=oO,mJ=aO,rE=Nw;const dO=P.createContext(null);function yJ({children:e}){const[n,t]=P.useState([]),r=P.useCallback(i=>{const a=i.id??ct();return t(l=>[...l.filter(c=>c.id!==i.id),{...i,id:a}]),a},[]),s=P.useCallback(i=>(t(a=>a.filter(l=>l.id!==i)),i),[]),o=P.useCallback(()=>{t(()=>[])},[]);return d.jsx(Jj,{children:d.jsx(dO.Provider,{value:{toasts:n,addToast:r,removeToast:s,clearToasts:o},children:e})})}function Qr(){const e=P.useContext(dO);if(!e)throw new Error("useToasts must be used within a ToastsProvider");return e}const ce=P.forwardRef(function({children:n,disabled:t,type:r,...s},o){return d.jsx("button",{ref:o,type:"button",draggable:!1,disabled:t,...s,className:le("tlui-button",`tlui-button__${r}`,s.className),children:n})});function wt({children:e}){return d.jsx("span",{className:"tlui-button__label",children:e})}const Cs=P.memo(function({small:n,invertIcon:t,icon:r,color:s,className:o,...i}){const a=Iw(),l=a.icons[r]??a.icons["question-mark-circle"],c=P.useRef(null);return P.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"?d.jsx("div",{className:le("tlui-icon tlui-icon__placeholder",{"tlui-icon__small":n},o)}):d.jsx("div",{...i,ref:c,className:le("tlui-icon",{"tlui-icon__small":n},o),style:{color:s,mask:`url(${l}) center 100% / 100% no-repeat`,transform:t?"scale(-1, 1)":void 0}})}),SJ={success:"check-circle",warning:"warning-triangle",error:"cross-circle",info:"info-circle"};function vJ({toast:e}){const{removeToast:n}=Qr(),t=xe(),r=i=>{i||n(e.id)},s=e.actions&&e.actions.length>0,o=e.icon||e.severity&&SJ[e.severity];return d.jsxs(pJ,{onOpenChange:r,className:"tlui-toast__container",duration:e.keepOpen?1/0:5e3,"data-severity":e.severity,children:[o&&d.jsx("div",{className:"tlui-toast__icon",children:d.jsx(Cs,{icon:o})}),d.jsxs("div",{className:"tlui-toast__main",children:[d.jsxs("div",{className:"tlui-toast__content",children:[e.title&&d.jsx(fJ,{className:"tlui-toast__title",children:e.title}),e.description&&d.jsx(gJ,{className:"tlui-toast__description",children:e.description})]}),e.actions&&d.jsxs("div",{className:"tlui-toast__actions",children:[e.actions.map((i,a)=>d.jsx(mJ,{altText:i.label,asChild:!0,onClick:i.onClick,children:d.jsx(ce,{type:i.type,children:d.jsx(wt,{children:i.label})})},a)),d.jsx(rE,{asChild:!0,children:d.jsx(ce,{type:"normal",className:"tlui-toast__close",style:{marginLeft:"auto"},children:d.jsx(wt,{children:e.closeLabel??t("toast.close")})})})]})]}),!s&&d.jsx(rE,{asChild:!0,children:d.jsx(ce,{type:"normal",className:"tlui-toast__close",children:d.jsx(wt,{children:e.closeLabel??t("toast.close")})})})]})}function xJ(){const{toasts:e}=Qr();return e.map(n=>d.jsx(vJ,{toast:n},n.id))}const wJ=P.memo(xJ);function bJ(){const e=F(),{toasts:n}=Qr(),[t,r]=P.useState(!1);return P.useEffect(()=>{let s=-1;return n.length?r(!0):s=e.timers.setTimeout(()=>{r(!1)},1e3),()=>{clearTimeout(s)}},[n.length,r,e]),t?d.jsx(tO,{className:"tlui-toast__viewport"}):null}function Se({icon:e,small:n,invertIcon:t}){return d.jsx(Cs,{className:"tlui-button__icon",icon:e,small:n,invertIcon:t})}const jy=[0,390,428,468,580,640,840,1023];var yt=(e=>(e[e.ZERO=0]="ZERO",e[e.MOBILE_XXS=1]="MOBILE_XXS",e[e.MOBILE_XS=2]="MOBILE_XS",e[e.MOBILE_SM=3]="MOBILE_SM",e[e.MOBILE=4]="MOBILE",e[e.TABLET_SM=5]="TABLET_SM",e[e.TABLET=6]="TABLET",e[e.DESKTOP=7]="DESKTOP",e))(yt||{});let qv={fonts:{draw:`${jo()}/fonts/Shantell_Sans-Tldrawish.woff2`,serif:`${jo()}/fonts/IBMPlexSerif-Medium.woff2`,sansSerif:`${jo()}/fonts/IBMPlexSans-Medium.woff2`,monospace:`${jo()}/fonts/IBMPlexMono-Medium.woff2`}};function hO(e){return P.useMemo(()=>e?{fonts:{...qv.fonts,...e==null?void 0:e.fonts}}:qv,[e])}const PJ=["align-bottom","align-center-horizontal","align-center-vertical","align-left","align-right","align-top","arrow-left","arrowhead-arrow","arrowhead-bar","arrowhead-diamond","arrowhead-dot","arrowhead-none","arrowhead-square","arrowhead-triangle-inverted","arrowhead-triangle","blob","bring-forward","bring-to-front","broken","check-circle","check","chevron-down","chevron-left","chevron-right","chevron-up","chevrons-ne","chevrons-sw","clipboard-copied","clipboard-copy","color","cross-2","cross-circle","dash-dashed","dash-dotted","dash-draw","dash-solid","disconnected","discord","distribute-horizontal","distribute-vertical","dot","dots-horizontal","dots-vertical","drag-handle-dots","duplicate","edit","external-link","fill-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","horizontal-align-end","horizontal-align-middle","horizontal-align-start","info-circle","leading","link","lock","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","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","undo","ungroup","unlock","vertical-align-end","vertical-align-middle","vertical-align-start","warning-triangle","zoom-in","zoom-out"];let cc={...qv,icons:Object.fromEntries(PJ.map(e=>[e,`${jo()}/icons/icon/${e}.svg`])),translations:Object.fromEntries(bu.map(e=>[e.locale,`${jo()}/translations/${e.locale}.json`])),embedIcons:Object.fromEntries(Wu.map(e=>[e.type,`${jo()}/embed-icons/${e.type}.png`]))};function CJ(e){return e?{fonts:Object.assign({...cc.fonts},{...e==null?void 0:e.fonts}),icons:Object.assign({...cc.icons},{...e==null?void 0:e.icons}),embedIcons:Object.assign({...cc.embedIcons},{...e==null?void 0:e.embedIcons}),translations:Object.assign({...cc.translations},{...e==null?void 0:e.translations})}:cc}function Ag({className:e,children:n}){return d.jsx("div",{className:le("tlui-dialog__header",e),children:n})}function jg({className:e,children:n}){return d.jsx(Hj,{dir:"ltr",className:le("tlui-dialog__header__title",e),children:n})}function Og(){return d.jsx("div",{className:"tlui-dialog__header__close",children:d.jsx(Gj,{"data-testid":"dialog.close",dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon","aria-label":"Close",onTouchEnd:e=>e.target.click(),children:d.jsx(Se,{small:!0,icon:"cross-2"})})})})}function Cu({className:e,children:n,style:t}){return d.jsx("div",{className:le("tlui-dialog__body",e),style:t,children:n})}function Fw({className:e,children:n}){return d.jsx("div",{className:le("tlui-dialog__footer",e),children:n})}const Dg=P.forwardRef(function({className:n,label:t,icon:r,iconLeft:s,autoSelect:o=!1,autoFocus:i=!1,defaultValue:a,placeholder:l,onComplete:c,onValueChange:u,onCancel:h,onFocus:p,onBlur:f,shouldManuallyMaintainScrollPositionWhenFocused:S=!1,children:y,value:x},m){const v=F(),w=P.useRef(null);P.useImperativeHandle(m,()=>w.current);const C=xe(),E=P.useRef(a??""),k=P.useRef(a??""),[I,_]=P.useState(!1),T=P.useCallback(j=>{_(!0);const O=j.currentTarget;k.current=O.value,v.timers.requestAnimationFrame(()=>{o&&O.select()}),p==null||p()},[o,p,v.timers]),M=P.useCallback(j=>{const O=j.currentTarget.value;k.current=O,u==null||u(O)},[u]),D=P.useCallback(j=>{switch(j.key){case"Enter":{j.currentTarget.blur(),Dt(j),c==null||c(j.currentTarget.value);break}case"Escape":{j.currentTarget.value=E.current,j.currentTarget.blur(),Dt(j),h==null||h(j.currentTarget.value);break}}},[c,h]),$=P.useCallback(j=>{_(!1);const O=j.currentTarget.value;f==null||f(O)},[f]);return P.useEffect(()=>{if(!v.environment.isIos)return;const j=window.visualViewport;if(I&&S&&j){const O=()=>{var R;(R=w.current)==null||R.scrollIntoView({block:"center"})};return j.addEventListener("resize",O),j.addEventListener("scroll",O),v.timers.requestAnimationFrame(()=>{var R;(R=w.current)==null||R.scrollIntoView({block:"center"})}),()=>{j.removeEventListener("resize",O),j.removeEventListener("scroll",O)}}},[v,I,S]),d.jsxs("div",{draggable:!1,className:"tlui-input__wrapper",children:[y,t&&d.jsx("label",{children:C(t)}),s&&d.jsx(Cs,{icon:s,className:"tlui-icon-left",small:!0}),d.jsx("input",{ref:w,className:le("tlui-input",n),type:"text",defaultValue:a,onKeyUp:D,onChange:M,onFocus:T,onBlur:$,autoFocus:i,placeholder:l,value:x}),r&&d.jsx(Cs,{icon:r,small:!!t})]})}),pO=Lt(function({onClose:n}){const t=F(),r=xe(),s=Iw(),[o,i]=P.useState(null),[a,l]=P.useState(""),[c,u]=P.useState(null),[h,p]=P.useState(!1),f=P.useRef(-1);return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:o?`${r("embed-dialog.title")} — ${o.title}`:r("embed-dialog.title")}),d.jsx(Og,{})]}),o?d.jsxs(d.Fragment,{children:[d.jsxs(Cu,{className:"tlui-embed-dialog__enter",children:[d.jsx(Dg,{className:"tlui-embed-dialog__input",label:"embed-dialog.url",placeholder:"http://example.com",autoFocus:!0,onValueChange:S=>{l(S);const y=Do(S);u(y&&y.definition.type===o.type?y:null),p(!1),clearTimeout(f.current),f.current=t.timers.setTimeout(()=>p(!y),320)}}),a===""?d.jsxs("div",{className:"tlui-embed-dialog__instruction",children:[d.jsx("span",{children:r("embed-dialog.instruction")})," ",o.instructionLink&&d.jsxs("a",{target:"_blank",rel:"noopener noreferrer",href:o.instructionLink,className:"tlui-embed-dialog__instruction__link",children:["Learn more.",d.jsx(Cs,{icon:"external-link",small:!0})]})]}):d.jsx("div",{className:"tlui-embed-dialog__warning",children:h?r("embed-dialog.invalid-url"):" "})]}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:()=>{i(null),u(null),l("")},children:d.jsx(wt,{children:r("embed-dialog.back")})}),d.jsx("div",{className:"tlui-embed__spacer"}),d.jsx(ce,{type:"normal",onClick:n,children:d.jsx(wt,{children:r("embed-dialog.cancel")})}),d.jsx(ce,{type:"primary",disabled:!c,onClick:()=>{c&&(t.putExternalContent({type:"embed",url:a,point:t.getViewportPageBounds().center,embed:c.definition}),n())},children:d.jsx(wt,{children:r("embed-dialog.create")})})]})]}):d.jsx(d.Fragment,{children:d.jsx(Cu,{className:"tlui-embed-dialog__list",children:Wu.map(S=>d.jsxs(ce,{type:"menu",onClick:()=>i(S),children:[d.jsx(wt,{children:S.title}),d.jsx("div",{className:"tlui-embed-dialog__item__image",style:{backgroundImage:`url(${s.embedIcons[S.type]})`}})]},S.type))})})]})});function fO(){const e=F(),n=P.useRef();return P.useEffect(()=>{const t=window.document.createElement("input");t.type="file",t.accept=j9,t.multiple=!0,n.current=t;async function r(s){const o=s.target.files;!o||o.length===0||(e.mark("insert media"),await e.putExternalContent({type:"files",files:Array.from(o),point:e.getViewportPageBounds().center,ignoreParent:!1}),t.value="")}return t.addEventListener("change",r),()=>{n.current=void 0,t.removeEventListener("change",r)}},[e]),P.useCallback(()=>{var t;(t=n.current)==null||t.click()},[n])}const gO=P.createContext(null);function IJ({overrides:e,children:n}){const t=F(),r=qt(),{addDialog:s}=aa(),o=fO(),i=P.useMemo(()=>{const a=[{id:"select",label:"tool.select",icon:"tool-pointer",kbd:"v",readonlyOk:!0,onSelect(c){t.setCurrentTool("select"),r("select-tool",{source:c,id:"select"})}},{id:"hand",label:"tool.hand",icon:"tool-hand",kbd:"h",readonlyOk:!0,onSelect(c){t.setCurrentTool("hand"),r("select-tool",{source:c,id:"hand"})}},{id:"eraser",label:"tool.eraser",icon:"tool-eraser",kbd:"e",onSelect(c){t.setCurrentTool("eraser"),r("select-tool",{source:c,id:"eraser"})}},{id:"draw",label:"tool.draw",icon:"tool-pencil",kbd:"d,b,x",onSelect(c){t.setCurrentTool("draw"),r("select-tool",{source:c,id:"draw"})}},...[...Br.values].map(c=>({id:c,label:`tool.${c}`,meta:{geo:c},kbd:c==="rectangle"?"r":c==="ellipse"?"o":void 0,icon:"geo-"+c,onSelect(u){t.run(()=>{t.setStyleForNextShapes(Br,c),t.setCurrentTool("geo"),r("select-tool",{source:u,id:`geo-${c}`})})}})),{id:"arrow",label:"tool.arrow",icon:"tool-arrow",kbd:"a",onSelect(c){t.setCurrentTool("arrow"),r("select-tool",{source:c,id:"arrow"})}},{id:"line",label:"tool.line",icon:"tool-line",kbd:"l",onSelect(c){t.setCurrentTool("line"),r("select-tool",{source:c,id:"line"})}},{id:"frame",label:"tool.frame",icon:"tool-frame",kbd:"f",onSelect(c){t.setCurrentTool("frame"),r("select-tool",{source:c,id:"frame"})}},{id:"text",label:"tool.text",icon:"tool-text",kbd:"t",onSelect(c){t.setCurrentTool("text"),r("select-tool",{source:c,id:"text"})}},{id:"asset",label:"tool.asset",icon:"tool-media",kbd:"$u",onSelect(c){o(),r("select-tool",{source:c,id:"media"})}},{id:"note",label:"tool.note",icon:"tool-note",kbd:"n",onSelect(c){t.setCurrentTool("note"),r("select-tool",{source:c,id:"note"})}},{id:"laser",label:"tool.laser",readonlyOk:!0,icon:"tool-laser",kbd:"k",onSelect(c){t.setCurrentTool("laser"),r("select-tool",{source:c,id:"laser"})}},{id:"embed",label:"tool.embed",icon:"dot",onSelect(c){s({component:pO}),r("select-tool",{source:c,id:"embed"})}},{id:"highlight",label:"tool.highlight",icon:"tool-highlight",kbd:"!d",onSelect(c){t.setCurrentTool("highlight"),r("select-tool",{source:c,id:"highlight"})}}];a.push();const l=Object.fromEntries(a.map(c=>[c.id,c]));return e?e(t,l,{insertMedia:o}):l},[e,t,r,o,s]);return d.jsx(gO.Provider,{value:i,children:n})}function Rg(){const e=P.useContext(gO);if(!e)throw new Error("useTools must be used within a ToolProvider");return e}const mO=Ce.createContext(null);function EJ({forceMobile:e=!1,children:n}){const t=F(),r=H("breakpoint",()=>{const{width:s}=t.getViewportScreenBounds(),o=e?yt.MOBILE_SM:jy.length-1;for(let i=0;ijy[i]&&s<=jy[i+1])return i;return o},[t]);return d.jsx(mO.Provider,{value:r,children:n})}function Cn(){const e=P.useContext(mO);if(e===null)throw new Error("useBreakpoint must be used inside of the component");return e}function _J(){const{addToast:e,removeToast:n,clearToasts:t}=Qr(),{addDialog:r,clearDialogs:s,removeDialog:o,updateDialog:i}=aa(),l=Cn()({addToast:e,removeToast:n,clearToasts:t,addDialog:r,clearDialogs:s,removeDialog:o,updateDialog:i,msg:c,isMobile:l}),[r,e,s,t,c,o,n,i,l])}function kJ(e,n){const t={};for(const r of e)if(r.translations)for(const[s,o]of Hn(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return{actions:(r,s)=>{for(const o of e)o.actions&&(s=o.actions(r,s,n));return s},tools:(r,s,o)=>{for(const i of e)i.tools&&(s=i.tools(r,s,{...n,...o}));return s},translations:t}}function yO(e){return P.useMemo(()=>e,e)}function TJ(e){const n=yO(e==null?[]:Array.isArray(e)?e:[e]);return P.useMemo(()=>{const t={};for(const r of n)if(r.translations)for(const[s,o]of Hn(r.translations)){let i=t[s];i||(i=t[s]={}),Object.assign(i,o)}return t},[n])}function MJ(e){const n=_J(),t=yO(e==null?[]:Array.isArray(e)?e:[e]);return P.useMemo(()=>kJ(t,n),[t,n])}function AJ(e,n){const t=me(n.map(s=>e.getShape(s)).filter(s=>s&&e.isShapeOfType(s,"frame")));if(!t.length)return;const r=[];e.run(()=>{t.map(s=>{const o=e.getSortedChildIdsForParent(s.id);o.length&&(e.reparentShapes(o,s.parentId,s.index),r.push(...o))}),e.setSelectedShapes(r),e.deleteShapes(n)})}const jJ=50;function OJ(e,n,t={}){const r=e.getShape(n);if(!r)return;const s=e.getSortedChildIdsForParent(r.id),o=me(s.map(f=>e.getShape(f)));if(!o.length)return;const i=Q.FromPoints(o.flatMap(f=>{const S=e.getShapeGeometry(f.id);return e.getShapeLocalTransform(f).applyToPoints(S.vertices)})),{padding:a=jJ}=t,l=i.w+2*a,c=i.h+2*a,u=a-i.minX,h=a-i.minY;if(u===0&&h===0&&r.props.w===l&&r.props.h===c)return;const p=new b(u,h).rot(r.rotation);e.run(()=>{const f=s.map(S=>{const y=e.getShape(S);return{id:y.id,type:y.type,x:y.x+u,y:y.y+h}});f.push({id:r.id,type:r.type,x:r.x-p.x,y:r.y-p.y,props:{w:l,h:c}}),e.updateShapes(f)})}function sE(e){return ar.isValid(e)?{isValid:!0,hasProtocol:!0}:ar.isValid("https://"+e)?{isValid:!0,hasProtocol:!1}:{isValid:!1,hasProtocol:!1}}const DJ=Lt(function({onClose:n}){const r=F().getOnlySelectedShape();return r&&"url"in r.props&&typeof r.props.url=="string"?d.jsx(RJ,{onClose:n,selectedShape:r}):null}),RJ=Lt(function({onClose:n,selectedShape:t}){const r=F(),s=xe(),o=P.useRef(null);P.useEffect(()=>{r.timers.requestAnimationFrame(()=>{var S;return(S=o.current)==null?void 0:S.focus()})},[r]);const i=P.useRef(t.props.url),[a,l]=P.useState(()=>{const S=sE(t.props.url),y=S.isValid===!0?S.hasProtocol?t.props.url:"https://"+t.props.url:"https://";return{actual:y,safe:y,valid:!0}}),c=P.useCallback(S=>{const y=S.replace(/https?:\/\/(https?:\/\/)/,(v,w)=>w),x=sE(y),m=x.isValid===!0?x.hasProtocol?y:"https://"+y:"https://";l({actual:y,safe:m,valid:x.isValid})},[]),u=P.useCallback(()=>{const S=r.getOnlySelectedShape();S&&(r.updateShapes([{id:S.id,type:S.type,props:{url:""}}]),n())},[r,n]),h=P.useCallback(()=>{const S=r.getOnlySelectedShape();S&&(S&&"url"in S.props&&S.props.url!==a.safe&&r.updateShapes([{id:S.id,type:S.type,props:{url:a.safe}}]),n())},[r,n,a]),p=P.useCallback(()=>{n()},[n]);if(!t)return n(),null;const f=i.current&&!a.valid;return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:s("edit-link-dialog.title")}),d.jsx(Og,{})]}),d.jsx(Cu,{children:d.jsxs("div",{className:"tlui-edit-link-dialog",children:[d.jsx(Dg,{ref:o,className:"tlui-edit-link-dialog__input",label:"edit-link-dialog.url",autoFocus:!0,value:a.actual,onValueChange:c,onComplete:h,onCancel:p}),d.jsx("div",{children:a.valid?s("edit-link-dialog.detail"):s("edit-link-dialog.invalid-url")})]})}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:p,onTouchEnd:p,children:d.jsx(wt,{children:s("edit-link-dialog.cancel")})}),f?d.jsx(ce,{type:"danger",onTouchEnd:u,onClick:u,children:d.jsx(wt,{children:s("edit-link-dialog.clear")})}):d.jsx(ce,{type:"primary",disabled:!a.valid,onTouchEnd:h,onClick:h,children:d.jsx(wt,{children:s("edit-link-dialog.save")})})]})]})});var zw={exports:{}};zw.exports;(function(e){var n=function(){var t=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",o={};function i(l,c){if(!o[l]){o[l]={};for(var u=0;u>>8,u[h*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,h=c.length;u>1}else{for(p=1,h=0;h>1}v--,v==0&&(v=Math.pow(2,C),C++),delete S[m]}else for(p=f[m],h=0;h>1;v--,v==0&&(v=Math.pow(2,C),C++),f[x]=w++,m=String(y)}if(m!==""){if(Object.prototype.hasOwnProperty.call(S,m)){if(m.charCodeAt(0)<256){for(h=0;h>1}else{for(p=1,h=0;h>1}v--,v==0&&(v=Math.pow(2,C),C++),delete S[m]}else for(p=f[m],h=0;h>1;v--,v==0&&(v=Math.pow(2,C),C++)}for(p=2,h=0;h>1;for(;;)if(k=k<<1,I==c-1){E.push(u(k));break}else I++;return E.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 h=[],p=4,f=4,S=3,y="",x=[],m,v,w,C,E,k,I,_={val:u(0),position:c,index:1};for(m=0;m<3;m+=1)h[m]=m;for(w=0,E=Math.pow(2,2),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;switch(w){case 0:for(w=0,E=Math.pow(2,8),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;I=t(w);break;case 1:for(w=0,E=Math.pow(2,16),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;I=t(w);break;case 2:return""}for(h[3]=I,v=I,x.push(I);;){if(_.index>l)return"";for(w=0,E=Math.pow(2,S),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;switch(I=w){case 0:for(w=0,E=Math.pow(2,8),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;h[f++]=t(w),I=f-1,p--;break;case 1:for(w=0,E=Math.pow(2,16),k=1;k!=E;)C=_.val&_.position,_.position>>=1,_.position==0&&(_.position=c,_.val=u(_.index++)),w|=(C>0?1:0)*k,k<<=1;h[f++]=t(w),I=f-1,p--;break;case 2:return x.join("")}if(p==0&&(p=Math.pow(2,S),S++),h[I])y=h[I];else if(I===f)y=v+v.charAt(0);else return null;x.push(y),h[f++]=v+y.charAt(0),p--,v=y,p==0&&(p=Math.pow(2,S),S++)}}};return a}();e!=null?e.exports=n:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return n})})(zw);var LJ=zw.exports;const SO=ti(LJ);async function $J(e,n,t){var m,v,w;const{elements:r,files:s}=n,o={shapes:[],bindings:[],rootShapeIds:[],assets:[],schema:e.store.schema.serialize()},i=new Map,a=new Map,l=e.getCurrentPageId(),c=new Map,u=[],h=new Set;r.forEach(C=>{if(c.set(C.id,je()),C.boundElements!==null)for(const E of C.boundElements)E.type==="text"&&h.add(E.id)});let p=oT;for(const C of r){if(h.has(C.id))continue;const E=c.get(C.id),k={id:E,typeName:"shape",parentId:l,index:p,x:C.x,y:C.y,rotation:0,isLocked:C.locked,opacity:NJ(C.opacity),meta:{}};switch(C.angle!==0&&a.set(E,C.angle),C.groupIds&&C.groupIds.length>0?i.has(C.groupIds[0])?(m=i.get(C.groupIds[0]))==null||m.push(E):i.set(C.groupIds[0],[E]):u.push(E),C.type){case"rectangle":case"ellipse":case"diamond":{let I="",_="middle";if(C.boundElements!==null){for(const M of C.boundElements)if(M.type==="text"){const D=r.find($=>$.id===M.id);D&&(I=D.text,_=KJ[D.textAlign])}}const T=C.backgroundColor==="transparent"?C.strokeColor:C.backgroundColor;o.shapes.push({...k,type:"geo",props:{geo:C.type,url:C.link??"",w:C.width,h:C.height,size:fh[C.strokeWidth]??"draw",color:uc[T]??"black",text:I,align:_,dash:gh(C),fill:VJ(C)}});break}case"freedraw":{o.shapes.push({...k,type:"draw",props:{dash:gh(C),size:fh[C.strokeWidth],color:uc[C.strokeColor]??"black",segments:[{type:"free",points:C.points.map(([I,_,T=.5])=>({x:I,y:_,z:T}))}]}});break}case"line":{if(C.points.slice().length<2)break;const _=xu(C.points.length);o.shapes.push({...k,type:"line",props:{dash:gh(C),size:fh[C.strokeWidth],color:uc[C.strokeColor]??"black",spline:C.roundness?"cubic":"line",points:{...Object.fromEntries(C.points.map(([T,M],D)=>{const $=_[D];return[$,{id:$,index:$,x:T,y:M}]}))}}});break}case"arrow":{let I="";if(C.boundElements!==null){for(const $ of C.boundElements)if($.type==="text"){const j=r.find(O=>O.id===$.id);j&&(I=j.text)}}const _=C.points[0],T=C.points[C.points.length-1],M=c.get((v=C.startBinding)==null?void 0:v.elementId),D=c.get((w=C.endBinding)==null?void 0:w.elementId);o.shapes.push({...k,type:"arrow",props:{text:I,bend:GJ(C,_,T),dash:gh(C),size:fh[C.strokeWidth]??"m",color:uc[C.strokeColor]??"black",start:{x:_[0],y:_[1]},end:{x:T[0],y:T[1]},arrowheadEnd:oE[C.endArrowhead]??"none",arrowheadStart:oE[C.startArrowhead]??"none"}}),M&&o.bindings.push({id:Oi(),typeName:"binding",type:"arrow",fromId:E,toId:M,props:{terminal:"start",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}}),D&&o.bindings.push({id:Oi(),typeName:"binding",type:"arrow",fromId:E,toId:D,props:{terminal:"end",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}});break}case"text":{const{size:I,scale:_}=zJ(C.fontSize);o.shapes.push({...k,type:"text",props:{size:I,scale:_,font:BJ[C.fontFamily]??"draw",color:uc[C.strokeColor]??"black",text:C.text,textAlign:WJ[C.textAlign]}});break}case"image":{const I=s[C.fileId];if(!I)break;const _=_i.createId();o.assets.push({id:_,typeName:"asset",type:"image",props:{w:C.width,h:C.height,fileSize:I.size,name:C.id??"Untitled",isAnimated:!1,mimeType:I.mimeType,src:I.dataURL},meta:{}}),o.shapes.push({...k,type:"image",props:{w:C.width,h:C.height,assetId:_}})}}p=Fr(p)}const f=t??(e.inputs.shiftKey?e.inputs.currentPagePoint:void 0);e.mark("paste"),e.putContentOntoCurrentPage(o,{point:f,select:!1,preserveIds:!0});for(const C of i.values())if(C.length>1){e.groupShapes(C);const E=e.getShape(C[0]);E!=null&&E.parentId&&An(E.parentId)&&u.push(E.parentId)}for(const[C,E]of a)e.select(C),e.rotateShapesBy([C],E);const S=me(u.map(C=>e.getShape(C))),y=Q.Common(S.map(C=>e.getShapePageBounds(C))),x=e.getViewportPageBounds().center;e.updateShapes(S.map(C=>{const E={x:(C.x??0)-(y.x+y.w/2),y:(C.y??0)-(y.y+y.h/2)};return{id:C.id,type:C.type,x:x.x+E.x,y:x.y+E.y}})),e.setSelectedShapes(u)}const NJ=e=>{const n=e/100;return n<.2?.1:n<.4?.25:n<.6?.5:n<.8?.75:1},fh={1:"s",2:"m",3:"l",4:"xl"},FJ={16:"s",20:"m",28:"l",36:"xl"};function zJ(e){const n=FJ[e];return n?{size:n,scale:1}:e<16?{size:"s",scale:e/16}:e>36?{size:"xl",scale:e/36}:{size:"m",scale:1}}const BJ={1:"draw",2:"sans",3:"mono"},uc={"#ffffff":"grey","#000000":"black","#343a40":"black","#495057":"grey","#c92a2a":"red","#a61e4d":"light-red","#862e9c":"violet","#5f3dc4":"light-violet","#364fc7":"blue","#1864ab":"light-blue","#0b7285":"light-green","#087f5b":"light-green","#2b8a3e":"green","#5c940d":"light-green","#e67700":"yellow","#d9480f":"orange","#ced4da":"grey","#868e96":"grey","#fa5252":"light-red","#e64980":"red","#be4bdb":"light-violet","#7950f2":"violet","#4c6ef5":"blue","#228be6":"light-blue","#15aabf":"light-green","#12b886":"green","#40c057":"green","#82c91e":"light-green","#fab005":"yellow","#fd7e14":"orange","#212529":"grey"},UJ={solid:"draw",dashed:"dashed",dotted:"dotted"},HJ={"cross-hatch":"pattern",hachure:"pattern",solid:"solid"},KJ={left:"start",center:"middle",right:"end"},WJ={left:"start",center:"middle",right:"end"},oE={arrow:"arrow",dot:"dot",triangle:"triangle",bar:"pipe"};function GJ(e,n,t){let r=0;if(e.points.length>2){const s=new b(n[0],n[1]),o=new b(t[0],t[1]),i=new b(e.points[1][0],e.points[1][1]),a=b.Sub(o,s),l=b.Per(a),c=b.Med(o,s),u=b.Sub(c,l),h=b.Add(c,l),p=b.NearestPointOnLineSegment(u,h,i,!1);r=b.Dist(p,c),b.Clockwise(p,o,c)&&(r*=-1)}return r}const gh=e=>{let n=UJ[e.strokeStyle]??"draw";return n==="draw"&&e.roughness===0&&(n="solid"),n},VJ=e=>e.backgroundColor==="transparent"?"none":HJ[e.fillStyle]??"solid";async function YJ(e,n,t,r){const o=(await Promise.all(n.map(async i=>await(await vs(i)).blob()))).map(i=>new File([i],"tldrawFile",{type:i.type}));e.mark("paste"),await e.putExternalContent({type:"files",files:o,point:t,ignoreParent:!1,sources:r}),n.forEach(i=>URL.revokeObjectURL(i))}function XJ(e,n,t){const r=e.getSelectionPageBounds();e.mark("paste"),e.putContentOntoCurrentPage(n,{point:t,select:!0});const s=e.getSelectionPageBounds();r&&s&&(r!=null&&r.collides(s))&&(e.updateInstanceState({isChangingStyle:!0}),e.timers.setTimeout(()=>{e.updateInstanceState({isChangingStyle:!1})},150))}async function Zv(e,n,t,r){return e.mark("paste"),await e.putExternalContent({type:"url",point:t,url:n,sources:r})}function qJ(e){const n=document.implementation.createHTMLDocument("");return n.documentElement.innerHTML=e.trim(),n.body.textContent||n.body.innerText||""}const ZJ=e=>{try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}},QJ=e=>{const n=e.split(/[\n\s]/);for(const t of n)try{const r=new URL(t);if(!(r.protocol==="http:"||r.protocol==="https:"))return}catch{return}return bM(n)},JJ=e=>/^-1)}const tee=e=>e.types.find(n=>n.match(/^image\//)),Dy=(e,n,t,r)=>{const s=QJ(n);if(s)for(const o of s)Zv(e,o,t);else ZJ(n)?Zv(e,n,t):JJ(n)?(e.mark("paste"),e.putExternalContent({type:"svg-text",text:n,point:t,sources:r})):(e.mark("paste"),e.putExternalContent({type:"text",text:n,point:t,sources:r}))},nee=async(e,n,t)=>{if(e.getEditingShapeId()!==null)return;if(!n)throw Error("No clipboard data");const r=[];for(const s of Object.values(n.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}}xO(e,r,t)},vO=async(e,n,t)=>{const r=[];for(const s of n){if(tee(s))for(const o of s.types)o.match(/^image\//)&&r.push({type:"blob",source:s.getType(o)});s.types.includes("text/html")&&r.push({type:"html",source:(async()=>{const o=await s.getType("text/html");return await ji.blobToText(o)})()}),s.types.includes("text/uri-list")&&r.push({type:"url",source:(async()=>{const o=await s.getType("text/uri-list");return await ji.blobToText(o)})()}),s.types.includes("text/plain")&&r.push({type:"text",source:(async()=>{const o=await s.getType("text/plain");return await ji.blobToText(o)})()})}return await xO(e,r,t)};async function xO(e,n,t){const r=n.filter(o=>(o.type==="file"||o.type==="blob")&&o.source!==null);if(r.length){const i=(await Promise.all(r.map(a=>a.source))).filter(Boolean).map(a=>URL.createObjectURL(a));return await YJ(e,i,t)}const s=await Promise.all(n.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>/))==null?void 0:u[1];if(c)try{const h=SO.decompressFromBase64(c);if(h===null){i({type:"error",data:h,reason:"found tldraw data comment but could not parse base64"});return}else{const p=JSON.parse(h);if(p.type!=="application/tldraw"&&i({type:"error",data:p,reason:`found tldraw data comment but JSON was of a different type: ${p.type}`}),typeof p.data=="string"){i({type:"error",data:p,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}i({type:"tldraw",data:p.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 h=JSON.parse(l);if(h.type==="excalidraw/clipboard"){i({type:"excalidraw",data:h});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"){XJ(e,o.data,t);return}for(const o of s)if(o.type==="excalidraw"){$J(e,o.data,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");Dy(e,c,t,s);return}if(!s.some(c=>c.type==="text"&&c.subtype!=="html")&&o.data.trim()){Dy(e,qJ(o.data),t,s);return}}for(const o of s)if(o.type==="text"&&o.subtype==="url"){Zv(e,o.data,t,s);return}for(const o of s)if(o.type==="text"&&o.subtype==="text"&&o.data.trim()){Dy(e,o.data,t,s);return}}const Cf=async e=>{var r;const n=await e.resolveAssetsInContent(e.getContentFromCurrentPage(e.getSelectedShapeIds()));if(!n){navigator&&navigator.clipboard&&navigator.clipboard.writeText("");return}const t=SO.compressToBase64(JSON.stringify({type:"application/tldraw",kind:"content",data:n}));if(!(typeof navigator>"u")){const s=n.shapes.map(o=>e.isShapeOfType(o,"text")||e.isShapeOfType(o,"geo")||e.isShapeOfType(o,"arrow")?o.props.text:e.isShapeOfType(o,"bookmark")||e.isShapeOfType(o,"embed")?o.props.url:null).filter(H9);if((r=navigator.clipboard)!=null&&r.write){const o=new Blob([`
${t}
`],{type:"text/html"});let i=s.join(" ");i===""&&(i=" "),navigator.clipboard.write([new ClipboardItem({"text/html":o,"text/plain":new Blob([i],{type:"text/plain"})})])}else navigator.clipboard.writeText&&navigator.clipboard.writeText(`
${t}
`)}};function ree(){const e=F(),n=qt(),t=P.useCallback(async function(i){e.getSelectedShapeIds().length!==0&&(await Cf(e),n("copy",{source:i}))},[e,n]),r=P.useCallback(async function(i){e.getSelectedShapeIds().length!==0&&(await Cf(e),e.deleteShapes(e.getSelectedShapeIds()),n("cut",{source:i}))},[e,n]),s=P.useCallback(async function(i,a,l){e.getEditingShapeId()===null&&(Array.isArray(i)&&i[0]instanceof ClipboardItem?(vO(e,i,l),n("paste",{source:"menu"})):navigator.clipboard.read().then(c=>{s(c,a,l)}))},[e,n]);return{copy:t,cut:r,paste:s}}function see(){const e=F(),n=qt(),t=H("editor.isFocused",()=>e.getInstanceState().isFocused,[e]);P.useEffect(()=>{if(!t)return;const r=async l=>{e.getSelectedShapeIds().length===0||e.getEditingShapeId()!==null||Oy(e)||(Ie(l),await Cf(e),n("copy",{source:"kbd"}))};async function s(l){e.getSelectedShapeIds().length===0||e.getEditingShapeId()!==null||Oy(e)||(Ie(l),await Cf(e),e.deleteShapes(e.getSelectedShapeIds()),n("cut",{source:"kbd"}))}let o=!1;const i=l=>{l.button===1&&(o=!0,e.timers.requestAnimationFrame(()=>{o=!1}))},a=l=>{if(o){Dt(l);return}if(e.getEditingShapeId()!==null||Oy(e))return;let c,u=!1;e.inputs.shiftKey&&(u=!0),e.user.getIsPasteAtCursorMode()&&(u=!u),u&&(c=e.inputs.currentPagePoint),l.clipboardData&&!e.inputs.shiftKey?nee(e,l.clipboardData,c):navigator.clipboard.read().then(h=>{Array.isArray(h)&&h[0]instanceof ClipboardItem&&vO(e,h,c)}),Ie(l),n("paste",{source:"kbd"})};return document.addEventListener("copy",r),document.addEventListener("cut",s),document.addEventListener("paste",a),document.addEventListener("pointerup",i),()=>{document.removeEventListener("copy",r),document.removeEventListener("cut",s),document.removeEventListener("paste",a),document.removeEventListener("pointerup",i)}},[e,n,t])}async function wO(e,n,t){const{type:r,quality:s,scale:o,width:i,height:a}=t;let[l,c]=await KY(i*o,a*o);l=Math.floor(l),c=Math.floor(c);const u=l/i,h=URL.createObjectURL(new Blob([n],{type:"image/svg+xml"})),p=await new Promise(S=>{const y=hl();y.crossOrigin="anonymous",y.onload=async()=>{e.environment.isSafari&&await new Promise(v=>e.timers.setTimeout(v,250));const x=document.createElement("canvas"),m=x.getContext("2d");x.width=l,x.height=c,m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.drawImage(y,0,0,l,c),URL.revokeObjectURL(h),S(x)},y.onerror=()=>{S(null)},y.src=h});if(!p)return null;const f=await new Promise(S=>p.toBlob(y=>{(!y||xt.throwToBlob.get())&&S(null),S(y)},"image/"+r,s));if(!f)return null;if(r==="png"){const S=new DataView(await f.arrayBuffer());return as.setPhysChunk(S,u,{type:"image/"+r})}else return f}async function bO(e,n,t){const r=await e.getSvgString(n!=null&&n.length?n:[...e.getCurrentPageShapeIds()],{scale:1,background:e.getInstanceState().exportBackground,...t});if(!r)throw new Error("Could not construct SVG.");return r}async function Qv(e,n,t,r={}){var s;switch(t){case"svg":return(s=await bO(e,n,r))==null?void 0:s.svg;case"json":{const o=await e.resolveAssetsInContent(e.getContentFromCurrentPage(n));return JSON.stringify(o)}default:cn(t)}}async function PO({editor:e,ids:n,format:t,opts:r={}}){switch(t){case"svg":return new Blob([await Qv(e,n,"svg",r)],{type:"text/plain"});case"json":return new Blob([await Qv(e,n,"json",r)],{type:"text/plain"});case"jpeg":case"png":case"webp":{const s=await bO(e,n,r);if(!s)throw new Error("Could not construct image.");const o=await wO(e,s.svg,{type:t,quality:1,scale:2,width:s.width,height:s.height});if(!o)throw new Error("Could not construct image.");return o}default:cn(t)}}const oee={jpeg:"image/jpeg",png:"image/png",webp:"image/webp",json:"text/plain",svg:"text/plain"};function iee(e,n,t,r={}){return{blobPromise:PO({editor:e,ids:n,format:t,opts:r}),mimeType:oee[t]}}function aee(e,n,t="svg",r={}){if(!window.navigator.clipboard)return Promise.reject(new Error("Copy not supported"));if(window.navigator.clipboard.write){const{blobPromise:s,mimeType:o}=iee(e,n,t,r);return window.navigator.clipboard.write([new ClipboardItem({[o]:s})]).catch(i=>(console.error(i),s.then(a=>window.navigator.clipboard.write([new ClipboardItem({[o]:a})]))))}switch(t){case"json":case"svg":return lee(async()=>Qv(e,n,t,r));case"jpeg":case"png":throw new Error("Copy not supported");default:cn(t)}}async function lee(e){var n,t;await((t=(n=navigator.clipboard)==null?void 0:n.writeText)==null?void 0:t.call(n,await e()))}function cee(){const e=F(),{addToast:n}=Qr(),t=xe();return P.useCallback((r,s="svg")=>{aee(e,r,s).catch(()=>{n({id:"copy-fail",severity:"warning",title:t("toast.error.copy-fail.title"),description:t("toast.error.copy-fail.desc")})})},[e,n,t])}async function uee(e,n,t="png",r,s={}){if(!r&&(r=`shapes at ${iE()}`,n.length===1)){const a=e.getShape(n[0]);e.isShapeOfType(a,"frame")?r=a.props.name??"frame":r=`${a.id.replace(/:/,"_")} at ${iE()}`}r+=`.${t}`;const o=await PO({editor:e,ids:n,format:t,opts:s}),i=new File([o],r,{type:o.type});dee(i)}function iE(){const e=new Date,n=String(e.getFullYear()).slice(2),t=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0"),s=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),i=String(e.getSeconds()).padStart(2,"0");return`${n}-${t}-${r} ${s}.${o}.${i}`}function dee(e){const n=document.createElement("a"),t=URL.createObjectURL(e);n.href=t,n.download=e.name,n.click(),URL.revokeObjectURL(t)}function hee(){const e=F(),{addToast:n}=Qr(),t=xe();return P.useCallback((r,s="png",o)=>{uee(e,r,s,o,{scale:1,background:e.getInstanceState().exportBackground}).catch(i=>{console.error(i.message),n({id:"export-fail",title:t("toast.error.export-fail.title"),description:t("toast.error.export-fail.desc"),severity:"error"})})},[e,n,t])}async function pee(e,n,t){const r=me(n.map(a=>{const l=e.getShape(a);if(!(!l||e.getShapeUtil(l.type).toSvg===void 0))return l}));if(r.length===0)return;if(r.length===1){const a=r[0];if(!a||e.isShapeOfType(a,"image"))return}const s=[];if(t!==void 0){const a=r.map(l=>({shape:l,bounds:e.getShapeMaskedPageBounds(l).clone().expandBy(t)}));for(let l=0;le.getShapeMaskedPageBounds(l)));s.push({shapes:r,bounds:a})}const o=e.options.flattenImageBoundsPadding;for(const a of s){t!==void 0&&a.bounds.expandBy(-t);const l=await e.getSvgString(a.shapes,{padding:o});if(!(l!=null&&l.svg))continue;const c=new Blob([l.svg],{type:"image/svg+xml"}),u=await e.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});u&&(a.asset=u)}const i=[];return gs(()=>{for(const a of s){const{asset:l,bounds:c,shapes:u}=a;if(!l)continue;const h=e.findCommonAncestor(u)??e.getCurrentPageId();if(!h)continue;let p="a1";for(const m of u)if(m.parentId===h){m.index>p&&(p=m.index);break}let f,S,y;if(An(h)){const m=e.getShape(h);if(!m)continue;const v=e.getPointInShapeSpace(m,{x:c.x,y:c.y});y=e.getShapePageTransform(h).rotation(),v.sub(new b(o,o).rot(-y)),f=v.x,S=v.y}else f=c.x-o,S=c.y-o,y=0;e.deleteShapes(u),e.createAssets([{...l,id:l.id}]);const x=je();e.createShape({id:x,type:"image",index:p,parentId:h,x:f,y:S,rotation:-y,props:{assetId:l.id,w:c.w+o*2,h:c.h+o*2}}),i.push(x)}}),i}function Lg(){return F().store.props.collaboration!==void 0}function fee(){const e=F();return H("sync status",()=>{var n;return(n=e.store.props.collaboration)!=null&&n.status?e.store.props.collaboration.status.get():null},[e])}function gee(){const e=F(),n=P.useRef(null),t=P.useRef(null);return P.useCallback(async function(){const s=document.createElement("div"),o=document.createElement("style"),i=(m,v)=>{m&&(m.innerHTML=""),v&&document.head.contains(v)&&document.head.removeChild(v),m&&document.body.contains(m)&&document.body.removeChild(m)};i(n.current,t.current),n.current=s,t.current=o;const a=`tl-print-surface-${ct()}`;s.className=a,o.innerHTML=` .${a} { display: none; } @@ -334,9 +334,9 @@ For more information, see https://radix-ui.com/primitives/docs/components/${n.do } - `;const l=()=>{document.head.appendChild(o),document.body.appendChild(s)},c=()=>{e.once("tick",()=>{i(s,o)})};window.addEventListener("beforeprint",l),window.addEventListener("afterprint",c);function u(y,v,w){try{s.innerHTML+=`
+ `;const l=()=>{document.head.appendChild(o),document.body.appendChild(s)},c=()=>{e.once("tick",()=>{i(s,o)})};window.addEventListener("beforeprint",l),window.addEventListener("afterprint",c);function u(m,v,w){try{s.innerHTML+=`
- ${y.replace(//g,">")} + ${m.replace(//g,">")}
${w} @@ -344,7 +344,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${n.do -
`}catch(C){console.error(C)}}function h(){e.environment.isChromeForIos?(l(),window.print()):e.environment.isSafari?(l(),document.execCommand("print",!1)):window.print()}const p=e.getSelectedShapeIds(),f=e.getCurrentPageId(),S=e.getPages(),x={scale:1,background:!1,darkMode:!1,preserveAspectRatio:"xMidYMid meet"};if(e.getSelectedShapeIds().length>0){const y=await e.getSvgString(p,x);if(y){const v=S.find(w=>w.id===f);u(`tldraw — ${v==null?void 0:v.name}`,null,y.svg),h()}}else{const y=e.getCurrentPage(),v=await e.getSvgString(e.getSortedChildIdsForParent(y.id),x);v&&(u(`tldraw — ${y.name}`,null,v.svg),h())}window.removeEventListener("beforeprint",l),window.removeEventListener("afterprint",c)},[e])}const CO=P.createContext(null);function mee(e){return Object.fromEntries(e.map(n=>[n.id,n]))}function wa(e,n){if(e.getSelectedShapes().length===0)return e.getDocumentSettings().name||n}function yee({overrides:e,children:n}){const t=F(),r=Lg(),{addDialog:s,clearDialogs:o}=aa(),{clearToasts:i,addToast:a}=Qr(),l=xe(),c=fO(),u=gee(),{cut:h,copy:p,paste:f}=ree(),S=cee(),m=hee(),x=l("document.default-name"),y=qt(),v=P.useMemo(()=>{function w(){return t.isIn("select")||(t.complete(),t.setCurrentTool("select")),!1}function C(){return t.isIn("select")&&t.getSelectedShapeIds().length>0}const E=[{id:"edit-link",label:"action.edit-link",icon:"link",onSelect(I){C()&&(w()||(y("edit-link",{source:I}),t.mark("edit-link"),s({component:DJ})))}},{id:"insert-embed",label:"action.insert-embed",kbd:"$i",onSelect(I){y("insert-embed",{source:I}),s({component:pO})}},{id:"insert-media",label:"action.insert-media",kbd:"$u",onSelect(I){y("insert-media",{source:I}),c()}},{id:"undo",label:"action.undo",icon:"undo",kbd:"$z",onSelect(I){y("undo",{source:I}),t.undo()}},{id:"redo",label:"action.redo",icon:"redo",kbd:"$!z",onSelect(I){y("redo",{source:I}),t.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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("export-as",{format:"svg",source:I}),m(_,"svg",wa(t,x)))}},{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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("export-as",{format:"png",source:I}),m(_,"png",wa(t,x)))}},{id:"export-as-json",label:{default:"action.export-as-json",menu:"action.export-as-json.short","context-menu":"action.export-as-json.short"},readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("export-as",{format:"json",source:I}),m(_,"json",wa(t,x)))}},{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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("export-all-as",{format:"svg",source:I}),m(Array.from(t.getCurrentPageShapeIds()),"svg",wa(t,x)))}},{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(I){const _=Array.from(t.getCurrentPageShapeIds().values());_.length!==0&&(y("export-all-as",{format:"png",source:I}),m(_,"png",wa(t,x)))}},{id:"export-all-as-json",label:{default:"action.export-all-as-json",menu:"action.export-all-as-json.short","context-menu":"action.export-all-as-json.short"},readonlyOk:!0,onSelect(I){const _=Array.from(t.getCurrentPageShapeIds().values());_.length!==0&&(y("export-all-as",{format:"json",source:I}),m(_,"json",wa(t,x)))}},{id:"copy-as-svg",label:{default:"action.copy-as-svg",menu:"action.copy-as-svg.short","context-menu":"action.copy-as-svg.short"},kbd:"$!c",readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("copy-as",{format:"svg",source:I}),S(_,"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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("copy-as",{format:"png",source:I}),S(_,"png"))}},{id:"copy-as-json",label:{default:"action.copy-as-json",menu:"action.copy-as-json.short","context-menu":"action.copy-as-json.short"},readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(y("copy-as",{format:"json",source:I}),S(_,"json"))}},{id:"toggle-auto-size",label:"action.toggle-auto-size",onSelect(I){if(!C()||w())return;y("toggle-auto-size",{source:I}),t.mark("toggling auto size");const _=t.getSelectedShapes().filter(T=>t.isShapeOfType(T,"text")&&T.props.autoSize===!1);t.updateShapes(_.map(T=>({id:T.id,type:T.type,props:{...T.props,w:8,autoSize:!0}}))),Ke(t,_.map(T=>T.id))}},{id:"open-embed-link",label:"action.open-embed-link",readonlyOk:!0,onSelect(I){y("open-embed-link",{source:I});const _=t.getSelectedShapeIds(),T="No embed shapes selected";if(_.length!==1){console.error(T);return}const M=t.getShape(_[0]);if(!M||!t.isShapeOfType(M,"embed")){console.error(T);return}lY(M.props.url,"_blank")}},{id:"select-zoom-tool",readonlyOk:!0,kbd:"z",onSelect(I){var _,T;if(((_=t.root.getCurrent())==null?void 0:_.id)!=="zoom"&&(y("zoom-tool",{source:I}),!(t.inputs.shiftKey||t.inputs.ctrlKey))){const M=t.root.getCurrent();M&&((T=M.getCurrent())==null?void 0:T.id)==="idle"&&t.setCurrentTool("zoom",{onInteractionEnd:M.id,maskAs:"zoom"})}}},{id:"convert-to-bookmark",label:"action.convert-to-bookmark",onSelect(I){C()&&(w()||t.run(()=>{y("convert-to-bookmark",{source:I});const _=t.getSelectedShapes(),T=[],M=[];for(const D of _){if(!D||!t.isShapeOfType(D,"embed")||!D.props.url)continue;const $=new b(D.x,D.y);$.rot(-D.rotation),$.add(new b(D.props.w/2-300/2,D.props.h/2-320/2)),$.rot(D.rotation);const j={id:je(),type:"bookmark",rotation:D.rotation,x:$.x,y:$.y,opacity:1,props:{url:D.props.url}};T.push(j),M.push(D.id)}t.mark("convert shapes to bookmark"),t.deleteShapes(M),t.createShapes(T)}))}},{id:"convert-to-embed",label:"action.convert-to-embed",onSelect(I){C()&&(w()||(y("convert-to-embed",{source:I}),t.run(()=>{const _=t.getSelectedShapeIds(),T=me(_.map($=>t.getShape($))),M=[],D=[];for(const $ of T){if(!t.isShapeOfType($,"bookmark"))continue;const{url:j}=$.props,O=Do($.props.url);if(!O||!O.definition)continue;const{width:R,height:K}=O.definition,B=new b($.x,$.y);B.rot(-$.rotation),B.add(new b($.props.w/2-R/2,$.props.h/2-K/2)),B.rot($.rotation);const z={id:je(),type:"embed",x:B.x,y:B.y,rotation:$.rotation,props:{url:j,w:R,h:K}};M.push(z),D.push($.id)}t.mark("convert shapes to embed"),t.deleteShapes(D),t.createShapes(M)})))}},{id:"duplicate",kbd:"$d",label:"action.duplicate",icon:"duplicate",onSelect(I){if(!C()||w())return;y("duplicate-shapes",{source:I});const _=t.getInstanceState();let T,M;if(_.duplicateProps)T=_.duplicateProps.shapeIds,M=_.duplicateProps.offset;else{T=t.getSelectedShapeIds();const D=Q.Common(me(T.map($=>t.getShapePageBounds($))));M=t.getCameraOptions().isLocked?{x:t.options.adjacentShapeMargin,y:t.options.adjacentShapeMargin}:{x:D.width+t.options.adjacentShapeMargin,y:0}}t.mark("duplicate shapes"),t.duplicateShapes(T,M),_.duplicateProps&&t.updateInstanceState({duplicateProps:{..._.duplicateProps,shapeIds:t.getSelectedShapeIds()}})}},{id:"ungroup",label:"action.ungroup",kbd:"$!g",icon:"ungroup",onSelect(I){C()&&(w()||(y("ungroup-shapes",{source:I}),t.mark("ungroup"),t.ungroupShapes(t.getSelectedShapeIds())))}},{id:"group",label:"action.group",kbd:"$g",icon:"group",onSelect(I){if(!C()||w())return;y("group-shapes",{source:I});const _=t.getOnlySelectedShape();_&&t.isShapeOfType(_,"group")?(t.mark("ungroup"),t.ungroupShapes(t.getSelectedShapeIds())):(t.mark("group"),t.groupShapes(t.getSelectedShapeIds()))}},{id:"remove-frame",label:"action.remove-frame",kbd:"$!f",onSelect(I){if(!C())return;y("remove-frame",{source:I});const _=t.getSelectedShapes();_.length>0&&_.every(T=>t.isShapeOfType(T,"frame"))&&(t.mark("remove-frame"),AJ(t,_.map(T=>T.id)))}},{id:"fit-frame-to-content",label:"action.fit-frame-to-content",onSelect(I){if(!C())return;y("fit-frame-to-content",{source:I});const _=t.getOnlySelectedShape();_&&t.isShapeOfType(_,"frame")&&(t.mark("fit-frame-to-content"),OJ(t,_.id))}},{id:"align-left",label:"action.align-left",kbd:"?A",icon:"align-left",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"left",source:I}),t.mark("align left");const _=t.getSelectedShapeIds();t.alignShapes(_,"left"),Ke(t,_)}},{id:"align-center-horizontal",label:{default:"action.align-center-horizontal","context-menu":"action.align-center-horizontal.short"},kbd:"?H",icon:"align-center-horizontal",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"center-horizontal",source:I}),t.mark("align center horizontal");const _=t.getSelectedShapeIds();t.alignShapes(_,"center-horizontal"),Ke(t,_)}},{id:"align-right",label:"action.align-right",kbd:"?D",icon:"align-right",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"right",source:I}),t.mark("align right");const _=t.getSelectedShapeIds();t.alignShapes(_,"right"),Ke(t,_)}},{id:"align-center-vertical",label:{default:"action.align-center-vertical","context-menu":"action.align-center-vertical.short"},kbd:"?V",icon:"align-center-vertical",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"center-vertical",source:I}),t.mark("align center vertical");const _=t.getSelectedShapeIds();t.alignShapes(_,"center-vertical"),Ke(t,_)}},{id:"align-top",label:"action.align-top",icon:"align-top",kbd:"?W",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"top",source:I}),t.mark("align top");const _=t.getSelectedShapeIds();t.alignShapes(_,"top"),Ke(t,_)}},{id:"align-bottom",label:"action.align-bottom",icon:"align-bottom",kbd:"?S",onSelect(I){if(!C()||w())return;y("align-shapes",{operation:"bottom",source:I}),t.mark("align bottom");const _=t.getSelectedShapeIds();t.alignShapes(_,"bottom"),Ke(t,_)}},{id:"distribute-horizontal",label:{default:"action.distribute-horizontal","context-menu":"action.distribute-horizontal.short"},icon:"distribute-horizontal",kbd:"?!h",onSelect(I){if(!C()||w())return;y("distribute-shapes",{operation:"horizontal",source:I}),t.mark("distribute horizontal");const _=t.getSelectedShapeIds();t.distributeShapes(_,"horizontal"),Ke(t,_)}},{id:"distribute-vertical",label:{default:"action.distribute-vertical","context-menu":"action.distribute-vertical.short"},icon:"distribute-vertical",kbd:"?!V",onSelect(I){if(!C()||w())return;y("distribute-shapes",{operation:"vertical",source:I}),t.mark("distribute vertical");const _=t.getSelectedShapeIds();t.distributeShapes(_,"vertical"),Ke(t,_)}},{id:"stretch-horizontal",label:{default:"action.stretch-horizontal","context-menu":"action.stretch-horizontal.short"},icon:"stretch-horizontal",onSelect(I){if(!C()||w())return;y("stretch-shapes",{operation:"horizontal",source:I}),t.mark("stretch horizontal");const _=t.getSelectedShapeIds();t.stretchShapes(_,"horizontal"),Ke(t,_)}},{id:"stretch-vertical",label:{default:"action.stretch-vertical","context-menu":"action.stretch-vertical.short"},icon:"stretch-vertical",onSelect(I){if(!C()||w())return;y("stretch-shapes",{operation:"vertical",source:I}),t.mark("stretch vertical");const _=t.getSelectedShapeIds();t.stretchShapes(_,"vertical"),Ke(t,_)}},{id:"flip-horizontal",label:{default:"action.flip-horizontal","context-menu":"action.flip-horizontal.short"},kbd:"!h",onSelect(I){if(!C()||w())return;y("flip-shapes",{operation:"horizontal",source:I}),t.mark("flip horizontal");const _=t.getSelectedShapeIds();t.flipShapes(_,"horizontal"),Ke(t,_)}},{id:"flip-vertical",label:{default:"action.flip-vertical","context-menu":"action.flip-vertical.short"},kbd:"!v",onSelect(I){if(!C()||w())return;y("flip-shapes",{operation:"vertical",source:I}),t.mark("flip vertical");const _=t.getSelectedShapeIds();t.flipShapes(_,"vertical"),Ke(t,_)}},{id:"pack",label:"action.pack",icon:"pack",onSelect(I){if(!C()||w())return;y("pack-shapes",{source:I}),t.mark("pack");const _=t.getSelectedShapeIds();t.packShapes(_,t.options.adjacentShapeMargin),Ke(t,_)}},{id:"stack-vertical",label:{default:"action.stack-vertical","context-menu":"action.stack-vertical.short"},icon:"stack-vertical",onSelect(I){if(!C()||w())return;y("stack-shapes",{operation:"vertical",source:I}),t.mark("stack-vertical");const _=t.getSelectedShapeIds();t.stackShapes(_,"vertical",16),Ke(t,_)}},{id:"stack-horizontal",label:{default:"action.stack-horizontal","context-menu":"action.stack-horizontal.short"},icon:"stack-horizontal",onSelect(I){if(!C()||w())return;y("stack-shapes",{operation:"horizontal",source:I}),t.mark("stack-horizontal");const _=t.getSelectedShapeIds();t.stackShapes(_,"horizontal",16),Ke(t,_)}},{id:"bring-to-front",label:"action.bring-to-front",kbd:"]",icon:"bring-to-front",onSelect(I){C()&&(w()||(y("reorder-shapes",{operation:"toFront",source:I}),t.mark("bring to front"),t.bringToFront(t.getSelectedShapeIds())))}},{id:"bring-forward",label:"action.bring-forward",icon:"bring-forward",kbd:"?]",onSelect(I){C()&&(w()||(y("reorder-shapes",{operation:"forward",source:I}),t.mark("bring forward"),t.bringForward(t.getSelectedShapeIds())))}},{id:"send-backward",label:"action.send-backward",icon:"send-backward",kbd:"?[",onSelect(I){C()&&(w()||(y("reorder-shapes",{operation:"backward",source:I}),t.mark("send backward"),t.sendBackward(t.getSelectedShapeIds())))}},{id:"send-to-back",label:"action.send-to-back",icon:"send-to-back",kbd:"[",onSelect(I){C()&&(w()||(y("reorder-shapes",{operation:"toBack",source:I}),t.mark("send to back"),t.sendToBack(t.getSelectedShapeIds())))}},{id:"cut",label:"action.cut",kbd:"$x",onSelect(I){C()&&(w()||(t.mark("cut"),h(I)))}},{id:"copy",label:"action.copy",kbd:"$c",readonlyOk:!0,onSelect(I){C()&&(w()||p(I))}},{id:"paste",label:"action.paste",kbd:"$v",onSelect(I){var _;(_=navigator.clipboard)==null||_.read().then(T=>{f(T,I,I==="context-menu"?t.inputs.currentPagePoint:void 0)}).catch(()=>{a({title:l("action.paste-error-title"),description:l("action.paste-error-description"),severity:"error"})})}},{id:"select-all",label:"action.select-all",kbd:"$a",readonlyOk:!0,onSelect(I){t.run(()=>{w()||(y("select-all-shapes",{source:I}),t.mark("select all kbd"),t.selectAll())})}},{id:"select-none",label:"action.select-none",readonlyOk:!0,onSelect(I){C()&&(w()||(y("select-none-shapes",{source:I}),t.mark("select none"),t.selectNone()))}},{id:"delete",label:"action.delete",kbd:"⌫,del,backspace",icon:"trash",onSelect(I){C()&&(w()||(y("delete-shapes",{source:I}),t.mark("delete"),t.deleteShapes(t.getSelectedShapeIds())))}},{id:"rotate-cw",label:"action.rotate-cw",icon:"rotate-cw",onSelect(I){if(!C()||w())return;y("rotate-cw",{source:I}),t.mark("rotate-cw");const _=t.getSelectionRotation()%(Ve/2),T=Wo(_,0)||Wo(_,Ve/2),M=t.getSelectedShapeIds();t.rotateShapesBy(M,Ve/2-(T?0:_)),Ke(t,M)}},{id:"rotate-ccw",label:"action.rotate-ccw",icon:"rotate-ccw",onSelect(I){if(!C()||w())return;y("rotate-ccw",{source:I}),t.mark("rotate-ccw");const _=t.getSelectionRotation()%(Ve/2),T=Wo(_,0),M=t.getSelectedShapeIds();t.rotateShapesBy(M,T?-(Ve/2):-_),Ke(t,M)}},{id:"zoom-in",label:"action.zoom-in",kbd:"$=,=",readonlyOk:!0,onSelect(I){y("zoom-in",{source:I}),t.zoomIn(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-out",label:"action.zoom-out",kbd:"$-,-",readonlyOk:!0,onSelect(I){y("zoom-out",{source:I}),t.zoomOut(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-100",label:"action.zoom-to-100",icon:"reset-zoom",kbd:"!0",readonlyOk:!0,onSelect(I){y("reset-zoom",{source:I}),t.resetZoom(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-fit",label:"action.zoom-to-fit",kbd:"!1",readonlyOk:!0,onSelect(I){y("zoom-to-fit",{source:I}),t.zoomToFit({animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-selection",label:"action.zoom-to-selection",kbd:"!2",readonlyOk:!0,onSelect(I){C()&&(w()||(y("zoom-to-selection",{source:I}),t.zoomToSelection({animation:{duration:t.options.animationMediumMs}})))}},{id:"toggle-snap-mode",label:{default:"action.toggle-snap-mode",menu:"action.toggle-snap-mode.menu"},onSelect(I){y("toggle-snap-mode",{source:I}),t.user.updateUserPreferences({isSnapMode:!t.user.getIsSnapMode()})},checkbox:!0},{id:"toggle-dark-mode",label:{default:"action.toggle-dark-mode",menu:"action.toggle-dark-mode.menu"},kbd:"$/",readonlyOk:!0,onSelect(I){const _=t.user.getIsDarkMode()?"light":"dark";y("color-scheme",{source:I,value:_}),t.user.updateUserPreferences({colorScheme:_})},checkbox:!0},{id:"toggle-wrap-mode",label:{default:"action.toggle-wrap-mode",menu:"action.toggle-wrap-mode.menu"},readonlyOk:!0,onSelect(I){y("toggle-wrap-mode",{source:I}),t.user.updateUserPreferences({isWrapMode:!t.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(I){y("toggle-dynamic-size-mode",{source:I}),t.user.updateUserPreferences({isDynamicSizeMode:!t.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(I){y("toggle-paste-at-cursor",{source:I}),t.user.updateUserPreferences({isPasteAtCursorMode:!t.user.getIsPasteAtCursorMode()})},checkbox:!0},{id:"toggle-reduce-motion",label:{default:"action.toggle-reduce-motion",menu:"action.toggle-reduce-motion.menu"},readonlyOk:!0,onSelect(I){y("toggle-reduce-motion",{source:I}),t.user.updateUserPreferences({animationSpeed:t.user.getAnimationSpeed()===0?1:0})},checkbox:!0},{id:"toggle-edge-scrolling",label:{default:"action.toggle-edge-scrolling",menu:"action.toggle-edge-scrolling.menu"},readonlyOk:!0,onSelect(I){y("toggle-edge-scrolling",{source:I}),t.user.updateUserPreferences({edgeScrollSpeed:t.user.getEdgeScrollSpeed()===0?1:0})},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(I){y("toggle-transparent",{source:I}),t.updateInstanceState({exportBackground:!t.getInstanceState().exportBackground})},checkbox:!0},{id:"toggle-tool-lock",label:{default:"action.toggle-tool-lock",menu:"action.toggle-tool-lock.menu"},kbd:"q",onSelect(I){y("toggle-tool-lock",{source:I}),t.updateInstanceState({isToolLocked:!t.getInstanceState().isToolLocked})},checkbox:!0},{id:"unlock-all",label:"action.unlock-all",onSelect(I){y("unlock-all",{source:I});const _=[];for(const T of t.getCurrentPageShapes())T.isLocked&&_.push({id:T.id,type:T.type,isLocked:!1});_.length>0&&t.updateShapes(_)}},{id:"toggle-focus-mode",label:{default:"action.toggle-focus-mode",menu:"action.toggle-focus-mode.menu"},readonlyOk:!0,kbd:"$.",checkbox:!0,onSelect(I){t.timers.requestAnimationFrame(()=>{t.run(()=>{y("toggle-focus-mode",{source:I}),o(),i(),t.updateInstanceState({isFocusMode:!t.getInstanceState().isFocusMode})})})}},{id:"toggle-grid",label:{default:"action.toggle-grid",menu:"action.toggle-grid.menu"},readonlyOk:!0,kbd:"$'",onSelect(I){y("toggle-grid-mode",{source:I}),t.updateInstanceState({isGridMode:!t.getInstanceState().isGridMode})},checkbox:!0},{id:"toggle-debug-mode",label:{default:"action.toggle-debug-mode",menu:"action.toggle-debug-mode.menu"},readonlyOk:!0,onSelect(I){y("toggle-debug-mode",{source:I}),t.updateInstanceState({isDebugMode:!t.getInstanceState().isDebugMode})},checkbox:!0},{id:"print",label:"action.print",kbd:"$p",readonlyOk:!0,onSelect(I){y("print",{source:I}),u()}},{id:"exit-pen-mode",label:"action.exit-pen-mode",icon:"cross-2",readonlyOk:!0,onSelect(I){y("exit-pen-mode",{source:I}),t.updateInstanceState({isPenMode:!1})}},{id:"stop-following",label:"action.stop-following",icon:"cross-2",readonlyOk:!0,onSelect(I){y("stop-following",{source:I}),t.stopFollowingUser()}},{id:"back-to-content",label:"action.back-to-content",icon:"arrow-left",readonlyOk:!0,onSelect(I){y("zoom-to-content",{source:I});const _=t.getSelectionPageBounds()??t.getCurrentPageBounds();_&&t.zoomToBounds(_,{targetZoom:Math.min(1,t.getZoomLevel()),animation:{duration:220}})}},{id:"toggle-lock",label:"action.toggle-lock",kbd:"!l",onSelect(I){t.mark("locking"),y("toggle-lock",{source:I}),t.toggleLock(t.getSelectedShapeIds())}},{id:"move-to-new-page",label:"context.pages.new-page",onSelect(I){const _=to.createId(),T=t.getSelectedShapeIds();t.run(()=>{t.mark("move_shapes_to_page"),t.createPage({name:l("page-menu.new-page-initial-name"),id:_}),t.moveShapesToPage(T,_)}),y("move-to-new-page",{source:I})}},{id:"select-white-color",label:"color-style.white",kbd:"?t",onSelect(I){const _=lr;t.run(()=>{t.mark("change-color"),t.isIn("select")&&t.setStyleForSelectedShapes(_,"white"),t.setStyleForNextShapes(_,"white")}),y("set-style",{source:I,id:_.id,value:"white"})}},{id:"select-fill-fill",label:"fill-style.fill",kbd:"?f",onSelect(I){const _=Hi;t.run(()=>{t.mark("change-fill"),t.isIn("select")&&t.setStyleForSelectedShapes(_,"fill"),t.setStyleForNextShapes(_,"fill")}),y("set-style",{source:I,id:_.id,value:"fill"})}},{id:"flatten-to-image",label:"action.flatten-to-image",kbd:"!f",onSelect:async I=>{const _=t.getSelectedShapeIds();if(_.length===0)return;t.mark("flattening to image"),y("flatten-to-image",{source:I});const T=await pee(t,_,t.options.flattenImageBoundsExpand);T!=null&&T.length&&t.setSelectedShapes(T)}}];r&&E.push({id:"open-cursor-chat",label:"action.open-cursor-chat",readonlyOk:!0,kbd:"/",onSelect(I){y("open-cursor-chat",{source:I}),!t.getInstanceState().isCoarsePointer&&t.timers.requestAnimationFrame(()=>{t.updateInstanceState({isChatting:!0})})}});const k=mee(E);return e?e(t,k,void 0):k},[t,y,e,s,a,c,m,S,h,p,f,o,i,u,l,x,r]);return d.jsx(CO.Provider,{value:v,children:n})}function ie(){const e=P.useContext(CO);if(!e)throw new Error("useTools must be used within a ToolProvider");return e}function Iu(e,n){return e?typeof e=="string"?e:n?e[n]??e.default:void 0:void 0}const See=["top","right","bottom","left"],hs=Math.min,Qn=Math.max,If=Math.round,mh=Math.floor,Qo=e=>({x:e,y:e}),vee={left:"right",right:"left",bottom:"top",top:"bottom"},xee={start:"end",end:"start"};function Jv(e,n,t){return Qn(e,hs(n,t))}function ro(e,n){return typeof e=="function"?e(n):e}function so(e){return e.split("-")[0]}function Dl(e){return e.split("-")[1]}function Bw(e){return e==="x"?"y":"x"}function Uw(e){return e==="y"?"height":"width"}function Jo(e){return["top","bottom"].includes(so(e))?"y":"x"}function Hw(e){return Bw(Jo(e))}function wee(e,n,t){t===void 0&&(t=!1);const r=Dl(e),s=Hw(e),o=Uw(s);let i=s==="x"?r===(t?"end":"start")?"right":"left":r==="start"?"bottom":"top";return n.reference[o]>n.floating[o]&&(i=Ef(i)),[i,Ef(i)]}function bee(e){const n=Ef(e);return[ex(e),n,ex(n)]}function ex(e){return e.replace(/start|end/g,n=>xee[n])}function Pee(e,n,t){const r=["left","right"],s=["right","left"],o=["top","bottom"],i=["bottom","top"];switch(e){case"top":case"bottom":return t?n?s:r:n?r:s;case"left":case"right":return n?o:i;default:return[]}}function Cee(e,n,t,r){const s=Dl(e);let o=Pee(so(e),t==="start",r);return s&&(o=o.map(i=>i+"-"+s),n&&(o=o.concat(o.map(ex)))),o}function Ef(e){return e.replace(/left|right|bottom|top/g,n=>vee[n])}function Iee(e){return{top:0,right:0,bottom:0,left:0,...e}}function IO(e){return typeof e!="number"?Iee(e):{top:e,right:e,bottom:e,left:e}}function _f(e){const{x:n,y:t,width:r,height:s}=e;return{width:r,height:s,top:t,left:n,right:n+r,bottom:t+s,x:n,y:t}}function aE(e,n,t){let{reference:r,floating:s}=e;const o=Jo(n),i=Hw(n),a=Uw(i),l=so(n),c=o==="y",u=r.x+r.width/2-s.width/2,h=r.y+r.height/2-s.height/2,p=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:h};break;case"left":f={x:r.x-s.width,y:h};break;default:f={x:r.x,y:r.y}}switch(Dl(n)){case"start":f[i]-=p*(t&&c?-1:1);break;case"end":f[i]+=p*(t&&c?-1:1);break}return f}const Eee=async(e,n,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(n));let c=await i.getElementRects({reference:e,floating:n,strategy:s}),{x:u,y:h}=aE(c,r,l),p=r,f={},S=0;for(let m=0;m({name:"arrow",options:e,async fn(n){const{x:t,y:r,placement:s,rects:o,platform:i,elements:a,middlewareData:l}=n,{element:c,padding:u=0}=ro(e,n)||{};if(c==null)return{};const h=IO(u),p={x:t,y:r},f=Hw(s),S=Uw(f),m=await i.getDimensions(c),x=f==="y",y=x?"top":"left",v=x?"bottom":"right",w=x?"clientHeight":"clientWidth",C=o.reference[S]+o.reference[f]-p[f]-o.floating[S],E=p[f]-o.reference[f],k=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=k?k[w]:0;(!I||!await(i.isElement==null?void 0:i.isElement(k)))&&(I=a.floating[w]||o.floating[S]);const _=C/2-E/2,T=I/2-m[S]/2-1,M=hs(h[y],T),D=hs(h[v],T),$=M,j=I-m[S]-D,O=I/2-m[S]/2+_,R=Jv($,O,j),K=!l.arrow&&Dl(s)!=null&&O!==R&&o.reference[S]/2-(O<$?M:D)-m[S]/2<0,B=K?O<$?O-$:O-j:0;return{[f]:p[f]+B,data:{[f]:R,centerOffset:O-R-B,...K&&{alignmentOffset:B}},reset:K}}}),kee=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(n){var t,r;const{placement:s,middlewareData:o,rects:i,initialPlacement:a,platform:l,elements:c}=n,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:m=!0,...x}=ro(e,n);if((t=o.arrow)!=null&&t.alignmentOffset)return{};const y=so(s),v=Jo(a),w=so(a)===a,C=await(l.isRTL==null?void 0:l.isRTL(c.floating)),E=p||(w||!m?[Ef(a)]:bee(a)),k=S!=="none";!p&&k&&E.push(...Cee(a,m,S,C));const I=[a,...E],_=await Eu(n,x),T=[];let M=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&T.push(_[y]),h){const O=wee(s,i,C);T.push(_[O[0]],_[O[1]])}if(M=[...M,{placement:s,overflows:T}],!T.every(O=>O<=0)){var D,$;const O=(((D=o.flip)==null?void 0:D.index)||0)+1,R=I[O];if(R)return{data:{index:O,overflows:M},reset:{placement:R}};let K=($=M.filter(B=>B.overflows[0]<=0).sort((B,z)=>B.overflows[1]-z.overflows[1])[0])==null?void 0:$.placement;if(!K)switch(f){case"bestFit":{var j;const B=(j=M.filter(z=>{if(k){const W=Jo(z.placement);return W===v||W==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(W=>W>0).reduce((W,Y)=>W+Y,0)]).sort((z,W)=>z[1]-W[1])[0])==null?void 0:j[0];B&&(K=B);break}case"initialPlacement":K=a;break}if(s!==K)return{reset:{placement:K}}}return{}}}};function lE(e,n){return{top:e.top-n.height,right:e.right-n.width,bottom:e.bottom-n.height,left:e.left-n.width}}function cE(e){return See.some(n=>e[n]>=0)}const Tee=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(n){const{rects:t}=n,{strategy:r="referenceHidden",...s}=ro(e,n);switch(r){case"referenceHidden":{const o=await Eu(n,{...s,elementContext:"reference"}),i=lE(o,t.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:cE(i)}}}case"escaped":{const o=await Eu(n,{...s,altBoundary:!0}),i=lE(o,t.floating);return{data:{escapedOffsets:i,escaped:cE(i)}}}default:return{}}}}};async function Mee(e,n){const{placement:t,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),i=so(t),a=Dl(t),l=Jo(t)==="y",c=["left","top"].includes(i)?-1:1,u=o&&l?-1:1,h=ro(n,e);let{mainAxis:p,crossAxis:f,alignmentAxis:S}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...h};return a&&typeof S=="number"&&(f=a==="end"?S*-1:S),l?{x:f*u,y:p*c}:{x:p*c,y:f*u}}const Aee=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(n){var t,r;const{x:s,y:o,placement:i,middlewareData:a}=n,l=await Mee(n,e);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}}}}},jee=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(n){const{x:t,y:r,placement:s}=n,{mainAxis:o=!0,crossAxis:i=!1,limiter:a={fn:x=>{let{x:y,y:v}=x;return{x:y,y:v}}},...l}=ro(e,n),c={x:t,y:r},u=await Eu(n,l),h=Jo(so(s)),p=Bw(h);let f=c[p],S=c[h];if(o){const x=p==="y"?"top":"left",y=p==="y"?"bottom":"right",v=f+u[x],w=f-u[y];f=Jv(v,f,w)}if(i){const x=h==="y"?"top":"left",y=h==="y"?"bottom":"right",v=S+u[x],w=S-u[y];S=Jv(v,S,w)}const m=a.fn({...n,[p]:f,[h]:S});return{...m,data:{x:m.x-t,y:m.y-r}}}}},Oee=function(e){return e===void 0&&(e={}),{options:e,fn(n){const{x:t,y:r,placement:s,rects:o,middlewareData:i}=n,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=ro(e,n),u={x:t,y:r},h=Jo(s),p=Bw(h);let f=u[p],S=u[h];const m=ro(a,n),x=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const w=p==="y"?"height":"width",C=o.reference[p]-o.floating[w]+x.mainAxis,E=o.reference[p]+o.reference[w]-x.mainAxis;fE&&(f=E)}if(c){var y,v;const w=p==="y"?"width":"height",C=["top","left"].includes(so(s)),E=o.reference[h]-o.floating[w]+(C&&((y=i.offset)==null?void 0:y[h])||0)+(C?0:x.crossAxis),k=o.reference[h]+o.reference[w]+(C?0:((v=i.offset)==null?void 0:v[h])||0)-(C?x.crossAxis:0);Sk&&(S=k)}return{[p]:f,[h]:S}}}},Dee=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(n){const{placement:t,rects:r,platform:s,elements:o}=n,{apply:i=()=>{},...a}=ro(e,n),l=await Eu(n,a),c=so(t),u=Dl(t),h=Jo(t)==="y",{width:p,height:f}=r.floating;let S,m;c==="top"||c==="bottom"?(S=c,m=u===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(m=c,S=u==="end"?"top":"bottom");const x=f-l.top-l.bottom,y=p-l.left-l.right,v=hs(f-l[S],x),w=hs(p-l[m],y),C=!n.middlewareData.shift;let E=v,k=w;if(h?k=u||C?hs(w,y):y:E=u||C?hs(v,x):x,C&&!u){const _=Qn(l.left,0),T=Qn(l.right,0),M=Qn(l.top,0),D=Qn(l.bottom,0);h?k=p-2*(_!==0||T!==0?_+T:Qn(l.left,l.right)):E=f-2*(M!==0||D!==0?M+D:Qn(l.top,l.bottom))}await i({...n,availableWidth:k,availableHeight:E});const I=await s.getDimensions(o.floating);return p!==I.width||f!==I.height?{reset:{rects:!0}}:{}}}};function Rl(e){return EO(e)?(e.nodeName||"").toLowerCase():"#document"}function or(e){var n;return(e==null||(n=e.ownerDocument)==null?void 0:n.defaultView)||window}function uo(e){var n;return(n=(EO(e)?e.ownerDocument:e.document)||window.document)==null?void 0:n.documentElement}function EO(e){return e instanceof Node||e instanceof or(e).Node}function Gr(e){return e instanceof Element||e instanceof or(e).Element}function Is(e){return e instanceof HTMLElement||e instanceof or(e).HTMLElement}function uE(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof or(e).ShadowRoot}function nd(e){const{overflow:n,overflowX:t,overflowY:r,display:s}=Vr(e);return/auto|scroll|overlay|hidden|clip/.test(n+r+t)&&!["inline","contents"].includes(s)}function Ree(e){return["table","td","th"].includes(Rl(e))}function $g(e){return[":popover-open",":modal"].some(n=>{try{return e.matches(n)}catch{return!1}})}function Kw(e){const n=Ww(),t=Gr(e)?Vr(e):e;return t.transform!=="none"||t.perspective!=="none"||(t.containerType?t.containerType!=="normal":!1)||!n&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!n&&(t.filter?t.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(t.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(t.contain||"").includes(r))}function Lee(e){let n=ei(e);for(;Is(n)&&!xl(n);){if(Kw(n))return n;if($g(n))return null;n=ei(n)}return null}function Ww(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function xl(e){return["html","body","#document"].includes(Rl(e))}function Vr(e){return or(e).getComputedStyle(e)}function Ng(e){return Gr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ei(e){if(Rl(e)==="html")return e;const n=e.assignedSlot||e.parentNode||uE(e)&&e.host||uo(e);return uE(n)?n.host:n}function _O(e){const n=ei(e);return xl(n)?e.ownerDocument?e.ownerDocument.body:e.body:Is(n)&&nd(n)?n:_O(n)}function _u(e,n,t){var r;n===void 0&&(n=[]),t===void 0&&(t=!0);const s=_O(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),i=or(s);if(o){const a=tx(i);return n.concat(i,i.visualViewport||[],nd(s)?s:[],a&&t?_u(a):[])}return n.concat(s,_u(s,[],t))}function tx(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function kO(e){const n=Vr(e);let t=parseFloat(n.width)||0,r=parseFloat(n.height)||0;const s=Is(e),o=s?e.offsetWidth:t,i=s?e.offsetHeight:r,a=If(t)!==o||If(r)!==i;return a&&(t=o,r=i),{width:t,height:r,$:a}}function Gw(e){return Gr(e)?e:e.contextElement}function sl(e){const n=Gw(e);if(!Is(n))return Qo(1);const t=n.getBoundingClientRect(),{width:r,height:s,$:o}=kO(n);let i=(o?If(t.width):t.width)/r,a=(o?If(t.height):t.height)/s;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const $ee=Qo(0);function TO(e){const n=or(e);return!Ww()||!n.visualViewport?$ee:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Nee(e,n,t){return n===void 0&&(n=!1),!t||n&&t!==or(e)?!1:n}function Xi(e,n,t,r){n===void 0&&(n=!1),t===void 0&&(t=!1);const s=e.getBoundingClientRect(),o=Gw(e);let i=Qo(1);n&&(r?Gr(r)&&(i=sl(r)):i=sl(e));const a=Nee(o,t,r)?TO(o):Qo(0);let l=(s.left+a.x)/i.x,c=(s.top+a.y)/i.y,u=s.width/i.x,h=s.height/i.y;if(o){const p=or(o),f=r&&Gr(r)?or(r):r;let S=p,m=tx(S);for(;m&&r&&f!==S;){const x=sl(m),y=m.getBoundingClientRect(),v=Vr(m),w=y.left+(m.clientLeft+parseFloat(v.paddingLeft))*x.x,C=y.top+(m.clientTop+parseFloat(v.paddingTop))*x.y;l*=x.x,c*=x.y,u*=x.x,h*=x.y,l+=w,c+=C,S=or(m),m=tx(S)}}return _f({width:u,height:h,x:l,y:c})}function Fee(e){let{elements:n,rect:t,offsetParent:r,strategy:s}=e;const o=s==="fixed",i=uo(r),a=n?$g(n.floating):!1;if(r===i||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Qo(1);const u=Qo(0),h=Is(r);if((h||!h&&!o)&&((Rl(r)!=="body"||nd(i))&&(l=Ng(r)),Is(r))){const p=Xi(r);c=sl(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x,y:t.y*c.y-l.scrollTop*c.y+u.y}}function zee(e){return Array.from(e.getClientRects())}function MO(e){return Xi(uo(e)).left+Ng(e).scrollLeft}function Bee(e){const n=uo(e),t=Ng(e),r=e.ownerDocument.body,s=Qn(n.scrollWidth,n.clientWidth,r.scrollWidth,r.clientWidth),o=Qn(n.scrollHeight,n.clientHeight,r.scrollHeight,r.clientHeight);let i=-t.scrollLeft+MO(e);const a=-t.scrollTop;return Vr(r).direction==="rtl"&&(i+=Qn(n.clientWidth,r.clientWidth)-s),{width:s,height:o,x:i,y:a}}function Uee(e,n){const t=or(e),r=uo(e),s=t.visualViewport;let o=r.clientWidth,i=r.clientHeight,a=0,l=0;if(s){o=s.width,i=s.height;const c=Ww();(!c||c&&n==="fixed")&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:i,x:a,y:l}}function Hee(e,n){const t=Xi(e,!0,n==="fixed"),r=t.top+e.clientTop,s=t.left+e.clientLeft,o=Is(e)?sl(e):Qo(1),i=e.clientWidth*o.x,a=e.clientHeight*o.y,l=s*o.x,c=r*o.y;return{width:i,height:a,x:l,y:c}}function dE(e,n,t){let r;if(n==="viewport")r=Uee(e,t);else if(n==="document")r=Bee(uo(e));else if(Gr(n))r=Hee(n,t);else{const s=TO(e);r={...n,x:n.x-s.x,y:n.y-s.y}}return _f(r)}function AO(e,n){const t=ei(e);return t===n||!Gr(t)||xl(t)?!1:Vr(t).position==="fixed"||AO(t,n)}function Kee(e,n){const t=n.get(e);if(t)return t;let r=_u(e,[],!1).filter(a=>Gr(a)&&Rl(a)!=="body"),s=null;const o=Vr(e).position==="fixed";let i=o?ei(e):e;for(;Gr(i)&&!xl(i);){const a=Vr(i),l=Kw(i);!l&&a.position==="fixed"&&(s=null),(o?!l&&!s:!l&&a.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||nd(i)&&!l&&AO(e,i))?r=r.filter(u=>u!==i):s=a,i=ei(i)}return n.set(e,r),r}function Wee(e){let{element:n,boundary:t,rootBoundary:r,strategy:s}=e;const i=[...t==="clippingAncestors"?$g(n)?[]:Kee(n,this._c):[].concat(t),r],a=i[0],l=i.reduce((c,u)=>{const h=dE(n,u,s);return c.top=Qn(h.top,c.top),c.right=hs(h.right,c.right),c.bottom=hs(h.bottom,c.bottom),c.left=Qn(h.left,c.left),c},dE(n,a,s));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Gee(e){const{width:n,height:t}=kO(e);return{width:n,height:t}}function Vee(e,n,t){const r=Is(n),s=uo(n),o=t==="fixed",i=Xi(e,!0,o,n);let a={scrollLeft:0,scrollTop:0};const l=Qo(0);if(r||!r&&!o)if((Rl(n)!=="body"||nd(s))&&(a=Ng(n)),r){const h=Xi(n,!0,o,n);l.x=h.x+n.clientLeft,l.y=h.y+n.clientTop}else s&&(l.x=MO(s));const c=i.left+a.scrollLeft-l.x,u=i.top+a.scrollTop-l.y;return{x:c,y:u,width:i.width,height:i.height}}function Ry(e){return Vr(e).position==="static"}function hE(e,n){return!Is(e)||Vr(e).position==="fixed"?null:n?n(e):e.offsetParent}function jO(e,n){const t=or(e);if($g(e))return t;if(!Is(e)){let s=ei(e);for(;s&&!xl(s);){if(Gr(s)&&!Ry(s))return s;s=ei(s)}return t}let r=hE(e,n);for(;r&&Ree(r)&&Ry(r);)r=hE(r,n);return r&&xl(r)&&Ry(r)&&!Kw(r)?t:r||Lee(e)||t}const Yee=async function(e){const n=this.getOffsetParent||jO,t=this.getDimensions,r=await t(e.floating);return{reference:Vee(e.reference,await n(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Xee(e){return Vr(e).direction==="rtl"}const qee={convertOffsetParentRelativeRectToViewportRelativeRect:Fee,getDocumentElement:uo,getClippingRect:Wee,getOffsetParent:jO,getElementRects:Yee,getClientRects:zee,getDimensions:Gee,getScale:sl,isElement:Gr,isRTL:Xee};function Zee(e,n){let t=null,r;const s=uo(e);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{left:c,top:u,width:h,height:p}=e.getBoundingClientRect();if(a||n(),!h||!p)return;const f=mh(u),S=mh(s.clientWidth-(c+h)),m=mh(s.clientHeight-(u+p)),x=mh(c),v={rootMargin:-f+"px "+-S+"px "+-m+"px "+-x+"px",threshold:Qn(0,hs(1,l))||1};let w=!0;function C(E){const k=E[0].intersectionRatio;if(k!==l){if(!w)return i();k?i(!1,k):r=setTimeout(()=>{i(!1,1e-7)},1e3)}w=!1}try{t=new IntersectionObserver(C,{...v,root:s.ownerDocument})}catch{t=new IntersectionObserver(C,v)}t.observe(e)}return i(!0),o}function Qee(e,n,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=Gw(e),u=s||o?[...c?_u(c):[],..._u(n)]:[];u.forEach(y=>{s&&y.addEventListener("scroll",t,{passive:!0}),o&&y.addEventListener("resize",t)});const h=c&&a?Zee(c,t):null;let p=-1,f=null;i&&(f=new ResizeObserver(y=>{let[v]=y;v&&v.target===c&&f&&(f.unobserve(n),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(n)})),t()}),c&&!l&&f.observe(c),f.observe(n));let S,m=l?Xi(e):null;l&&x();function x(){const y=Xi(e);m&&(y.x!==m.x||y.y!==m.y||y.width!==m.width||y.height!==m.height)&&t(),m=y,S=requestAnimationFrame(x)}return t(),()=>{var y;u.forEach(v=>{s&&v.removeEventListener("scroll",t),o&&v.removeEventListener("resize",t)}),h==null||h(),(y=f)==null||y.disconnect(),f=null,l&&cancelAnimationFrame(S)}}const Jee=Aee,ete=jee,tte=kee,nte=Dee,rte=Tee,pE=_ee,ste=Oee,ote=(e,n,t)=>{const r=new Map,s={platform:qee,...t},o={...s.platform,_c:r};return Eee(e,n,{...s,platform:o})};var gp=typeof document<"u"?P.useLayoutEffect:P.useEffect;function kf(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(typeof e=="function"&&e.toString()===n.toString())return!0;let t,r,s;if(e&&n&&typeof e=="object"){if(Array.isArray(e)){if(t=e.length,t!==n.length)return!1;for(r=t;r--!==0;)if(!kf(e[r],n[r]))return!1;return!0}if(s=Object.keys(e),t=s.length,t!==Object.keys(n).length)return!1;for(r=t;r--!==0;)if(!{}.hasOwnProperty.call(n,s[r]))return!1;for(r=t;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!kf(e[o],n[o]))return!1}return!0}return e!==e&&n!==n}function OO(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function fE(e,n){const t=OO(e);return Math.round(n*t)/t}function gE(e){const n=P.useRef(e);return gp(()=>{n.current=e}),n}function ite(e){e===void 0&&(e={});const{placement:n="bottom",strategy:t="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[u,h]=P.useState({x:0,y:0,strategy:t,placement:n,middlewareData:{},isPositioned:!1}),[p,f]=P.useState(r);kf(p,r)||f(r);const[S,m]=P.useState(null),[x,y]=P.useState(null),v=P.useCallback(B=>{B!==k.current&&(k.current=B,m(B))},[]),w=P.useCallback(B=>{B!==I.current&&(I.current=B,y(B))},[]),C=o||S,E=i||x,k=P.useRef(null),I=P.useRef(null),_=P.useRef(u),T=l!=null,M=gE(l),D=gE(s),$=P.useCallback(()=>{if(!k.current||!I.current)return;const B={placement:n,strategy:t,middleware:p};D.current&&(B.platform=D.current),ote(k.current,I.current,B).then(z=>{const W={...z,isPositioned:!0};j.current&&!kf(_.current,W)&&(_.current=W,ta.flushSync(()=>{h(W)}))})},[p,n,t,D]);gp(()=>{c===!1&&_.current.isPositioned&&(_.current.isPositioned=!1,h(B=>({...B,isPositioned:!1})))},[c]);const j=P.useRef(!1);gp(()=>(j.current=!0,()=>{j.current=!1}),[]),gp(()=>{if(C&&(k.current=C),E&&(I.current=E),C&&E){if(M.current)return M.current(C,E,$);$()}},[C,E,$,M,T]);const O=P.useMemo(()=>({reference:k,floating:I,setReference:v,setFloating:w}),[v,w]),R=P.useMemo(()=>({reference:C,floating:E}),[C,E]),K=P.useMemo(()=>{const B={position:t,left:0,top:0};if(!R.floating)return B;const z=fE(R.floating,u.x),W=fE(R.floating,u.y);return a?{...B,transform:"translate("+z+"px, "+W+"px)",...OO(R.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:z,top:W}},[t,a,R.floating,u.x,u.y]);return P.useMemo(()=>({...u,update:$,refs:O,elements:R,floatingStyles:K}),[u,$,O,R,K])}const ate=e=>{function n(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:e,fn(t){const{element:r,padding:s}=typeof e=="function"?e(t):e;return r&&n(r)?r.current!=null?pE({element:r.current,padding:s}).fn(t):{}:r?pE({element:r,padding:s}).fn(t):{}}}},lte=(e,n)=>({...Jee(e),options:[e,n]}),cte=(e,n)=>({...ete(e),options:[e,n]}),ute=(e,n)=>({...ste(e),options:[e,n]}),dte=(e,n)=>({...tte(e),options:[e,n]}),hte=(e,n)=>({...nte(e),options:[e,n]}),pte=(e,n)=>({...rte(e),options:[e,n]}),fte=(e,n)=>({...ate(e),options:[e,n]});var gte="Arrow",DO=P.forwardRef((e,n)=>{const{children:t,width:r=10,height:s=5,...o}=e;return d.jsx(_e.svg,{...o,ref:n,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?t:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});DO.displayName=gte;var mte=DO;function RO(e){const[n,t]=P.useState(void 0);return Zo(()=>{if(e){t({width:e.offsetWidth,height:e.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=e.offsetWidth,a=e.offsetHeight;t({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else t(void 0)},[e]),n}var Vw="Popper",[LO,Fg]=Ts(Vw),[yte,$O]=LO(Vw),NO=e=>{const{__scopePopper:n,children:t}=e,[r,s]=P.useState(null);return d.jsx(yte,{scope:n,anchor:r,onAnchorChange:s,children:t})};NO.displayName=Vw;var FO="PopperAnchor",zO=P.forwardRef((e,n)=>{const{__scopePopper:t,virtualRef:r,...s}=e,o=$O(FO,t),i=P.useRef(null),a=Xe(n,i);return P.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||i.current)}),r?null:d.jsx(_e.div,{...s,ref:a})});zO.displayName=FO;var Yw="PopperContent",[Ste,vte]=LO(Yw),BO=P.forwardRef((e,n)=>{var Oe,tt,Ae,ot,Ne,Vn;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:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:S,...m}=e,x=$O(Yw,t),[y,v]=P.useState(null),w=Xe(n,Nt=>v(Nt)),[C,E]=P.useState(null),k=RO(C),I=(k==null?void 0:k.width)??0,_=(k==null?void 0:k.height)??0,T=r+(o!=="center"?"-"+o:""),M=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},D=Array.isArray(c)?c:[c],$=D.length>0,j={padding:M,boundary:D.filter(wte),altBoundary:$},{refs:O,floatingStyles:R,placement:K,isPositioned:B,middlewareData:z}=ite({strategy:"fixed",placement:T,whileElementsMounted:(...Nt)=>Qee(...Nt,{animationFrame:f==="always"}),elements:{reference:x.anchor},middleware:[lte({mainAxis:s+_,alignmentAxis:i}),l&&cte({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?ute():void 0,...j}),l&&dte({...j}),hte({...j,apply:({elements:Nt,rects:_n,availableWidth:St,availableHeight:Zt})=>{const{width:Ms,height:$l}=_n.reference,go=Nt.floating.style;go.setProperty("--radix-popper-available-width",`${St}px`),go.setProperty("--radix-popper-available-height",`${Zt}px`),go.setProperty("--radix-popper-anchor-width",`${Ms}px`),go.setProperty("--radix-popper-anchor-height",`${$l}px`)}}),C&&fte({element:C,padding:a}),bte({arrowWidth:I,arrowHeight:_}),p&&pte({strategy:"referenceHidden",...j})]}),[W,Y]=KO(K),q=Yt(S);Zo(()=>{B&&(q==null||q())},[B,q]);const ae=(Oe=z.arrow)==null?void 0:Oe.x,fe=(tt=z.arrow)==null?void 0:tt.y,we=((Ae=z.arrow)==null?void 0:Ae.centerOffset)!==0,[J,Ue]=P.useState();return Zo(()=>{y&&Ue(window.getComputedStyle(y).zIndex)},[y]),d.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...R,transform:B?R.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[(ot=z.transformOrigin)==null?void 0:ot.x,(Ne=z.transformOrigin)==null?void 0:Ne.y].join(" "),...((Vn=z.hide)==null?void 0:Vn.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:d.jsx(Ste,{scope:t,placedSide:W,onArrowChange:E,arrowX:ae,arrowY:fe,shouldHideArrow:we,children:d.jsx(_e.div,{"data-side":W,"data-align":Y,...m,ref:w,style:{...m.style,animation:B?void 0:"none"}})})})});BO.displayName=Yw;var UO="PopperArrow",xte={top:"bottom",right:"left",bottom:"top",left:"right"},HO=P.forwardRef(function(n,t){const{__scopePopper:r,...s}=n,o=vte(UO,r),i=xte[o.placedSide];return d.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:d.jsx(mte,{...s,ref:t,style:{...s.style,display:"block"}})})});HO.displayName=UO;function wte(e){return e!==null}var bte=e=>({name:"transformOrigin",options:e,fn(n){var x,y,v;const{placement:t,rects:r,middlewareData:s}=n,i=((x=s.arrow)==null?void 0:x.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,u]=KO(t),h={start:"0%",center:"50%",end:"100%"}[u],p=(((y=s.arrow)==null?void 0:y.x)??0)+a/2,f=(((v=s.arrow)==null?void 0:v.y)??0)+l/2;let S="",m="";return c==="bottom"?(S=i?h:`${p}px`,m=`${-l}px`):c==="top"?(S=i?h:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(S=`${-l}px`,m=i?h:`${f}px`):c==="left"&&(S=`${r.floating.width+l}px`,m=i?h:`${f}px`),{data:{x:S,y:m}}}});function KO(e){const[n,t="center"]=e.split("-");return[n,t]}var Xw=NO,qw=zO,WO=BO,GO=HO,Zw="Popover",[VO,Rae]=Ts(Zw,[Fg]),rd=Fg(),[Pte,ui]=VO(Zw),YO=e=>{const{__scopePopover:n,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=e,a=rd(n),l=P.useRef(null),[c,u]=P.useState(!1),[h=!1,p]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(Xw,{...a,children:d.jsx(Pte,{scope:n,contentId:Xs(),triggerRef:l,open:h,onOpenChange:p,onOpenToggle:P.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:c,onCustomAnchorAdd:P.useCallback(()=>u(!0),[]),onCustomAnchorRemove:P.useCallback(()=>u(!1),[]),modal:i,children:t})})};YO.displayName=Zw;var XO="PopoverAnchor",Cte=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(XO,t),o=rd(t),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return P.useEffect(()=>(i(),()=>a()),[i,a]),d.jsx(qw,{...o,...r,ref:n})});Cte.displayName=XO;var qO="PopoverTrigger",ZO=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(qO,t),o=rd(t),i=Xe(n,s.triggerRef),a=d.jsx(_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":nD(s.open),...r,ref:i,onClick:re(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:d.jsx(qw,{asChild:!0,...o,children:a})});ZO.displayName=qO;var Qw="PopoverPortal",[Ite,Ete]=VO(Qw,{forceMount:void 0}),QO=e=>{const{__scopePopover:n,forceMount:t,children:r,container:s}=e,o=ui(Qw,n);return d.jsx(Ite,{scope:n,forceMount:t,children:d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:r})})})};QO.displayName=Qw;var wl="PopoverContent",JO=P.forwardRef((e,n)=>{const t=Ete(wl,e.__scopePopover),{forceMount:r=t.forceMount,...s}=e,o=ui(wl,e.__scopePopover);return d.jsx(qr,{present:r||o.open,children:o.modal?d.jsx(_te,{...s,ref:n}):d.jsx(kte,{...s,ref:n})})});JO.displayName=wl;var _te=P.forwardRef((e,n)=>{const t=ui(wl,e.__scopePopover),r=P.useRef(null),s=Xe(n,r),o=P.useRef(!1);return P.useEffect(()=>{const i=r.current;if(i)return Mw(i)},[]),d.jsx(_g,{as:Vi,allowPinchZoom:!0,children:d.jsx(eD,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:re(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:re(e.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:re(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),kte=P.forwardRef((e,n)=>{const t=ui(wl,e.__scopePopover),r=P.useRef(!1),s=P.useRef(!1);return d.jsx(eD,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,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=e.onInteractOutside)==null||l.call(e,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()}})}),eD=P.forwardRef((e,n)=>{const{__scopePopover:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...h}=e,p=ui(wl,t),f=rd(t);return Tw(),d.jsx(Ig,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:d.jsx(ed,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>p.onOpenChange(!1),children:d.jsx(WO,{"data-state":nD(p.open),role:"dialog",id:p.contentId,...f,...h,ref:n,style:{...h.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)"}})})})}),tD="PopoverClose",Tte=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(tD,t);return d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,()=>s.onOpenChange(!1))})});Tte.displayName=tD;var Mte="PopoverArrow",Ate=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=rd(t);return d.jsx(GO,{...s,...r,ref:n})});Ate.displayName=Mte;function nD(e){return e?"open":"closed"}var Jw=YO,e1=ZO,t1=QO,n1=JO;function ho(e,n){const t=F(),r=P.useRef(!1),s=qt(),o=P.useCallback(a=>{r.current=a,t.run(()=>{a?(t.complete(),t.addOpenMenu(e)):t.updateInstanceState({openMenus:t.getOpenMenus().filter(l=>!l.startsWith(e))}),n==null||n(a)})},[t,e,n]),i=H("is menu open",()=>t.getOpenMenus().includes(e),[t,e]);return P.useEffect(()=>(r.current&&(s("open-menu",{source:"unknown",id:e}),t.addOpenMenu(e)),()=>{r.current&&(t.deleteOpenMenu(e),t.getOpenMenus().forEach(a=>{a.startsWith(e)&&(s("close-menu",{source:"unknown",id:e}),t.deleteOpenMenu(a))}),r.current=!1)}),[t,e,s]),[i,o]}function r1({id:e,children:n,onOpenChange:t,open:r}){const[s,o]=ho(e,t);return d.jsx(Jw,{onOpenChange:o,open:r||s,children:d.jsx("div",{className:"tlui-popover",children:n})})}function s1({children:e}){return d.jsx(e1,{asChild:!0,dir:"ltr",children:e})}function o1({side:e,children:n,align:t="center",sideOffset:r=8,alignOffset:s=0}){const o=$t();return d.jsx(t1,{container:o,children:d.jsx(n1,{className:"tlui-popover__content",side:e,sideOffset:r,align:t,alignOffset:s,dir:"ltr",children:n})})}const rD=P.createContext(null);function zg(){const e=P.useContext(rD);if(!e)throw new Error("useTldrawUiMenuContext must be used within a TldrawUiMenuContextProvider");return e}function Tr({type:e,sourceId:n,children:t}){return d.jsx(rD.Provider,{value:{type:e,sourceId:n},children:t})}function jte(e){return e.getSelectedShapeIds().map(r=>e.getShape(r)).filter(r=>{if(!r)return!1;if(e.isShapeOfType(r,"arrow")){const s=Rn(e,r);if(s.start||s.end)return!1}return!0})}const sD=()=>{const e=F();return H("threeStackableItems",()=>jte(e).length>2,[e])},po=()=>{const e=F();return H("isInSelectState",()=>e.isIn("select"),[e])},oD=()=>{const e=F();return H("allow group",()=>{const n=e.getSelectedShapes();if(n.length<2)return!1;for(const t of n)if(e.isShapeOfType(t,"arrow")){const r=Rn(e,t);if(r.start&&!n.some(s=>s.id===r.start.toId)||r.end&&!n.some(s=>s.id===r.end.toId))return!1}return!0},[e])},iD=()=>{const e=F();return H("allowUngroup",()=>e.getSelectedShapeIds().some(n=>{var t;return((t=e.getShape(n))==null?void 0:t.type)==="group"}),[e])},Ote=typeof window<"u"&&"navigator"in window&&!!navigator.clipboard&&!!navigator.clipboard.read;function aD(e,n){const t=F();return H("selectedShapes",()=>t.getSelectedShapes().length>=e,[t,e,n])}function In(e,n){const t=F();return H("selectedShapes",()=>{const r=t.getSelectedShapes().filter(s=>!t.isShapeOrAncestorLocked(s)).length;return e===void 0?r:r>=e},[t])}function Dte(){const e=F();return H("showAutoSizeToggle",()=>{const n=e.getSelectedShapes();return n.length===1&&e.isShapeOfType(n[0],"text")&&n[0].props.autoSize===!1},[e])}function lD(){const e=F();return H("hasLinkShapeSelected",()=>{const n=e.getOnlySelectedShape();return!!(n&&n.type!=="embed"&&"url"in n.props&&!n.isLocked)},[e])}function Rte(){const e=F();return H("onlyFlippableShape",()=>{const n=e.getOnlySelectedShape();return n&&(e.isShapeOfType(n,"group")||e.isShapeOfType(n,"image")||e.isShapeOfType(n,"arrow")||e.isShapeOfType(n,"line")||e.isShapeOfType(n,"draw"))},[e])}function cD(){const e=F();return H("useCanRedo",()=>e.getCanRedo(),[e])}function uD(){const e=F();return H("useCanUndo",()=>e.getCanUndo(),[e])}var Lte=P.createContext(void 0);function i1(e){const n=P.useContext(Lte);return e||n||"ltr"}var Ly="rovingFocusGroup.onEntryFocus",$te={bubbles:!1,cancelable:!0},Bg="RovingFocusGroup",[nx,dD,Nte]=kg(Bg),[Fte,hD]=Ts(Bg,[Nte]),[zte,Bte]=Fte(Bg),pD=P.forwardRef((e,n)=>d.jsx(nx.Provider,{scope:e.__scopeRovingFocusGroup,children:d.jsx(nx.Slot,{scope:e.__scopeRovingFocusGroup,children:d.jsx(Ute,{...e,ref:n})})}));pD.displayName=Bg;var Ute=P.forwardRef((e,n)=>{const{__scopeRovingFocusGroup:t,orientation:r,loop:s=!1,dir:o,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...h}=e,p=P.useRef(null),f=Xe(n,p),S=i1(o),[m=null,x]=ci({prop:i,defaultProp:a,onChange:l}),[y,v]=P.useState(!1),w=Yt(c),C=dD(t),E=P.useRef(!1),[k,I]=P.useState(0);return P.useEffect(()=>{const _=p.current;if(_)return _.addEventListener(Ly,w),()=>_.removeEventListener(Ly,w)},[w]),d.jsx(zte,{scope:t,orientation:r,dir:S,loop:s,currentTabStopId:m,onItemFocus:P.useCallback(_=>x(_),[x]),onItemShiftTab:P.useCallback(()=>v(!0),[]),onFocusableItemAdd:P.useCallback(()=>I(_=>_+1),[]),onFocusableItemRemove:P.useCallback(()=>I(_=>_-1),[]),children:d.jsx(_e.div,{tabIndex:y||k===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...e.style},onMouseDown:re(e.onMouseDown,()=>{E.current=!0}),onFocus:re(e.onFocus,_=>{const T=!E.current;if(_.target===_.currentTarget&&T&&!y){const M=new CustomEvent(Ly,$te);if(_.currentTarget.dispatchEvent(M),!M.defaultPrevented){const D=C().filter(K=>K.focusable),$=D.find(K=>K.active),j=D.find(K=>K.id===m),R=[$,j,...D].filter(Boolean).map(K=>K.ref.current);mD(R,u)}}E.current=!1}),onBlur:re(e.onBlur,()=>v(!1))})})}),fD="RovingFocusGroupItem",gD=P.forwardRef((e,n)=>{const{__scopeRovingFocusGroup:t,focusable:r=!0,active:s=!1,tabStopId:o,...i}=e,a=Xs(),l=o||a,c=Bte(fD,t),u=c.currentTabStopId===l,h=dD(t),{onFocusableItemAdd:p,onFocusableItemRemove:f}=c;return P.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),d.jsx(nx.ItemSlot,{scope:t,id:l,focusable:r,active:s,children:d.jsx(_e.span,{tabIndex:u?0:-1,"data-orientation":c.orientation,...i,ref:n,onMouseDown:re(e.onMouseDown,S=>{r?c.onItemFocus(l):S.preventDefault()}),onFocus:re(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:re(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){c.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const m=Wte(S,c.orientation,c.dir);if(m!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let y=h().filter(v=>v.focusable).map(v=>v.ref.current);if(m==="last")y.reverse();else if(m==="prev"||m==="next"){m==="prev"&&y.reverse();const v=y.indexOf(S.currentTarget);y=c.loop?Gte(y,v+1):y.slice(v+1)}setTimeout(()=>mD(y))}})})})});gD.displayName=fD;var Hte={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Kte(e,n){return n!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Wte(e,n,t){const r=Kte(e.key,t);if(!(n==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(n==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Hte[r]}function mD(e,n=!1){const t=document.activeElement;for(const r of e)if(r===t||(r.focus({preventScroll:n}),document.activeElement!==t))return}function Gte(e,n){return e.map((t,r)=>e[(n+r)%e.length])}var Vte=pD,Yte=gD,rx=["Enter"," "],Xte=["ArrowDown","PageUp","Home"],yD=["ArrowUp","PageDown","End"],qte=[...Xte,...yD],Zte={ltr:[...rx,"ArrowRight"],rtl:[...rx,"ArrowLeft"]},Qte={ltr:["ArrowLeft"],rtl:["ArrowRight"]},sd="Menu",[ku,Jte,ene]=kg(sd),[la,Ug]=Ts(sd,[ene,Fg,hD]),od=Fg(),SD=hD(),[vD,di]=la(sd),[tne,id]=la(sd),xD=e=>{const{__scopeMenu:n,open:t=!1,children:r,dir:s,onOpenChange:o,modal:i=!0}=e,a=od(n),[l,c]=P.useState(null),u=P.useRef(!1),h=Yt(o),p=i1(s);return P.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",S,{capture:!0,once:!0}),document.addEventListener("pointermove",S,{capture:!0,once:!0})},S=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",S,{capture:!0}),document.removeEventListener("pointermove",S,{capture:!0})}},[]),d.jsx(Xw,{...a,children:d.jsx(vD,{scope:n,open:t,onOpenChange:h,content:l,onContentChange:c,children:d.jsx(tne,{scope:n,onClose:P.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:p,modal:i,children:r})})})};xD.displayName=sd;var nne="MenuAnchor",a1=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e,s=od(t);return d.jsx(qw,{...s,...r,ref:n})});a1.displayName=nne;var l1="MenuPortal",[rne,wD]=la(l1,{forceMount:void 0}),bD=e=>{const{__scopeMenu:n,forceMount:t,children:r,container:s}=e,o=di(l1,n);return d.jsx(rne,{scope:n,forceMount:t,children:d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:r})})})};bD.displayName=l1;var Er="MenuContent",[sne,c1]=la(Er),PD=P.forwardRef((e,n)=>{const t=wD(Er,e.__scopeMenu),{forceMount:r=t.forceMount,...s}=e,o=di(Er,e.__scopeMenu),i=id(Er,e.__scopeMenu);return d.jsx(ku.Provider,{scope:e.__scopeMenu,children:d.jsx(qr,{present:r||o.open,children:d.jsx(ku.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(one,{...s,ref:n}):d.jsx(ine,{...s,ref:n})})})})}),one=P.forwardRef((e,n)=>{const t=di(Er,e.__scopeMenu),r=P.useRef(null),s=Xe(n,r);return P.useEffect(()=>{const o=r.current;if(o)return Mw(o)},[]),d.jsx(u1,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:re(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),ine=P.forwardRef((e,n)=>{const t=di(Er,e.__scopeMenu);return d.jsx(u1,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),u1=P.forwardRef((e,n)=>{const{__scopeMenu:t,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:S,...m}=e,x=di(Er,t),y=id(Er,t),v=od(t),w=SD(t),C=Jte(t),[E,k]=P.useState(null),I=P.useRef(null),_=Xe(n,I,x.onContentChange),T=P.useRef(0),M=P.useRef(""),D=P.useRef(0),$=P.useRef(null),j=P.useRef("right"),O=P.useRef(0),R=S?_g:P.Fragment,K=S?{as:Vi,allowPinchZoom:!0}:void 0,B=W=>{var Oe,tt;const Y=M.current+W,q=C().filter(Ae=>!Ae.disabled),ae=document.activeElement,fe=(Oe=q.find(Ae=>Ae.ref.current===ae))==null?void 0:Oe.textValue,we=q.map(Ae=>Ae.textValue),J=Sne(we,Y,fe),Ue=(tt=q.find(Ae=>Ae.textValue===J))==null?void 0:tt.ref.current;(function Ae(ot){M.current=ot,window.clearTimeout(T.current),ot!==""&&(T.current=window.setTimeout(()=>Ae(""),1e3))})(Y),Ue&&setTimeout(()=>Ue.focus())};P.useEffect(()=>()=>window.clearTimeout(T.current),[]),Tw();const z=P.useCallback(W=>{var q,ae;return j.current===((q=$.current)==null?void 0:q.side)&&xne(W,(ae=$.current)==null?void 0:ae.area)},[]);return d.jsx(sne,{scope:t,searchRef:M,onItemEnter:P.useCallback(W=>{z(W)&&W.preventDefault()},[z]),onItemLeave:P.useCallback(W=>{var Y;z(W)||((Y=I.current)==null||Y.focus(),k(null))},[z]),onTriggerLeave:P.useCallback(W=>{z(W)&&W.preventDefault()},[z]),pointerGraceTimerRef:D,onPointerGraceIntentChange:P.useCallback(W=>{$.current=W},[]),children:d.jsx(R,{...K,children:d.jsx(Ig,{asChild:!0,trapped:s,onMountAutoFocus:re(o,W=>{var Y;W.preventDefault(),(Y=I.current)==null||Y.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(ed,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:d.jsx(Vte,{asChild:!0,...w,dir:y.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:k,onEntryFocus:re(l,W=>{y.isUsingKeyboardRef.current||W.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(WO,{role:"menu","aria-orientation":"vertical","data-state":zD(x.open),"data-radix-menu-content":"",dir:y.dir,...v,...m,ref:_,style:{outline:"none",...m.style},onKeyDown:re(m.onKeyDown,W=>{const q=W.target.closest("[data-radix-menu-content]")===W.currentTarget,ae=W.ctrlKey||W.altKey||W.metaKey,fe=W.key.length===1;q&&(W.key==="Tab"&&W.preventDefault(),!ae&&fe&&B(W.key));const we=I.current;if(W.target!==we||!qte.includes(W.key))return;W.preventDefault();const Ue=C().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);yD.includes(W.key)&&Ue.reverse(),mne(Ue)}),onBlur:re(e.onBlur,W=>{W.currentTarget.contains(W.target)||(window.clearTimeout(T.current),M.current="")}),onPointerMove:re(e.onPointerMove,Tu(W=>{const Y=W.target,q=O.current!==W.clientX;if(W.currentTarget.contains(Y)&&q){const ae=W.clientX>O.current?"right":"left";j.current=ae,O.current=W.clientX}}))})})})})})})});PD.displayName=Er;var ane="MenuGroup",d1=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{role:"group",...r,ref:n})});d1.displayName=ane;var lne="MenuLabel",CD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});CD.displayName=lne;var Tf="MenuItem",mE="menu.itemSelect",Hg=P.forwardRef((e,n)=>{const{disabled:t=!1,onSelect:r,...s}=e,o=P.useRef(null),i=id(Tf,e.__scopeMenu),a=c1(Tf,e.__scopeMenu),l=Xe(n,o),c=P.useRef(!1),u=()=>{const h=o.current;if(!t&&h){const p=new CustomEvent(mE,{bubbles:!0,cancelable:!0});h.addEventListener(mE,f=>r==null?void 0:r(f),{once:!0}),kw(h,p),p.defaultPrevented?c.current=!1:i.onClose()}};return d.jsx(ID,{...s,ref:l,disabled:t,onClick:re(e.onClick,u),onPointerDown:h=>{var p;(p=e.onPointerDown)==null||p.call(e,h),c.current=!0},onPointerUp:re(e.onPointerUp,h=>{var p;c.current||(p=h.currentTarget)==null||p.click()}),onKeyDown:re(e.onKeyDown,h=>{const p=a.searchRef.current!=="";t||p&&h.key===" "||rx.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Hg.displayName=Tf;var ID=P.forwardRef((e,n)=>{const{__scopeMenu:t,disabled:r=!1,textValue:s,...o}=e,i=c1(Tf,t),a=SD(t),l=P.useRef(null),c=Xe(n,l),[u,h]=P.useState(!1),[p,f]=P.useState("");return P.useEffect(()=>{const S=l.current;S&&f((S.textContent??"").trim())},[o.children]),d.jsx(ku.ItemSlot,{scope:t,disabled:r,textValue:s??p,children:d.jsx(Yte,{asChild:!0,...a,focusable:!r,children:d.jsx(_e.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:c,onPointerMove:re(e.onPointerMove,Tu(S=>{r?i.onItemLeave(S):(i.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:re(e.onPointerLeave,Tu(S=>i.onItemLeave(S))),onFocus:re(e.onFocus,()=>h(!0)),onBlur:re(e.onBlur,()=>h(!1))})})})}),cne="MenuCheckboxItem",ED=P.forwardRef((e,n)=>{const{checked:t=!1,onCheckedChange:r,...s}=e;return d.jsx(AD,{scope:e.__scopeMenu,checked:t,children:d.jsx(Hg,{role:"menuitemcheckbox","aria-checked":Mf(t)?"mixed":t,...s,ref:n,"data-state":f1(t),onSelect:re(s.onSelect,()=>r==null?void 0:r(Mf(t)?!0:!t),{checkForDefaultPrevented:!1})})})});ED.displayName=cne;var _D="MenuRadioGroup",[une,dne]=la(_D,{value:void 0,onValueChange:()=>{}}),kD=P.forwardRef((e,n)=>{const{value:t,onValueChange:r,...s}=e,o=Yt(r);return d.jsx(une,{scope:e.__scopeMenu,value:t,onValueChange:o,children:d.jsx(d1,{...s,ref:n})})});kD.displayName=_D;var TD="MenuRadioItem",MD=P.forwardRef((e,n)=>{const{value:t,...r}=e,s=dne(TD,e.__scopeMenu),o=t===s.value;return d.jsx(AD,{scope:e.__scopeMenu,checked:o,children:d.jsx(Hg,{role:"menuitemradio","aria-checked":o,...r,ref:n,"data-state":f1(o),onSelect:re(r.onSelect,()=>{var i;return(i=s.onValueChange)==null?void 0:i.call(s,t)},{checkForDefaultPrevented:!1})})})});MD.displayName=TD;var h1="MenuItemIndicator",[AD,hne]=la(h1,{checked:!1}),jD=P.forwardRef((e,n)=>{const{__scopeMenu:t,forceMount:r,...s}=e,o=hne(h1,t);return d.jsx(qr,{present:r||Mf(o.checked)||o.checked===!0,children:d.jsx(_e.span,{...s,ref:n,"data-state":f1(o.checked)})})});jD.displayName=h1;var pne="MenuSeparator",OD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{role:"separator","aria-orientation":"horizontal",...r,ref:n})});OD.displayName=pne;var fne="MenuArrow",DD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e,s=od(t);return d.jsx(GO,{...s,...r,ref:n})});DD.displayName=fne;var p1="MenuSub",[gne,RD]=la(p1),LD=e=>{const{__scopeMenu:n,children:t,open:r=!1,onOpenChange:s}=e,o=di(p1,n),i=od(n),[a,l]=P.useState(null),[c,u]=P.useState(null),h=Yt(s);return P.useEffect(()=>(o.open===!1&&h(!1),()=>h(!1)),[o.open,h]),d.jsx(Xw,{...i,children:d.jsx(vD,{scope:n,open:r,onOpenChange:h,content:c,onContentChange:u,children:d.jsx(gne,{scope:n,contentId:Xs(),triggerId:Xs(),trigger:a,onTriggerChange:l,children:t})})})};LD.displayName=p1;var Dc="MenuSubTrigger",$D=P.forwardRef((e,n)=>{const t=di(Dc,e.__scopeMenu),r=id(Dc,e.__scopeMenu),s=RD(Dc,e.__scopeMenu),o=c1(Dc,e.__scopeMenu),i=P.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=o,c={__scopeMenu:e.__scopeMenu},u=P.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return P.useEffect(()=>u,[u]),P.useEffect(()=>{const h=a.current;return()=>{window.clearTimeout(h),l(null)}},[a,l]),d.jsx(a1,{asChild:!0,...c,children:d.jsx(ID,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":s.contentId,"data-state":zD(t.open),...e,ref:Cg(n,s.onTriggerChange),onClick:h=>{var p;(p=e.onClick)==null||p.call(e,h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:re(e.onPointerMove,Tu(h=>{o.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!t.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{t.onOpenChange(!0),u()},100))})),onPointerLeave:re(e.onPointerLeave,Tu(h=>{var f,S;u();const p=(f=t.content)==null?void 0:f.getBoundingClientRect();if(p){const m=(S=t.content)==null?void 0:S.dataset.side,x=m==="right",y=x?-5:5,v=p[x?"left":"right"],w=p[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:h.clientX+y,y:h.clientY},{x:v,y:p.top},{x:w,y:p.top},{x:w,y:p.bottom},{x:v,y:p.bottom}],side:m}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(h),h.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:re(e.onKeyDown,h=>{var f;const p=o.searchRef.current!=="";e.disabled||p&&h.key===" "||Zte[r.dir].includes(h.key)&&(t.onOpenChange(!0),(f=t.content)==null||f.focus(),h.preventDefault())})})})});$D.displayName=Dc;var ND="MenuSubContent",FD=P.forwardRef((e,n)=>{const t=wD(Er,e.__scopeMenu),{forceMount:r=t.forceMount,...s}=e,o=di(Er,e.__scopeMenu),i=id(Er,e.__scopeMenu),a=RD(ND,e.__scopeMenu),l=P.useRef(null),c=Xe(n,l);return d.jsx(ku.Provider,{scope:e.__scopeMenu,children:d.jsx(qr,{present:r||o.open,children:d.jsx(ku.Slot,{scope:e.__scopeMenu,children:d.jsx(u1,{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 h;i.isUsingKeyboardRef.current&&((h=l.current)==null||h.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:re(e.onFocusOutside,u=>{u.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:re(e.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:re(e.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),p=Qte[i.dir].includes(u.key);h&&p&&(o.onOpenChange(!1),(f=a.trigger)==null||f.focus(),u.preventDefault())})})})})})});FD.displayName=ND;function zD(e){return e?"open":"closed"}function Mf(e){return e==="indeterminate"}function f1(e){return Mf(e)?"indeterminate":e?"checked":"unchecked"}function mne(e){const n=document.activeElement;for(const t of e)if(t===n||(t.focus(),document.activeElement!==n))return}function yne(e,n){return e.map((t,r)=>e[(n+r)%e.length])}function Sne(e,n,t){const s=n.length>1&&Array.from(n).every(c=>c===n[0])?n[0]:n,o=t?e.indexOf(t):-1;let i=yne(e,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 vne(e,n){const{x:t,y:r}=e;let s=!1;for(let o=0,i=n.length-1;or!=u>r&&t<(c-a)*(r-l)/(u-l)+a&&(s=!s)}return s}function xne(e,n){if(!n)return!1;const t={x:e.clientX,y:e.clientY};return vne(t,n)}function Tu(e){return n=>n.pointerType==="mouse"?e(n):void 0}var BD=xD,UD=a1,HD=bD,KD=PD,WD=d1,GD=CD,VD=Hg,YD=ED,XD=kD,qD=MD,ZD=jD,QD=OD,JD=DD,eR=LD,tR=$D,nR=FD,g1="ContextMenu",[wne,Lae]=Ts(g1,[Ug]),hn=Ug(),[bne,rR]=wne(g1),sR=e=>{const{__scopeContextMenu:n,children:t,onOpenChange:r,dir:s,modal:o=!0}=e,[i,a]=P.useState(!1),l=hn(n),c=Yt(r),u=P.useCallback(h=>{a(h),c(h)},[c]);return d.jsx(bne,{scope:n,open:i,onOpenChange:u,modal:o,children:d.jsx(BD,{...l,dir:s,open:i,onOpenChange:u,modal:o,children:t})})};sR.displayName=g1;var oR="ContextMenuTrigger",iR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,disabled:r=!1,...s}=e,o=rR(oR,t),i=hn(t),a=P.useRef({x:0,y:0}),l=P.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),c=P.useRef(0),u=P.useCallback(()=>window.clearTimeout(c.current),[]),h=p=>{a.current={x:p.clientX,y:p.clientY},o.onOpenChange(!0)};return P.useEffect(()=>u,[u]),P.useEffect(()=>void(r&&u()),[r,u]),d.jsxs(d.Fragment,{children:[d.jsx(UD,{...i,virtualRef:l}),d.jsx(_e.span,{"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,...s,ref:n,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:re(e.onContextMenu,p=>{u(),h(p),p.preventDefault()}),onPointerDown:r?e.onPointerDown:re(e.onPointerDown,yh(p=>{u(),c.current=window.setTimeout(()=>h(p),700)})),onPointerMove:r?e.onPointerMove:re(e.onPointerMove,yh(u)),onPointerCancel:r?e.onPointerCancel:re(e.onPointerCancel,yh(u)),onPointerUp:r?e.onPointerUp:re(e.onPointerUp,yh(u))})]})});iR.displayName=oR;var Pne="ContextMenuPortal",m1=e=>{const{__scopeContextMenu:n,...t}=e,r=hn(n);return d.jsx(HD,{...r,...t})};m1.displayName=Pne;var aR="ContextMenuContent",lR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=rR(aR,t),o=hn(t),i=P.useRef(!1);return d.jsx(KD,{...o,...r,ref:n,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:a=>{var l;(l=e.onCloseAutoFocus)==null||l.call(e,a),!a.defaultPrevented&&i.current&&a.preventDefault(),i.current=!1},onInteractOutside:a=>{var l;(l=e.onInteractOutside)==null||l.call(e,a),!a.defaultPrevented&&!s.modal&&(i.current=!0)},style:{...e.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)"}})});lR.displayName=aR;var Cne="ContextMenuGroup",cR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(WD,{...s,...r,ref:n})});cR.displayName=Cne;var Ine="ContextMenuLabel",Ene=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(GD,{...s,...r,ref:n})});Ene.displayName=Ine;var _ne="ContextMenuItem",uR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(VD,{...s,...r,ref:n})});uR.displayName=_ne;var kne="ContextMenuCheckboxItem",dR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(YD,{...s,...r,ref:n})});dR.displayName=kne;var Tne="ContextMenuRadioGroup",Mne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(XD,{...s,...r,ref:n})});Mne.displayName=Tne;var Ane="ContextMenuRadioItem",jne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(qD,{...s,...r,ref:n})});jne.displayName=Ane;var One="ContextMenuItemIndicator",Dne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(ZD,{...s,...r,ref:n})});Dne.displayName=One;var Rne="ContextMenuSeparator",Lne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(QD,{...s,...r,ref:n})});Lne.displayName=Rne;var $ne="ContextMenuArrow",Nne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(JD,{...s,...r,ref:n})});Nne.displayName=$ne;var Fne="ContextMenuSub",hR=e=>{const{__scopeContextMenu:n,children:t,onOpenChange:r,open:s,defaultOpen:o}=e,i=hn(n),[a,l]=ci({prop:s,defaultProp:o,onChange:r});return d.jsx(eR,{...i,open:a,onOpenChange:l,children:t})};hR.displayName=Fne;var zne="ContextMenuSubTrigger",pR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(tR,{...s,...r,ref:n})});pR.displayName=zne;var Bne="ContextMenuSubContent",fR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(nR,{...s,...r,ref:n,style:{...e.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)"}})});fR.displayName=Bne;function yh(e){return n=>n.pointerType!=="mouse"?e(n):void 0}var Une=sR,Hne=iR,Kne=m1,Wne=lR,Gne=dR;const gR=typeof window>"u"?!1:window.navigator.userAgent.toLowerCase().indexOf("mac")>-1,Vne=gR?"⌘":"Ctrl",Yne=gR?"⌥":"Alt";function mR(e){return e.split(",")[0].split("").map(n=>{const t=n.replace(/\$/g,Vne).replace(/\?/g,Yne).replace(/!/g,"⇧");return t[0].toUpperCase()+t.slice(1)})}function sx(e){return"— "+mR(e).join(" ")}function Xne(e){return d.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",...e,children:d.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[d.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),d.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor",children:d.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}var y1="DropdownMenu",[qne,$ae]=Ts(y1,[Ug]),pn=Ug(),[Zne,yR]=qne(y1),SR=e=>{const{__scopeDropdownMenu:n,children:t,dir:r,open:s,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,l=pn(n),c=P.useRef(null),[u=!1,h]=ci({prop:s,defaultProp:o,onChange:i});return d.jsx(Zne,{scope:n,triggerId:Xs(),triggerRef:c,contentId:Xs(),open:u,onOpenChange:h,onOpenToggle:P.useCallback(()=>h(p=>!p),[h]),modal:a,children:d.jsx(BD,{...l,open:u,onOpenChange:h,dir:r,modal:a,children:t})})};SR.displayName=y1;var vR="DropdownMenuTrigger",xR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,disabled:r=!1,...s}=e,o=yR(vR,t),i=pn(t);return d.jsx(UD,{asChild:!0,...i,children:d.jsx(_e.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:Cg(n,o.triggerRef),onPointerDown:re(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:re(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});xR.displayName=vR;var Qne="DropdownMenuPortal",wR=e=>{const{__scopeDropdownMenu:n,...t}=e,r=pn(n);return d.jsx(HD,{...r,...t})};wR.displayName=Qne;var bR="DropdownMenuContent",PR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=yR(bR,t),o=pn(t),i=P.useRef(!1);return d.jsx(KD,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:n,onCloseAutoFocus:re(e.onCloseAutoFocus,a=>{var l;i.current||(l=s.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:re(e.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:{...e.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)"}})});PR.displayName=bR;var Jne="DropdownMenuGroup",CR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(WD,{...s,...r,ref:n})});CR.displayName=Jne;var ere="DropdownMenuLabel",tre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(GD,{...s,...r,ref:n})});tre.displayName=ere;var nre="DropdownMenuItem",IR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(VD,{...s,...r,ref:n})});IR.displayName=nre;var rre="DropdownMenuCheckboxItem",ER=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(YD,{...s,...r,ref:n})});ER.displayName=rre;var sre="DropdownMenuRadioGroup",ore=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(XD,{...s,...r,ref:n})});ore.displayName=sre;var ire="DropdownMenuRadioItem",are=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(qD,{...s,...r,ref:n})});are.displayName=ire;var lre="DropdownMenuItemIndicator",cre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(ZD,{...s,...r,ref:n})});cre.displayName=lre;var ure="DropdownMenuSeparator",dre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(QD,{...s,...r,ref:n})});dre.displayName=ure;var hre="DropdownMenuArrow",pre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(JD,{...s,...r,ref:n})});pre.displayName=hre;var fre=e=>{const{__scopeDropdownMenu:n,children:t,open:r,onOpenChange:s,defaultOpen:o}=e,i=pn(n),[a=!1,l]=ci({prop:r,defaultProp:o,onChange:s});return d.jsx(eR,{...i,open:a,onOpenChange:l,children:t})},gre="DropdownMenuSubTrigger",_R=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(tR,{...s,...r,ref:n})});_R.displayName=gre;var mre="DropdownMenuSubContent",kR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(nR,{...s,...r,ref:n,style:{...e.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)"}})});kR.displayName=mre;var S1=SR,v1=xR,Kg=wR,x1=PR,yre=CR,Sre=IR,vre=ER,xre=fre,wre=_R,bre=kR;function qi({id:e,children:n,modal:t=!1,debugOpen:r=!1}){const[s,o]=ho(e);return d.jsx(S1,{open:r||s,dir:"ltr",modal:t,onOpenChange:o,children:n})}function Zi({children:e,...n}){return d.jsx(v1,{dir:"ltr",asChild:!0,onTouchEnd:t=>Ie(t),...n,children:e})}function Qi({side:e="bottom",align:n="start",sideOffset:t=8,alignOffset:r=8,children:s}){const o=$t();return d.jsx(Kg,{container:o,children:d.jsx(x1,{className:"tlui-menu",side:e,sideOffset:t,align:n,alignOffset:r,collisionPadding:4,children:s})})}function Pre({id:e,children:n}){const[t,r]=ho(e);return d.jsx(xre,{open:t,onOpenChange:r,children:n})}function Cre({id:e,label:n,title:t,disabled:r}){return d.jsx(wre,{dir:"ltr",asChild:!0,disabled:r,children:d.jsxs(ce,{"data-testid":e,type:"menu",className:"tlui-menu__submenu__trigger",disabled:r,title:t,children:[d.jsx(wt,{children:n}),d.jsx(Se,{icon:"chevron-right",small:!0})]})})}function Ire({id:e,alignOffset:n=-1,sideOffset:t=-4,size:r="small",children:s}){const o=$t();return d.jsx(Kg,{container:o,children:d.jsx(bre,{"data-testid":e,className:"tlui-menu tlui-menu__submenu__content",alignOffset:n,sideOffset:t,collisionPadding:4,"data-size":r,children:s})})}function Ere({children:e}){return d.jsx(yre,{dir:"ltr",className:"tlui-menu__group",children:e})}function Mu({noClose:e,children:n}){return d.jsx(Sre,{dir:"ltr",asChild:!0,onClick:e?Ie:void 0,children:n})}function qc({children:e,visibleOnMobileLayout:n=!1}){const t=Cn();return!n&&td.jsx("span",{children:r},s))})}function U({disabled:e=!1,spinner:n=!1,readonlyOk:t=!1,id:r,kbd:s,label:o,icon:i,onSelect:a,noClose:l,isSelected:c}){const{type:u,sourceId:h}=zg(),p=xe(),[f,S]=P.useState(!1);if(co()&&!t)return null;const x=Iu(o,u),y=s?sx(s):void 0,v=x?p(x):void 0,w=v&&y?`${v} ${y}`:v;switch(u){case"menu":return d.jsx(Mu,{children:d.jsxs(ce,{type:"menu","data-testid":`${h}.${r}`,disabled:e,title:w,onClick:C=>{l&&Ie(C),f?S(!1):a(h)},children:[d.jsx(wt,{children:v}),s&&d.jsx(qc,{children:s})]})});case"context-menu":return e?null:d.jsxs(uR,{dir:"ltr",title:w,draggable:!1,className:"tlui-button tlui-button__menu","data-testid":`${h}.${r}`,onSelect:C=>{l&&Ie(C),f?S(!1):a(h)},children:[d.jsx("span",{className:"tlui-button__label",draggable:!1,children:v}),s&&d.jsx(qc,{children:s}),n&&d.jsx(Xne,{})]});case"panel":return d.jsxs(ce,{"data-testid":`${h}.${r}`,type:"menu",title:w,disabled:e,onClick:()=>a(h),children:[d.jsx(wt,{children:v}),i&&d.jsx(Se,{icon:i})]});case"small-icons":case"icons":return d.jsx(ce,{"data-testid":`${h}.${r}`,type:"icon",title:w,disabled:e,onClick:()=>a(h),children:d.jsx(Se,{icon:i,small:u==="small-icons"})});case"keyboard-shortcuts":return s?d.jsxs("div",{className:"tlui-shortcuts-dialog__key-pair","data-testid":`${h}.${r}`,children:[d.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__key",children:v}),d.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__value",children:d.jsx(qc,{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 d.jsxs(ce,{type:"low",onClick:()=>a(h),children:[d.jsx(Se,{icon:i}),d.jsx(wt,{children:v})]});case"toolbar":return d.jsx(ce,{type:"tool","data-testid":`tools.${r}`,"aria-label":x,"data-value":r,onClick:()=>a("toolbar"),title:w,onTouchStart:C=>{Ie(C),a("toolbar")},role:"radio","aria-checked":c?"true":"false",children:d.jsx(Se,{icon:i})});case"toolbar-overflow":return d.jsx(Mu,{"aria-label":o,children:d.jsx(ce,{type:"icon",className:"tlui-button-grid__button",onClick:()=>{a("toolbar")},"data-testid":`tools.more.${r}`,title:w,role:"radio","aria-checked":c?"true":"false","data-value":r,children:d.jsx(Se,{icon:i})})});default:throw cn(u)}}function _re(){return d.jsxs(d.Fragment,{children:[d.jsx(kre,{}),d.jsx(Tre,{}),d.jsx(Mre,{}),d.jsx(Are,{}),d.jsx(jre,{}),d.jsx(Rre,{}),d.jsx(Lre,{}),d.jsx($re,{})]})}function kre(){const e=ie(),n=In(2),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["align-left"],disabled:!r}),d.jsx(U,{...e["align-center-horizontal"],disabled:!r}),d.jsx(U,{...e["align-right"],disabled:!r}),d.jsx(U,{...e["stretch-horizontal"],disabled:!r}),d.jsx(U,{...e["align-top"],disabled:!r}),d.jsx(U,{...e["align-center-vertical"],disabled:!r}),d.jsx(U,{...e["align-bottom"],disabled:!r}),d.jsx(U,{...e["stretch-vertical"],disabled:!r})]})}function Tre(){const e=ie(),n=In(3),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["distribute-horizontal"],disabled:!r}),d.jsx(U,{...e["distribute-vertical"],disabled:!r})]})}function Mre(){const e=ie(),n=sD(),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["stack-horizontal"],disabled:!r}),d.jsx(U,{...e["stack-vertical"],disabled:!r})]})}function Are(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["send-to-back"],disabled:!r}),d.jsx(U,{...e["send-backward"],disabled:!r}),d.jsx(U,{...e["bring-forward"],disabled:!r}),d.jsx(U,{...e["bring-to-front"],disabled:!r})]})}function jre(){return Cn()n.getZoomLevel()===1,[n]);return d.jsx(U,{...e["zoom-to-100"],disabled:t})}function Dre(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsx(U,{...e["rotate-ccw"],disabled:!r})}function Rre(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsx(U,{...e["rotate-cw"],disabled:!r})}function Lre(){const e=ie(),n=lD(),t=po(),r=n&&t;return d.jsx(U,{...e["edit-link"],disabled:!r})}function $re(){const e=oD(),n=iD();return e?d.jsx(yE,{}):n?d.jsx(Nre,{}):d.jsx(yE,{})}function yE(){const e=ie(),n=In(2),t=po(),r=n&&t;return d.jsx(U,{...e.group,disabled:!r})}function Nre(){const e=ie();return d.jsx(U,{...e.ungroup})}const Fre=P.memo(function({children:n}){const t=xe(),r=Cn(),s=co(),o=F(),i=H("should display quick actions when in readonly",()=>o.isInAny("hand","zoom"),[o]),a=n??d.jsx(_re,{});if(!(s&&!i))return d.jsxs(r1,{id:"actions-menu",children:[d.jsx(s1,{children:d.jsx(ce,{type:"icon","data-testid":"actions-menu.button",title:t("actions-menu.title"),children:d.jsx(Se,{icon:"dots-vertical",small:!0})})}),d.jsx(o1,{side:r>=yt.TABLET?"bottom":"top",sideOffset:6,children:d.jsx("div",{className:"tlui-actions-menu tlui-buttons__grid","data-testid":"actions-menu.content",children:d.jsx(Tr,{type:"icons",sourceId:"actions-menu",children:a})})})]})});function Gn({id:e,kbd:n,label:t,readonlyOk:r,onSelect:s,toggle:o=!1,disabled:i=!1,checked:a=!1}){const{type:l,sourceId:c}=zg(),u=co(),h=xe();if(u&&!r)return null;const p=Iu(t,l),f=p?h(p):void 0;switch(l){case"menu":return d.jsxs(vre,{dir:"ltr",className:"tlui-button tlui-button__menu tlui-button__checkbox",title:f,onSelect:S=>{s==null||s(c),Ie(S)},disabled:i,checked:a,children:[d.jsx(Cs,{small:!0,icon:o?a?"toggle-on":"toggle-off":a?"check":"none"}),f&&d.jsx("span",{className:"tlui-button__label",draggable:!1,children:f}),n&&d.jsx(qc,{children:n})]});case"context-menu":return d.jsxs(Gne,{className:"tlui-button tlui-button__menu tlui-button__checkbox",dir:"ltr",title:f,onSelect:S=>{s(c),Ie(S)},disabled:i,checked:a,children:[d.jsx(Cs,{small:!0,icon:o?a?"toggle-on":"toggle-off":a?"check":"none"}),f&&d.jsx("span",{className:"tlui-button__label",draggable:!1,children:f}),n&&d.jsx(qc,{children:n})]},e);default:return null}}function pe({id:e,label:n,children:t}){const{type:r,sourceId:s}=zg(),o=xe(),i=Iu(n,r),a=i?o(i):void 0;switch(r){case"panel":return d.jsx("div",{className:"tlui-menu__group","data-testid":`${s}-group.${e}`,children:t});case"menu":return d.jsx(Ere,{"data-testid":`${s}-group.${e}`,children:t});case"context-menu":return d.jsx(cR,{dir:"ltr",className:"tlui-menu__group","data-testid":`${s}-group.${e}`,children:t});case"keyboard-shortcuts":return d.jsxs("div",{className:"tlui-shortcuts-dialog__group","data-testid":`${s}-group.${e}`,children:[d.jsx("h2",{className:"tlui-shortcuts-dialog__group__title",children:a}),d.jsx("div",{className:"tlui-shortcuts-dialog__group__content",children:t})]});default:return t}}function En({id:e,disabled:n=!1,label:t,size:r="small",children:s}){const{type:o,sourceId:i}=zg(),a=$t(),l=xe(),c=t?typeof t=="string"?t:t[o]??t.default:void 0,u=c?l(c):void 0;switch(o){case"menu":return d.jsxs(Pre,{id:`${i}-sub.${e}`,children:[d.jsx(Cre,{id:`${i}-sub.${u?u.toLowerCase()+"-button":""}`,disabled:n,label:u,title:u}),d.jsx(Ire,{id:`${i}-sub.${u?u.toLowerCase()+"-content":""}`,size:r,children:s})]});case"context-menu":return n?null:d.jsxs(zre,{id:`${i}-sub.${e}`,children:[d.jsx(pR,{dir:"ltr",disabled:n,asChild:!0,children:d.jsxs(ce,{"data-testid":`${i}-sub-trigger.${e}`,type:"menu",className:"tlui-menu__submenu__trigger",children:[d.jsx(wt,{children:u}),d.jsx(Se,{icon:"chevron-right",small:!0})]})}),d.jsx(m1,{container:a,children:d.jsx(fR,{"data-testid":`${i}-sub-content.${e}`,className:"tlui-menu tlui-menu__submenu__content",alignOffset:-1,sideOffset:-4,collisionPadding:4,"data-size":r,children:s})})]});default:return s}}function zre({id:e,children:n}){const[t,r]=ho(e);return d.jsx(hR,{open:t,onOpenChange:r,children:n})}function TR(){const e=ie();return Dte()?d.jsx(U,{...e["toggle-auto-size"]}):null}function MR(){const e=ie();return lD()?d.jsx(U,{...e["edit-link"]}):null}function Bre(){const e=ie();return In(1)?d.jsx(U,{...e.duplicate}):null}function AR(){const e=ie(),n=F();return H("should display flatten option",()=>{if(n.getSelectedShapeIds().length===0)return!1;const s=n.getOnlySelectedShape();return!(s&&n.isShapeOfType(s,"image"))},[n])?d.jsx(U,{...e["flatten-to-image"]}):null}function jR(){const e=ie();return oD()?d.jsx(U,{...e.group}):null}function OR(){const e=ie();return iD()?d.jsx(U,{...e.ungroup}):null}function DR(){const e=F(),n=ie();return H("allow unframe",()=>{const r=e.getSelectedShapes();return r.length===0?!1:r.every(s=>e.isShapeOfType(s,"frame"))},[e])?d.jsx(U,{...n["remove-frame"]}):null}function RR(){const e=F(),n=ie();return H("allow fit frame to content",()=>{const r=e.getOnlySelectedShape();return r?e.isShapeOfType(r,"frame")&&e.getSortedChildIdsForParent(r).length>0:!1},[e])?d.jsx(U,{...n["fit-frame-to-content"]}):null}function LR(){const e=F(),n=ie();return H("selected shapes",()=>e.getSelectedShapes().length>0,[e])?d.jsx(U,{...n["toggle-lock"]}):null}function w1(){const e=ie(),n=F(),t=H("isTransparentBg",()=>!n.getInstanceState().exportBackground,[n]);return d.jsx(Gn,{...e["toggle-transparent"],checked:t,toggle:!0})}function Ure(){const e=F(),n=ie(),t=H("any shapes",()=>e.getCurrentPageShapeIds().size>0,[e]);return d.jsx(U,{...n["unlock-all"],disabled:!t})}function $R(){const e=F(),n=H("zoomed to 100",()=>e.getZoomLevel()===1,[e]),t=ie();return d.jsx(U,{...t["zoom-to-100"],noClose:!0,disabled:n})}function NR(){const e=F(),n=H("has shapes",()=>e.getCurrentPageShapeIds().size>0,[e]),t=ie();return d.jsx(U,{...t["zoom-to-fit"],disabled:!n,"data-testid":"minimap.zoom-menu.zoom-to-fit",noClose:!0})}function FR(){const e=F(),n=H("has shapes",()=>e.getSelectedShapeIds().length>0,[e]),t=ie();return d.jsx(U,{...t["zoom-to-selection"],disabled:!n,"data-testid":"minimap.zoom-menu.zoom-to-selection",noClose:!0})}function zR(){return d.jsxs(pe,{id:"clipboard",children:[d.jsx(Kre,{}),d.jsx(Wre,{}),d.jsx(Gre,{}),d.jsx(Bre,{}),d.jsx(Vre,{})]})}function Hre(){var r;const e=F(),n=ie(),t=H("atLeastOneShapeOnPage",()=>e.getCurrentPageShapeIds().size>0,[e]);return d.jsxs(En,{id:"copy-as",label:"context-menu.copy-as",size:"small",disabled:!t,children:[d.jsxs(pe,{id:"copy-as-group",children:[d.jsx(U,{...n["copy-as-svg"]}),!!((r=window.navigator.clipboard)!=null&&r.write)&&d.jsx(U,{...n["copy-as-png"]}),d.jsx(U,{...n["copy-as-json"]})]}),d.jsx(pe,{id:"copy-as-bg",children:d.jsx(w1,{})})]})}function Kre(){const e=ie(),n=In(1);return d.jsx(U,{...e.cut,disabled:!n})}function Wre(){const e=ie(),n=aD(1);return d.jsx(U,{...e.copy,disabled:!n})}function Gre(){const e=ie(),n=Ote;return d.jsx(U,{...e.paste,disabled:!n})}function BR(){const e=F(),n=ie();return H("atLeastOneShapeOnPage",()=>e.getCurrentPageShapeIds().size>0,[e])?d.jsxs(pe,{id:"conversions",children:[d.jsx(Hre,{}),d.jsxs(En,{id:"export-as",label:"context-menu.export-as",size:"small",children:[d.jsxs(pe,{id:"export-as-group",children:[d.jsx(U,{...n["export-as-svg"]}),d.jsx(U,{...n["export-as-png"]}),d.jsx(U,{...n["export-as-json"]})]}),d.jsx(pe,{id:"export-as-bg",children:d.jsx(w1,{})})]})]}):null}function UR(){const e=ie(),n=F(),t=H("atLeastOneShapeOnPage",()=>n.getCurrentPageShapeIds().size>0,[n]);return d.jsx(U,{...e["select-all"],disabled:!t})}function Vre(){const e=ie(),n=In(1);return d.jsx(U,{...e.delete,disabled:!n})}function Yre(){return aD(1)?d.jsxs(En,{id:"edit",label:"context-menu.edit",size:"small",children:[d.jsx(jR,{}),d.jsx(OR,{}),d.jsx(AR,{}),d.jsx(MR,{}),d.jsx(RR,{}),d.jsx(DR,{}),d.jsx(KR,{}),d.jsx(HR,{}),d.jsx(TR,{}),d.jsx(LR,{})]}):null}function Xre(){const e=In(2),n=Rte(),t=ie();return e||n?d.jsxs(En,{id:"arrange",label:"context-menu.arrange",size:"small",children:[e&&d.jsxs(pe,{id:"align",children:[d.jsx(U,{...t["align-left"]}),d.jsx(U,{...t["align-center-horizontal"]}),d.jsx(U,{...t["align-right"]}),d.jsx(U,{...t["align-top"]}),d.jsx(U,{...t["align-center-vertical"]}),d.jsx(U,{...t["align-bottom"]})]}),d.jsx(qre,{}),e&&d.jsxs(pe,{id:"stretch",children:[d.jsx(U,{...t["stretch-horizontal"]}),d.jsx(U,{...t["stretch-vertical"]})]}),(e||n)&&d.jsxs(pe,{id:"flip",children:[d.jsx(U,{...t["flip-horizontal"]}),d.jsx(U,{...t["flip-vertical"]})]}),d.jsx(Zre,{})]}):null}function qre(){const e=ie();return In(3)?d.jsxs(pe,{id:"distribute",children:[d.jsx(U,{...e["distribute-horizontal"]}),d.jsx(U,{...e["distribute-vertical"]})]}):null}function Zre(){const e=ie(),n=In(2),t=sD();return n?d.jsxs(pe,{id:"order",children:[d.jsx(U,{...e.pack}),t&&d.jsx(U,{...e["stack-horizontal"]}),t&&d.jsx(U,{...e["stack-vertical"]})]}):null}function Qre(){const e=ie();return In(1)?d.jsx(En,{id:"reorder",label:"context-menu.reorder",size:"small",children:d.jsxs(pe,{id:"reorder",children:[d.jsx(U,{...e["bring-to-front"]}),d.jsx(U,{...e["bring-forward"]}),d.jsx(U,{...e["send-backward"]}),d.jsx(U,{...e["send-to-back"]})]})}):null}function Jre(){const e=F(),n=H("pages",()=>e.getPages(),[e]),t=H("current page id",()=>e.getCurrentPageId(),[e]),{addToast:r}=Qr(),s=ie(),o=qt();return In(1)?d.jsxs(En,{id:"move-to-page",label:"context-menu.move-to-page",size:"small",children:[d.jsx(pe,{id:"pages",children:n.map(a=>d.jsx(U,{id:a.id,disabled:t===a.id,label:a.name,onSelect:()=>{e.mark("move_shapes_to_page"),e.moveShapesToPage(e.getSelectedShapeIds(),a.id);const l=e.getPage(a.id);l&&r({title:"Changed Page",description:`Moved to ${l.name}.`,actions:[{label:"Go Back",type:"primary",onClick:()=>{e.mark("change-page"),e.setCurrentPage(t)}}]}),o("move-to-page",{source:"context-menu"})}},a.id))}),d.jsx(pe,{id:"new-page",children:d.jsx(U,{...s["move-to-new-page"]})})]}):null}function HR(){const e=F(),n=ie();return H("oneEmbedSelected",()=>{const r=e.getOnlySelectedShape();return r?!!(e.isShapeOfType(r,"embed")&&r.props.url&&!e.isShapeOrAncestorLocked(r)):!1},[e])?d.jsx(U,{...n["convert-to-bookmark"]}):null}function KR(){const e=F(),n=ie();return H("oneEmbeddableBookmarkSelected",()=>{const r=e.getOnlySelectedShape();return r?!!(e.isShapeOfType(r,"bookmark")&&r.props.url&&Do(r.props.url)&&!e.isShapeOrAncestorLocked(r)):!1},[e])?d.jsx(U,{...n["convert-to-embed"]}):null}function ese(){const e=ie(),n=F(),t=H("isSnapMode",()=>n.user.getIsSnapMode(),[n]);return d.jsx(Gn,{...e["toggle-snap-mode"],checked:t})}function tse(){const e=ie(),n=F(),t=H("isToolLock",()=>n.getInstanceState().isToolLocked,[n]);return d.jsx(Gn,{...e["toggle-tool-lock"],checked:t})}function nse(){const e=ie(),n=F(),t=H("isGridMode",()=>n.getInstanceState().isGridMode,[n]);return d.jsx(Gn,{...e["toggle-grid"],checked:t})}function rse(){const e=ie(),n=F(),t=H("isWrapMode",()=>n.user.getIsWrapMode(),[n]);return d.jsx(Gn,{...e["toggle-wrap-mode"],checked:t})}function sse(){const e=ie(),n=F(),t=H("isFocusMode",()=>n.getInstanceState().isFocusMode,[n]);return d.jsx(Gn,{...e["toggle-focus-mode"],checked:t})}function ose(){const e=ie(),n=F(),t=H("edgeScrollSpeed",()=>n.user.getEdgeScrollSpeed(),[n]);return d.jsx(Gn,{...e["toggle-edge-scrolling"],checked:t===1})}function ise(){const e=ie(),n=F(),t=H("animationSpeed",()=>n.user.getAnimationSpeed(),[n]);return d.jsx(Gn,{...e["toggle-reduce-motion"],checked:t===0})}function ase(){const e=ie(),n=F(),t=H("isDebugMode",()=>n.getInstanceState().isDebugMode,[n]);return d.jsx(Gn,{...e["toggle-debug-mode"],checked:t})}function lse(){const e=ie(),n=F(),t=H("dynamic resize",()=>n.user.getIsDynamicResizeMode(),[n]);return d.jsx(Gn,{...e["toggle-dynamic-size-mode"],checked:t})}function cse(){const e=ie(),n=F(),t=H("paste at cursor",()=>n.user.getIsPasteAtCursorMode(),[n]);return d.jsx(Gn,{...e["toggle-paste-at-cursor"],checked:t})}function use(){const e=F(),n=ie();return H("show cursor chat",()=>e.getCurrentToolId()==="select"&&!e.getInstanceState().isCoarsePointer,[e])?d.jsx(U,{...n["open-cursor-chat"]}):null}function dse(){const e=F(),n=Lg();return H("isSelectToolActive",()=>e.getCurrentToolId()==="select",[e])?d.jsxs(d.Fragment,{children:[n&&d.jsx(use,{}),d.jsxs(pe,{id:"modify",children:[d.jsx(Yre,{}),d.jsx(Xre,{}),d.jsx(Qre,{}),d.jsx(Jre,{})]}),d.jsx(zR,{}),d.jsx(BR,{}),d.jsx(pe,{id:"select-all",children:d.jsx(UR,{})})]}):null}const hse=P.memo(function({children:n}){const t=F(),{Canvas:r}=st(),s=P.useCallback(c=>{if(c){if(t.getInstanceState().isCoarsePointer){const u=t.getSelectedShapes(),{inputs:{currentPagePoint:h}}=t,p=t.getShapesAtPoint(h);if(!t.getSelectedShapes().length||!p.some(f=>u.includes(f))){const f=p.filter(S=>t.isShapeOrAncestorLocked(S));f.length&&t.select(...f.map(S=>S.id))}}}else{const u=t.getOnlySelectedShape();u&&t.isShapeOrAncestorLocked(u)&&t.setSelectedShapes([])}},[t]),o=$t(),[i,a]=ho("context menu",s),l=n??d.jsx(dse,{});return d.jsxs(Une,{dir:"ltr",onOpenChange:a,modal:!1,children:[d.jsx(Hne,{onContextMenu:void 0,dir:"ltr",children:r?d.jsx(r,{}):null}),i&&d.jsx(Kne,{container:o,children:d.jsx(Wne,{className:"tlui-menu scrollable","data-testid":"context-menu",alignOffset:-4,collisionPadding:4,onContextMenu:Ie,children:d.jsx(Tr,{type:"context-menu",sourceId:"context-menu",children:l})})})]})}),pse=2e3,fse=5e3,gse=Lt(function(){const n=F(),{isChatting:t,chatMessage:r}=n.getInstanceState(),s=P.useRef(-1),[o,i]=P.useState("");return P.useEffect(()=>{if(!t&&r||t){const l=t?fse:pse;s.current=n.timers.setTimeout(()=>{n.updateInstanceState({chatMessage:"",isChatting:!1}),i(""),n.focus()},l)}return()=>{clearTimeout(s.current)}},[n,r,t]),t?d.jsx(yse,{value:o,setValue:i,chatMessage:r}):r.trim()?d.jsx(mse,{chatMessage:r}):null});function WR(e){const n=F();P.useLayoutEffect(()=>{var i;if(!e.current)return;const{x:r,y:s}=n.inputs.currentScreenPoint;(i=e.current)==null||i.style.setProperty("transform",`translate(${r}px, ${s}px)`);function o(a){var u;const{minX:l,minY:c}=n.getViewportScreenBounds();(u=e.current)==null||u.style.setProperty("transform",`translate(${a.clientX-l}px, ${a.clientY-c}px)`)}return window.addEventListener("pointermove",o),()=>{window.removeEventListener("pointermove",o)}},[e,n])}const mse=({chatMessage:e})=>{const n=F(),t=P.useRef(null);return WR(t),d.jsx("div",{ref:t,className:"tl-cursor-chat tl-cursor-chat__bubble",style:{backgroundColor:n.user.getColor()},children:e})},yse=Lt(function({chatMessage:n,value:t,setValue:r}){const s=F(),o=xe(),i=P.useRef(null),a=n||o("cursor-chat.type-to-chat");WR(i),P.useLayoutEffect(()=>{const p=i.current;if(!p)return;const f=s.textMeasure.measureText(t||a,{fontFamily:"var(--font-body)",fontSize:12,fontWeight:"500",fontStyle:"normal",maxWidth:null,lineHeight:1,padding:"6px"});p.style.setProperty("width",f.w+"px")},[s,t,a]),P.useLayoutEffect(()=>{const p=s.timers.requestAnimationFrame(()=>{var f;(f=i.current)==null||f.focus()});return()=>{cancelAnimationFrame(p)}},[s]);const l=P.useCallback(()=>{s.updateInstanceState({isChatting:!1}),s.focus()},[s]),c=P.useCallback(p=>{const{value:f}=p.target;r(f.slice(0,64)),s.updateInstanceState({chatMessage:f})},[s,r]),u=P.useCallback(p=>{const f=i.current;if(!f)return;const{value:S}=f;switch(p.key){case"Enter":{if(Ie(p),p.stopPropagation(),!S){l();return}r("");break}case"Escape":{Ie(p),p.stopPropagation(),l();break}}},[l,r]),h=P.useCallback(p=>{p.stopPropagation()},[]);return d.jsx("input",{ref:i,className:"tl-cursor-chat",style:{backgroundColor:s.user.getColor()},onBlur:l,onChange:c,onKeyDown:u,onPaste:h,value:t,placeholder:a,spellCheck:!1})});function ox({checked:e}){return d.jsx(Cs,{icon:e?"check":"none",className:"tlui-button__icon",small:!0})}function Sse(){const e=F(),{addToast:n}=Qr(),{addDialog:t}=aa(),[r,s]=Ce.useState(!1);return d.jsxs(d.Fragment,{children:[d.jsxs(pe,{id:"items",children:[d.jsx(U,{id:"add-toast",onSelect:()=>{n({id:ct(),title:"Something good happened",description:"Hey, attend to this thing over here. It might be important!",keepOpen:!0,severity:"success"}),n({id:ct(),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:()=>{}}]}),n({id:ct(),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:()=>{}}]}),n({id:ct(),title:"Something bad happened",severity:"error",keepOpen:!0})},label:"Show toast"}),d.jsx(U,{id:"show-dialog",label:"Show dialog",onSelect:()=>{t({component:({onClose:o})=>d.jsx(wse,{displayDontShowAgain:!0,onCancel:()=>o(),onContinue:()=>o()}),onClose:()=>{}})}}),d.jsx(U,{id:"create-shapes",label:"Create 100 shapes",onSelect:()=>bse(e,100)}),d.jsx(U,{id:"count-nodes",label:"Count shapes / nodes",onSelect:()=>{var a;const o=e.getSelectedShapes(),i=o.length===0?e.getRenderingShapes():o;window.alert(`Shapes ${i.length}, DOM nodes:${(a=document.querySelector(".tl-shapes").querySelectorAll("*"))==null?void 0:a.length}`)}}),(()=>{if(r)throw Error("oh no!");return null})(),d.jsx(U,{id:"throw-error",onSelect:()=>s(!0),label:"Throw error"}),d.jsx(U,{id:"hard-reset",onSelect:MM,label:"Hard reset"})]}),d.jsxs(pe,{id:"flags",children:[d.jsx(vse,{}),d.jsx(xse,{})]})]})}function vse(){const e=Object.values(xt);return e.length?d.jsx(En,{id:"debug flags",label:"Debug Flags",children:d.jsx(pe,{id:"debug flags",children:e.map(n=>d.jsx(GR,{flag:n},n.name))})}):null}function xse(){const e=Object.values(B0);return e.length?d.jsx(En,{id:"feature flags",label:"Feature Flags",children:d.jsx(pe,{id:"feature flags",children:e.map(n=>d.jsx(GR,{flag:n},n.name))})}):null}function wse({title:e="title",body:n="hello hello hello",cancel:t="Cancel",confirm:r="Continue",displayDontShowAgain:s=!1,onCancel:o,onContinue:i}){const[a,l]=Ce.useState(!1);return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:e}),d.jsx(Og,{})]}),d.jsx(Cu,{style:{maxWidth:350},children:n}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[s&&d.jsxs(ce,{type:"normal",onClick:()=>l(!a),style:{marginRight:"auto"},children:[d.jsx(ox,{checked:a}),d.jsx(wt,{children:"Don’t show again"})]}),d.jsx(ce,{type:"normal",onClick:o,children:d.jsx(wt,{children:t})}),d.jsx(ce,{type:"primary",onClick:async()=>i(),children:d.jsx(wt,{children:r})})]})]})}const GR=Lt(function({flag:n,onChange:t}){const r=n.get();return d.jsx(Gn,{id:n.name,title:n.name,label:n.name.replace(/([a-z0-9])([A-Z])/g,s=>`${s[0]} ${s[1].toLowerCase()}`).replace(/^[a-z]/,s=>s.toUpperCase()),checked:r,onSelect:()=>{n.set(!r),t==null||t(!r)}})});let SE=0;function bse(e,n){const t=Array(n),r=Math.floor(Math.sqrt(n));for(let s=0;s{e.createShapes(t).setSelectedShapes(t.map(s=>s.id))})}function Pse({children:e}){const n=e??d.jsx(Sse,{});return d.jsxs(qi,{id:"debug",children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon",title:"Debug menu",children:d.jsx(Se,{icon:"dots-horizontal"})})}),d.jsx(Qi,{side:"top",align:"end",alignOffset:0,children:d.jsx(Tr,{type:"menu",sourceId:"debug-panel",children:n})})]})}const Cse=P.memo(function(){const{DebugMenu:n}=pi();return d.jsxs("div",{className:"tlui-debug-panel",children:[d.jsx(Ese,{}),d.jsx(_se,{}),n&&d.jsx(n,{})]})});function Ise(e=!0){const[n,t]=P.useState(0),r=F();P.useEffect(()=>{if(!e)return;const s=()=>t(o=>o+1);return r.on("tick",s),()=>{r.off("tick",s)}},[r,e])}const Ese=Lt(function(){Ise();const n=F(),t=n.getPath(),r=n.getHoveredShape(),s=n.getOnlySelectedShape(),o=t==="select.idle"||!t.includes("select.")?r:s,i=o&&t.includes("select.")?` / ${o.type||""}${"geo"in o.props?" / "+o.props.geo:""} / [${b.ToInt(n.getPointInShapeSpace(o,n.inputs.currentPagePoint))}]`:"",a=t.startsWith("select.")&&!t.includes(".idle")?` / [${b.ToInt(n.inputs.originPagePoint)}] → [${b.ToInt(n.inputs.currentPagePoint)}] = ${b.Dist(n.inputs.originPagePoint,n.inputs.currentPagePoint).toFixed(0)}`:"";return d.jsx("div",{className:"tlui-debug-panel__current-state",children:`${t}${i}${a}`})});function _se(){const e=F(),n=H("show_fps",()=>xt.showFps.get(),[xt]),t=P.useRef(null);return P.useEffect(()=>{if(!n)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 h=Math.round(l*(r/a)*(1e3/r));h>s&&(s=h);const p=s*.75;(h=p&&c)&&(c=!c),t.current.innerHTML=`FPS ${h.toString()}`,t.current.className="tlui-debug-panel__fps"+(c?" tlui-debug-panel__fps__slow":""),a-=r,l=0,i=performance.now()}o=e.timers.requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(o)}},[n,e]),n?d.jsx("div",{ref:t}):null}const kse=P.memo(function(){const n=Cn(),{MainMenu:t,QuickActions:r,ActionsMenu:s,PageMenu:o}=pi();return!t&&!o&&n<6?null:d.jsx("div",{className:"tlui-menu-zone",children:d.jsxs("div",{className:"tlui-buttons__horizontal",children:[t&&d.jsx(t,{}),o&&d.jsx(o,{}),n<6?null:d.jsxs(d.Fragment,{children:[r&&d.jsx(r,{}),s&&d.jsx(s,{})]})]})})});function Tse(){const e=F(),n=ie(),[t,r]=P.useState(!1),s=P.useRef(!1);return Ko("toggle showback to content",()=>{const o=s.current,i=e.getCurrentPageShapeIds();let a=!1;i.size&&(a=i.size===e.getCulledShapes().size),o!==a&&(r(a),s.current=a)},[e]),t?d.jsx(U,{...n["back-to-content"],onSelect:()=>{n["back-to-content"].onSelect("helper-buttons"),r(!1)}}):null}function Mse(){const e=F(),n=ie();return H("is pen mode",()=>e.getInstanceState().isPenMode,[e])?d.jsx(U,{...n["exit-pen-mode"]}):null}function Ase(){const e=F(),n=ie();return H("is following user",()=>!!e.getInstanceState().followingUserId,[e])?d.jsx(U,{...n["stop-following"]}):null}function jse(){return d.jsxs(d.Fragment,{children:[d.jsx(Mse,{}),d.jsx(Tse,{}),d.jsx(Ase,{})]})}function Ose({children:e}){const n=e??d.jsx(jse,{});return d.jsx("div",{className:"tlui-helper-buttons",children:d.jsx(Tr,{type:"helper-buttons",sourceId:"helper-buttons",children:n})})}function Dse(){const e=ie(),n=Rg(),t=Lg();return d.jsxs(d.Fragment,{children:[d.jsxs(pe,{label:"shortcuts-dialog.tools",id:"tools",children:[d.jsx(U,{...e["toggle-tool-lock"]}),d.jsx(U,{...e["insert-media"]}),d.jsx(U,{...n.select}),d.jsx(U,{...n.draw}),d.jsx(U,{...n.eraser}),d.jsx(U,{...n.hand}),d.jsx(U,{...n.rectangle}),d.jsx(U,{...n.ellipse}),d.jsx(U,{...n.arrow}),d.jsx(U,{...n.line}),d.jsx(U,{...n.text}),d.jsx(U,{...n.frame}),d.jsx(U,{...n.note}),d.jsx(U,{...n.laser})]}),d.jsxs(pe,{label:"shortcuts-dialog.preferences",id:"preferences",children:[d.jsx(U,{...e["toggle-dark-mode"]}),d.jsx(U,{...e["toggle-focus-mode"]}),d.jsx(U,{...e["toggle-grid"]})]}),d.jsxs(pe,{label:"shortcuts-dialog.edit",id:"edit",children:[d.jsx(U,{...e.undo}),d.jsx(U,{...e.redo}),d.jsx(U,{...e.cut}),d.jsx(U,{...e.copy}),d.jsx(U,{...e.paste}),d.jsx(U,{...e["select-all"]}),d.jsx(U,{...e.delete}),d.jsx(U,{...e.duplicate})]}),d.jsxs(pe,{label:"shortcuts-dialog.view",id:"view",children:[d.jsx(U,{...e["zoom-in"]}),d.jsx(U,{...e["zoom-out"]}),d.jsx(U,{...e["zoom-to-100"]}),d.jsx(U,{...e["zoom-to-fit"]}),d.jsx(U,{...e["zoom-to-selection"]})]}),d.jsxs(pe,{label:"shortcuts-dialog.transform",id:"transform",children:[d.jsx(U,{...e["bring-to-front"]}),d.jsx(U,{...e["bring-forward"]}),d.jsx(U,{...e["send-backward"]}),d.jsx(U,{...e["send-to-back"]}),d.jsx(U,{...e.group}),d.jsx(U,{...e.ungroup}),d.jsx(U,{...e["flip-horizontal"]}),d.jsx(U,{...e["flip-vertical"]}),d.jsx(U,{...e["align-top"]}),d.jsx(U,{...e["align-center-vertical"]}),d.jsx(U,{...e["align-bottom"]}),d.jsx(U,{...e["align-left"]}),d.jsx(U,{...e["align-center-horizontal"]}),d.jsx(U,{...e["align-right"]})]}),t&&d.jsx(pe,{label:"shortcuts-dialog.collaboration",id:"collaboration",children:d.jsx(U,{...e["open-cursor-chat"]})})]})}const Rse=P.memo(function({children:n}){const t=xe(),r=Cn(),s=n??d.jsx(Dse,{});return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{className:"tlui-shortcuts-dialog__header",children:[d.jsx(jg,{children:t("shortcuts-dialog.title")}),d.jsx(Og,{})]}),d.jsx(Cu,{className:le("tlui-shortcuts-dialog__body",{"tlui-shortcuts-dialog__body__mobile":r<=yt.MOBILE_XS,"tlui-shortcuts-dialog__body__tablet":r<=yt.TABLET}),children:d.jsx(Tr,{type:"keyboard-shortcuts",sourceId:"kbd",children:s})}),d.jsx("div",{className:"tlui-dialog__scrim"})]})}),Lse=[{colorScheme:"light",label:"theme.light"},{colorScheme:"dark",label:"theme.dark"},{colorScheme:"system",label:"theme.system"}];function $se(){const e=F(),n=qt(),t=H("colorScheme",()=>e.user.getUserPreferences().colorScheme??e.user.getIsDarkMode()?"dark":"light",[e]);return d.jsx(En,{id:"help menu color-scheme",label:"menu.theme",children:d.jsx(pe,{id:"languages",children:Lse.map(({colorScheme:r,label:s})=>d.jsx(Gn,{id:`color-scheme-${r}`,label:s,checked:r===t,onSelect:()=>{e.user.updateUserPreferences({colorScheme:r}),n("color-scheme",{source:"menu",value:r})}},r))})})}function VR(){const e=F(),n=qt(),t=H("locale",()=>e.user.getLocale(),[e]);return d.jsx(En,{id:"help menu language",label:"menu.language",children:d.jsx(pe,{id:"languages",children:bu.map(({locale:r,label:s})=>d.jsx(Gn,{id:`language-${r}`,title:r,label:s,checked:r===t,onSelect:()=>{e.user.updateUserPreferences({locale:r}),n("change-language",{source:"menu",locale:r})}},r))})})}function Nse(){return d.jsxs(d.Fragment,{children:[d.jsx(VR,{}),d.jsx(YR,{})]})}function YR(){const{KeyboardShortcutsDialog:e}=pi(),{addDialog:n}=aa();return e?d.jsx(U,{id:"keyboard-shortcuts-button",label:"help-menu.keyboard-shortcuts",readonlyOk:!0,onSelect:()=>{n({component:e})}}):null}function Fse(){return d.jsxs(d.Fragment,{children:[d.jsx(Bse,{}),d.jsx(Wse,{}),d.jsx(zse,{}),d.jsx(Gse,{}),d.jsx(Yse,{}),d.jsx(Vse,{})]})}function zse(){const e=ie();return d.jsxs(En,{id:"export-all-as",label:"context-menu.export-all-as",size:"small",children:[d.jsxs(pe,{id:"export-all-as-group",children:[d.jsx(U,{...e["export-all-as-svg"]}),d.jsx(U,{...e["export-all-as-png"]}),d.jsx(U,{...e["export-all-as-json"]})]}),d.jsx(pe,{id:"export-all-as-bg",children:d.jsx(w1,{})})]})}function Bse(){const e=F(),n=H("isSelectToolActive",()=>e.getCurrentToolId()==="select",[e]);return d.jsxs(En,{id:"edit",label:"menu.edit",disabled:!n,children:[d.jsx(Kse,{}),d.jsx(zR,{}),d.jsx(BR,{}),d.jsx(Use,{}),d.jsx(Hse,{}),d.jsx(pe,{id:"select-all",children:d.jsx(UR,{})})]})}function Use(){return d.jsxs(pe,{id:"misc",children:[d.jsx(jR,{}),d.jsx(OR,{}),d.jsx(MR,{}),d.jsx(TR,{}),d.jsx(DR,{}),d.jsx(RR,{}),d.jsx(KR,{}),d.jsx(HR,{}),d.jsx(AR,{})]})}function Hse(){return d.jsxs(pe,{id:"lock",children:[d.jsx(LR,{}),d.jsx(Ure,{})]})}function Kse(){const e=ie(),n=uD(),t=cD();return d.jsxs(pe,{id:"undo-redo",children:[d.jsx(U,{...e.undo,disabled:!n}),d.jsx(U,{...e.redo,disabled:!t})]})}function Wse(){const e=ie();return d.jsx(En,{id:"view",label:"menu.view",children:d.jsxs(pe,{id:"view-actions",children:[d.jsx(U,{...e["zoom-in"]}),d.jsx(U,{...e["zoom-out"]}),d.jsx($R,{}),d.jsx(NR,{}),d.jsx(FR,{})]})})}function Gse(){const e=ie();return d.jsxs(pe,{id:"extras",children:[d.jsx(U,{...e["insert-embed"]}),d.jsx(U,{...e["insert-media"]})]})}function Vse(){function e(n){window.open(n,"_blank")}return d.jsx(pe,{id:"help",children:d.jsx(En,{id:"help",label:"menu.help",children:d.jsxs(pe,{id:"help-actions",children:[d.jsx(YR,{}),d.jsx(U,{id:"about",label:"help-menu.docs",icon:"external-link",readonlyOk:!0,onSelect:()=>{e("https://tldraw.dev")}})]})})})}function Yse(){return d.jsx(pe,{id:"preferences",children:d.jsxs(En,{id:"preferences",label:"menu.preferences",children:[d.jsxs(pe,{id:"preferences-actions",children:[d.jsx(ese,{}),d.jsx(tse,{}),d.jsx(nse,{}),d.jsx(rse,{}),d.jsx(sse,{}),d.jsx(ose,{}),d.jsx(ise,{}),d.jsx(lse,{}),d.jsx(cse,{}),d.jsx(ase,{})]}),d.jsx(pe,{id:"color-scheme",children:d.jsx($se,{})}),d.jsx(pe,{id:"language",children:d.jsx(VR,{})})]})})}const Xse=P.memo(function({children:n}){const t=$t(),[r,s]=ho("main menu"),o=xe(),i=n??d.jsx(Fse,{});return d.jsxs(S1,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[d.jsx(v1,{asChild:!0,dir:"ltr",children:d.jsx(ce,{type:"icon","data-testid":"main-menu.button",title:o("menu.title"),children:d.jsx(Se,{icon:"menu",small:!0})})}),d.jsx(Kg,{container:t,children:d.jsx(x1,{className:"tlui-menu",side:"bottom",align:"start",collisionPadding:4,alignOffset:0,sideOffset:6,children:d.jsx(Tr,{type:"menu",sourceId:"main-menu",children:i})})})]})}),$y={};function dc(e){if($y[e])return $y[e];const t=document.createElement("canvas").getContext("2d");t.fillStyle=e,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 $y[e]=a,a}const mp=10,XR=4*6*mp+12+4*12;function Pa(e,{center:n,radius:t,numArcSegments:r=20,startAngle:s=0,endAngle:o=Le,offset:i=0}){const a=(o-s)/r;let l=i;for(let c=s;c`}catch(C){console.error(C)}}function h(){e.environment.isChromeForIos?(l(),window.print()):e.environment.isSafari?(l(),document.execCommand("print",!1)):window.print()}const p=e.getSelectedShapeIds(),f=e.getCurrentPageId(),S=e.getPages(),x={scale:1,background:!1,darkMode:!1,preserveAspectRatio:"xMidYMid meet"};if(e.getSelectedShapeIds().length>0){const m=await e.getSvgString(p,x);if(m){const v=S.find(w=>w.id===f);u(`tldraw — ${v==null?void 0:v.name}`,null,m.svg),h()}}else{const m=e.getCurrentPage(),v=await e.getSvgString(e.getSortedChildIdsForParent(m.id),x);v&&(u(`tldraw — ${m.name}`,null,v.svg),h())}window.removeEventListener("beforeprint",l),window.removeEventListener("afterprint",c)},[e])}const CO=P.createContext(null);function mee(e){return Object.fromEntries(e.map(n=>[n.id,n]))}function wa(e,n){if(e.getSelectedShapes().length===0)return e.getDocumentSettings().name||n}function yee({overrides:e,children:n}){const t=F(),r=Lg(),{addDialog:s,clearDialogs:o}=aa(),{clearToasts:i,addToast:a}=Qr(),l=xe(),c=fO(),u=gee(),{cut:h,copy:p,paste:f}=ree(),S=cee(),y=hee(),x=l("document.default-name"),m=qt(),v=P.useMemo(()=>{function w(){return t.isIn("select")||(t.complete(),t.setCurrentTool("select")),!1}function C(){return t.isIn("select")&&t.getSelectedShapeIds().length>0}const E=[{id:"edit-link",label:"action.edit-link",icon:"link",onSelect(I){C()&&(w()||(m("edit-link",{source:I}),t.mark("edit-link"),s({component:DJ})))}},{id:"insert-embed",label:"action.insert-embed",kbd:"$i",onSelect(I){m("insert-embed",{source:I}),s({component:pO})}},{id:"insert-media",label:"action.insert-media",kbd:"$u",onSelect(I){m("insert-media",{source:I}),c()}},{id:"undo",label:"action.undo",icon:"undo",kbd:"$z",onSelect(I){m("undo",{source:I}),t.undo()}},{id:"redo",label:"action.redo",icon:"redo",kbd:"$!z",onSelect(I){m("redo",{source:I}),t.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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("export-as",{format:"svg",source:I}),y(_,"svg",wa(t,x)))}},{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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("export-as",{format:"png",source:I}),y(_,"png",wa(t,x)))}},{id:"export-as-json",label:{default:"action.export-as-json",menu:"action.export-as-json.short","context-menu":"action.export-as-json.short"},readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("export-as",{format:"json",source:I}),y(_,"json",wa(t,x)))}},{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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("export-all-as",{format:"svg",source:I}),y(Array.from(t.getCurrentPageShapeIds()),"svg",wa(t,x)))}},{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(I){const _=Array.from(t.getCurrentPageShapeIds().values());_.length!==0&&(m("export-all-as",{format:"png",source:I}),y(_,"png",wa(t,x)))}},{id:"export-all-as-json",label:{default:"action.export-all-as-json",menu:"action.export-all-as-json.short","context-menu":"action.export-all-as-json.short"},readonlyOk:!0,onSelect(I){const _=Array.from(t.getCurrentPageShapeIds().values());_.length!==0&&(m("export-all-as",{format:"json",source:I}),y(_,"json",wa(t,x)))}},{id:"copy-as-svg",label:{default:"action.copy-as-svg",menu:"action.copy-as-svg.short","context-menu":"action.copy-as-svg.short"},kbd:"$!c",readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("copy-as",{format:"svg",source:I}),S(_,"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(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("copy-as",{format:"png",source:I}),S(_,"png"))}},{id:"copy-as-json",label:{default:"action.copy-as-json",menu:"action.copy-as-json.short","context-menu":"action.copy-as-json.short"},readonlyOk:!0,onSelect(I){let _=t.getSelectedShapeIds();_.length===0&&(_=Array.from(t.getCurrentPageShapeIds().values())),_.length!==0&&(m("copy-as",{format:"json",source:I}),S(_,"json"))}},{id:"toggle-auto-size",label:"action.toggle-auto-size",onSelect(I){if(!C()||w())return;m("toggle-auto-size",{source:I}),t.mark("toggling auto size");const _=t.getSelectedShapes().filter(T=>t.isShapeOfType(T,"text")&&T.props.autoSize===!1);t.updateShapes(_.map(T=>({id:T.id,type:T.type,props:{...T.props,w:8,autoSize:!0}}))),Ke(t,_.map(T=>T.id))}},{id:"open-embed-link",label:"action.open-embed-link",readonlyOk:!0,onSelect(I){m("open-embed-link",{source:I});const _=t.getSelectedShapeIds(),T="No embed shapes selected";if(_.length!==1){console.error(T);return}const M=t.getShape(_[0]);if(!M||!t.isShapeOfType(M,"embed")){console.error(T);return}lY(M.props.url,"_blank")}},{id:"select-zoom-tool",readonlyOk:!0,kbd:"z",onSelect(I){var _,T;if(((_=t.root.getCurrent())==null?void 0:_.id)!=="zoom"&&(m("zoom-tool",{source:I}),!(t.inputs.shiftKey||t.inputs.ctrlKey))){const M=t.root.getCurrent();M&&((T=M.getCurrent())==null?void 0:T.id)==="idle"&&t.setCurrentTool("zoom",{onInteractionEnd:M.id,maskAs:"zoom"})}}},{id:"convert-to-bookmark",label:"action.convert-to-bookmark",onSelect(I){C()&&(w()||t.run(()=>{m("convert-to-bookmark",{source:I});const _=t.getSelectedShapes(),T=[],M=[];for(const D of _){if(!D||!t.isShapeOfType(D,"embed")||!D.props.url)continue;const $=new b(D.x,D.y);$.rot(-D.rotation),$.add(new b(D.props.w/2-300/2,D.props.h/2-320/2)),$.rot(D.rotation);const j={id:je(),type:"bookmark",rotation:D.rotation,x:$.x,y:$.y,opacity:1,props:{url:D.props.url}};T.push(j),M.push(D.id)}t.mark("convert shapes to bookmark"),t.deleteShapes(M),t.createShapes(T)}))}},{id:"convert-to-embed",label:"action.convert-to-embed",onSelect(I){C()&&(w()||(m("convert-to-embed",{source:I}),t.run(()=>{const _=t.getSelectedShapeIds(),T=me(_.map($=>t.getShape($))),M=[],D=[];for(const $ of T){if(!t.isShapeOfType($,"bookmark"))continue;const{url:j}=$.props,O=Do($.props.url);if(!O||!O.definition)continue;const{width:R,height:K}=O.definition,B=new b($.x,$.y);B.rot(-$.rotation),B.add(new b($.props.w/2-R/2,$.props.h/2-K/2)),B.rot($.rotation);const z={id:je(),type:"embed",x:B.x,y:B.y,rotation:$.rotation,props:{url:j,w:R,h:K}};M.push(z),D.push($.id)}t.mark("convert shapes to embed"),t.deleteShapes(D),t.createShapes(M)})))}},{id:"duplicate",kbd:"$d",label:"action.duplicate",icon:"duplicate",onSelect(I){if(!C()||w())return;m("duplicate-shapes",{source:I});const _=t.getInstanceState();let T,M;if(_.duplicateProps)T=_.duplicateProps.shapeIds,M=_.duplicateProps.offset;else{T=t.getSelectedShapeIds();const D=Q.Common(me(T.map($=>t.getShapePageBounds($))));M=t.getCameraOptions().isLocked?{x:t.options.adjacentShapeMargin,y:t.options.adjacentShapeMargin}:{x:D.width+t.options.adjacentShapeMargin,y:0}}t.mark("duplicate shapes"),t.duplicateShapes(T,M),_.duplicateProps&&t.updateInstanceState({duplicateProps:{..._.duplicateProps,shapeIds:t.getSelectedShapeIds()}})}},{id:"ungroup",label:"action.ungroup",kbd:"$!g",icon:"ungroup",onSelect(I){C()&&(w()||(m("ungroup-shapes",{source:I}),t.mark("ungroup"),t.ungroupShapes(t.getSelectedShapeIds())))}},{id:"group",label:"action.group",kbd:"$g",icon:"group",onSelect(I){if(!C()||w())return;m("group-shapes",{source:I});const _=t.getOnlySelectedShape();_&&t.isShapeOfType(_,"group")?(t.mark("ungroup"),t.ungroupShapes(t.getSelectedShapeIds())):(t.mark("group"),t.groupShapes(t.getSelectedShapeIds()))}},{id:"remove-frame",label:"action.remove-frame",kbd:"$!f",onSelect(I){if(!C())return;m("remove-frame",{source:I});const _=t.getSelectedShapes();_.length>0&&_.every(T=>t.isShapeOfType(T,"frame"))&&(t.mark("remove-frame"),AJ(t,_.map(T=>T.id)))}},{id:"fit-frame-to-content",label:"action.fit-frame-to-content",onSelect(I){if(!C())return;m("fit-frame-to-content",{source:I});const _=t.getOnlySelectedShape();_&&t.isShapeOfType(_,"frame")&&(t.mark("fit-frame-to-content"),OJ(t,_.id))}},{id:"align-left",label:"action.align-left",kbd:"?A",icon:"align-left",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"left",source:I}),t.mark("align left");const _=t.getSelectedShapeIds();t.alignShapes(_,"left"),Ke(t,_)}},{id:"align-center-horizontal",label:{default:"action.align-center-horizontal","context-menu":"action.align-center-horizontal.short"},kbd:"?H",icon:"align-center-horizontal",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"center-horizontal",source:I}),t.mark("align center horizontal");const _=t.getSelectedShapeIds();t.alignShapes(_,"center-horizontal"),Ke(t,_)}},{id:"align-right",label:"action.align-right",kbd:"?D",icon:"align-right",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"right",source:I}),t.mark("align right");const _=t.getSelectedShapeIds();t.alignShapes(_,"right"),Ke(t,_)}},{id:"align-center-vertical",label:{default:"action.align-center-vertical","context-menu":"action.align-center-vertical.short"},kbd:"?V",icon:"align-center-vertical",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"center-vertical",source:I}),t.mark("align center vertical");const _=t.getSelectedShapeIds();t.alignShapes(_,"center-vertical"),Ke(t,_)}},{id:"align-top",label:"action.align-top",icon:"align-top",kbd:"?W",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"top",source:I}),t.mark("align top");const _=t.getSelectedShapeIds();t.alignShapes(_,"top"),Ke(t,_)}},{id:"align-bottom",label:"action.align-bottom",icon:"align-bottom",kbd:"?S",onSelect(I){if(!C()||w())return;m("align-shapes",{operation:"bottom",source:I}),t.mark("align bottom");const _=t.getSelectedShapeIds();t.alignShapes(_,"bottom"),Ke(t,_)}},{id:"distribute-horizontal",label:{default:"action.distribute-horizontal","context-menu":"action.distribute-horizontal.short"},icon:"distribute-horizontal",kbd:"?!h",onSelect(I){if(!C()||w())return;m("distribute-shapes",{operation:"horizontal",source:I}),t.mark("distribute horizontal");const _=t.getSelectedShapeIds();t.distributeShapes(_,"horizontal"),Ke(t,_)}},{id:"distribute-vertical",label:{default:"action.distribute-vertical","context-menu":"action.distribute-vertical.short"},icon:"distribute-vertical",kbd:"?!V",onSelect(I){if(!C()||w())return;m("distribute-shapes",{operation:"vertical",source:I}),t.mark("distribute vertical");const _=t.getSelectedShapeIds();t.distributeShapes(_,"vertical"),Ke(t,_)}},{id:"stretch-horizontal",label:{default:"action.stretch-horizontal","context-menu":"action.stretch-horizontal.short"},icon:"stretch-horizontal",onSelect(I){if(!C()||w())return;m("stretch-shapes",{operation:"horizontal",source:I}),t.mark("stretch horizontal");const _=t.getSelectedShapeIds();t.stretchShapes(_,"horizontal"),Ke(t,_)}},{id:"stretch-vertical",label:{default:"action.stretch-vertical","context-menu":"action.stretch-vertical.short"},icon:"stretch-vertical",onSelect(I){if(!C()||w())return;m("stretch-shapes",{operation:"vertical",source:I}),t.mark("stretch vertical");const _=t.getSelectedShapeIds();t.stretchShapes(_,"vertical"),Ke(t,_)}},{id:"flip-horizontal",label:{default:"action.flip-horizontal","context-menu":"action.flip-horizontal.short"},kbd:"!h",onSelect(I){if(!C()||w())return;m("flip-shapes",{operation:"horizontal",source:I}),t.mark("flip horizontal");const _=t.getSelectedShapeIds();t.flipShapes(_,"horizontal"),Ke(t,_)}},{id:"flip-vertical",label:{default:"action.flip-vertical","context-menu":"action.flip-vertical.short"},kbd:"!v",onSelect(I){if(!C()||w())return;m("flip-shapes",{operation:"vertical",source:I}),t.mark("flip vertical");const _=t.getSelectedShapeIds();t.flipShapes(_,"vertical"),Ke(t,_)}},{id:"pack",label:"action.pack",icon:"pack",onSelect(I){if(!C()||w())return;m("pack-shapes",{source:I}),t.mark("pack");const _=t.getSelectedShapeIds();t.packShapes(_,t.options.adjacentShapeMargin),Ke(t,_)}},{id:"stack-vertical",label:{default:"action.stack-vertical","context-menu":"action.stack-vertical.short"},icon:"stack-vertical",onSelect(I){if(!C()||w())return;m("stack-shapes",{operation:"vertical",source:I}),t.mark("stack-vertical");const _=t.getSelectedShapeIds();t.stackShapes(_,"vertical",16),Ke(t,_)}},{id:"stack-horizontal",label:{default:"action.stack-horizontal","context-menu":"action.stack-horizontal.short"},icon:"stack-horizontal",onSelect(I){if(!C()||w())return;m("stack-shapes",{operation:"horizontal",source:I}),t.mark("stack-horizontal");const _=t.getSelectedShapeIds();t.stackShapes(_,"horizontal",16),Ke(t,_)}},{id:"bring-to-front",label:"action.bring-to-front",kbd:"]",icon:"bring-to-front",onSelect(I){C()&&(w()||(m("reorder-shapes",{operation:"toFront",source:I}),t.mark("bring to front"),t.bringToFront(t.getSelectedShapeIds())))}},{id:"bring-forward",label:"action.bring-forward",icon:"bring-forward",kbd:"?]",onSelect(I){C()&&(w()||(m("reorder-shapes",{operation:"forward",source:I}),t.mark("bring forward"),t.bringForward(t.getSelectedShapeIds())))}},{id:"send-backward",label:"action.send-backward",icon:"send-backward",kbd:"?[",onSelect(I){C()&&(w()||(m("reorder-shapes",{operation:"backward",source:I}),t.mark("send backward"),t.sendBackward(t.getSelectedShapeIds())))}},{id:"send-to-back",label:"action.send-to-back",icon:"send-to-back",kbd:"[",onSelect(I){C()&&(w()||(m("reorder-shapes",{operation:"toBack",source:I}),t.mark("send to back"),t.sendToBack(t.getSelectedShapeIds())))}},{id:"cut",label:"action.cut",kbd:"$x",onSelect(I){C()&&(w()||(t.mark("cut"),h(I)))}},{id:"copy",label:"action.copy",kbd:"$c",readonlyOk:!0,onSelect(I){C()&&(w()||p(I))}},{id:"paste",label:"action.paste",kbd:"$v",onSelect(I){var _;(_=navigator.clipboard)==null||_.read().then(T=>{f(T,I,I==="context-menu"?t.inputs.currentPagePoint:void 0)}).catch(()=>{a({title:l("action.paste-error-title"),description:l("action.paste-error-description"),severity:"error"})})}},{id:"select-all",label:"action.select-all",kbd:"$a",readonlyOk:!0,onSelect(I){t.run(()=>{w()||(m("select-all-shapes",{source:I}),t.mark("select all kbd"),t.selectAll())})}},{id:"select-none",label:"action.select-none",readonlyOk:!0,onSelect(I){C()&&(w()||(m("select-none-shapes",{source:I}),t.mark("select none"),t.selectNone()))}},{id:"delete",label:"action.delete",kbd:"⌫,del,backspace",icon:"trash",onSelect(I){C()&&(w()||(m("delete-shapes",{source:I}),t.mark("delete"),t.deleteShapes(t.getSelectedShapeIds())))}},{id:"rotate-cw",label:"action.rotate-cw",icon:"rotate-cw",onSelect(I){if(!C()||w())return;m("rotate-cw",{source:I}),t.mark("rotate-cw");const _=t.getSelectionRotation()%(Ve/2),T=Wo(_,0)||Wo(_,Ve/2),M=t.getSelectedShapeIds();t.rotateShapesBy(M,Ve/2-(T?0:_)),Ke(t,M)}},{id:"rotate-ccw",label:"action.rotate-ccw",icon:"rotate-ccw",onSelect(I){if(!C()||w())return;m("rotate-ccw",{source:I}),t.mark("rotate-ccw");const _=t.getSelectionRotation()%(Ve/2),T=Wo(_,0),M=t.getSelectedShapeIds();t.rotateShapesBy(M,T?-(Ve/2):-_),Ke(t,M)}},{id:"zoom-in",label:"action.zoom-in",kbd:"$=,=",readonlyOk:!0,onSelect(I){m("zoom-in",{source:I}),t.zoomIn(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-out",label:"action.zoom-out",kbd:"$-,-",readonlyOk:!0,onSelect(I){m("zoom-out",{source:I}),t.zoomOut(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-100",label:"action.zoom-to-100",icon:"reset-zoom",kbd:"!0",readonlyOk:!0,onSelect(I){m("reset-zoom",{source:I}),t.resetZoom(void 0,{animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-fit",label:"action.zoom-to-fit",kbd:"!1",readonlyOk:!0,onSelect(I){m("zoom-to-fit",{source:I}),t.zoomToFit({animation:{duration:t.options.animationMediumMs}})}},{id:"zoom-to-selection",label:"action.zoom-to-selection",kbd:"!2",readonlyOk:!0,onSelect(I){C()&&(w()||(m("zoom-to-selection",{source:I}),t.zoomToSelection({animation:{duration:t.options.animationMediumMs}})))}},{id:"toggle-snap-mode",label:{default:"action.toggle-snap-mode",menu:"action.toggle-snap-mode.menu"},onSelect(I){m("toggle-snap-mode",{source:I}),t.user.updateUserPreferences({isSnapMode:!t.user.getIsSnapMode()})},checkbox:!0},{id:"toggle-dark-mode",label:{default:"action.toggle-dark-mode",menu:"action.toggle-dark-mode.menu"},kbd:"$/",readonlyOk:!0,onSelect(I){const _=t.user.getIsDarkMode()?"light":"dark";m("color-scheme",{source:I,value:_}),t.user.updateUserPreferences({colorScheme:_})},checkbox:!0},{id:"toggle-wrap-mode",label:{default:"action.toggle-wrap-mode",menu:"action.toggle-wrap-mode.menu"},readonlyOk:!0,onSelect(I){m("toggle-wrap-mode",{source:I}),t.user.updateUserPreferences({isWrapMode:!t.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(I){m("toggle-dynamic-size-mode",{source:I}),t.user.updateUserPreferences({isDynamicSizeMode:!t.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(I){m("toggle-paste-at-cursor",{source:I}),t.user.updateUserPreferences({isPasteAtCursorMode:!t.user.getIsPasteAtCursorMode()})},checkbox:!0},{id:"toggle-reduce-motion",label:{default:"action.toggle-reduce-motion",menu:"action.toggle-reduce-motion.menu"},readonlyOk:!0,onSelect(I){m("toggle-reduce-motion",{source:I}),t.user.updateUserPreferences({animationSpeed:t.user.getAnimationSpeed()===0?1:0})},checkbox:!0},{id:"toggle-edge-scrolling",label:{default:"action.toggle-edge-scrolling",menu:"action.toggle-edge-scrolling.menu"},readonlyOk:!0,onSelect(I){m("toggle-edge-scrolling",{source:I}),t.user.updateUserPreferences({edgeScrollSpeed:t.user.getEdgeScrollSpeed()===0?1:0})},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(I){m("toggle-transparent",{source:I}),t.updateInstanceState({exportBackground:!t.getInstanceState().exportBackground})},checkbox:!0},{id:"toggle-tool-lock",label:{default:"action.toggle-tool-lock",menu:"action.toggle-tool-lock.menu"},kbd:"q",onSelect(I){m("toggle-tool-lock",{source:I}),t.updateInstanceState({isToolLocked:!t.getInstanceState().isToolLocked})},checkbox:!0},{id:"unlock-all",label:"action.unlock-all",onSelect(I){m("unlock-all",{source:I});const _=[];for(const T of t.getCurrentPageShapes())T.isLocked&&_.push({id:T.id,type:T.type,isLocked:!1});_.length>0&&t.updateShapes(_)}},{id:"toggle-focus-mode",label:{default:"action.toggle-focus-mode",menu:"action.toggle-focus-mode.menu"},readonlyOk:!0,kbd:"$.",checkbox:!0,onSelect(I){t.timers.requestAnimationFrame(()=>{t.run(()=>{m("toggle-focus-mode",{source:I}),o(),i(),t.updateInstanceState({isFocusMode:!t.getInstanceState().isFocusMode})})})}},{id:"toggle-grid",label:{default:"action.toggle-grid",menu:"action.toggle-grid.menu"},readonlyOk:!0,kbd:"$'",onSelect(I){m("toggle-grid-mode",{source:I}),t.updateInstanceState({isGridMode:!t.getInstanceState().isGridMode})},checkbox:!0},{id:"toggle-debug-mode",label:{default:"action.toggle-debug-mode",menu:"action.toggle-debug-mode.menu"},readonlyOk:!0,onSelect(I){m("toggle-debug-mode",{source:I}),t.updateInstanceState({isDebugMode:!t.getInstanceState().isDebugMode})},checkbox:!0},{id:"print",label:"action.print",kbd:"$p",readonlyOk:!0,onSelect(I){m("print",{source:I}),u()}},{id:"exit-pen-mode",label:"action.exit-pen-mode",icon:"cross-2",readonlyOk:!0,onSelect(I){m("exit-pen-mode",{source:I}),t.updateInstanceState({isPenMode:!1})}},{id:"stop-following",label:"action.stop-following",icon:"cross-2",readonlyOk:!0,onSelect(I){m("stop-following",{source:I}),t.stopFollowingUser()}},{id:"back-to-content",label:"action.back-to-content",icon:"arrow-left",readonlyOk:!0,onSelect(I){m("zoom-to-content",{source:I});const _=t.getSelectionPageBounds()??t.getCurrentPageBounds();_&&t.zoomToBounds(_,{targetZoom:Math.min(1,t.getZoomLevel()),animation:{duration:220}})}},{id:"toggle-lock",label:"action.toggle-lock",kbd:"!l",onSelect(I){t.mark("locking"),m("toggle-lock",{source:I}),t.toggleLock(t.getSelectedShapeIds())}},{id:"move-to-new-page",label:"context.pages.new-page",onSelect(I){const _=to.createId(),T=t.getSelectedShapeIds();t.run(()=>{t.mark("move_shapes_to_page"),t.createPage({name:l("page-menu.new-page-initial-name"),id:_}),t.moveShapesToPage(T,_)}),m("move-to-new-page",{source:I})}},{id:"select-white-color",label:"color-style.white",kbd:"?t",onSelect(I){const _=lr;t.run(()=>{t.mark("change-color"),t.isIn("select")&&t.setStyleForSelectedShapes(_,"white"),t.setStyleForNextShapes(_,"white")}),m("set-style",{source:I,id:_.id,value:"white"})}},{id:"select-fill-fill",label:"fill-style.fill",kbd:"?f",onSelect(I){const _=Hi;t.run(()=>{t.mark("change-fill"),t.isIn("select")&&t.setStyleForSelectedShapes(_,"fill"),t.setStyleForNextShapes(_,"fill")}),m("set-style",{source:I,id:_.id,value:"fill"})}},{id:"flatten-to-image",label:"action.flatten-to-image",kbd:"!f",onSelect:async I=>{const _=t.getSelectedShapeIds();if(_.length===0)return;t.mark("flattening to image"),m("flatten-to-image",{source:I});const T=await pee(t,_,t.options.flattenImageBoundsExpand);T!=null&&T.length&&t.setSelectedShapes(T)}}];r&&E.push({id:"open-cursor-chat",label:"action.open-cursor-chat",readonlyOk:!0,kbd:"/",onSelect(I){m("open-cursor-chat",{source:I}),!t.getInstanceState().isCoarsePointer&&t.timers.requestAnimationFrame(()=>{t.updateInstanceState({isChatting:!0})})}});const k=mee(E);return e?e(t,k,void 0):k},[t,m,e,s,a,c,y,S,h,p,f,o,i,u,l,x,r]);return d.jsx(CO.Provider,{value:v,children:n})}function ie(){const e=P.useContext(CO);if(!e)throw new Error("useTools must be used within a ToolProvider");return e}function Iu(e,n){return e?typeof e=="string"?e:n?e[n]??e.default:void 0:void 0}const See=["top","right","bottom","left"],hs=Math.min,Qn=Math.max,If=Math.round,mh=Math.floor,Qo=e=>({x:e,y:e}),vee={left:"right",right:"left",bottom:"top",top:"bottom"},xee={start:"end",end:"start"};function Jv(e,n,t){return Qn(e,hs(n,t))}function ro(e,n){return typeof e=="function"?e(n):e}function so(e){return e.split("-")[0]}function Dl(e){return e.split("-")[1]}function Bw(e){return e==="x"?"y":"x"}function Uw(e){return e==="y"?"height":"width"}function Jo(e){return["top","bottom"].includes(so(e))?"y":"x"}function Hw(e){return Bw(Jo(e))}function wee(e,n,t){t===void 0&&(t=!1);const r=Dl(e),s=Hw(e),o=Uw(s);let i=s==="x"?r===(t?"end":"start")?"right":"left":r==="start"?"bottom":"top";return n.reference[o]>n.floating[o]&&(i=Ef(i)),[i,Ef(i)]}function bee(e){const n=Ef(e);return[ex(e),n,ex(n)]}function ex(e){return e.replace(/start|end/g,n=>xee[n])}function Pee(e,n,t){const r=["left","right"],s=["right","left"],o=["top","bottom"],i=["bottom","top"];switch(e){case"top":case"bottom":return t?n?s:r:n?r:s;case"left":case"right":return n?o:i;default:return[]}}function Cee(e,n,t,r){const s=Dl(e);let o=Pee(so(e),t==="start",r);return s&&(o=o.map(i=>i+"-"+s),n&&(o=o.concat(o.map(ex)))),o}function Ef(e){return e.replace(/left|right|bottom|top/g,n=>vee[n])}function Iee(e){return{top:0,right:0,bottom:0,left:0,...e}}function IO(e){return typeof e!="number"?Iee(e):{top:e,right:e,bottom:e,left:e}}function _f(e){const{x:n,y:t,width:r,height:s}=e;return{width:r,height:s,top:t,left:n,right:n+r,bottom:t+s,x:n,y:t}}function aE(e,n,t){let{reference:r,floating:s}=e;const o=Jo(n),i=Hw(n),a=Uw(i),l=so(n),c=o==="y",u=r.x+r.width/2-s.width/2,h=r.y+r.height/2-s.height/2,p=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:h};break;case"left":f={x:r.x-s.width,y:h};break;default:f={x:r.x,y:r.y}}switch(Dl(n)){case"start":f[i]-=p*(t&&c?-1:1);break;case"end":f[i]+=p*(t&&c?-1:1);break}return f}const Eee=async(e,n,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(n));let c=await i.getElementRects({reference:e,floating:n,strategy:s}),{x:u,y:h}=aE(c,r,l),p=r,f={},S=0;for(let y=0;y({name:"arrow",options:e,async fn(n){const{x:t,y:r,placement:s,rects:o,platform:i,elements:a,middlewareData:l}=n,{element:c,padding:u=0}=ro(e,n)||{};if(c==null)return{};const h=IO(u),p={x:t,y:r},f=Hw(s),S=Uw(f),y=await i.getDimensions(c),x=f==="y",m=x?"top":"left",v=x?"bottom":"right",w=x?"clientHeight":"clientWidth",C=o.reference[S]+o.reference[f]-p[f]-o.floating[S],E=p[f]-o.reference[f],k=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let I=k?k[w]:0;(!I||!await(i.isElement==null?void 0:i.isElement(k)))&&(I=a.floating[w]||o.floating[S]);const _=C/2-E/2,T=I/2-y[S]/2-1,M=hs(h[m],T),D=hs(h[v],T),$=M,j=I-y[S]-D,O=I/2-y[S]/2+_,R=Jv($,O,j),K=!l.arrow&&Dl(s)!=null&&O!==R&&o.reference[S]/2-(O<$?M:D)-y[S]/2<0,B=K?O<$?O-$:O-j:0;return{[f]:p[f]+B,data:{[f]:R,centerOffset:O-R-B,...K&&{alignmentOffset:B}},reset:K}}}),kee=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(n){var t,r;const{placement:s,middlewareData:o,rects:i,initialPlacement:a,platform:l,elements:c}=n,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:S="none",flipAlignment:y=!0,...x}=ro(e,n);if((t=o.arrow)!=null&&t.alignmentOffset)return{};const m=so(s),v=Jo(a),w=so(a)===a,C=await(l.isRTL==null?void 0:l.isRTL(c.floating)),E=p||(w||!y?[Ef(a)]:bee(a)),k=S!=="none";!p&&k&&E.push(...Cee(a,y,S,C));const I=[a,...E],_=await Eu(n,x),T=[];let M=((r=o.flip)==null?void 0:r.overflows)||[];if(u&&T.push(_[m]),h){const O=wee(s,i,C);T.push(_[O[0]],_[O[1]])}if(M=[...M,{placement:s,overflows:T}],!T.every(O=>O<=0)){var D,$;const O=(((D=o.flip)==null?void 0:D.index)||0)+1,R=I[O];if(R)return{data:{index:O,overflows:M},reset:{placement:R}};let K=($=M.filter(B=>B.overflows[0]<=0).sort((B,z)=>B.overflows[1]-z.overflows[1])[0])==null?void 0:$.placement;if(!K)switch(f){case"bestFit":{var j;const B=(j=M.filter(z=>{if(k){const W=Jo(z.placement);return W===v||W==="y"}return!0}).map(z=>[z.placement,z.overflows.filter(W=>W>0).reduce((W,Y)=>W+Y,0)]).sort((z,W)=>z[1]-W[1])[0])==null?void 0:j[0];B&&(K=B);break}case"initialPlacement":K=a;break}if(s!==K)return{reset:{placement:K}}}return{}}}};function lE(e,n){return{top:e.top-n.height,right:e.right-n.width,bottom:e.bottom-n.height,left:e.left-n.width}}function cE(e){return See.some(n=>e[n]>=0)}const Tee=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(n){const{rects:t}=n,{strategy:r="referenceHidden",...s}=ro(e,n);switch(r){case"referenceHidden":{const o=await Eu(n,{...s,elementContext:"reference"}),i=lE(o,t.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:cE(i)}}}case"escaped":{const o=await Eu(n,{...s,altBoundary:!0}),i=lE(o,t.floating);return{data:{escapedOffsets:i,escaped:cE(i)}}}default:return{}}}}};async function Mee(e,n){const{placement:t,platform:r,elements:s}=e,o=await(r.isRTL==null?void 0:r.isRTL(s.floating)),i=so(t),a=Dl(t),l=Jo(t)==="y",c=["left","top"].includes(i)?-1:1,u=o&&l?-1:1,h=ro(n,e);let{mainAxis:p,crossAxis:f,alignmentAxis:S}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...h};return a&&typeof S=="number"&&(f=a==="end"?S*-1:S),l?{x:f*u,y:p*c}:{x:p*c,y:f*u}}const Aee=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(n){var t,r;const{x:s,y:o,placement:i,middlewareData:a}=n,l=await Mee(n,e);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}}}}},jee=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(n){const{x:t,y:r,placement:s}=n,{mainAxis:o=!0,crossAxis:i=!1,limiter:a={fn:x=>{let{x:m,y:v}=x;return{x:m,y:v}}},...l}=ro(e,n),c={x:t,y:r},u=await Eu(n,l),h=Jo(so(s)),p=Bw(h);let f=c[p],S=c[h];if(o){const x=p==="y"?"top":"left",m=p==="y"?"bottom":"right",v=f+u[x],w=f-u[m];f=Jv(v,f,w)}if(i){const x=h==="y"?"top":"left",m=h==="y"?"bottom":"right",v=S+u[x],w=S-u[m];S=Jv(v,S,w)}const y=a.fn({...n,[p]:f,[h]:S});return{...y,data:{x:y.x-t,y:y.y-r}}}}},Oee=function(e){return e===void 0&&(e={}),{options:e,fn(n){const{x:t,y:r,placement:s,rects:o,middlewareData:i}=n,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=ro(e,n),u={x:t,y:r},h=Jo(s),p=Bw(h);let f=u[p],S=u[h];const y=ro(a,n),x=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(l){const w=p==="y"?"height":"width",C=o.reference[p]-o.floating[w]+x.mainAxis,E=o.reference[p]+o.reference[w]-x.mainAxis;fE&&(f=E)}if(c){var m,v;const w=p==="y"?"width":"height",C=["top","left"].includes(so(s)),E=o.reference[h]-o.floating[w]+(C&&((m=i.offset)==null?void 0:m[h])||0)+(C?0:x.crossAxis),k=o.reference[h]+o.reference[w]+(C?0:((v=i.offset)==null?void 0:v[h])||0)-(C?x.crossAxis:0);Sk&&(S=k)}return{[p]:f,[h]:S}}}},Dee=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(n){const{placement:t,rects:r,platform:s,elements:o}=n,{apply:i=()=>{},...a}=ro(e,n),l=await Eu(n,a),c=so(t),u=Dl(t),h=Jo(t)==="y",{width:p,height:f}=r.floating;let S,y;c==="top"||c==="bottom"?(S=c,y=u===(await(s.isRTL==null?void 0:s.isRTL(o.floating))?"start":"end")?"left":"right"):(y=c,S=u==="end"?"top":"bottom");const x=f-l.top-l.bottom,m=p-l.left-l.right,v=hs(f-l[S],x),w=hs(p-l[y],m),C=!n.middlewareData.shift;let E=v,k=w;if(h?k=u||C?hs(w,m):m:E=u||C?hs(v,x):x,C&&!u){const _=Qn(l.left,0),T=Qn(l.right,0),M=Qn(l.top,0),D=Qn(l.bottom,0);h?k=p-2*(_!==0||T!==0?_+T:Qn(l.left,l.right)):E=f-2*(M!==0||D!==0?M+D:Qn(l.top,l.bottom))}await i({...n,availableWidth:k,availableHeight:E});const I=await s.getDimensions(o.floating);return p!==I.width||f!==I.height?{reset:{rects:!0}}:{}}}};function Rl(e){return EO(e)?(e.nodeName||"").toLowerCase():"#document"}function or(e){var n;return(e==null||(n=e.ownerDocument)==null?void 0:n.defaultView)||window}function uo(e){var n;return(n=(EO(e)?e.ownerDocument:e.document)||window.document)==null?void 0:n.documentElement}function EO(e){return e instanceof Node||e instanceof or(e).Node}function Gr(e){return e instanceof Element||e instanceof or(e).Element}function Is(e){return e instanceof HTMLElement||e instanceof or(e).HTMLElement}function uE(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof or(e).ShadowRoot}function nd(e){const{overflow:n,overflowX:t,overflowY:r,display:s}=Vr(e);return/auto|scroll|overlay|hidden|clip/.test(n+r+t)&&!["inline","contents"].includes(s)}function Ree(e){return["table","td","th"].includes(Rl(e))}function $g(e){return[":popover-open",":modal"].some(n=>{try{return e.matches(n)}catch{return!1}})}function Kw(e){const n=Ww(),t=Gr(e)?Vr(e):e;return t.transform!=="none"||t.perspective!=="none"||(t.containerType?t.containerType!=="normal":!1)||!n&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!n&&(t.filter?t.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(t.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(t.contain||"").includes(r))}function Lee(e){let n=ei(e);for(;Is(n)&&!xl(n);){if(Kw(n))return n;if($g(n))return null;n=ei(n)}return null}function Ww(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function xl(e){return["html","body","#document"].includes(Rl(e))}function Vr(e){return or(e).getComputedStyle(e)}function Ng(e){return Gr(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function ei(e){if(Rl(e)==="html")return e;const n=e.assignedSlot||e.parentNode||uE(e)&&e.host||uo(e);return uE(n)?n.host:n}function _O(e){const n=ei(e);return xl(n)?e.ownerDocument?e.ownerDocument.body:e.body:Is(n)&&nd(n)?n:_O(n)}function _u(e,n,t){var r;n===void 0&&(n=[]),t===void 0&&(t=!0);const s=_O(e),o=s===((r=e.ownerDocument)==null?void 0:r.body),i=or(s);if(o){const a=tx(i);return n.concat(i,i.visualViewport||[],nd(s)?s:[],a&&t?_u(a):[])}return n.concat(s,_u(s,[],t))}function tx(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function kO(e){const n=Vr(e);let t=parseFloat(n.width)||0,r=parseFloat(n.height)||0;const s=Is(e),o=s?e.offsetWidth:t,i=s?e.offsetHeight:r,a=If(t)!==o||If(r)!==i;return a&&(t=o,r=i),{width:t,height:r,$:a}}function Gw(e){return Gr(e)?e:e.contextElement}function sl(e){const n=Gw(e);if(!Is(n))return Qo(1);const t=n.getBoundingClientRect(),{width:r,height:s,$:o}=kO(n);let i=(o?If(t.width):t.width)/r,a=(o?If(t.height):t.height)/s;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const $ee=Qo(0);function TO(e){const n=or(e);return!Ww()||!n.visualViewport?$ee:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Nee(e,n,t){return n===void 0&&(n=!1),!t||n&&t!==or(e)?!1:n}function Xi(e,n,t,r){n===void 0&&(n=!1),t===void 0&&(t=!1);const s=e.getBoundingClientRect(),o=Gw(e);let i=Qo(1);n&&(r?Gr(r)&&(i=sl(r)):i=sl(e));const a=Nee(o,t,r)?TO(o):Qo(0);let l=(s.left+a.x)/i.x,c=(s.top+a.y)/i.y,u=s.width/i.x,h=s.height/i.y;if(o){const p=or(o),f=r&&Gr(r)?or(r):r;let S=p,y=tx(S);for(;y&&r&&f!==S;){const x=sl(y),m=y.getBoundingClientRect(),v=Vr(y),w=m.left+(y.clientLeft+parseFloat(v.paddingLeft))*x.x,C=m.top+(y.clientTop+parseFloat(v.paddingTop))*x.y;l*=x.x,c*=x.y,u*=x.x,h*=x.y,l+=w,c+=C,S=or(y),y=tx(S)}}return _f({width:u,height:h,x:l,y:c})}function Fee(e){let{elements:n,rect:t,offsetParent:r,strategy:s}=e;const o=s==="fixed",i=uo(r),a=n?$g(n.floating):!1;if(r===i||a&&o)return t;let l={scrollLeft:0,scrollTop:0},c=Qo(1);const u=Qo(0),h=Is(r);if((h||!h&&!o)&&((Rl(r)!=="body"||nd(i))&&(l=Ng(r)),Is(r))){const p=Xi(r);c=sl(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}return{width:t.width*c.x,height:t.height*c.y,x:t.x*c.x-l.scrollLeft*c.x+u.x,y:t.y*c.y-l.scrollTop*c.y+u.y}}function zee(e){return Array.from(e.getClientRects())}function MO(e){return Xi(uo(e)).left+Ng(e).scrollLeft}function Bee(e){const n=uo(e),t=Ng(e),r=e.ownerDocument.body,s=Qn(n.scrollWidth,n.clientWidth,r.scrollWidth,r.clientWidth),o=Qn(n.scrollHeight,n.clientHeight,r.scrollHeight,r.clientHeight);let i=-t.scrollLeft+MO(e);const a=-t.scrollTop;return Vr(r).direction==="rtl"&&(i+=Qn(n.clientWidth,r.clientWidth)-s),{width:s,height:o,x:i,y:a}}function Uee(e,n){const t=or(e),r=uo(e),s=t.visualViewport;let o=r.clientWidth,i=r.clientHeight,a=0,l=0;if(s){o=s.width,i=s.height;const c=Ww();(!c||c&&n==="fixed")&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:i,x:a,y:l}}function Hee(e,n){const t=Xi(e,!0,n==="fixed"),r=t.top+e.clientTop,s=t.left+e.clientLeft,o=Is(e)?sl(e):Qo(1),i=e.clientWidth*o.x,a=e.clientHeight*o.y,l=s*o.x,c=r*o.y;return{width:i,height:a,x:l,y:c}}function dE(e,n,t){let r;if(n==="viewport")r=Uee(e,t);else if(n==="document")r=Bee(uo(e));else if(Gr(n))r=Hee(n,t);else{const s=TO(e);r={...n,x:n.x-s.x,y:n.y-s.y}}return _f(r)}function AO(e,n){const t=ei(e);return t===n||!Gr(t)||xl(t)?!1:Vr(t).position==="fixed"||AO(t,n)}function Kee(e,n){const t=n.get(e);if(t)return t;let r=_u(e,[],!1).filter(a=>Gr(a)&&Rl(a)!=="body"),s=null;const o=Vr(e).position==="fixed";let i=o?ei(e):e;for(;Gr(i)&&!xl(i);){const a=Vr(i),l=Kw(i);!l&&a.position==="fixed"&&(s=null),(o?!l&&!s:!l&&a.position==="static"&&!!s&&["absolute","fixed"].includes(s.position)||nd(i)&&!l&&AO(e,i))?r=r.filter(u=>u!==i):s=a,i=ei(i)}return n.set(e,r),r}function Wee(e){let{element:n,boundary:t,rootBoundary:r,strategy:s}=e;const i=[...t==="clippingAncestors"?$g(n)?[]:Kee(n,this._c):[].concat(t),r],a=i[0],l=i.reduce((c,u)=>{const h=dE(n,u,s);return c.top=Qn(h.top,c.top),c.right=hs(h.right,c.right),c.bottom=hs(h.bottom,c.bottom),c.left=Qn(h.left,c.left),c},dE(n,a,s));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function Gee(e){const{width:n,height:t}=kO(e);return{width:n,height:t}}function Vee(e,n,t){const r=Is(n),s=uo(n),o=t==="fixed",i=Xi(e,!0,o,n);let a={scrollLeft:0,scrollTop:0};const l=Qo(0);if(r||!r&&!o)if((Rl(n)!=="body"||nd(s))&&(a=Ng(n)),r){const h=Xi(n,!0,o,n);l.x=h.x+n.clientLeft,l.y=h.y+n.clientTop}else s&&(l.x=MO(s));const c=i.left+a.scrollLeft-l.x,u=i.top+a.scrollTop-l.y;return{x:c,y:u,width:i.width,height:i.height}}function Ry(e){return Vr(e).position==="static"}function hE(e,n){return!Is(e)||Vr(e).position==="fixed"?null:n?n(e):e.offsetParent}function jO(e,n){const t=or(e);if($g(e))return t;if(!Is(e)){let s=ei(e);for(;s&&!xl(s);){if(Gr(s)&&!Ry(s))return s;s=ei(s)}return t}let r=hE(e,n);for(;r&&Ree(r)&&Ry(r);)r=hE(r,n);return r&&xl(r)&&Ry(r)&&!Kw(r)?t:r||Lee(e)||t}const Yee=async function(e){const n=this.getOffsetParent||jO,t=this.getDimensions,r=await t(e.floating);return{reference:Vee(e.reference,await n(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Xee(e){return Vr(e).direction==="rtl"}const qee={convertOffsetParentRelativeRectToViewportRelativeRect:Fee,getDocumentElement:uo,getClippingRect:Wee,getOffsetParent:jO,getElementRects:Yee,getClientRects:zee,getDimensions:Gee,getScale:sl,isElement:Gr,isRTL:Xee};function Zee(e,n){let t=null,r;const s=uo(e);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{left:c,top:u,width:h,height:p}=e.getBoundingClientRect();if(a||n(),!h||!p)return;const f=mh(u),S=mh(s.clientWidth-(c+h)),y=mh(s.clientHeight-(u+p)),x=mh(c),v={rootMargin:-f+"px "+-S+"px "+-y+"px "+-x+"px",threshold:Qn(0,hs(1,l))||1};let w=!0;function C(E){const k=E[0].intersectionRatio;if(k!==l){if(!w)return i();k?i(!1,k):r=setTimeout(()=>{i(!1,1e-7)},1e3)}w=!1}try{t=new IntersectionObserver(C,{...v,root:s.ownerDocument})}catch{t=new IntersectionObserver(C,v)}t.observe(e)}return i(!0),o}function Qee(e,n,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=Gw(e),u=s||o?[...c?_u(c):[],..._u(n)]:[];u.forEach(m=>{s&&m.addEventListener("scroll",t,{passive:!0}),o&&m.addEventListener("resize",t)});const h=c&&a?Zee(c,t):null;let p=-1,f=null;i&&(f=new ResizeObserver(m=>{let[v]=m;v&&v.target===c&&f&&(f.unobserve(n),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(n)})),t()}),c&&!l&&f.observe(c),f.observe(n));let S,y=l?Xi(e):null;l&&x();function x(){const m=Xi(e);y&&(m.x!==y.x||m.y!==y.y||m.width!==y.width||m.height!==y.height)&&t(),y=m,S=requestAnimationFrame(x)}return t(),()=>{var m;u.forEach(v=>{s&&v.removeEventListener("scroll",t),o&&v.removeEventListener("resize",t)}),h==null||h(),(m=f)==null||m.disconnect(),f=null,l&&cancelAnimationFrame(S)}}const Jee=Aee,ete=jee,tte=kee,nte=Dee,rte=Tee,pE=_ee,ste=Oee,ote=(e,n,t)=>{const r=new Map,s={platform:qee,...t},o={...s.platform,_c:r};return Eee(e,n,{...s,platform:o})};var gp=typeof document<"u"?P.useLayoutEffect:P.useEffect;function kf(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(typeof e=="function"&&e.toString()===n.toString())return!0;let t,r,s;if(e&&n&&typeof e=="object"){if(Array.isArray(e)){if(t=e.length,t!==n.length)return!1;for(r=t;r--!==0;)if(!kf(e[r],n[r]))return!1;return!0}if(s=Object.keys(e),t=s.length,t!==Object.keys(n).length)return!1;for(r=t;r--!==0;)if(!{}.hasOwnProperty.call(n,s[r]))return!1;for(r=t;r--!==0;){const o=s[r];if(!(o==="_owner"&&e.$$typeof)&&!kf(e[o],n[o]))return!1}return!0}return e!==e&&n!==n}function OO(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function fE(e,n){const t=OO(e);return Math.round(n*t)/t}function gE(e){const n=P.useRef(e);return gp(()=>{n.current=e}),n}function ite(e){e===void 0&&(e={});const{placement:n="bottom",strategy:t="absolute",middleware:r=[],platform:s,elements:{reference:o,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=e,[u,h]=P.useState({x:0,y:0,strategy:t,placement:n,middlewareData:{},isPositioned:!1}),[p,f]=P.useState(r);kf(p,r)||f(r);const[S,y]=P.useState(null),[x,m]=P.useState(null),v=P.useCallback(B=>{B!==k.current&&(k.current=B,y(B))},[]),w=P.useCallback(B=>{B!==I.current&&(I.current=B,m(B))},[]),C=o||S,E=i||x,k=P.useRef(null),I=P.useRef(null),_=P.useRef(u),T=l!=null,M=gE(l),D=gE(s),$=P.useCallback(()=>{if(!k.current||!I.current)return;const B={placement:n,strategy:t,middleware:p};D.current&&(B.platform=D.current),ote(k.current,I.current,B).then(z=>{const W={...z,isPositioned:!0};j.current&&!kf(_.current,W)&&(_.current=W,ta.flushSync(()=>{h(W)}))})},[p,n,t,D]);gp(()=>{c===!1&&_.current.isPositioned&&(_.current.isPositioned=!1,h(B=>({...B,isPositioned:!1})))},[c]);const j=P.useRef(!1);gp(()=>(j.current=!0,()=>{j.current=!1}),[]),gp(()=>{if(C&&(k.current=C),E&&(I.current=E),C&&E){if(M.current)return M.current(C,E,$);$()}},[C,E,$,M,T]);const O=P.useMemo(()=>({reference:k,floating:I,setReference:v,setFloating:w}),[v,w]),R=P.useMemo(()=>({reference:C,floating:E}),[C,E]),K=P.useMemo(()=>{const B={position:t,left:0,top:0};if(!R.floating)return B;const z=fE(R.floating,u.x),W=fE(R.floating,u.y);return a?{...B,transform:"translate("+z+"px, "+W+"px)",...OO(R.floating)>=1.5&&{willChange:"transform"}}:{position:t,left:z,top:W}},[t,a,R.floating,u.x,u.y]);return P.useMemo(()=>({...u,update:$,refs:O,elements:R,floatingStyles:K}),[u,$,O,R,K])}const ate=e=>{function n(t){return{}.hasOwnProperty.call(t,"current")}return{name:"arrow",options:e,fn(t){const{element:r,padding:s}=typeof e=="function"?e(t):e;return r&&n(r)?r.current!=null?pE({element:r.current,padding:s}).fn(t):{}:r?pE({element:r,padding:s}).fn(t):{}}}},lte=(e,n)=>({...Jee(e),options:[e,n]}),cte=(e,n)=>({...ete(e),options:[e,n]}),ute=(e,n)=>({...ste(e),options:[e,n]}),dte=(e,n)=>({...tte(e),options:[e,n]}),hte=(e,n)=>({...nte(e),options:[e,n]}),pte=(e,n)=>({...rte(e),options:[e,n]}),fte=(e,n)=>({...ate(e),options:[e,n]});var gte="Arrow",DO=P.forwardRef((e,n)=>{const{children:t,width:r=10,height:s=5,...o}=e;return d.jsx(_e.svg,{...o,ref:n,width:r,height:s,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?t:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});DO.displayName=gte;var mte=DO;function RO(e){const[n,t]=P.useState(void 0);return Zo(()=>{if(e){t({width:e.offsetWidth,height:e.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=e.offsetWidth,a=e.offsetHeight;t({width:i,height:a})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else t(void 0)},[e]),n}var Vw="Popper",[LO,Fg]=Ts(Vw),[yte,$O]=LO(Vw),NO=e=>{const{__scopePopper:n,children:t}=e,[r,s]=P.useState(null);return d.jsx(yte,{scope:n,anchor:r,onAnchorChange:s,children:t})};NO.displayName=Vw;var FO="PopperAnchor",zO=P.forwardRef((e,n)=>{const{__scopePopper:t,virtualRef:r,...s}=e,o=$O(FO,t),i=P.useRef(null),a=Xe(n,i);return P.useEffect(()=>{o.onAnchorChange((r==null?void 0:r.current)||i.current)}),r?null:d.jsx(_e.div,{...s,ref:a})});zO.displayName=FO;var Yw="PopperContent",[Ste,vte]=LO(Yw),BO=P.forwardRef((e,n)=>{var Oe,tt,Ae,ot,Ne,Vn;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:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:S,...y}=e,x=$O(Yw,t),[m,v]=P.useState(null),w=Xe(n,Nt=>v(Nt)),[C,E]=P.useState(null),k=RO(C),I=(k==null?void 0:k.width)??0,_=(k==null?void 0:k.height)??0,T=r+(o!=="center"?"-"+o:""),M=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},D=Array.isArray(c)?c:[c],$=D.length>0,j={padding:M,boundary:D.filter(wte),altBoundary:$},{refs:O,floatingStyles:R,placement:K,isPositioned:B,middlewareData:z}=ite({strategy:"fixed",placement:T,whileElementsMounted:(...Nt)=>Qee(...Nt,{animationFrame:f==="always"}),elements:{reference:x.anchor},middleware:[lte({mainAxis:s+_,alignmentAxis:i}),l&&cte({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?ute():void 0,...j}),l&&dte({...j}),hte({...j,apply:({elements:Nt,rects:_n,availableWidth:St,availableHeight:Zt})=>{const{width:Ms,height:$l}=_n.reference,go=Nt.floating.style;go.setProperty("--radix-popper-available-width",`${St}px`),go.setProperty("--radix-popper-available-height",`${Zt}px`),go.setProperty("--radix-popper-anchor-width",`${Ms}px`),go.setProperty("--radix-popper-anchor-height",`${$l}px`)}}),C&&fte({element:C,padding:a}),bte({arrowWidth:I,arrowHeight:_}),p&&pte({strategy:"referenceHidden",...j})]}),[W,Y]=KO(K),q=Yt(S);Zo(()=>{B&&(q==null||q())},[B,q]);const ae=(Oe=z.arrow)==null?void 0:Oe.x,fe=(tt=z.arrow)==null?void 0:tt.y,we=((Ae=z.arrow)==null?void 0:Ae.centerOffset)!==0,[J,Ue]=P.useState();return Zo(()=>{m&&Ue(window.getComputedStyle(m).zIndex)},[m]),d.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...R,transform:B?R.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[(ot=z.transformOrigin)==null?void 0:ot.x,(Ne=z.transformOrigin)==null?void 0:Ne.y].join(" "),...((Vn=z.hide)==null?void 0:Vn.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:d.jsx(Ste,{scope:t,placedSide:W,onArrowChange:E,arrowX:ae,arrowY:fe,shouldHideArrow:we,children:d.jsx(_e.div,{"data-side":W,"data-align":Y,...y,ref:w,style:{...y.style,animation:B?void 0:"none"}})})})});BO.displayName=Yw;var UO="PopperArrow",xte={top:"bottom",right:"left",bottom:"top",left:"right"},HO=P.forwardRef(function(n,t){const{__scopePopper:r,...s}=n,o=vte(UO,r),i=xte[o.placedSide];return d.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:d.jsx(mte,{...s,ref:t,style:{...s.style,display:"block"}})})});HO.displayName=UO;function wte(e){return e!==null}var bte=e=>({name:"transformOrigin",options:e,fn(n){var x,m,v;const{placement:t,rects:r,middlewareData:s}=n,i=((x=s.arrow)==null?void 0:x.centerOffset)!==0,a=i?0:e.arrowWidth,l=i?0:e.arrowHeight,[c,u]=KO(t),h={start:"0%",center:"50%",end:"100%"}[u],p=(((m=s.arrow)==null?void 0:m.x)??0)+a/2,f=(((v=s.arrow)==null?void 0:v.y)??0)+l/2;let S="",y="";return c==="bottom"?(S=i?h:`${p}px`,y=`${-l}px`):c==="top"?(S=i?h:`${p}px`,y=`${r.floating.height+l}px`):c==="right"?(S=`${-l}px`,y=i?h:`${f}px`):c==="left"&&(S=`${r.floating.width+l}px`,y=i?h:`${f}px`),{data:{x:S,y}}}});function KO(e){const[n,t="center"]=e.split("-");return[n,t]}var Xw=NO,qw=zO,WO=BO,GO=HO,Zw="Popover",[VO,Rae]=Ts(Zw,[Fg]),rd=Fg(),[Pte,ui]=VO(Zw),YO=e=>{const{__scopePopover:n,children:t,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=e,a=rd(n),l=P.useRef(null),[c,u]=P.useState(!1),[h=!1,p]=ci({prop:r,defaultProp:s,onChange:o});return d.jsx(Xw,{...a,children:d.jsx(Pte,{scope:n,contentId:Xs(),triggerRef:l,open:h,onOpenChange:p,onOpenToggle:P.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:c,onCustomAnchorAdd:P.useCallback(()=>u(!0),[]),onCustomAnchorRemove:P.useCallback(()=>u(!1),[]),modal:i,children:t})})};YO.displayName=Zw;var XO="PopoverAnchor",Cte=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(XO,t),o=rd(t),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return P.useEffect(()=>(i(),()=>a()),[i,a]),d.jsx(qw,{...o,...r,ref:n})});Cte.displayName=XO;var qO="PopoverTrigger",ZO=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(qO,t),o=rd(t),i=Xe(n,s.triggerRef),a=d.jsx(_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":nD(s.open),...r,ref:i,onClick:re(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:d.jsx(qw,{asChild:!0,...o,children:a})});ZO.displayName=qO;var Qw="PopoverPortal",[Ite,Ete]=VO(Qw,{forceMount:void 0}),QO=e=>{const{__scopePopover:n,forceMount:t,children:r,container:s}=e,o=ui(Qw,n);return d.jsx(Ite,{scope:n,forceMount:t,children:d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:r})})})};QO.displayName=Qw;var wl="PopoverContent",JO=P.forwardRef((e,n)=>{const t=Ete(wl,e.__scopePopover),{forceMount:r=t.forceMount,...s}=e,o=ui(wl,e.__scopePopover);return d.jsx(qr,{present:r||o.open,children:o.modal?d.jsx(_te,{...s,ref:n}):d.jsx(kte,{...s,ref:n})})});JO.displayName=wl;var _te=P.forwardRef((e,n)=>{const t=ui(wl,e.__scopePopover),r=P.useRef(null),s=Xe(n,r),o=P.useRef(!1);return P.useEffect(()=>{const i=r.current;if(i)return Mw(i)},[]),d.jsx(_g,{as:Vi,allowPinchZoom:!0,children:d.jsx(eD,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:re(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=t.triggerRef.current)==null||a.focus()}),onPointerDownOutside:re(e.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:re(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),kte=P.forwardRef((e,n)=>{const t=ui(wl,e.__scopePopover),r=P.useRef(!1),s=P.useRef(!1);return d.jsx(eD,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,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=e.onInteractOutside)==null||l.call(e,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()}})}),eD=P.forwardRef((e,n)=>{const{__scopePopover:t,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...h}=e,p=ui(wl,t),f=rd(t);return Tw(),d.jsx(Ig,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:d.jsx(ed,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>p.onOpenChange(!1),children:d.jsx(WO,{"data-state":nD(p.open),role:"dialog",id:p.contentId,...f,...h,ref:n,style:{...h.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)"}})})})}),tD="PopoverClose",Tte=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=ui(tD,t);return d.jsx(_e.button,{type:"button",...r,ref:n,onClick:re(e.onClick,()=>s.onOpenChange(!1))})});Tte.displayName=tD;var Mte="PopoverArrow",Ate=P.forwardRef((e,n)=>{const{__scopePopover:t,...r}=e,s=rd(t);return d.jsx(GO,{...s,...r,ref:n})});Ate.displayName=Mte;function nD(e){return e?"open":"closed"}var Jw=YO,e1=ZO,t1=QO,n1=JO;function ho(e,n){const t=F(),r=P.useRef(!1),s=qt(),o=P.useCallback(a=>{r.current=a,t.run(()=>{a?(t.complete(),t.addOpenMenu(e)):t.updateInstanceState({openMenus:t.getOpenMenus().filter(l=>!l.startsWith(e))}),n==null||n(a)})},[t,e,n]),i=H("is menu open",()=>t.getOpenMenus().includes(e),[t,e]);return P.useEffect(()=>(r.current&&(s("open-menu",{source:"unknown",id:e}),t.addOpenMenu(e)),()=>{r.current&&(t.deleteOpenMenu(e),t.getOpenMenus().forEach(a=>{a.startsWith(e)&&(s("close-menu",{source:"unknown",id:e}),t.deleteOpenMenu(a))}),r.current=!1)}),[t,e,s]),[i,o]}function r1({id:e,children:n,onOpenChange:t,open:r}){const[s,o]=ho(e,t);return d.jsx(Jw,{onOpenChange:o,open:r||s,children:d.jsx("div",{className:"tlui-popover",children:n})})}function s1({children:e}){return d.jsx(e1,{asChild:!0,dir:"ltr",children:e})}function o1({side:e,children:n,align:t="center",sideOffset:r=8,alignOffset:s=0}){const o=$t();return d.jsx(t1,{container:o,children:d.jsx(n1,{className:"tlui-popover__content",side:e,sideOffset:r,align:t,alignOffset:s,dir:"ltr",children:n})})}const rD=P.createContext(null);function zg(){const e=P.useContext(rD);if(!e)throw new Error("useTldrawUiMenuContext must be used within a TldrawUiMenuContextProvider");return e}function Tr({type:e,sourceId:n,children:t}){return d.jsx(rD.Provider,{value:{type:e,sourceId:n},children:t})}function jte(e){return e.getSelectedShapeIds().map(r=>e.getShape(r)).filter(r=>{if(!r)return!1;if(e.isShapeOfType(r,"arrow")){const s=Rn(e,r);if(s.start||s.end)return!1}return!0})}const sD=()=>{const e=F();return H("threeStackableItems",()=>jte(e).length>2,[e])},po=()=>{const e=F();return H("isInSelectState",()=>e.isIn("select"),[e])},oD=()=>{const e=F();return H("allow group",()=>{const n=e.getSelectedShapes();if(n.length<2)return!1;for(const t of n)if(e.isShapeOfType(t,"arrow")){const r=Rn(e,t);if(r.start&&!n.some(s=>s.id===r.start.toId)||r.end&&!n.some(s=>s.id===r.end.toId))return!1}return!0},[e])},iD=()=>{const e=F();return H("allowUngroup",()=>e.getSelectedShapeIds().some(n=>{var t;return((t=e.getShape(n))==null?void 0:t.type)==="group"}),[e])},Ote=typeof window<"u"&&"navigator"in window&&!!navigator.clipboard&&!!navigator.clipboard.read;function aD(e,n){const t=F();return H("selectedShapes",()=>t.getSelectedShapes().length>=e,[t,e,n])}function In(e,n){const t=F();return H("selectedShapes",()=>{const r=t.getSelectedShapes().filter(s=>!t.isShapeOrAncestorLocked(s)).length;return e===void 0?r:r>=e},[t])}function Dte(){const e=F();return H("showAutoSizeToggle",()=>{const n=e.getSelectedShapes();return n.length===1&&e.isShapeOfType(n[0],"text")&&n[0].props.autoSize===!1},[e])}function lD(){const e=F();return H("hasLinkShapeSelected",()=>{const n=e.getOnlySelectedShape();return!!(n&&n.type!=="embed"&&"url"in n.props&&!n.isLocked)},[e])}function Rte(){const e=F();return H("onlyFlippableShape",()=>{const n=e.getOnlySelectedShape();return n&&(e.isShapeOfType(n,"group")||e.isShapeOfType(n,"image")||e.isShapeOfType(n,"arrow")||e.isShapeOfType(n,"line")||e.isShapeOfType(n,"draw"))},[e])}function cD(){const e=F();return H("useCanRedo",()=>e.getCanRedo(),[e])}function uD(){const e=F();return H("useCanUndo",()=>e.getCanUndo(),[e])}var Lte=P.createContext(void 0);function i1(e){const n=P.useContext(Lte);return e||n||"ltr"}var Ly="rovingFocusGroup.onEntryFocus",$te={bubbles:!1,cancelable:!0},Bg="RovingFocusGroup",[nx,dD,Nte]=kg(Bg),[Fte,hD]=Ts(Bg,[Nte]),[zte,Bte]=Fte(Bg),pD=P.forwardRef((e,n)=>d.jsx(nx.Provider,{scope:e.__scopeRovingFocusGroup,children:d.jsx(nx.Slot,{scope:e.__scopeRovingFocusGroup,children:d.jsx(Ute,{...e,ref:n})})}));pD.displayName=Bg;var Ute=P.forwardRef((e,n)=>{const{__scopeRovingFocusGroup:t,orientation:r,loop:s=!1,dir:o,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...h}=e,p=P.useRef(null),f=Xe(n,p),S=i1(o),[y=null,x]=ci({prop:i,defaultProp:a,onChange:l}),[m,v]=P.useState(!1),w=Yt(c),C=dD(t),E=P.useRef(!1),[k,I]=P.useState(0);return P.useEffect(()=>{const _=p.current;if(_)return _.addEventListener(Ly,w),()=>_.removeEventListener(Ly,w)},[w]),d.jsx(zte,{scope:t,orientation:r,dir:S,loop:s,currentTabStopId:y,onItemFocus:P.useCallback(_=>x(_),[x]),onItemShiftTab:P.useCallback(()=>v(!0),[]),onFocusableItemAdd:P.useCallback(()=>I(_=>_+1),[]),onFocusableItemRemove:P.useCallback(()=>I(_=>_-1),[]),children:d.jsx(_e.div,{tabIndex:m||k===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...e.style},onMouseDown:re(e.onMouseDown,()=>{E.current=!0}),onFocus:re(e.onFocus,_=>{const T=!E.current;if(_.target===_.currentTarget&&T&&!m){const M=new CustomEvent(Ly,$te);if(_.currentTarget.dispatchEvent(M),!M.defaultPrevented){const D=C().filter(K=>K.focusable),$=D.find(K=>K.active),j=D.find(K=>K.id===y),R=[$,j,...D].filter(Boolean).map(K=>K.ref.current);mD(R,u)}}E.current=!1}),onBlur:re(e.onBlur,()=>v(!1))})})}),fD="RovingFocusGroupItem",gD=P.forwardRef((e,n)=>{const{__scopeRovingFocusGroup:t,focusable:r=!0,active:s=!1,tabStopId:o,...i}=e,a=Xs(),l=o||a,c=Bte(fD,t),u=c.currentTabStopId===l,h=dD(t),{onFocusableItemAdd:p,onFocusableItemRemove:f}=c;return P.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),d.jsx(nx.ItemSlot,{scope:t,id:l,focusable:r,active:s,children:d.jsx(_e.span,{tabIndex:u?0:-1,"data-orientation":c.orientation,...i,ref:n,onMouseDown:re(e.onMouseDown,S=>{r?c.onItemFocus(l):S.preventDefault()}),onFocus:re(e.onFocus,()=>c.onItemFocus(l)),onKeyDown:re(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){c.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const y=Wte(S,c.orientation,c.dir);if(y!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let m=h().filter(v=>v.focusable).map(v=>v.ref.current);if(y==="last")m.reverse();else if(y==="prev"||y==="next"){y==="prev"&&m.reverse();const v=m.indexOf(S.currentTarget);m=c.loop?Gte(m,v+1):m.slice(v+1)}setTimeout(()=>mD(m))}})})})});gD.displayName=fD;var Hte={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Kte(e,n){return n!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Wte(e,n,t){const r=Kte(e.key,t);if(!(n==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(n==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Hte[r]}function mD(e,n=!1){const t=document.activeElement;for(const r of e)if(r===t||(r.focus({preventScroll:n}),document.activeElement!==t))return}function Gte(e,n){return e.map((t,r)=>e[(n+r)%e.length])}var Vte=pD,Yte=gD,rx=["Enter"," "],Xte=["ArrowDown","PageUp","Home"],yD=["ArrowUp","PageDown","End"],qte=[...Xte,...yD],Zte={ltr:[...rx,"ArrowRight"],rtl:[...rx,"ArrowLeft"]},Qte={ltr:["ArrowLeft"],rtl:["ArrowRight"]},sd="Menu",[ku,Jte,ene]=kg(sd),[la,Ug]=Ts(sd,[ene,Fg,hD]),od=Fg(),SD=hD(),[vD,di]=la(sd),[tne,id]=la(sd),xD=e=>{const{__scopeMenu:n,open:t=!1,children:r,dir:s,onOpenChange:o,modal:i=!0}=e,a=od(n),[l,c]=P.useState(null),u=P.useRef(!1),h=Yt(o),p=i1(s);return P.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",S,{capture:!0,once:!0}),document.addEventListener("pointermove",S,{capture:!0,once:!0})},S=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",S,{capture:!0}),document.removeEventListener("pointermove",S,{capture:!0})}},[]),d.jsx(Xw,{...a,children:d.jsx(vD,{scope:n,open:t,onOpenChange:h,content:l,onContentChange:c,children:d.jsx(tne,{scope:n,onClose:P.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:p,modal:i,children:r})})})};xD.displayName=sd;var nne="MenuAnchor",a1=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e,s=od(t);return d.jsx(qw,{...s,...r,ref:n})});a1.displayName=nne;var l1="MenuPortal",[rne,wD]=la(l1,{forceMount:void 0}),bD=e=>{const{__scopeMenu:n,forceMount:t,children:r,container:s}=e,o=di(l1,n);return d.jsx(rne,{scope:n,forceMount:t,children:d.jsx(qr,{present:t||o.open,children:d.jsx(td,{asChild:!0,container:s,children:r})})})};bD.displayName=l1;var Er="MenuContent",[sne,c1]=la(Er),PD=P.forwardRef((e,n)=>{const t=wD(Er,e.__scopeMenu),{forceMount:r=t.forceMount,...s}=e,o=di(Er,e.__scopeMenu),i=id(Er,e.__scopeMenu);return d.jsx(ku.Provider,{scope:e.__scopeMenu,children:d.jsx(qr,{present:r||o.open,children:d.jsx(ku.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(one,{...s,ref:n}):d.jsx(ine,{...s,ref:n})})})})}),one=P.forwardRef((e,n)=>{const t=di(Er,e.__scopeMenu),r=P.useRef(null),s=Xe(n,r);return P.useEffect(()=>{const o=r.current;if(o)return Mw(o)},[]),d.jsx(u1,{...e,ref:s,trapFocus:t.open,disableOutsidePointerEvents:t.open,disableOutsideScroll:!0,onFocusOutside:re(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>t.onOpenChange(!1)})}),ine=P.forwardRef((e,n)=>{const t=di(Er,e.__scopeMenu);return d.jsx(u1,{...e,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>t.onOpenChange(!1)})}),u1=P.forwardRef((e,n)=>{const{__scopeMenu:t,loop:r=!1,trapFocus:s,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:S,...y}=e,x=di(Er,t),m=id(Er,t),v=od(t),w=SD(t),C=Jte(t),[E,k]=P.useState(null),I=P.useRef(null),_=Xe(n,I,x.onContentChange),T=P.useRef(0),M=P.useRef(""),D=P.useRef(0),$=P.useRef(null),j=P.useRef("right"),O=P.useRef(0),R=S?_g:P.Fragment,K=S?{as:Vi,allowPinchZoom:!0}:void 0,B=W=>{var Oe,tt;const Y=M.current+W,q=C().filter(Ae=>!Ae.disabled),ae=document.activeElement,fe=(Oe=q.find(Ae=>Ae.ref.current===ae))==null?void 0:Oe.textValue,we=q.map(Ae=>Ae.textValue),J=Sne(we,Y,fe),Ue=(tt=q.find(Ae=>Ae.textValue===J))==null?void 0:tt.ref.current;(function Ae(ot){M.current=ot,window.clearTimeout(T.current),ot!==""&&(T.current=window.setTimeout(()=>Ae(""),1e3))})(Y),Ue&&setTimeout(()=>Ue.focus())};P.useEffect(()=>()=>window.clearTimeout(T.current),[]),Tw();const z=P.useCallback(W=>{var q,ae;return j.current===((q=$.current)==null?void 0:q.side)&&xne(W,(ae=$.current)==null?void 0:ae.area)},[]);return d.jsx(sne,{scope:t,searchRef:M,onItemEnter:P.useCallback(W=>{z(W)&&W.preventDefault()},[z]),onItemLeave:P.useCallback(W=>{var Y;z(W)||((Y=I.current)==null||Y.focus(),k(null))},[z]),onTriggerLeave:P.useCallback(W=>{z(W)&&W.preventDefault()},[z]),pointerGraceTimerRef:D,onPointerGraceIntentChange:P.useCallback(W=>{$.current=W},[]),children:d.jsx(R,{...K,children:d.jsx(Ig,{asChild:!0,trapped:s,onMountAutoFocus:re(o,W=>{var Y;W.preventDefault(),(Y=I.current)==null||Y.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(ed,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:d.jsx(Vte,{asChild:!0,...w,dir:m.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:k,onEntryFocus:re(l,W=>{m.isUsingKeyboardRef.current||W.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(WO,{role:"menu","aria-orientation":"vertical","data-state":zD(x.open),"data-radix-menu-content":"",dir:m.dir,...v,...y,ref:_,style:{outline:"none",...y.style},onKeyDown:re(y.onKeyDown,W=>{const q=W.target.closest("[data-radix-menu-content]")===W.currentTarget,ae=W.ctrlKey||W.altKey||W.metaKey,fe=W.key.length===1;q&&(W.key==="Tab"&&W.preventDefault(),!ae&&fe&&B(W.key));const we=I.current;if(W.target!==we||!qte.includes(W.key))return;W.preventDefault();const Ue=C().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);yD.includes(W.key)&&Ue.reverse(),mne(Ue)}),onBlur:re(e.onBlur,W=>{W.currentTarget.contains(W.target)||(window.clearTimeout(T.current),M.current="")}),onPointerMove:re(e.onPointerMove,Tu(W=>{const Y=W.target,q=O.current!==W.clientX;if(W.currentTarget.contains(Y)&&q){const ae=W.clientX>O.current?"right":"left";j.current=ae,O.current=W.clientX}}))})})})})})})});PD.displayName=Er;var ane="MenuGroup",d1=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{role:"group",...r,ref:n})});d1.displayName=ane;var lne="MenuLabel",CD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{...r,ref:n})});CD.displayName=lne;var Tf="MenuItem",mE="menu.itemSelect",Hg=P.forwardRef((e,n)=>{const{disabled:t=!1,onSelect:r,...s}=e,o=P.useRef(null),i=id(Tf,e.__scopeMenu),a=c1(Tf,e.__scopeMenu),l=Xe(n,o),c=P.useRef(!1),u=()=>{const h=o.current;if(!t&&h){const p=new CustomEvent(mE,{bubbles:!0,cancelable:!0});h.addEventListener(mE,f=>r==null?void 0:r(f),{once:!0}),kw(h,p),p.defaultPrevented?c.current=!1:i.onClose()}};return d.jsx(ID,{...s,ref:l,disabled:t,onClick:re(e.onClick,u),onPointerDown:h=>{var p;(p=e.onPointerDown)==null||p.call(e,h),c.current=!0},onPointerUp:re(e.onPointerUp,h=>{var p;c.current||(p=h.currentTarget)==null||p.click()}),onKeyDown:re(e.onKeyDown,h=>{const p=a.searchRef.current!=="";t||p&&h.key===" "||rx.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Hg.displayName=Tf;var ID=P.forwardRef((e,n)=>{const{__scopeMenu:t,disabled:r=!1,textValue:s,...o}=e,i=c1(Tf,t),a=SD(t),l=P.useRef(null),c=Xe(n,l),[u,h]=P.useState(!1),[p,f]=P.useState("");return P.useEffect(()=>{const S=l.current;S&&f((S.textContent??"").trim())},[o.children]),d.jsx(ku.ItemSlot,{scope:t,disabled:r,textValue:s??p,children:d.jsx(Yte,{asChild:!0,...a,focusable:!r,children:d.jsx(_e.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...o,ref:c,onPointerMove:re(e.onPointerMove,Tu(S=>{r?i.onItemLeave(S):(i.onItemEnter(S),S.defaultPrevented||S.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:re(e.onPointerLeave,Tu(S=>i.onItemLeave(S))),onFocus:re(e.onFocus,()=>h(!0)),onBlur:re(e.onBlur,()=>h(!1))})})})}),cne="MenuCheckboxItem",ED=P.forwardRef((e,n)=>{const{checked:t=!1,onCheckedChange:r,...s}=e;return d.jsx(AD,{scope:e.__scopeMenu,checked:t,children:d.jsx(Hg,{role:"menuitemcheckbox","aria-checked":Mf(t)?"mixed":t,...s,ref:n,"data-state":f1(t),onSelect:re(s.onSelect,()=>r==null?void 0:r(Mf(t)?!0:!t),{checkForDefaultPrevented:!1})})})});ED.displayName=cne;var _D="MenuRadioGroup",[une,dne]=la(_D,{value:void 0,onValueChange:()=>{}}),kD=P.forwardRef((e,n)=>{const{value:t,onValueChange:r,...s}=e,o=Yt(r);return d.jsx(une,{scope:e.__scopeMenu,value:t,onValueChange:o,children:d.jsx(d1,{...s,ref:n})})});kD.displayName=_D;var TD="MenuRadioItem",MD=P.forwardRef((e,n)=>{const{value:t,...r}=e,s=dne(TD,e.__scopeMenu),o=t===s.value;return d.jsx(AD,{scope:e.__scopeMenu,checked:o,children:d.jsx(Hg,{role:"menuitemradio","aria-checked":o,...r,ref:n,"data-state":f1(o),onSelect:re(r.onSelect,()=>{var i;return(i=s.onValueChange)==null?void 0:i.call(s,t)},{checkForDefaultPrevented:!1})})})});MD.displayName=TD;var h1="MenuItemIndicator",[AD,hne]=la(h1,{checked:!1}),jD=P.forwardRef((e,n)=>{const{__scopeMenu:t,forceMount:r,...s}=e,o=hne(h1,t);return d.jsx(qr,{present:r||Mf(o.checked)||o.checked===!0,children:d.jsx(_e.span,{...s,ref:n,"data-state":f1(o.checked)})})});jD.displayName=h1;var pne="MenuSeparator",OD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e;return d.jsx(_e.div,{role:"separator","aria-orientation":"horizontal",...r,ref:n})});OD.displayName=pne;var fne="MenuArrow",DD=P.forwardRef((e,n)=>{const{__scopeMenu:t,...r}=e,s=od(t);return d.jsx(GO,{...s,...r,ref:n})});DD.displayName=fne;var p1="MenuSub",[gne,RD]=la(p1),LD=e=>{const{__scopeMenu:n,children:t,open:r=!1,onOpenChange:s}=e,o=di(p1,n),i=od(n),[a,l]=P.useState(null),[c,u]=P.useState(null),h=Yt(s);return P.useEffect(()=>(o.open===!1&&h(!1),()=>h(!1)),[o.open,h]),d.jsx(Xw,{...i,children:d.jsx(vD,{scope:n,open:r,onOpenChange:h,content:c,onContentChange:u,children:d.jsx(gne,{scope:n,contentId:Xs(),triggerId:Xs(),trigger:a,onTriggerChange:l,children:t})})})};LD.displayName=p1;var Dc="MenuSubTrigger",$D=P.forwardRef((e,n)=>{const t=di(Dc,e.__scopeMenu),r=id(Dc,e.__scopeMenu),s=RD(Dc,e.__scopeMenu),o=c1(Dc,e.__scopeMenu),i=P.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=o,c={__scopeMenu:e.__scopeMenu},u=P.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return P.useEffect(()=>u,[u]),P.useEffect(()=>{const h=a.current;return()=>{window.clearTimeout(h),l(null)}},[a,l]),d.jsx(a1,{asChild:!0,...c,children:d.jsx(ID,{id:s.triggerId,"aria-haspopup":"menu","aria-expanded":t.open,"aria-controls":s.contentId,"data-state":zD(t.open),...e,ref:Cg(n,s.onTriggerChange),onClick:h=>{var p;(p=e.onClick)==null||p.call(e,h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),t.open||t.onOpenChange(!0))},onPointerMove:re(e.onPointerMove,Tu(h=>{o.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!t.open&&!i.current&&(o.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{t.onOpenChange(!0),u()},100))})),onPointerLeave:re(e.onPointerLeave,Tu(h=>{var f,S;u();const p=(f=t.content)==null?void 0:f.getBoundingClientRect();if(p){const y=(S=t.content)==null?void 0:S.dataset.side,x=y==="right",m=x?-5:5,v=p[x?"left":"right"],w=p[x?"right":"left"];o.onPointerGraceIntentChange({area:[{x:h.clientX+m,y:h.clientY},{x:v,y:p.top},{x:w,y:p.top},{x:w,y:p.bottom},{x:v,y:p.bottom}],side:y}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>o.onPointerGraceIntentChange(null),300)}else{if(o.onTriggerLeave(h),h.defaultPrevented)return;o.onPointerGraceIntentChange(null)}})),onKeyDown:re(e.onKeyDown,h=>{var f;const p=o.searchRef.current!=="";e.disabled||p&&h.key===" "||Zte[r.dir].includes(h.key)&&(t.onOpenChange(!0),(f=t.content)==null||f.focus(),h.preventDefault())})})})});$D.displayName=Dc;var ND="MenuSubContent",FD=P.forwardRef((e,n)=>{const t=wD(Er,e.__scopeMenu),{forceMount:r=t.forceMount,...s}=e,o=di(Er,e.__scopeMenu),i=id(Er,e.__scopeMenu),a=RD(ND,e.__scopeMenu),l=P.useRef(null),c=Xe(n,l);return d.jsx(ku.Provider,{scope:e.__scopeMenu,children:d.jsx(qr,{present:r||o.open,children:d.jsx(ku.Slot,{scope:e.__scopeMenu,children:d.jsx(u1,{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 h;i.isUsingKeyboardRef.current&&((h=l.current)==null||h.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:re(e.onFocusOutside,u=>{u.target!==a.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:re(e.onEscapeKeyDown,u=>{i.onClose(),u.preventDefault()}),onKeyDown:re(e.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),p=Qte[i.dir].includes(u.key);h&&p&&(o.onOpenChange(!1),(f=a.trigger)==null||f.focus(),u.preventDefault())})})})})})});FD.displayName=ND;function zD(e){return e?"open":"closed"}function Mf(e){return e==="indeterminate"}function f1(e){return Mf(e)?"indeterminate":e?"checked":"unchecked"}function mne(e){const n=document.activeElement;for(const t of e)if(t===n||(t.focus(),document.activeElement!==n))return}function yne(e,n){return e.map((t,r)=>e[(n+r)%e.length])}function Sne(e,n,t){const s=n.length>1&&Array.from(n).every(c=>c===n[0])?n[0]:n,o=t?e.indexOf(t):-1;let i=yne(e,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 vne(e,n){const{x:t,y:r}=e;let s=!1;for(let o=0,i=n.length-1;or!=u>r&&t<(c-a)*(r-l)/(u-l)+a&&(s=!s)}return s}function xne(e,n){if(!n)return!1;const t={x:e.clientX,y:e.clientY};return vne(t,n)}function Tu(e){return n=>n.pointerType==="mouse"?e(n):void 0}var BD=xD,UD=a1,HD=bD,KD=PD,WD=d1,GD=CD,VD=Hg,YD=ED,XD=kD,qD=MD,ZD=jD,QD=OD,JD=DD,eR=LD,tR=$D,nR=FD,g1="ContextMenu",[wne,Lae]=Ts(g1,[Ug]),hn=Ug(),[bne,rR]=wne(g1),sR=e=>{const{__scopeContextMenu:n,children:t,onOpenChange:r,dir:s,modal:o=!0}=e,[i,a]=P.useState(!1),l=hn(n),c=Yt(r),u=P.useCallback(h=>{a(h),c(h)},[c]);return d.jsx(bne,{scope:n,open:i,onOpenChange:u,modal:o,children:d.jsx(BD,{...l,dir:s,open:i,onOpenChange:u,modal:o,children:t})})};sR.displayName=g1;var oR="ContextMenuTrigger",iR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,disabled:r=!1,...s}=e,o=rR(oR,t),i=hn(t),a=P.useRef({x:0,y:0}),l=P.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),c=P.useRef(0),u=P.useCallback(()=>window.clearTimeout(c.current),[]),h=p=>{a.current={x:p.clientX,y:p.clientY},o.onOpenChange(!0)};return P.useEffect(()=>u,[u]),P.useEffect(()=>void(r&&u()),[r,u]),d.jsxs(d.Fragment,{children:[d.jsx(UD,{...i,virtualRef:l}),d.jsx(_e.span,{"data-state":o.open?"open":"closed","data-disabled":r?"":void 0,...s,ref:n,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:re(e.onContextMenu,p=>{u(),h(p),p.preventDefault()}),onPointerDown:r?e.onPointerDown:re(e.onPointerDown,yh(p=>{u(),c.current=window.setTimeout(()=>h(p),700)})),onPointerMove:r?e.onPointerMove:re(e.onPointerMove,yh(u)),onPointerCancel:r?e.onPointerCancel:re(e.onPointerCancel,yh(u)),onPointerUp:r?e.onPointerUp:re(e.onPointerUp,yh(u))})]})});iR.displayName=oR;var Pne="ContextMenuPortal",m1=e=>{const{__scopeContextMenu:n,...t}=e,r=hn(n);return d.jsx(HD,{...r,...t})};m1.displayName=Pne;var aR="ContextMenuContent",lR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=rR(aR,t),o=hn(t),i=P.useRef(!1);return d.jsx(KD,{...o,...r,ref:n,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:a=>{var l;(l=e.onCloseAutoFocus)==null||l.call(e,a),!a.defaultPrevented&&i.current&&a.preventDefault(),i.current=!1},onInteractOutside:a=>{var l;(l=e.onInteractOutside)==null||l.call(e,a),!a.defaultPrevented&&!s.modal&&(i.current=!0)},style:{...e.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)"}})});lR.displayName=aR;var Cne="ContextMenuGroup",cR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(WD,{...s,...r,ref:n})});cR.displayName=Cne;var Ine="ContextMenuLabel",Ene=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(GD,{...s,...r,ref:n})});Ene.displayName=Ine;var _ne="ContextMenuItem",uR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(VD,{...s,...r,ref:n})});uR.displayName=_ne;var kne="ContextMenuCheckboxItem",dR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(YD,{...s,...r,ref:n})});dR.displayName=kne;var Tne="ContextMenuRadioGroup",Mne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(XD,{...s,...r,ref:n})});Mne.displayName=Tne;var Ane="ContextMenuRadioItem",jne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(qD,{...s,...r,ref:n})});jne.displayName=Ane;var One="ContextMenuItemIndicator",Dne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(ZD,{...s,...r,ref:n})});Dne.displayName=One;var Rne="ContextMenuSeparator",Lne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(QD,{...s,...r,ref:n})});Lne.displayName=Rne;var $ne="ContextMenuArrow",Nne=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(JD,{...s,...r,ref:n})});Nne.displayName=$ne;var Fne="ContextMenuSub",hR=e=>{const{__scopeContextMenu:n,children:t,onOpenChange:r,open:s,defaultOpen:o}=e,i=hn(n),[a,l]=ci({prop:s,defaultProp:o,onChange:r});return d.jsx(eR,{...i,open:a,onOpenChange:l,children:t})};hR.displayName=Fne;var zne="ContextMenuSubTrigger",pR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(tR,{...s,...r,ref:n})});pR.displayName=zne;var Bne="ContextMenuSubContent",fR=P.forwardRef((e,n)=>{const{__scopeContextMenu:t,...r}=e,s=hn(t);return d.jsx(nR,{...s,...r,ref:n,style:{...e.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)"}})});fR.displayName=Bne;function yh(e){return n=>n.pointerType!=="mouse"?e(n):void 0}var Une=sR,Hne=iR,Kne=m1,Wne=lR,Gne=dR;const gR=typeof window>"u"?!1:window.navigator.userAgent.toLowerCase().indexOf("mac")>-1,Vne=gR?"⌘":"Ctrl",Yne=gR?"⌥":"Alt";function mR(e){return e.split(",")[0].split("").map(n=>{const t=n.replace(/\$/g,Vne).replace(/\?/g,Yne).replace(/!/g,"⇧");return t[0].toUpperCase()+t.slice(1)})}function sx(e){return"— "+mR(e).join(" ")}function Xne(e){return d.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",...e,children:d.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[d.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),d.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor",children:d.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}var y1="DropdownMenu",[qne,$ae]=Ts(y1,[Ug]),pn=Ug(),[Zne,yR]=qne(y1),SR=e=>{const{__scopeDropdownMenu:n,children:t,dir:r,open:s,defaultOpen:o,onOpenChange:i,modal:a=!0}=e,l=pn(n),c=P.useRef(null),[u=!1,h]=ci({prop:s,defaultProp:o,onChange:i});return d.jsx(Zne,{scope:n,triggerId:Xs(),triggerRef:c,contentId:Xs(),open:u,onOpenChange:h,onOpenToggle:P.useCallback(()=>h(p=>!p),[h]),modal:a,children:d.jsx(BD,{...l,open:u,onOpenChange:h,dir:r,modal:a,children:t})})};SR.displayName=y1;var vR="DropdownMenuTrigger",xR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,disabled:r=!1,...s}=e,o=yR(vR,t),i=pn(t);return d.jsx(UD,{asChild:!0,...i,children:d.jsx(_e.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:Cg(n,o.triggerRef),onPointerDown:re(e.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(o.onOpenToggle(),o.open||a.preventDefault())}),onKeyDown:re(e.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&o.onOpenToggle(),a.key==="ArrowDown"&&o.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});xR.displayName=vR;var Qne="DropdownMenuPortal",wR=e=>{const{__scopeDropdownMenu:n,...t}=e,r=pn(n);return d.jsx(HD,{...r,...t})};wR.displayName=Qne;var bR="DropdownMenuContent",PR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=yR(bR,t),o=pn(t),i=P.useRef(!1);return d.jsx(KD,{id:s.contentId,"aria-labelledby":s.triggerId,...o,...r,ref:n,onCloseAutoFocus:re(e.onCloseAutoFocus,a=>{var l;i.current||(l=s.triggerRef.current)==null||l.focus(),i.current=!1,a.preventDefault()}),onInteractOutside:re(e.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:{...e.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)"}})});PR.displayName=bR;var Jne="DropdownMenuGroup",CR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(WD,{...s,...r,ref:n})});CR.displayName=Jne;var ere="DropdownMenuLabel",tre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(GD,{...s,...r,ref:n})});tre.displayName=ere;var nre="DropdownMenuItem",IR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(VD,{...s,...r,ref:n})});IR.displayName=nre;var rre="DropdownMenuCheckboxItem",ER=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(YD,{...s,...r,ref:n})});ER.displayName=rre;var sre="DropdownMenuRadioGroup",ore=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(XD,{...s,...r,ref:n})});ore.displayName=sre;var ire="DropdownMenuRadioItem",are=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(qD,{...s,...r,ref:n})});are.displayName=ire;var lre="DropdownMenuItemIndicator",cre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(ZD,{...s,...r,ref:n})});cre.displayName=lre;var ure="DropdownMenuSeparator",dre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(QD,{...s,...r,ref:n})});dre.displayName=ure;var hre="DropdownMenuArrow",pre=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(JD,{...s,...r,ref:n})});pre.displayName=hre;var fre=e=>{const{__scopeDropdownMenu:n,children:t,open:r,onOpenChange:s,defaultOpen:o}=e,i=pn(n),[a=!1,l]=ci({prop:r,defaultProp:o,onChange:s});return d.jsx(eR,{...i,open:a,onOpenChange:l,children:t})},gre="DropdownMenuSubTrigger",_R=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(tR,{...s,...r,ref:n})});_R.displayName=gre;var mre="DropdownMenuSubContent",kR=P.forwardRef((e,n)=>{const{__scopeDropdownMenu:t,...r}=e,s=pn(t);return d.jsx(nR,{...s,...r,ref:n,style:{...e.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)"}})});kR.displayName=mre;var S1=SR,v1=xR,Kg=wR,x1=PR,yre=CR,Sre=IR,vre=ER,xre=fre,wre=_R,bre=kR;function qi({id:e,children:n,modal:t=!1,debugOpen:r=!1}){const[s,o]=ho(e);return d.jsx(S1,{open:r||s,dir:"ltr",modal:t,onOpenChange:o,children:n})}function Zi({children:e,...n}){return d.jsx(v1,{dir:"ltr",asChild:!0,onTouchEnd:t=>Ie(t),...n,children:e})}function Qi({side:e="bottom",align:n="start",sideOffset:t=8,alignOffset:r=8,children:s}){const o=$t();return d.jsx(Kg,{container:o,children:d.jsx(x1,{className:"tlui-menu",side:e,sideOffset:t,align:n,alignOffset:r,collisionPadding:4,children:s})})}function Pre({id:e,children:n}){const[t,r]=ho(e);return d.jsx(xre,{open:t,onOpenChange:r,children:n})}function Cre({id:e,label:n,title:t,disabled:r}){return d.jsx(wre,{dir:"ltr",asChild:!0,disabled:r,children:d.jsxs(ce,{"data-testid":e,type:"menu",className:"tlui-menu__submenu__trigger",disabled:r,title:t,children:[d.jsx(wt,{children:n}),d.jsx(Se,{icon:"chevron-right",small:!0})]})})}function Ire({id:e,alignOffset:n=-1,sideOffset:t=-4,size:r="small",children:s}){const o=$t();return d.jsx(Kg,{container:o,children:d.jsx(bre,{"data-testid":e,className:"tlui-menu tlui-menu__submenu__content",alignOffset:n,sideOffset:t,collisionPadding:4,"data-size":r,children:s})})}function Ere({children:e}){return d.jsx(yre,{dir:"ltr",className:"tlui-menu__group",children:e})}function Mu({noClose:e,children:n}){return d.jsx(Sre,{dir:"ltr",asChild:!0,onClick:e?Ie:void 0,children:n})}function qc({children:e,visibleOnMobileLayout:n=!1}){const t=Cn();return!n&&td.jsx("span",{children:r},s))})}function U({disabled:e=!1,spinner:n=!1,readonlyOk:t=!1,id:r,kbd:s,label:o,icon:i,onSelect:a,noClose:l,isSelected:c}){const{type:u,sourceId:h}=zg(),p=xe(),[f,S]=P.useState(!1);if(co()&&!t)return null;const x=Iu(o,u),m=s?sx(s):void 0,v=x?p(x):void 0,w=v&&m?`${v} ${m}`:v;switch(u){case"menu":return d.jsx(Mu,{children:d.jsxs(ce,{type:"menu","data-testid":`${h}.${r}`,disabled:e,title:w,onClick:C=>{l&&Ie(C),f?S(!1):a(h)},children:[d.jsx(wt,{children:v}),s&&d.jsx(qc,{children:s})]})});case"context-menu":return e?null:d.jsxs(uR,{dir:"ltr",title:w,draggable:!1,className:"tlui-button tlui-button__menu","data-testid":`${h}.${r}`,onSelect:C=>{l&&Ie(C),f?S(!1):a(h)},children:[d.jsx("span",{className:"tlui-button__label",draggable:!1,children:v}),s&&d.jsx(qc,{children:s}),n&&d.jsx(Xne,{})]});case"panel":return d.jsxs(ce,{"data-testid":`${h}.${r}`,type:"menu",title:w,disabled:e,onClick:()=>a(h),children:[d.jsx(wt,{children:v}),i&&d.jsx(Se,{icon:i})]});case"small-icons":case"icons":return d.jsx(ce,{"data-testid":`${h}.${r}`,type:"icon",title:w,disabled:e,onClick:()=>a(h),children:d.jsx(Se,{icon:i,small:u==="small-icons"})});case"keyboard-shortcuts":return s?d.jsxs("div",{className:"tlui-shortcuts-dialog__key-pair","data-testid":`${h}.${r}`,children:[d.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__key",children:v}),d.jsx("div",{className:"tlui-shortcuts-dialog__key-pair__value",children:d.jsx(qc,{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 d.jsxs(ce,{type:"low",onClick:()=>a(h),children:[d.jsx(Se,{icon:i}),d.jsx(wt,{children:v})]});case"toolbar":return d.jsx(ce,{type:"tool","data-testid":`tools.${r}`,"aria-label":x,"data-value":r,onClick:()=>a("toolbar"),title:w,onTouchStart:C=>{Ie(C),a("toolbar")},role:"radio","aria-checked":c?"true":"false",children:d.jsx(Se,{icon:i})});case"toolbar-overflow":return d.jsx(Mu,{"aria-label":o,children:d.jsx(ce,{type:"icon",className:"tlui-button-grid__button",onClick:()=>{a("toolbar")},"data-testid":`tools.more.${r}`,title:w,role:"radio","aria-checked":c?"true":"false","data-value":r,children:d.jsx(Se,{icon:i})})});default:throw cn(u)}}function _re(){return d.jsxs(d.Fragment,{children:[d.jsx(kre,{}),d.jsx(Tre,{}),d.jsx(Mre,{}),d.jsx(Are,{}),d.jsx(jre,{}),d.jsx(Rre,{}),d.jsx(Lre,{}),d.jsx($re,{})]})}function kre(){const e=ie(),n=In(2),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["align-left"],disabled:!r}),d.jsx(U,{...e["align-center-horizontal"],disabled:!r}),d.jsx(U,{...e["align-right"],disabled:!r}),d.jsx(U,{...e["stretch-horizontal"],disabled:!r}),d.jsx(U,{...e["align-top"],disabled:!r}),d.jsx(U,{...e["align-center-vertical"],disabled:!r}),d.jsx(U,{...e["align-bottom"],disabled:!r}),d.jsx(U,{...e["stretch-vertical"],disabled:!r})]})}function Tre(){const e=ie(),n=In(3),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["distribute-horizontal"],disabled:!r}),d.jsx(U,{...e["distribute-vertical"],disabled:!r})]})}function Mre(){const e=ie(),n=sD(),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["stack-horizontal"],disabled:!r}),d.jsx(U,{...e["stack-vertical"],disabled:!r})]})}function Are(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["send-to-back"],disabled:!r}),d.jsx(U,{...e["send-backward"],disabled:!r}),d.jsx(U,{...e["bring-forward"],disabled:!r}),d.jsx(U,{...e["bring-to-front"],disabled:!r})]})}function jre(){return Cn()n.getZoomLevel()===1,[n]);return d.jsx(U,{...e["zoom-to-100"],disabled:t})}function Dre(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsx(U,{...e["rotate-ccw"],disabled:!r})}function Rre(){const e=ie(),n=In(1),t=po(),r=n&&t;return d.jsx(U,{...e["rotate-cw"],disabled:!r})}function Lre(){const e=ie(),n=lD(),t=po(),r=n&&t;return d.jsx(U,{...e["edit-link"],disabled:!r})}function $re(){const e=oD(),n=iD();return e?d.jsx(yE,{}):n?d.jsx(Nre,{}):d.jsx(yE,{})}function yE(){const e=ie(),n=In(2),t=po(),r=n&&t;return d.jsx(U,{...e.group,disabled:!r})}function Nre(){const e=ie();return d.jsx(U,{...e.ungroup})}const Fre=P.memo(function({children:n}){const t=xe(),r=Cn(),s=co(),o=F(),i=H("should display quick actions when in readonly",()=>o.isInAny("hand","zoom"),[o]),a=n??d.jsx(_re,{});if(!(s&&!i))return d.jsxs(r1,{id:"actions-menu",children:[d.jsx(s1,{children:d.jsx(ce,{type:"icon","data-testid":"actions-menu.button",title:t("actions-menu.title"),children:d.jsx(Se,{icon:"dots-vertical",small:!0})})}),d.jsx(o1,{side:r>=yt.TABLET?"bottom":"top",sideOffset:6,children:d.jsx("div",{className:"tlui-actions-menu tlui-buttons__grid","data-testid":"actions-menu.content",children:d.jsx(Tr,{type:"icons",sourceId:"actions-menu",children:a})})})]})});function Gn({id:e,kbd:n,label:t,readonlyOk:r,onSelect:s,toggle:o=!1,disabled:i=!1,checked:a=!1}){const{type:l,sourceId:c}=zg(),u=co(),h=xe();if(u&&!r)return null;const p=Iu(t,l),f=p?h(p):void 0;switch(l){case"menu":return d.jsxs(vre,{dir:"ltr",className:"tlui-button tlui-button__menu tlui-button__checkbox",title:f,onSelect:S=>{s==null||s(c),Ie(S)},disabled:i,checked:a,children:[d.jsx(Cs,{small:!0,icon:o?a?"toggle-on":"toggle-off":a?"check":"none"}),f&&d.jsx("span",{className:"tlui-button__label",draggable:!1,children:f}),n&&d.jsx(qc,{children:n})]});case"context-menu":return d.jsxs(Gne,{className:"tlui-button tlui-button__menu tlui-button__checkbox",dir:"ltr",title:f,onSelect:S=>{s(c),Ie(S)},disabled:i,checked:a,children:[d.jsx(Cs,{small:!0,icon:o?a?"toggle-on":"toggle-off":a?"check":"none"}),f&&d.jsx("span",{className:"tlui-button__label",draggable:!1,children:f}),n&&d.jsx(qc,{children:n})]},e);default:return null}}function pe({id:e,label:n,children:t}){const{type:r,sourceId:s}=zg(),o=xe(),i=Iu(n,r),a=i?o(i):void 0;switch(r){case"panel":return d.jsx("div",{className:"tlui-menu__group","data-testid":`${s}-group.${e}`,children:t});case"menu":return d.jsx(Ere,{"data-testid":`${s}-group.${e}`,children:t});case"context-menu":return d.jsx(cR,{dir:"ltr",className:"tlui-menu__group","data-testid":`${s}-group.${e}`,children:t});case"keyboard-shortcuts":return d.jsxs("div",{className:"tlui-shortcuts-dialog__group","data-testid":`${s}-group.${e}`,children:[d.jsx("h2",{className:"tlui-shortcuts-dialog__group__title",children:a}),d.jsx("div",{className:"tlui-shortcuts-dialog__group__content",children:t})]});default:return t}}function En({id:e,disabled:n=!1,label:t,size:r="small",children:s}){const{type:o,sourceId:i}=zg(),a=$t(),l=xe(),c=t?typeof t=="string"?t:t[o]??t.default:void 0,u=c?l(c):void 0;switch(o){case"menu":return d.jsxs(Pre,{id:`${i}-sub.${e}`,children:[d.jsx(Cre,{id:`${i}-sub.${u?u.toLowerCase()+"-button":""}`,disabled:n,label:u,title:u}),d.jsx(Ire,{id:`${i}-sub.${u?u.toLowerCase()+"-content":""}`,size:r,children:s})]});case"context-menu":return n?null:d.jsxs(zre,{id:`${i}-sub.${e}`,children:[d.jsx(pR,{dir:"ltr",disabled:n,asChild:!0,children:d.jsxs(ce,{"data-testid":`${i}-sub-trigger.${e}`,type:"menu",className:"tlui-menu__submenu__trigger",children:[d.jsx(wt,{children:u}),d.jsx(Se,{icon:"chevron-right",small:!0})]})}),d.jsx(m1,{container:a,children:d.jsx(fR,{"data-testid":`${i}-sub-content.${e}`,className:"tlui-menu tlui-menu__submenu__content",alignOffset:-1,sideOffset:-4,collisionPadding:4,"data-size":r,children:s})})]});default:return s}}function zre({id:e,children:n}){const[t,r]=ho(e);return d.jsx(hR,{open:t,onOpenChange:r,children:n})}function TR(){const e=ie();return Dte()?d.jsx(U,{...e["toggle-auto-size"]}):null}function MR(){const e=ie();return lD()?d.jsx(U,{...e["edit-link"]}):null}function Bre(){const e=ie();return In(1)?d.jsx(U,{...e.duplicate}):null}function AR(){const e=ie(),n=F();return H("should display flatten option",()=>{if(n.getSelectedShapeIds().length===0)return!1;const s=n.getOnlySelectedShape();return!(s&&n.isShapeOfType(s,"image"))},[n])?d.jsx(U,{...e["flatten-to-image"]}):null}function jR(){const e=ie();return oD()?d.jsx(U,{...e.group}):null}function OR(){const e=ie();return iD()?d.jsx(U,{...e.ungroup}):null}function DR(){const e=F(),n=ie();return H("allow unframe",()=>{const r=e.getSelectedShapes();return r.length===0?!1:r.every(s=>e.isShapeOfType(s,"frame"))},[e])?d.jsx(U,{...n["remove-frame"]}):null}function RR(){const e=F(),n=ie();return H("allow fit frame to content",()=>{const r=e.getOnlySelectedShape();return r?e.isShapeOfType(r,"frame")&&e.getSortedChildIdsForParent(r).length>0:!1},[e])?d.jsx(U,{...n["fit-frame-to-content"]}):null}function LR(){const e=F(),n=ie();return H("selected shapes",()=>e.getSelectedShapes().length>0,[e])?d.jsx(U,{...n["toggle-lock"]}):null}function w1(){const e=ie(),n=F(),t=H("isTransparentBg",()=>!n.getInstanceState().exportBackground,[n]);return d.jsx(Gn,{...e["toggle-transparent"],checked:t,toggle:!0})}function Ure(){const e=F(),n=ie(),t=H("any shapes",()=>e.getCurrentPageShapeIds().size>0,[e]);return d.jsx(U,{...n["unlock-all"],disabled:!t})}function $R(){const e=F(),n=H("zoomed to 100",()=>e.getZoomLevel()===1,[e]),t=ie();return d.jsx(U,{...t["zoom-to-100"],noClose:!0,disabled:n})}function NR(){const e=F(),n=H("has shapes",()=>e.getCurrentPageShapeIds().size>0,[e]),t=ie();return d.jsx(U,{...t["zoom-to-fit"],disabled:!n,"data-testid":"minimap.zoom-menu.zoom-to-fit",noClose:!0})}function FR(){const e=F(),n=H("has shapes",()=>e.getSelectedShapeIds().length>0,[e]),t=ie();return d.jsx(U,{...t["zoom-to-selection"],disabled:!n,"data-testid":"minimap.zoom-menu.zoom-to-selection",noClose:!0})}function zR(){return d.jsxs(pe,{id:"clipboard",children:[d.jsx(Kre,{}),d.jsx(Wre,{}),d.jsx(Gre,{}),d.jsx(Bre,{}),d.jsx(Vre,{})]})}function Hre(){var r;const e=F(),n=ie(),t=H("atLeastOneShapeOnPage",()=>e.getCurrentPageShapeIds().size>0,[e]);return d.jsxs(En,{id:"copy-as",label:"context-menu.copy-as",size:"small",disabled:!t,children:[d.jsxs(pe,{id:"copy-as-group",children:[d.jsx(U,{...n["copy-as-svg"]}),!!((r=window.navigator.clipboard)!=null&&r.write)&&d.jsx(U,{...n["copy-as-png"]}),d.jsx(U,{...n["copy-as-json"]})]}),d.jsx(pe,{id:"copy-as-bg",children:d.jsx(w1,{})})]})}function Kre(){const e=ie(),n=In(1);return d.jsx(U,{...e.cut,disabled:!n})}function Wre(){const e=ie(),n=aD(1);return d.jsx(U,{...e.copy,disabled:!n})}function Gre(){const e=ie(),n=Ote;return d.jsx(U,{...e.paste,disabled:!n})}function BR(){const e=F(),n=ie();return H("atLeastOneShapeOnPage",()=>e.getCurrentPageShapeIds().size>0,[e])?d.jsxs(pe,{id:"conversions",children:[d.jsx(Hre,{}),d.jsxs(En,{id:"export-as",label:"context-menu.export-as",size:"small",children:[d.jsxs(pe,{id:"export-as-group",children:[d.jsx(U,{...n["export-as-svg"]}),d.jsx(U,{...n["export-as-png"]}),d.jsx(U,{...n["export-as-json"]})]}),d.jsx(pe,{id:"export-as-bg",children:d.jsx(w1,{})})]})]}):null}function UR(){const e=ie(),n=F(),t=H("atLeastOneShapeOnPage",()=>n.getCurrentPageShapeIds().size>0,[n]);return d.jsx(U,{...e["select-all"],disabled:!t})}function Vre(){const e=ie(),n=In(1);return d.jsx(U,{...e.delete,disabled:!n})}function Yre(){return aD(1)?d.jsxs(En,{id:"edit",label:"context-menu.edit",size:"small",children:[d.jsx(jR,{}),d.jsx(OR,{}),d.jsx(AR,{}),d.jsx(MR,{}),d.jsx(RR,{}),d.jsx(DR,{}),d.jsx(KR,{}),d.jsx(HR,{}),d.jsx(TR,{}),d.jsx(LR,{})]}):null}function Xre(){const e=In(2),n=Rte(),t=ie();return e||n?d.jsxs(En,{id:"arrange",label:"context-menu.arrange",size:"small",children:[e&&d.jsxs(pe,{id:"align",children:[d.jsx(U,{...t["align-left"]}),d.jsx(U,{...t["align-center-horizontal"]}),d.jsx(U,{...t["align-right"]}),d.jsx(U,{...t["align-top"]}),d.jsx(U,{...t["align-center-vertical"]}),d.jsx(U,{...t["align-bottom"]})]}),d.jsx(qre,{}),e&&d.jsxs(pe,{id:"stretch",children:[d.jsx(U,{...t["stretch-horizontal"]}),d.jsx(U,{...t["stretch-vertical"]})]}),(e||n)&&d.jsxs(pe,{id:"flip",children:[d.jsx(U,{...t["flip-horizontal"]}),d.jsx(U,{...t["flip-vertical"]})]}),d.jsx(Zre,{})]}):null}function qre(){const e=ie();return In(3)?d.jsxs(pe,{id:"distribute",children:[d.jsx(U,{...e["distribute-horizontal"]}),d.jsx(U,{...e["distribute-vertical"]})]}):null}function Zre(){const e=ie(),n=In(2),t=sD();return n?d.jsxs(pe,{id:"order",children:[d.jsx(U,{...e.pack}),t&&d.jsx(U,{...e["stack-horizontal"]}),t&&d.jsx(U,{...e["stack-vertical"]})]}):null}function Qre(){const e=ie();return In(1)?d.jsx(En,{id:"reorder",label:"context-menu.reorder",size:"small",children:d.jsxs(pe,{id:"reorder",children:[d.jsx(U,{...e["bring-to-front"]}),d.jsx(U,{...e["bring-forward"]}),d.jsx(U,{...e["send-backward"]}),d.jsx(U,{...e["send-to-back"]})]})}):null}function Jre(){const e=F(),n=H("pages",()=>e.getPages(),[e]),t=H("current page id",()=>e.getCurrentPageId(),[e]),{addToast:r}=Qr(),s=ie(),o=qt();return In(1)?d.jsxs(En,{id:"move-to-page",label:"context-menu.move-to-page",size:"small",children:[d.jsx(pe,{id:"pages",children:n.map(a=>d.jsx(U,{id:a.id,disabled:t===a.id,label:a.name,onSelect:()=>{e.mark("move_shapes_to_page"),e.moveShapesToPage(e.getSelectedShapeIds(),a.id);const l=e.getPage(a.id);l&&r({title:"Changed Page",description:`Moved to ${l.name}.`,actions:[{label:"Go Back",type:"primary",onClick:()=>{e.mark("change-page"),e.setCurrentPage(t)}}]}),o("move-to-page",{source:"context-menu"})}},a.id))}),d.jsx(pe,{id:"new-page",children:d.jsx(U,{...s["move-to-new-page"]})})]}):null}function HR(){const e=F(),n=ie();return H("oneEmbedSelected",()=>{const r=e.getOnlySelectedShape();return r?!!(e.isShapeOfType(r,"embed")&&r.props.url&&!e.isShapeOrAncestorLocked(r)):!1},[e])?d.jsx(U,{...n["convert-to-bookmark"]}):null}function KR(){const e=F(),n=ie();return H("oneEmbeddableBookmarkSelected",()=>{const r=e.getOnlySelectedShape();return r?!!(e.isShapeOfType(r,"bookmark")&&r.props.url&&Do(r.props.url)&&!e.isShapeOrAncestorLocked(r)):!1},[e])?d.jsx(U,{...n["convert-to-embed"]}):null}function ese(){const e=ie(),n=F(),t=H("isSnapMode",()=>n.user.getIsSnapMode(),[n]);return d.jsx(Gn,{...e["toggle-snap-mode"],checked:t})}function tse(){const e=ie(),n=F(),t=H("isToolLock",()=>n.getInstanceState().isToolLocked,[n]);return d.jsx(Gn,{...e["toggle-tool-lock"],checked:t})}function nse(){const e=ie(),n=F(),t=H("isGridMode",()=>n.getInstanceState().isGridMode,[n]);return d.jsx(Gn,{...e["toggle-grid"],checked:t})}function rse(){const e=ie(),n=F(),t=H("isWrapMode",()=>n.user.getIsWrapMode(),[n]);return d.jsx(Gn,{...e["toggle-wrap-mode"],checked:t})}function sse(){const e=ie(),n=F(),t=H("isFocusMode",()=>n.getInstanceState().isFocusMode,[n]);return d.jsx(Gn,{...e["toggle-focus-mode"],checked:t})}function ose(){const e=ie(),n=F(),t=H("edgeScrollSpeed",()=>n.user.getEdgeScrollSpeed(),[n]);return d.jsx(Gn,{...e["toggle-edge-scrolling"],checked:t===1})}function ise(){const e=ie(),n=F(),t=H("animationSpeed",()=>n.user.getAnimationSpeed(),[n]);return d.jsx(Gn,{...e["toggle-reduce-motion"],checked:t===0})}function ase(){const e=ie(),n=F(),t=H("isDebugMode",()=>n.getInstanceState().isDebugMode,[n]);return d.jsx(Gn,{...e["toggle-debug-mode"],checked:t})}function lse(){const e=ie(),n=F(),t=H("dynamic resize",()=>n.user.getIsDynamicResizeMode(),[n]);return d.jsx(Gn,{...e["toggle-dynamic-size-mode"],checked:t})}function cse(){const e=ie(),n=F(),t=H("paste at cursor",()=>n.user.getIsPasteAtCursorMode(),[n]);return d.jsx(Gn,{...e["toggle-paste-at-cursor"],checked:t})}function use(){const e=F(),n=ie();return H("show cursor chat",()=>e.getCurrentToolId()==="select"&&!e.getInstanceState().isCoarsePointer,[e])?d.jsx(U,{...n["open-cursor-chat"]}):null}function dse(){const e=F(),n=Lg();return H("isSelectToolActive",()=>e.getCurrentToolId()==="select",[e])?d.jsxs(d.Fragment,{children:[n&&d.jsx(use,{}),d.jsxs(pe,{id:"modify",children:[d.jsx(Yre,{}),d.jsx(Xre,{}),d.jsx(Qre,{}),d.jsx(Jre,{})]}),d.jsx(zR,{}),d.jsx(BR,{}),d.jsx(pe,{id:"select-all",children:d.jsx(UR,{})})]}):null}const hse=P.memo(function({children:n}){const t=F(),{Canvas:r}=st(),s=P.useCallback(c=>{if(c){if(t.getInstanceState().isCoarsePointer){const u=t.getSelectedShapes(),{inputs:{currentPagePoint:h}}=t,p=t.getShapesAtPoint(h);if(!t.getSelectedShapes().length||!p.some(f=>u.includes(f))){const f=p.filter(S=>t.isShapeOrAncestorLocked(S));f.length&&t.select(...f.map(S=>S.id))}}}else{const u=t.getOnlySelectedShape();u&&t.isShapeOrAncestorLocked(u)&&t.setSelectedShapes([])}},[t]),o=$t(),[i,a]=ho("context menu",s),l=n??d.jsx(dse,{});return d.jsxs(Une,{dir:"ltr",onOpenChange:a,modal:!1,children:[d.jsx(Hne,{onContextMenu:void 0,dir:"ltr",children:r?d.jsx(r,{}):null}),i&&d.jsx(Kne,{container:o,children:d.jsx(Wne,{className:"tlui-menu scrollable","data-testid":"context-menu",alignOffset:-4,collisionPadding:4,onContextMenu:Ie,children:d.jsx(Tr,{type:"context-menu",sourceId:"context-menu",children:l})})})]})}),pse=2e3,fse=5e3,gse=Lt(function(){const n=F(),{isChatting:t,chatMessage:r}=n.getInstanceState(),s=P.useRef(-1),[o,i]=P.useState("");return P.useEffect(()=>{if(!t&&r||t){const l=t?fse:pse;s.current=n.timers.setTimeout(()=>{n.updateInstanceState({chatMessage:"",isChatting:!1}),i(""),n.focus()},l)}return()=>{clearTimeout(s.current)}},[n,r,t]),t?d.jsx(yse,{value:o,setValue:i,chatMessage:r}):r.trim()?d.jsx(mse,{chatMessage:r}):null});function WR(e){const n=F();P.useLayoutEffect(()=>{var i;if(!e.current)return;const{x:r,y:s}=n.inputs.currentScreenPoint;(i=e.current)==null||i.style.setProperty("transform",`translate(${r}px, ${s}px)`);function o(a){var u;const{minX:l,minY:c}=n.getViewportScreenBounds();(u=e.current)==null||u.style.setProperty("transform",`translate(${a.clientX-l}px, ${a.clientY-c}px)`)}return window.addEventListener("pointermove",o),()=>{window.removeEventListener("pointermove",o)}},[e,n])}const mse=({chatMessage:e})=>{const n=F(),t=P.useRef(null);return WR(t),d.jsx("div",{ref:t,className:"tl-cursor-chat tl-cursor-chat__bubble",style:{backgroundColor:n.user.getColor()},children:e})},yse=Lt(function({chatMessage:n,value:t,setValue:r}){const s=F(),o=xe(),i=P.useRef(null),a=n||o("cursor-chat.type-to-chat");WR(i),P.useLayoutEffect(()=>{const p=i.current;if(!p)return;const f=s.textMeasure.measureText(t||a,{fontFamily:"var(--font-body)",fontSize:12,fontWeight:"500",fontStyle:"normal",maxWidth:null,lineHeight:1,padding:"6px"});p.style.setProperty("width",f.w+"px")},[s,t,a]),P.useLayoutEffect(()=>{const p=s.timers.requestAnimationFrame(()=>{var f;(f=i.current)==null||f.focus()});return()=>{cancelAnimationFrame(p)}},[s]);const l=P.useCallback(()=>{s.updateInstanceState({isChatting:!1}),s.focus()},[s]),c=P.useCallback(p=>{const{value:f}=p.target;r(f.slice(0,64)),s.updateInstanceState({chatMessage:f})},[s,r]),u=P.useCallback(p=>{const f=i.current;if(!f)return;const{value:S}=f;switch(p.key){case"Enter":{if(Ie(p),p.stopPropagation(),!S){l();return}r("");break}case"Escape":{Ie(p),p.stopPropagation(),l();break}}},[l,r]),h=P.useCallback(p=>{p.stopPropagation()},[]);return d.jsx("input",{ref:i,className:"tl-cursor-chat",style:{backgroundColor:s.user.getColor()},onBlur:l,onChange:c,onKeyDown:u,onPaste:h,value:t,placeholder:a,spellCheck:!1})});function ox({checked:e}){return d.jsx(Cs,{icon:e?"check":"none",className:"tlui-button__icon",small:!0})}function Sse(){const e=F(),{addToast:n}=Qr(),{addDialog:t}=aa(),[r,s]=Ce.useState(!1);return d.jsxs(d.Fragment,{children:[d.jsxs(pe,{id:"items",children:[d.jsx(U,{id:"add-toast",onSelect:()=>{n({id:ct(),title:"Something good happened",description:"Hey, attend to this thing over here. It might be important!",keepOpen:!0,severity:"success"}),n({id:ct(),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:()=>{}}]}),n({id:ct(),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:()=>{}}]}),n({id:ct(),title:"Something bad happened",severity:"error",keepOpen:!0})},label:"Show toast"}),d.jsx(U,{id:"show-dialog",label:"Show dialog",onSelect:()=>{t({component:({onClose:o})=>d.jsx(wse,{displayDontShowAgain:!0,onCancel:()=>o(),onContinue:()=>o()}),onClose:()=>{}})}}),d.jsx(U,{id:"create-shapes",label:"Create 100 shapes",onSelect:()=>bse(e,100)}),d.jsx(U,{id:"count-nodes",label:"Count shapes / nodes",onSelect:()=>{var a;const o=e.getSelectedShapes(),i=o.length===0?e.getRenderingShapes():o;window.alert(`Shapes ${i.length}, DOM nodes:${(a=document.querySelector(".tl-shapes").querySelectorAll("*"))==null?void 0:a.length}`)}}),(()=>{if(r)throw Error("oh no!");return null})(),d.jsx(U,{id:"throw-error",onSelect:()=>s(!0),label:"Throw error"}),d.jsx(U,{id:"hard-reset",onSelect:MM,label:"Hard reset"})]}),d.jsxs(pe,{id:"flags",children:[d.jsx(vse,{}),d.jsx(xse,{})]})]})}function vse(){const e=Object.values(xt);return e.length?d.jsx(En,{id:"debug flags",label:"Debug Flags",children:d.jsx(pe,{id:"debug flags",children:e.map(n=>d.jsx(GR,{flag:n},n.name))})}):null}function xse(){const e=Object.values(B0);return e.length?d.jsx(En,{id:"feature flags",label:"Feature Flags",children:d.jsx(pe,{id:"feature flags",children:e.map(n=>d.jsx(GR,{flag:n},n.name))})}):null}function wse({title:e="title",body:n="hello hello hello",cancel:t="Cancel",confirm:r="Continue",displayDontShowAgain:s=!1,onCancel:o,onContinue:i}){const[a,l]=Ce.useState(!1);return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{children:[d.jsx(jg,{children:e}),d.jsx(Og,{})]}),d.jsx(Cu,{style:{maxWidth:350},children:n}),d.jsxs(Fw,{className:"tlui-dialog__footer__actions",children:[s&&d.jsxs(ce,{type:"normal",onClick:()=>l(!a),style:{marginRight:"auto"},children:[d.jsx(ox,{checked:a}),d.jsx(wt,{children:"Don’t show again"})]}),d.jsx(ce,{type:"normal",onClick:o,children:d.jsx(wt,{children:t})}),d.jsx(ce,{type:"primary",onClick:async()=>i(),children:d.jsx(wt,{children:r})})]})]})}const GR=Lt(function({flag:n,onChange:t}){const r=n.get();return d.jsx(Gn,{id:n.name,title:n.name,label:n.name.replace(/([a-z0-9])([A-Z])/g,s=>`${s[0]} ${s[1].toLowerCase()}`).replace(/^[a-z]/,s=>s.toUpperCase()),checked:r,onSelect:()=>{n.set(!r),t==null||t(!r)}})});let SE=0;function bse(e,n){const t=Array(n),r=Math.floor(Math.sqrt(n));for(let s=0;s{e.createShapes(t).setSelectedShapes(t.map(s=>s.id))})}function Pse({children:e}){const n=e??d.jsx(Sse,{});return d.jsxs(qi,{id:"debug",children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon",title:"Debug menu",children:d.jsx(Se,{icon:"dots-horizontal"})})}),d.jsx(Qi,{side:"top",align:"end",alignOffset:0,children:d.jsx(Tr,{type:"menu",sourceId:"debug-panel",children:n})})]})}const Cse=P.memo(function(){const{DebugMenu:n}=pi();return d.jsxs("div",{className:"tlui-debug-panel",children:[d.jsx(Ese,{}),d.jsx(_se,{}),n&&d.jsx(n,{})]})});function Ise(e=!0){const[n,t]=P.useState(0),r=F();P.useEffect(()=>{if(!e)return;const s=()=>t(o=>o+1);return r.on("tick",s),()=>{r.off("tick",s)}},[r,e])}const Ese=Lt(function(){Ise();const n=F(),t=n.getPath(),r=n.getHoveredShape(),s=n.getOnlySelectedShape(),o=t==="select.idle"||!t.includes("select.")?r:s,i=o&&t.includes("select.")?` / ${o.type||""}${"geo"in o.props?" / "+o.props.geo:""} / [${b.ToInt(n.getPointInShapeSpace(o,n.inputs.currentPagePoint))}]`:"",a=t.startsWith("select.")&&!t.includes(".idle")?` / [${b.ToInt(n.inputs.originPagePoint)}] → [${b.ToInt(n.inputs.currentPagePoint)}] = ${b.Dist(n.inputs.originPagePoint,n.inputs.currentPagePoint).toFixed(0)}`:"";return d.jsx("div",{className:"tlui-debug-panel__current-state",children:`${t}${i}${a}`})});function _se(){const e=F(),n=H("show_fps",()=>xt.showFps.get(),[xt]),t=P.useRef(null);return P.useEffect(()=>{if(!n)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 h=Math.round(l*(r/a)*(1e3/r));h>s&&(s=h);const p=s*.75;(h=p&&c)&&(c=!c),t.current.innerHTML=`FPS ${h.toString()}`,t.current.className="tlui-debug-panel__fps"+(c?" tlui-debug-panel__fps__slow":""),a-=r,l=0,i=performance.now()}o=e.timers.requestAnimationFrame(u)}return u(),()=>{cancelAnimationFrame(o)}},[n,e]),n?d.jsx("div",{ref:t}):null}const kse=P.memo(function(){const n=Cn(),{MainMenu:t,QuickActions:r,ActionsMenu:s,PageMenu:o}=pi();return!t&&!o&&n<6?null:d.jsx("div",{className:"tlui-menu-zone",children:d.jsxs("div",{className:"tlui-buttons__horizontal",children:[t&&d.jsx(t,{}),o&&d.jsx(o,{}),n<6?null:d.jsxs(d.Fragment,{children:[r&&d.jsx(r,{}),s&&d.jsx(s,{})]})]})})});function Tse(){const e=F(),n=ie(),[t,r]=P.useState(!1),s=P.useRef(!1);return Ko("toggle showback to content",()=>{const o=s.current,i=e.getCurrentPageShapeIds();let a=!1;i.size&&(a=i.size===e.getCulledShapes().size),o!==a&&(r(a),s.current=a)},[e]),t?d.jsx(U,{...n["back-to-content"],onSelect:()=>{n["back-to-content"].onSelect("helper-buttons"),r(!1)}}):null}function Mse(){const e=F(),n=ie();return H("is pen mode",()=>e.getInstanceState().isPenMode,[e])?d.jsx(U,{...n["exit-pen-mode"]}):null}function Ase(){const e=F(),n=ie();return H("is following user",()=>!!e.getInstanceState().followingUserId,[e])?d.jsx(U,{...n["stop-following"]}):null}function jse(){return d.jsxs(d.Fragment,{children:[d.jsx(Mse,{}),d.jsx(Tse,{}),d.jsx(Ase,{})]})}function Ose({children:e}){const n=e??d.jsx(jse,{});return d.jsx("div",{className:"tlui-helper-buttons",children:d.jsx(Tr,{type:"helper-buttons",sourceId:"helper-buttons",children:n})})}function Dse(){const e=ie(),n=Rg(),t=Lg();return d.jsxs(d.Fragment,{children:[d.jsxs(pe,{label:"shortcuts-dialog.tools",id:"tools",children:[d.jsx(U,{...e["toggle-tool-lock"]}),d.jsx(U,{...e["insert-media"]}),d.jsx(U,{...n.select}),d.jsx(U,{...n.draw}),d.jsx(U,{...n.eraser}),d.jsx(U,{...n.hand}),d.jsx(U,{...n.rectangle}),d.jsx(U,{...n.ellipse}),d.jsx(U,{...n.arrow}),d.jsx(U,{...n.line}),d.jsx(U,{...n.text}),d.jsx(U,{...n.frame}),d.jsx(U,{...n.note}),d.jsx(U,{...n.laser})]}),d.jsxs(pe,{label:"shortcuts-dialog.preferences",id:"preferences",children:[d.jsx(U,{...e["toggle-dark-mode"]}),d.jsx(U,{...e["toggle-focus-mode"]}),d.jsx(U,{...e["toggle-grid"]})]}),d.jsxs(pe,{label:"shortcuts-dialog.edit",id:"edit",children:[d.jsx(U,{...e.undo}),d.jsx(U,{...e.redo}),d.jsx(U,{...e.cut}),d.jsx(U,{...e.copy}),d.jsx(U,{...e.paste}),d.jsx(U,{...e["select-all"]}),d.jsx(U,{...e.delete}),d.jsx(U,{...e.duplicate})]}),d.jsxs(pe,{label:"shortcuts-dialog.view",id:"view",children:[d.jsx(U,{...e["zoom-in"]}),d.jsx(U,{...e["zoom-out"]}),d.jsx(U,{...e["zoom-to-100"]}),d.jsx(U,{...e["zoom-to-fit"]}),d.jsx(U,{...e["zoom-to-selection"]})]}),d.jsxs(pe,{label:"shortcuts-dialog.transform",id:"transform",children:[d.jsx(U,{...e["bring-to-front"]}),d.jsx(U,{...e["bring-forward"]}),d.jsx(U,{...e["send-backward"]}),d.jsx(U,{...e["send-to-back"]}),d.jsx(U,{...e.group}),d.jsx(U,{...e.ungroup}),d.jsx(U,{...e["flip-horizontal"]}),d.jsx(U,{...e["flip-vertical"]}),d.jsx(U,{...e["align-top"]}),d.jsx(U,{...e["align-center-vertical"]}),d.jsx(U,{...e["align-bottom"]}),d.jsx(U,{...e["align-left"]}),d.jsx(U,{...e["align-center-horizontal"]}),d.jsx(U,{...e["align-right"]})]}),t&&d.jsx(pe,{label:"shortcuts-dialog.collaboration",id:"collaboration",children:d.jsx(U,{...e["open-cursor-chat"]})})]})}const Rse=P.memo(function({children:n}){const t=xe(),r=Cn(),s=n??d.jsx(Dse,{});return d.jsxs(d.Fragment,{children:[d.jsxs(Ag,{className:"tlui-shortcuts-dialog__header",children:[d.jsx(jg,{children:t("shortcuts-dialog.title")}),d.jsx(Og,{})]}),d.jsx(Cu,{className:le("tlui-shortcuts-dialog__body",{"tlui-shortcuts-dialog__body__mobile":r<=yt.MOBILE_XS,"tlui-shortcuts-dialog__body__tablet":r<=yt.TABLET}),children:d.jsx(Tr,{type:"keyboard-shortcuts",sourceId:"kbd",children:s})}),d.jsx("div",{className:"tlui-dialog__scrim"})]})}),Lse=[{colorScheme:"light",label:"theme.light"},{colorScheme:"dark",label:"theme.dark"},{colorScheme:"system",label:"theme.system"}];function $se(){const e=F(),n=qt(),t=H("colorScheme",()=>e.user.getUserPreferences().colorScheme??e.user.getIsDarkMode()?"dark":"light",[e]);return d.jsx(En,{id:"help menu color-scheme",label:"menu.theme",children:d.jsx(pe,{id:"languages",children:Lse.map(({colorScheme:r,label:s})=>d.jsx(Gn,{id:`color-scheme-${r}`,label:s,checked:r===t,onSelect:()=>{e.user.updateUserPreferences({colorScheme:r}),n("color-scheme",{source:"menu",value:r})}},r))})})}function VR(){const e=F(),n=qt(),t=H("locale",()=>e.user.getLocale(),[e]);return d.jsx(En,{id:"help menu language",label:"menu.language",children:d.jsx(pe,{id:"languages",children:bu.map(({locale:r,label:s})=>d.jsx(Gn,{id:`language-${r}`,title:r,label:s,checked:r===t,onSelect:()=>{e.user.updateUserPreferences({locale:r}),n("change-language",{source:"menu",locale:r})}},r))})})}function Nse(){return d.jsxs(d.Fragment,{children:[d.jsx(VR,{}),d.jsx(YR,{})]})}function YR(){const{KeyboardShortcutsDialog:e}=pi(),{addDialog:n}=aa();return e?d.jsx(U,{id:"keyboard-shortcuts-button",label:"help-menu.keyboard-shortcuts",readonlyOk:!0,onSelect:()=>{n({component:e})}}):null}function Fse(){return d.jsxs(d.Fragment,{children:[d.jsx(Bse,{}),d.jsx(Wse,{}),d.jsx(zse,{}),d.jsx(Gse,{}),d.jsx(Yse,{}),d.jsx(Vse,{})]})}function zse(){const e=ie();return d.jsxs(En,{id:"export-all-as",label:"context-menu.export-all-as",size:"small",children:[d.jsxs(pe,{id:"export-all-as-group",children:[d.jsx(U,{...e["export-all-as-svg"]}),d.jsx(U,{...e["export-all-as-png"]}),d.jsx(U,{...e["export-all-as-json"]})]}),d.jsx(pe,{id:"export-all-as-bg",children:d.jsx(w1,{})})]})}function Bse(){const e=F(),n=H("isSelectToolActive",()=>e.getCurrentToolId()==="select",[e]);return d.jsxs(En,{id:"edit",label:"menu.edit",disabled:!n,children:[d.jsx(Kse,{}),d.jsx(zR,{}),d.jsx(BR,{}),d.jsx(Use,{}),d.jsx(Hse,{}),d.jsx(pe,{id:"select-all",children:d.jsx(UR,{})})]})}function Use(){return d.jsxs(pe,{id:"misc",children:[d.jsx(jR,{}),d.jsx(OR,{}),d.jsx(MR,{}),d.jsx(TR,{}),d.jsx(DR,{}),d.jsx(RR,{}),d.jsx(KR,{}),d.jsx(HR,{}),d.jsx(AR,{})]})}function Hse(){return d.jsxs(pe,{id:"lock",children:[d.jsx(LR,{}),d.jsx(Ure,{})]})}function Kse(){const e=ie(),n=uD(),t=cD();return d.jsxs(pe,{id:"undo-redo",children:[d.jsx(U,{...e.undo,disabled:!n}),d.jsx(U,{...e.redo,disabled:!t})]})}function Wse(){const e=ie();return d.jsx(En,{id:"view",label:"menu.view",children:d.jsxs(pe,{id:"view-actions",children:[d.jsx(U,{...e["zoom-in"]}),d.jsx(U,{...e["zoom-out"]}),d.jsx($R,{}),d.jsx(NR,{}),d.jsx(FR,{})]})})}function Gse(){const e=ie();return d.jsxs(pe,{id:"extras",children:[d.jsx(U,{...e["insert-embed"]}),d.jsx(U,{...e["insert-media"]})]})}function Vse(){function e(n){window.open(n,"_blank")}return d.jsx(pe,{id:"help",children:d.jsx(En,{id:"help",label:"menu.help",children:d.jsxs(pe,{id:"help-actions",children:[d.jsx(YR,{}),d.jsx(U,{id:"about",label:"help-menu.docs",icon:"external-link",readonlyOk:!0,onSelect:()=>{e("https://tldraw.dev")}})]})})})}function Yse(){return d.jsx(pe,{id:"preferences",children:d.jsxs(En,{id:"preferences",label:"menu.preferences",children:[d.jsxs(pe,{id:"preferences-actions",children:[d.jsx(ese,{}),d.jsx(tse,{}),d.jsx(nse,{}),d.jsx(rse,{}),d.jsx(sse,{}),d.jsx(ose,{}),d.jsx(ise,{}),d.jsx(lse,{}),d.jsx(cse,{}),d.jsx(ase,{})]}),d.jsx(pe,{id:"color-scheme",children:d.jsx($se,{})}),d.jsx(pe,{id:"language",children:d.jsx(VR,{})})]})})}const Xse=P.memo(function({children:n}){const t=$t(),[r,s]=ho("main menu"),o=xe(),i=n??d.jsx(Fse,{});return d.jsxs(S1,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[d.jsx(v1,{asChild:!0,dir:"ltr",children:d.jsx(ce,{type:"icon","data-testid":"main-menu.button",title:o("menu.title"),children:d.jsx(Se,{icon:"menu",small:!0})})}),d.jsx(Kg,{container:t,children:d.jsx(x1,{className:"tlui-menu",side:"bottom",align:"start",collisionPadding:4,alignOffset:0,sideOffset:6,children:d.jsx(Tr,{type:"menu",sourceId:"main-menu",children:i})})})]})}),$y={};function dc(e){if($y[e])return $y[e];const t=document.createElement("canvas").getContext("2d");t.fillStyle=e,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 $y[e]=a,a}const mp=10,XR=4*6*mp+12+4*12;function Pa(e,{center:n,radius:t,numArcSegments:r=20,startAngle:s=0,endAngle:o=Le,offset:i=0}){const a=(o-s)/r;let l=i;for(let c=s;c{for(var s=Jse(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&Qse(n,t,s),s};class fo{constructor(n,t,r){g(this,"disposables",[]);g(this,"close",()=>this.disposables.forEach(n=>n()));g(this,"gl");g(this,"shapeGeometryCache");g(this,"colors");g(this,"id",ct());g(this,"canvasBoundingClientRect",Mt("canvasBoundingClientRect",new Q));g(this,"originPagePoint",new b);g(this,"originPageCenter",new b);g(this,"isInViewport",!1);g(this,"getMinimapPagePoint",(n,t)=>{const r=this.getCanvasPageBounds(),s=this.getCanvasScreenBounds();let o=n-s.x,i=t-s.y;return o*=r.width/s.width,i*=r.height/s.height,o+=r.minX,i+=r.minY,new b(o,i,1)});g(this,"minimapScreenPointToPagePoint",(n,t,r=!1,s=!1)=>{const{editor:o}=this,i=o.getViewportPageBounds();let{x:a,y:l}=this.getMinimapPagePoint(n,t);if(s){const c=this.editor.getCurrentPageBounds()??new Q,u=c.minX-i.width/2,h=c.maxX+i.width/2,p=c.minY-i.height/2,f=c.maxY+i.height/2,S=Math.max(0,u+i.width-a),m=Math.max(0,-(h-i.width-a)),x=Math.max(0,p+i.height-l),y=Math.max(0,-(f-i.height-l));a+=(S-m)/2,l+=(x-y)/2,a=kt(a,u,h),l=kt(l,p,f)}if(r){const{originPagePoint:c}=this,u=Math.abs(a-c.x),h=Math.abs(l-c.y);u>h?l=c.y:a=c.x}return new b(a,l)});g(this,"render",()=>{const n=this.gl.context,t=this.getCanvasSize();this.gl.setCanvasPageBounds(this.getCanvasPageBoundsArray()),this.elem.width=t.x,this.elem.height=t.y,n.viewport(0,0,t.x,t.y),n.clearColor(this.colors.background[0],this.colors.background[1],this.colors.background[2],1),n.clear(n.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 l=0,c=a.length;l{const o=n.getShapeMaskedPageBounds(s.id);if(!o)return null;const i=new Float32Array(12);return Ca(i,0,o.x,o.y,o.w,o.h),i}),this.colors=this._getColors(),this.disposables.push(this._listenForCanvasResize(),oa("minimap render",this.render))}_getColors(){const n=getComputedStyle(this.editor.getContainer());return{shapeFill:dc(n.getPropertyValue("--color-text-3").trim()),selectFill:dc(n.getPropertyValue("--color-selected").trim()),viewportFill:dc(n.getPropertyValue("--color-muted-1").trim()),background:dc(n.getPropertyValue("--color-low").trim())}}updateColors(){this.colors=this._getColors()}getDpr(){return this.editor.getInstanceState().devicePixelRatio}getContentPageBounds(){const n=this.editor.getViewportPageBounds(),t=this.editor.getCurrentPageBounds();return t?Q.Expand(t,n):n}getContentScreenBounds(){const n=this.getContentPageBounds(),t=this.editor.pageToScreen(n.point),r=this.editor.pageToScreen(new b(n.maxX,n.maxY));return new Q(t.x,t.y,r.x-t.x,r.y-t.y)}_getCanvasBoundingRect(){const{x:n,y:t,width:r,height:s}=this.elem.getBoundingClientRect();return new Q(n,t,r,s)}getCanvasScreenBounds(){return this.canvasBoundingClientRect.get()}_listenForCanvasResize(){const n=new ResizeObserver(()=>{const t=this._getCanvasBoundingRect();this.canvasBoundingClientRect.set(t)});return n.observe(this.elem),n.observe(this.container),()=>n.disconnect()}getCanvasSize(){const n=this.canvasBoundingClientRect.get(),t=this.getDpr();return new b(n.width*t,n.height*t)}getCanvasClientPosition(){return this.canvasBoundingClientRect.get().point}getCanvasPageBounds(){const n=this.getCanvasScreenBounds(),t=this.getContentPageBounds(),r=n.width/n.height;let s=t.width,o=s/r;o{try{const u=new fo(e,t.current,n);return s.current=u,s.current.close}catch(u){e.annotateError(u,{origin:"minimap",willCrashApp:!1}),e.timers.setTimeout(()=>{throw u})}},[e,n]);const o=P.useCallback(u=>{if(!e.getCurrentPageShapeIds().size||!s.current)return;const h=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),p=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);s.current.originPagePoint.setTo(p),s.current.originPageCenter.setTo(e.getViewportPageBounds().center),e.centerOnPoint(h,{animation:{duration:e.options.animationMediumMs}})},[e]),i=P.useCallback(u=>{if(!s.current)return;const h=u.currentTarget;if(Vu(h,u),!e.getCurrentPageShapeIds().size)return;r.current=!0,s.current.isInViewport=!1;const p=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),f=e.getViewportPageBounds(),S=s.current.getContentPageBounds();if(new Q(S.x-f.width/2,S.y-f.height/2,S.width+f.width,S.height+f.height).containsPoint(p)&&!f.containsPoint(p)){s.current.isInViewport=f.containsPoint(p);const y=b.Sub(f.center,f.point),v=b.Add(p,y);s.current.originPagePoint.setTo(v),s.current.originPageCenter.setTo(p),e.centerOnPoint(p,{animation:{duration:e.options.animationMediumMs}})}else{const y=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);s.current.isInViewport=f.containsPoint(y),s.current.originPagePoint.setTo(y),s.current.originPageCenter.setTo(f.center)}function x(y){h&&Yu(h,y),r.current=!1,document.body.removeEventListener("pointerup",x)}document.body.addEventListener("pointerup",x)},[e]),a=P.useCallback(u=>{if(!s.current)return;const h=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,u.shiftKey,!0);if(r.current){if(s.current.isInViewport){const m=s.current.originPagePoint.clone().sub(s.current.originPageCenter);e.centerOnPoint(b.Sub(h,m));return}e.centerOnPoint(h)}const p=s.current.getMinimapPagePoint(u.clientX,u.clientY),f=e.pageToScreen(p),S={type:"pointer",target:"canvas",name:"pointer_move",...Nn(u),point:f,isPen:e.getInstanceState().isPenMode};e.dispatch(S)},[e]),l=P.useCallback(u=>{const h=SM(u);e.dispatch({type:"wheel",name:"wheel",delta:h,point:new b(u.clientX,u.clientY),shiftKey:u.shiftKey,altKey:u.altKey,ctrlKey:u.metaKey||u.ctrlKey})},[e]),c=Ju();return P.useEffect(()=>{e.timers.setTimeout(()=>{var u,h;(u=s.current)==null||u.updateColors(),(h=s.current)==null||h.render()})},[c,e]),d.jsx("div",{className:"tlui-minimap",children:d.jsx("canvas",{role:"img","aria-label":"minimap",ref:t,className:"tlui-minimap__canvas",onDoubleClick:o,onPointerMove:a,onPointerDown:i,onWheel:l})})}function toe(e,n){const[t,r]=Ce.useState(n);Ce.useLayoutEffect(()=>{const o=N0(e);if(o)try{r(JSON.parse(o))}catch{console.error(`Could not restore value ${e} from local storage.`)}},[e]);const s=Ce.useCallback(o=>{r(i=>{const a=typeof o=="function"?o(i):o;return F0(e,JSON.stringify(a)),a})},[e]);return[t,s]}const noe=P.memo(function(){const n=ie(),t=xe(),r=Cn(),[s,o]=toe("minimap",!0),i=P.useCallback(()=>{o(c=>!c)},[o]),{ZoomMenu:a,Minimap:l}=pi();return rn["zoom-out"].onSelect("navigation-zone"),children:d.jsx(Se,{icon:"minus"})}),a&&d.jsx(a,{}),d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-in",title:`${t(Iu(n["zoom-in"].label))} ${sx(n["zoom-in"].kbd)}`,onClick:()=>n["zoom-in"].onSelect("navigation-zone"),children:d.jsx(Se,{icon:"plus"})}),l&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:t("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:i,children:d.jsx(Se,{icon:s?"chevrons-ne":"chevrons-sw"})})]})}),l&&r>=yt.TABLET&&!s&&d.jsx(l,{})]})}),roe=function({name:n,id:t,isCurrentPage:r}){const s=F(),o=qt(),i=P.useRef(null),a=P.useCallback(()=>{s.mark("rename page")},[s]),l=P.useCallback(c=>{s.renamePage(t,c||"New Page"),o("rename-page",{source:"page-menu"})},[s,t,o]);return d.jsx(Dg,{className:"tlui-page-menu__item__input",ref:c=>i.current=c,defaultValue:n,onValueChange:l,onFocus:a,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:r,autoSelect:!0})},ix=(e,n,t,r,s)=>{let o;const i=e.getPages(),a=t>r?i[r-1]:i[r],l=t>r?i[r]:i[r+1];a&&!l?o=Fr(a.index):!a&&l?o=R9(i[0].index):o=vu(a.index,l.index),o!==i[t].index&&(e.mark("moving page"),e.updatePage({id:n,index:o}),s("move-page",{source:"page-menu"}))},xE=Lt(function({index:n,listSize:t,item:r,onRename:s}){const o=F(),i=xe(),a=o.getPages(),l=qt(),c=P.useCallback(()=>{o.mark("creating page");const f=to.createId();o.duplicatePage(r.id,f),l("duplicate-page",{source:"page-menu"})},[o,r,l]),u=P.useCallback(()=>{ix(o,r.id,n,n-1,l)},[o,r,n,l]),h=P.useCallback(()=>{ix(o,r.id,n,n+1,l)},[o,r,n,l]),p=P.useCallback(()=>{o.mark("deleting page"),o.deletePage(r.id),l("delete-page",{source:"page-menu"})},[o,r,l]);return d.jsxs(qi,{id:`page item submenu ${n}`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon",title:i("page-menu.submenu.title"),children:d.jsx(Se,{icon:"dots-vertical"})})}),d.jsx(Qi,{alignOffset:0,side:"right",sideOffset:-4,children:d.jsxs(Tr,{type:"menu",sourceId:"page-menu",children:[d.jsxs(pe,{id:"modify",children:[s&&d.jsx(U,{id:"rename",label:"page-menu.submenu.rename",onSelect:s}),d.jsx(U,{id:"duplicate",label:"page-menu.submenu.duplicate-page",onSelect:c,disabled:a.length>=o.options.maxPages}),n>0&&d.jsx(U,{id:"move-up",onSelect:u,label:"page-menu.submenu.move-up"}),n1&&d.jsx(pe,{id:"delete",children:d.jsx(U,{id:"delete",onSelect:p,label:"page-menu.submenu.delete"})})]})})]})}),soe=P.memo(function(){const n=F(),t=qt(),r=xe(),s=Cn(),o=P.useCallback(()=>y(!1),[]),[i,a]=ho("page-menu",o),l=36,c=P.useRef(null),u=H("pages",()=>n.getPages(),[n]),h=H("currentPage",()=>n.getCurrentPage(),[n]),p=H("currentPageId",()=>n.getCurrentPageId(),[n]),f=co(),S=H("maxPageCountReached",()=>n.getPages().length>=n.options.maxPages,[n]),m=H("isCoarsePointer",()=>n.getInstanceState().isCoarsePointer,[n]),[x,y]=P.useState(!1),v=P.useCallback(()=>{f||y(j=>!j)},[f]),w=P.useRef({isPointing:!1,status:"idle",pointing:null,startY:0,startIndex:0,dragIndex:0}),[C,E]=P.useState(Object.fromEntries(u.map((j,O)=>[j.id,{y:O*l,offsetY:0,isSelected:!1}])));P.useLayoutEffect(()=>{E(Object.fromEntries(u.map((j,O)=>[j.id,{y:O*l,offsetY:0,isSelected:!1}])))},[l,u]),P.useEffect(()=>{i&&n.timers.requestAnimationFrame(()=>{const j=document.querySelector(`[data-testid="page-menu-item-${p}"]`);if(j){const O=c.current;if(!O)return;const R=j.offsetTop,K=O.scrollTop;Rz&&O.scrollTo({top:B-O.offsetHeight})}})},[l,p,i,n]);const k=P.useCallback(j=>{const{clientY:O,currentTarget:R}=j,{dataset:{id:K,index:B}}=R;if(!K||!B)return;const z=w.current;Vu(j.currentTarget,j),z.status="pointing",z.pointing={id:K,index:+B};const Y=C[K].y;z.startY=O,z.startIndex=Math.max(0,Math.min(Math.round(Y/l),u.length-1))},[l,u.length,C]),I=P.useCallback(j=>{const O=w.current;if(O.status==="pointing"){const{clientY:R}=j,K=R-O.startY;Math.abs(K)>5&&(O.status="dragging")}if(O.status==="dragging"){const{clientY:R}=j,K=R-O.startY,B=C[O.pointing.id],{startIndex:z,pointing:W}=O,Y=B.y+K,q=Math.max(0,Math.min(Math.round(Y/l),u.length-1)),ae={...C};if(ae[W.id]={y:B.y,offsetY:K,isSelected:!0},q!==O.dragIndex){O.dragIndex=q;for(let fe=0;fez&&(q>=fe&&fe>z?J=(fe-1)*l:J=fe*l),J!==ae[we.id].y&&(ae[we.id]={y:J,offsetY:0,isSelected:!0})}}E(ae)}},[l,u,C]),_=P.useCallback(j=>{const O=w.current;if(O.status==="dragging"){const{id:R,index:K}=O.pointing;ix(n,R,K,O.dragIndex,t)}Yu(j.currentTarget,j),O.status="idle"},[n,t]),T=P.useCallback(j=>{const O=w.current;j.key==="Escape"&&(O.status==="dragging"&&E(Object.fromEntries(u.map((R,K)=>[R.id,{y:K*l,offsetY:0,isSelected:!1}]))),O.status="idle")},[l,u]),M=P.useCallback(()=>{f||(n.run(()=>{n.mark("creating page");const j=to.createId();n.createPage({name:r("page-menu.new-page-initial-name"),id:j}),n.setCurrentPage(j),y(!0)}),t("new-page",{source:"page-menu"}))},[n,r,f,t]),D=P.useCallback(j=>{n.setCurrentPage(j),t("change-page",{source:"page-menu"})},[n,t]),$=P.useCallback((j,O)=>{n.renamePage(j,O),t("rename-page",{source:"page-menu"})},[n,t]);return d.jsxs(r1,{id:"pages",onOpenChange:a,open:i,children:[d.jsx(s1,{"data-testid":"main.page-menu",children:d.jsxs(ce,{type:"menu",title:h.name,"data-testid":"page-menu.button",className:"tlui-page-menu__trigger",children:[d.jsx("div",{className:"tlui-page-menu__name",children:h.name}),d.jsx(Se,{icon:"chevron-down",small:!0})]})}),d.jsx(o1,{side:"bottom",align:"start",sideOffset:6,children:d.jsxs("div",{className:"tlui-page-menu__wrapper",children:[d.jsxs("div",{className:"tlui-page-menu__header",children:[d.jsx("div",{className:"tlui-page-menu__header__title",children:r("page-menu.title")}),!f&&d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsx(ce,{type:"icon","data-testid":"page-menu.edit",title:r(x?"page-menu.edit-done":"page-menu.edit-start"),onClick:v,children:d.jsx(Se,{icon:x?"check":"edit"})}),d.jsx(ce,{type:"icon","data-testid":"page-menu.create",title:r(S?"page-menu.max-page-count-reached":"page-menu.create-new-page"),disabled:S,onClick:M,children:d.jsx(Se,{icon:"plus"})})]})]}),d.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((j,O)=>{const R=C[j.id]??{position:O*40,offsetY:0};return x?d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page_menu__item__sortable",style:{zIndex:j.id===h.id?888:O,transform:`translate(0px, ${R.y+R.offsetY}px)`},children:[d.jsx(ce,{type:"icon",tabIndex:-1,className:"tlui-page_menu__item__sortable__handle",onPointerDown:k,onPointerUp:_,onPointerMove:I,onKeyDown:T,"data-id":j.id,"data-index":O,children:d.jsx(Se,{icon:"drag-handle-dots"})}),s{const K=window.prompt("Rename page",j.name);K&&K!==j.name&&$(j.id,K)},onDoubleClick:v,children:[d.jsx(ox,{checked:j.id===h.id}),d.jsx(wt,{children:j.name})]}):d.jsx("div",{className:"tlui-page_menu__item__sortable__title",style:{height:l},children:d.jsx(roe,{id:j.id,name:j.name,isCurrentPage:j.id===h.id})}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu","data-isediting":x,children:d.jsx(xE,{index:O,item:j,listSize:u.length})})]},j.id+"_editing"):d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page-menu__item",children:[d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>D(j.id),onDoubleClick:v,title:r("page-menu.go-to-page"),children:[d.jsx(ox,{checked:j.id===h.id}),d.jsx(wt,{children:j.name})]}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu",children:d.jsx(xE,{index:O,item:j,listSize:u.length,onRename:()=>{if(n.environment.isIos){const K=window.prompt("Rename page",j.name);K&&K!==j.name&&$(j.id,K)}else y(!0),p!==j.id&&D(j.id)}})})]},j.id)})})]})})]})});function ooe(){const e=ie(),n=F(),t=uD(),r=cD(),s=In(1),o=co(),i=H("should display quick actions",()=>n.isInAny("select","hand","zoom"),[n]),a=po(),l=s&&a;if(!(o&&!i))return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e.undo,disabled:!t}),d.jsx(U,{...e.redo,disabled:!r}),d.jsx(U,{...e.delete,disabled:!l}),d.jsx(U,{...e.duplicate,disabled:!l})]})}const ioe=P.memo(function({children:n}){const t=n??d.jsx(ooe,{});return d.jsx(Tr,{type:"small-icons",sourceId:"quick-actions",children:t})});function aoe({userId:e}){const n=ug(e);return n?d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:n.color},children:n.userName==="New User"?"":n.userName[0]??""},e):null}const loe=Lt(function({userId:n}){const t=F(),r=xe(),s=qt(),o=ug(n),i=P.useCallback(()=>{t.getInstanceState().followingUserId===n?(t.stopFollowingUser(),s("stop-following",{source:"people-menu"})):(t.startFollowingUser(n),s("start-following",{source:"people-menu"}))},[t,n,s]),a=(o==null?void 0:o.followingUserId)===t.user.getId(),l=t.getInstanceState().followingUserId===n;return o?d.jsxs("div",{className:"tlui-people-menu__item tlui-buttons__horizontal",children:[d.jsxs(ce,{type:"menu",className:"tlui-people-menu__item__button",onClick:()=>t.zoomToUser(n),onDoubleClick:i,children:[d.jsx(Cs,{icon:"color",color:o.color}),d.jsx("div",{className:"tlui-people-menu__name",children:o.userName??"New User"})]}),d.jsx(ce,{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,"data-active":l||a,children:d.jsx(Se,{icon:a?"leading":l?"following":"follow"})})]}):null});function coe({count:e}){return d.jsx("div",{className:"tlui-people-menu__more",children:"+"+Math.abs(e)})}const uoe=Lt(function(){const n=F(),t=$t(),r=xe(),s=qt(),o=P.useRef(!1),[i,a]=P.useState(!1),l=P.useCallback(m=>{a(m)},[]),c=n.user.getColor(),u=P.useCallback(m=>{n.user.updateUserPreferences({color:m}),s("set-color",{source:"people-menu"})},[n,s]),{handleButtonClick:h,handleButtonPointerDown:p,handleButtonPointerEnter:f,handleButtonPointerUp:S}=Ce.useMemo(()=>{const m=()=>{o.current=!1,window.removeEventListener("pointerup",m)};return{handleButtonClick:C=>{const{id:E}=C.currentTarget.dataset;E&&c!==E&&u(E)},handleButtonPointerDown:C=>{const{id:E}=C.currentTarget.dataset;E&&(u(E),o.current=!0,window.addEventListener("pointerup",m))},handleButtonPointerEnter:C=>{if(!o.current)return;const{id:E}=C.currentTarget.dataset;E&&u(E)},handleButtonPointerUp:C=>{const{id:E}=C.currentTarget.dataset;E&&u(E)}}},[c,u]);return d.jsxs(Jw,{onOpenChange:l,open:i,children:[d.jsx(e1,{dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__color",style:{color:n.user.getColor()},title:r("people-menu.change-color"),children:d.jsx(Se,{icon:"color"})})}),d.jsx(t1,{container:t,children:d.jsx(n1,{dir:"ltr",className:"tlui-menu tlui-people-menu__user__color-picker",align:"start",side:"left",sideOffset:8,children:d.jsx("div",{className:"tlui-buttons__grid",children:_v.map(m=>d.jsx(ce,{type:"icon","data-id":m,"data-testid":m,"aria-label":m,"data-state":c===m?"hinted":void 0,title:m,className:"tlui-button-grid__button",style:{color:m},onPointerEnter:f,onPointerDown:p,onPointerUp:S,onClick:h,children:d.jsx(Se,{icon:"color"})},m))})})})]})});function doe(){const e=F(),n=qt(),t=H("userName",()=>e.user.getName(),[]),r=xe(),s=P.useRef(t),o=P.useRef(t),[i,a]=P.useState(!1),l=P.useCallback(()=>{a(h=>!h)},[]),c=P.useCallback(h=>{o.current=h,e.user.updateUserPreferences({name:h})},[e]),u=P.useCallback(()=>{s.current!==o.current&&(n("change-user-name",{source:"people-menu"}),s.current=o.current)},[n]);return d.jsxs("div",{className:"tlui-people-menu__user",children:[d.jsx(uoe,{}),i?d.jsx(Dg,{className:"tlui-people-menu__user__input",defaultValue:t,onValueChange:c,onComplete:l,onCancel:l,onBlur:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:!0,autoSelect:!0}):d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"tlui-people-menu__user__name",onDoubleClick:()=>{i||a(!0)},children:t}),t==="New User"?d.jsx("div",{className:"tlui-people-menu__user__label",children:r("people-menu.user")}):null]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__edit","data-testid":"people-menu.change-name",title:r("people-menu.change-name"),onClick:l,children:d.jsx(Se,{icon:i?"check":"edit"})})]})}const hoe=Lt(function({children:n}){const t=xe(),r=$t(),s=F(),o=PM(),i=H("user",()=>s.user.getColor(),[s]),a=H("user",()=>s.user.getName(),[s]),[l,c]=ho("people menu");return d.jsxs(Jw,{onOpenChange:c,open:l,children:[d.jsx(e1,{dir:"ltr",asChild:!0,children:d.jsxs("button",{className:"tlui-people-menu__avatars-button",title:t("people-menu.title"),children:[o.length>5&&d.jsx(coe,{count:o.length-5}),d.jsxs("div",{className:"tlui-people-menu__avatars",children:[o.slice(-5).map(u=>d.jsx(aoe,{userId:u},u)),d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:i},children:a==="New User"?"":a[0]??""})]})]})}),d.jsx(t1,{container:r,children:d.jsx(n1,{dir:"ltr",className:"tlui-menu",align:"end",side:"bottom",sideOffset:2,alignOffset:-5,children:d.jsxs("div",{className:"tlui-people-menu__wrapper",children:[d.jsx("div",{className:"tlui-people-menu__section",children:d.jsx(doe,{})}),o.length>0&&d.jsx("div",{className:"tlui-people-menu__section",children:o.map(u=>d.jsx(loe,{userId:u},u+"_presence"))}),n]})})})]})});function poe(){return d.jsx("div",{className:"tlui-share-zone",draggable:!1,children:d.jsx(hoe,{})})}const foe=Object.freeze([lr,Ui,Hi,ws]);function qR(e=foe){const n=F();return H("getRelevantStyles",()=>{var o;const t=new Tv(n.getSharedStyles()),r=!!((o=n.root.getCurrent())!=null&&o.shapeType),s=n.isIn("select")&&n.getSelectedShapeIds().length>0;if(t.size===0&&n.isIn("select")&&n.getSelectedShapeIds().length===0)for(const i of e)t.applyValue(i,n.getStyleForNextShape(i));return r||s||t.size>0?t:null},[n])}const Pr={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"},{value:"pattern",icon:"fill-pattern"}],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"}],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"}]},ki=P.memo(function(n){const{uiType:t,items:r,title:s,style:o,value:i,onValueChange:a,theme:l}=n,c=F(),u=xe(),h=P.useRef(!1),p=P.useRef(null),{handleButtonClick:f,handleButtonPointerDown:S,handleButtonPointerEnter:m,handleButtonPointerUp:x}=P.useMemo(()=>{const y=()=>{h.current=!1,window.removeEventListener("pointerup",y);const k=p.current;k&&["TEXTAREA","INPUT"].includes(k.nodeName)&&k.focus(),p.current=null};return{handleButtonClick:k=>{const{id:I}=k.currentTarget.dataset;i.type==="shared"&&i.value===I||(c.mark("point picker item"),a(o,I))},handleButtonPointerDown:k=>{const{id:I}=k.currentTarget.dataset;c.mark("point picker item"),a(o,I),h.current=!0,p.current=document.activeElement,window.addEventListener("pointerup",y)},handleButtonPointerEnter:k=>{if(!h.current)return;const{id:I}=k.currentTarget.dataset;a(o,I)},handleButtonPointerUp:k=>{const{id:I}=k.currentTarget.dataset;i.type==="shared"&&i.value===I||a(o,I)}}},[i,c,a,o]);return d.jsx("div",{"data-testid":`style.${t}`,className:le("tlui-buttons__grid"),children:r.map(y=>d.jsx(ce,{type:"icon","data-id":y.value,"data-testid":`style.${t}.${y.value}`,"aria-label":y.value,"data-state":i.type==="shared"&&i.value===y.value?"hinted":void 0,title:s+" — "+u(`${t}-style.${y.value}`),className:le("tlui-button-grid__button"),style:o===lr?{color:l[y.value].solid}:void 0,onPointerEnter:m,onPointerDown:S,onPointerUp:x,onClick:f,children:d.jsx(Se,{icon:y.icon})},y.value))})});function ZR(e,[n,t]){return Math.min(t,Math.max(n,e))}function goe(e){const n=P.useRef({value:e,previous:e});return P.useMemo(()=>(n.current.value!==e&&(n.current.previous=n.current.value,n.current.value=e),n.current.previous),[e])}var QR=["PageUp","PageDown"],JR=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],eL={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Ll="Slider",[ax,moe,yoe]=kg(Ll),[tL,Nae]=Ts(Ll,[yoe]),[Soe,Wg]=tL(Ll),nL=P.forwardRef((e,n)=>{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:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,...S}=e,m=P.useRef(new Set),x=P.useRef(0),v=i==="horizontal"?voe:xoe,[w=[],C]=ci({prop:u,defaultProp:c,onChange:M=>{var $;($=[...m.current][x.current])==null||$.focus(),h(M)}}),E=P.useRef(w);function k(M){const D=Ioe(w,M);T(M,D)}function I(M){T(M,x.current)}function _(){const M=E.current[x.current];w[x.current]!==M&&p(w)}function T(M,D,{commit:$}={commit:!1}){const j=Toe(o),O=Moe(Math.round((M-r)/o)*o+r,j),R=ZR(O,[r,s]);C((K=[])=>{const B=Poe(K,R,D);if(koe(B,l*o)){x.current=B.indexOf(R);const z=String(B)!==String(K);return z&&$&&p(B),z?B:K}else return K})}return d.jsx(Soe,{scope:e.__scopeSlider,name:t,disabled:a,min:r,max:s,valueIndexToChangeRef:x,thumbs:m.current,values:w,orientation:i,children:d.jsx(ax.Provider,{scope:e.__scopeSlider,children:d.jsx(ax.Slot,{scope:e.__scopeSlider,children:d.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...S,ref:n,onPointerDown:re(S.onPointerDown,()=>{a||(E.current=w)}),min:r,max:s,inverted:f,onSlideStart:a?void 0:k,onSlideMove:a?void 0:I,onSlideEnd:a?void 0:_,onHomeKeyDown:()=>!a&&T(r,0,{commit:!0}),onEndKeyDown:()=>!a&&T(s,w.length-1,{commit:!0}),onStepKeyDown:({event:M,direction:D})=>{if(!a){const O=QR.includes(M.key)||M.shiftKey&&JR.includes(M.key)?10:1,R=x.current,K=w[R],B=o*O*D;T(K+B,R,{commit:!0})}}})})})})});nL.displayName=Ll;var[rL,sL]=tL(Ll,{startEdge:"left",endEdge:"right",size:"width",direction:1}),voe=P.forwardRef((e,n)=>{const{min:t,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=e,[h,p]=P.useState(null),f=Xe(n,w=>p(w)),S=P.useRef(),m=i1(s),x=m==="ltr",y=x&&!o||!x&&o;function v(w){const C=S.current||h.getBoundingClientRect(),E=[0,C.width],I=b1(E,y?[t,r]:[r,t]);return S.current=C,I(w-C.left)}return d.jsx(rL,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:d.jsx(oL,{dir:m,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=v(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=v(w.clientX);a==null||a(C)},onSlideEnd:()=>{S.current=void 0,l==null||l()},onStepKeyDown:w=>{const E=eL[y?"from-left":"from-right"].includes(w.key);c==null||c({event:w,direction:E?-1:1})}})})}),xoe=P.forwardRef((e,n)=>{const{min:t,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=e,u=P.useRef(null),h=Xe(n,u),p=P.useRef(),f=!s;function S(m){const x=p.current||u.current.getBoundingClientRect(),y=[0,x.height],w=b1(y,f?[r,t]:[t,r]);return p.current=x,w(m-x.top)}return d.jsx(rL,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:d.jsx(oL,{"data-orientation":"vertical",...c,ref:h,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{const x=S(m.clientY);o==null||o(x)},onSlideMove:m=>{const x=S(m.clientY);i==null||i(x)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:m=>{const y=eL[f?"from-bottom":"from-top"].includes(m.key);l==null||l({event:m,direction:y?-1:1})}})})}),oL=P.forwardRef((e,n)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=e,u=Wg(Ll,t);return d.jsx(_e.span,{...c,ref:n,onKeyDown:re(e.onKeyDown,h=>{h.key==="Home"?(i(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):QR.concat(JR).includes(h.key)&&(l(h),h.preventDefault())}),onPointerDown:re(e.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:re(e.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&s(h)}),onPointerUp:re(e.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),o(h))})})}),iL="SliderTrack",aL=P.forwardRef((e,n)=>{const{__scopeSlider:t,...r}=e,s=Wg(iL,t);return d.jsx(_e.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:n})});aL.displayName=iL;var lx="SliderRange",lL=P.forwardRef((e,n)=>{const{__scopeSlider:t,...r}=e,s=Wg(lx,t),o=sL(lx,t),i=P.useRef(null),a=Xe(n,i),l=s.values.length,c=s.values.map(p=>uL(p,s.min,s.max)),u=l>1?Math.min(...c):0,h=100-Math.max(...c);return d.jsx(_e.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:u+"%",[o.endEdge]:h+"%"}})});lL.displayName=lx;var cx="SliderThumb",cL=P.forwardRef((e,n)=>{const t=moe(e.__scopeSlider),[r,s]=P.useState(null),o=Xe(n,a=>s(a)),i=P.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return d.jsx(woe,{...e,ref:o,index:i})}),woe=P.forwardRef((e,n)=>{const{__scopeSlider:t,index:r,name:s,...o}=e,i=Wg(cx,t),a=sL(cx,t),[l,c]=P.useState(null),u=Xe(n,v=>c(v)),h=l?!!l.closest("form"):!0,p=RO(l),f=i.values[r],S=f===void 0?0:uL(f,i.min,i.max),m=Coe(r,i.values.length),x=p==null?void 0:p[a.size],y=x?Eoe(x,S,a.direction):0;return P.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${S}% + ${y}px)`},children:[d.jsx(ax.ItemSlot,{scope:e.__scopeSlider,children:d.jsx(_e.span,{role:"slider","aria-label":e["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"}:e.style,onFocus:re(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),h&&d.jsx(boe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),value:f},r)]})});cL.displayName=cx;var boe=e=>{const{value:n,...t}=e,r=P.useRef(null),s=goe(n);return P.useEffect(()=>{const o=r.current,i=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==n&&l){const c=new Event("input",{bubbles:!0});l.call(o,n),o.dispatchEvent(c)}},[s,n]),d.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:n})};function Poe(e=[],n,t){const r=[...e];return r[t]=n,r.sort((s,o)=>s-o)}function uL(e,n,t){const o=100/(t-n)*(e-n);return ZR(o,[0,100])}function Coe(e,n){return n>2?`Value ${e+1} of ${n}`:n===2?["Minimum","Maximum"][e]:void 0}function Ioe(e,n){if(e.length===1)return 0;const t=e.map(s=>Math.abs(s-n)),r=Math.min(...t);return t.indexOf(r)}function Eoe(e,n,t){const r=e/2,o=b1([0,50],[0,r]);return(r-o(n)*t)*t}function _oe(e){return e.slice(0,-1).map((n,t)=>e[t+1]-n)}function koe(e,n){if(n>0){const t=_oe(e);return Math.min(...t)>=n}return!0}function b1(e,n){return t=>{if(e[0]===e[1]||n[0]===n[1])return n[0];const r=(n[1]-n[0])/(e[1]-e[0]);return n[0]+r*(t-e[0])}}function Toe(e){return(String(e).split(".")[1]||"").length}function Moe(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}var Aoe=nL,joe=aL,Ooe=lL,Doe=cL;const Roe=P.memo(function(n){const{title:t,steps:r,value:s,label:o,onValueChange:i}=n,a=F(),l=xe(),c=P.useCallback(p=>{i(p[0])},[i]),u=P.useCallback(()=>{a.mark("click slider")},[a]),h=P.useCallback(()=>{s&&i(s)},[s,i]);return d.jsx("div",{className:"tlui-slider__container",children:d.jsxs(Aoe,{"data-testid":n["data-testid"],className:"tlui-slider","area-label":"Opacity",dir:"ltr",min:0,max:r,step:1,value:s?[s]:void 0,onPointerDown:u,onValueChange:c,onPointerUp:h,title:t+" — "+l(o),children:[d.jsx(joe,{className:"tlui-slider__track",dir:"ltr",children:s!==null&&d.jsx(Ooe,{className:"tlui-slider__range",dir:"ltr"})}),s!==null&&d.jsx(Doe,{className:"tlui-slider__thumb",dir:"ltr"})]})})});function Loe({label:e,uiTypeA:n,uiTypeB:t,labelA:r,labelB:s,itemsA:o,itemsB:i,styleA:a,styleB:l,valueA:c,valueB:u,onValueChange:h}){const p=xe(),f=P.useMemo(()=>{var m;return((m=o.find(x=>c.type==="shared"&&c.value===x.value))==null?void 0:m.icon)??"mixed"},[o,c]),S=P.useMemo(()=>{var m;return((m=i.find(x=>u.type==="shared"&&u.value===x.value))==null?void 0:m.icon)??"mixed"},[i,u]);return c===void 0&&u===void 0?null:d.jsxs("div",{className:"tlui-style-panel__double-select-picker",children:[d.jsx("div",{title:p(e),className:"tlui-style-panel__double-select-picker-label",children:p(e)}),d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsxs(qi,{id:`style panel ${n} A`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}`,title:p(r)+" — "+(c===null||c.type==="mixed"?p("style-panel.mixed"):p(`${n}-style.${c.value}`)),children:d.jsx(Se,{icon:f,small:!0,invertIcon:!0})})}),d.jsx(Qi,{side:"left",align:"center",sideOffset:80,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:o.map((m,x)=>d.jsx(Mu,{"data-testid":`style.${n}.${m.value}`,children:d.jsx(ce,{type:"icon",onClick:()=>h(a,m.value),title:`${p(r)} — ${p(`${n}-style.${m.value}`)}`,children:d.jsx(Se,{icon:m.icon,invertIcon:!0})},m.value)},x))})})]}),d.jsxs(qi,{id:`style panel ${t}`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon","data-testid":`style.${t}`,title:p(s)+" — "+(u===null||u.type==="mixed"?p("style-panel.mixed"):p(`${t}-style.${u.value}`)),children:d.jsx(Se,{icon:S,small:!0})})}),d.jsx(Qi,{side:"left",align:"center",sideOffset:116,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:i.map(m=>d.jsx(Mu,{children:d.jsx(ce,{type:"icon",title:`${p(s)} — ${p(`${t}-style.${m.value}`)}`,"data-testid":`style.${t}.${m.value}`,onClick:()=>h(l,m.value),children:d.jsx(Se,{icon:m.icon})})},m.value))})})]})]})]})}const $oe=P.memo(Loe);function Noe({id:e,label:n,uiType:t,style:r,items:s,type:o,value:i,onValueChange:a}){const l=xe(),c=F(),u=P.useMemo(()=>{var f;return(f=s.find(S=>i.type==="shared"&&S.value===i.value))==null?void 0:f.icon},[s,i]),h=i.type==="mixed"?l("style-panel.mixed"):l(`${t}-style.${i.value}`),p=n?l(n):"";return d.jsxs(qi,{id:`style panel ${e}`,children:[d.jsx(Zi,{children:d.jsxs(ce,{type:o,"data-testid":`style.${t}`,title:h,children:[d.jsx(wt,{children:p}),d.jsx(Se,{icon:u??"mixed"})]})}),d.jsx(Qi,{side:"left",align:"center",alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map(f=>d.jsx(Mu,{children:d.jsx(ce,{type:"icon","data-testid":`style.${t}.${f.value}`,title:l(`${t}-style.${f.value}`),onClick:()=>{c.mark("select style dropdown item"),a(r,f.value)},children:d.jsx(Se,{icon:f.icon})})},f.value))})})]})}const P1=P.memo(Noe);function Foe({styles:e}){const n=Ju();if(!e)return null;const t=e.get(Br),r=e.get(sf),s=e.get(rf),o=e.get(cf),i=e.get(xs),a=t===void 0,l=r===void 0&&s===void 0,c=o===void 0,u=i===void 0,h=lo({isDarkMode:n});return d.jsxs(d.Fragment,{children:[d.jsx(zoe,{theme:h,styles:e}),!u&&d.jsx(Boe,{theme:h,styles:e}),!(a&&l&&c)&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[d.jsx(Uoe,{styles:e}),d.jsx(Koe,{styles:e}),d.jsx(Hoe,{styles:e})]})]})}function ad(){const e=F(),n=qt();return Ce.useMemo(()=>function(r,s){e.run(()=>{e.isIn("select")&&e.setStyleForSelectedShapes(r,s),e.setStyleForNextShapes(r,s),e.updateInstanceState({isChangingStyle:!0})}),n("set-style",{source:"style-panel",id:r.id,value:s})},[e,n])}function zoe({styles:e,theme:n}){const t=xe(),r=F(),s=ad(),o=e.get(lr),i=e.get(Hi),a=e.get(Ui),l=e.get(ws),c=i!==void 0||a!==void 0||l!==void 0;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{tabIndex:-1,className:"tlui-style-panel__section__common","aria-label":"style panel styles","data-testid":"style.panel",children:[o===void 0?null:d.jsx(ki,{title:t("style-panel.color"),uiType:"color",style:lr,items:Pr.color,value:o,onValueChange:s,theme:n}),d.jsx(Woe,{})]}),c&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[i===void 0?null:d.jsx(ki,{title:t("style-panel.fill"),uiType:"fill",style:Hi,items:Pr.fill,value:i,onValueChange:s,theme:n}),a===void 0?null:d.jsx(ki,{title:t("style-panel.dash"),uiType:"dash",style:Ui,items:Pr.dash,value:a,onValueChange:s,theme:n}),l===void 0?null:d.jsx(ki,{title:t("style-panel.size"),uiType:"size",style:ws,items:Pr.size,value:l,onValueChange:(u,h)=>{s(u,h);const p=r.getSelectedShapeIds();p.length>0&&Ke(r,p)},theme:n})]})]})}function Boe({theme:e,styles:n}){const t=xe(),r=ad(),s=n.get(xs),o=n.get(bv),i=n.get(af),a=n.get(lf);return s===void 0&&i===void 0?null:d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel text",children:[s===void 0?null:d.jsx(ki,{title:t("style-panel.font"),uiType:"font",style:xs,items:Pr.font,value:s,onValueChange:r,theme:e}),o===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(ki,{title:t("style-panel.align"),uiType:"align",style:bv,items:Pr.textAlign,value:o,onValueChange:r,theme:e}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:d.jsx(ce,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(Se,{icon:"vertical-align-middle"})})})]}),i===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(ki,{title:t("style-panel.align"),uiType:"align",style:af,items:Pr.horizontalAlign,value:i,onValueChange:r,theme:e}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:a===void 0?d.jsx(ce,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(Se,{icon:"vertical-align-middle"})}):d.jsx(P1,{type:"icon",id:"geo-vertical-alignment",uiType:"verticalAlign",style:lf,items:Pr.verticalAlign,value:a,onValueChange:r})})]})]})}function Uoe({styles:e}){const n=ad(),t=e.get(Br);return t===void 0?null:d.jsx(P1,{id:"geo",type:"menu",label:"style-panel.geo",uiType:"geo",style:Br,items:Pr.geo,value:t,onValueChange:n})}function Hoe({styles:e}){const n=ad(),t=e.get(cf);return t===void 0?null:d.jsx(P1,{id:"spline",type:"menu",label:"style-panel.spline",uiType:"spline",style:cf,items:Pr.spline,value:t,onValueChange:n})}function Koe({styles:e}){const n=ad(),t=e.get(sf),r=e.get(rf);return!t||!r?null:d.jsx($oe,{label:"style-panel.arrowheads",uiTypeA:"arrowheadStart",styleA:rf,itemsA:Pr.arrowheadStart,valueA:r,uiTypeB:"arrowheadEnd",styleB:sf,itemsB:Pr.arrowheadEnd,valueB:t,onValueChange:n,labelA:"style-panel.arrowhead-start",labelB:"style-panel.arrowhead-end"})}const hc=[.1,.25,.5,.75,1];function Woe(){const e=F(),n=H("opacity",()=>e.getSharedOpacity(),[e]),t=qt(),r=xe(),s=Ce.useCallback(i=>{const a=hc[i];e.run(()=>{e.isIn("select")&&e.setOpacityForSelectedShapes(a),e.setOpacityForNextShapes(a),e.updateInstanceState({isChangingStyle:!0})}),t("set-style",{source:"style-panel",id:"opacity",value:i})},[e,t]);if(n===void 0)return null;const o=n.type==="mixed"?-1:hc.indexOf(b9(hc,i=>Math.abs(i-n.value)));return d.jsx(Roe,{"data-testid":"style.opacity",value:o>=0?o:hc.length-1,label:n.type==="mixed"?"style-panel.mixed":`opacity-style.${n.value}`,onValueChange:s,steps:hc.length-1,title:r("style-panel.opacity")})}const Goe=P.memo(function({isMobile:n,children:t}){const r=F(),s=qR(),o=P.useCallback(()=>{n||r.updateInstanceState({isChangingStyle:!1})},[r,n]),i=t??d.jsx(Foe,{styles:s});return d.jsx("div",{className:le("tlui-style-panel",{"tlui-style-panel__wrapper":!n}),"data-ismobile":n,onPointerLeave:o,children:i})});function Voe(){const e=F(),n=xe(),t=qR(),r=t==null?void 0:t.get(lr),s=lo({isDarkMode:e.user.getIsDarkMode()}),o=((r==null?void 0:r.type)==="shared"?s[r.value]:s.black).solid,i=H("disable style panel",()=>e.isInAny("hand","zoom","eraser","laser"),[e]),a=P.useCallback(c=>{c||e.updateInstanceState({isChangingStyle:!1})},[e]),{StylePanel:l}=pi();return l?d.jsxs(r1,{id:"mobile style menu",onOpenChange:a,children:[d.jsx(s1,{children:d.jsx(ce,{type:"tool","data-testid":"mobile-styles.button",style:{color:i?"var(--color-muted-1)":o},title:n("style-panel.title"),disabled:i,children:d.jsx(Se,{icon:i?"blob":(r==null?void 0:r.type)==="mixed"?"mixed":"blob"})})}),d.jsx(o1,{side:"top",align:"end",children:l&&d.jsx(l,{isMobile:!0})})]}):null}function Yoe(){return d.jsxs(d.Fragment,{children:[d.jsx(qoe,{}),d.jsx(Zoe,{}),d.jsx(Qoe,{}),d.jsx(Joe,{}),d.jsx(eie,{}),d.jsx(tie,{}),d.jsx(nie,{}),d.jsx(rie,{}),d.jsx(sie,{}),d.jsx(oie,{}),d.jsx(aie,{}),d.jsx(iie,{}),d.jsx(uie,{}),d.jsx(pie,{}),d.jsx(lie,{}),d.jsx(hie,{}),d.jsx(die,{}),d.jsx(cie,{}),d.jsx(fie,{}),d.jsx(gie,{}),d.jsx(mie,{}),d.jsx(yie,{}),d.jsx(Sie,{}),d.jsx(vie,{}),d.jsx(xie,{}),d.jsx(wie,{}),d.jsx(Pie,{}),d.jsx(bie,{})]})}function Xoe(e){var r;const n=F(),t=(r=e.meta)==null?void 0:r.geo;return H("is tool selected",()=>{const s=n.getCurrentToolId(),o=n.getSharedStyles().getAsKnownValue(Br);return t?s==="geo"&&o===t:s===e.id},[n,e.id,t])}function He({tool:e}){const n=Rg(),t=Xoe(n[e]);return d.jsx(U,{...n[e],isSelected:t})}function qoe(){return d.jsx(He,{tool:"select"})}function Zoe(){return d.jsx(He,{tool:"hand"})}function Qoe(){return d.jsx(He,{tool:"draw"})}function Joe(){return d.jsx(He,{tool:"eraser"})}function eie(){return d.jsx(He,{tool:"arrow"})}function tie(){return d.jsx(He,{tool:"text"})}function nie(){return d.jsx(He,{tool:"note"})}function rie(){const e=Rg();return d.jsx(U,{...e.asset})}function sie(){return d.jsx(He,{tool:"rectangle"})}function oie(){return d.jsx(He,{tool:"ellipse"})}function iie(){return d.jsx(He,{tool:"diamond"})}function aie(){return d.jsx(He,{tool:"triangle"})}function lie(){return d.jsx(He,{tool:"rhombus"})}function cie(){return d.jsx(He,{tool:"heart"})}function uie(){return d.jsx(He,{tool:"hexagon"})}function die(){return d.jsx(He,{tool:"cloud"})}function hie(){return d.jsx(He,{tool:"star"})}function pie(){return d.jsx(He,{tool:"oval"})}function fie(){return d.jsx(He,{tool:"x-box"})}function gie(){return d.jsx(He,{tool:"check-box"})}function mie(){return d.jsx(He,{tool:"arrow-left"})}function yie(){return d.jsx(He,{tool:"arrow-up"})}function Sie(){return d.jsx(He,{tool:"arrow-down"})}function vie(){return d.jsx(He,{tool:"arrow-right"})}function xie(){return d.jsx(He,{tool:"line"})}function wie(){return d.jsx(He,{tool:"highlight"})}function bie(){return d.jsx(He,{tool:"frame"})}function Pie(){return d.jsx(He,{tool:"laser"})}const Ny=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function Fy(e,n,t,r){e.addEventListener?e.addEventListener(n,t,r):e.attachEvent&&e.attachEvent("on".concat(n),t)}function pc(e,n,t,r){e.removeEventListener?e.removeEventListener(n,t,r):e.detachEvent&&e.detachEvent("on".concat(n),t)}function dL(e,n){const t=n.slice(0,n.length-1);for(let r=0;r=0;)n[t-1]+=",",n.splice(t,1),t=n.lastIndexOf("");return n}function Cie(e,n){const t=e.length>=n.length?e:n,r=e.length>=n.length?n:e;let s=!0;for(let o=0;oAu[e.toLowerCase()]||Es[e.toLowerCase()]||e.toUpperCase().charCodeAt(0),Iie=e=>Object.keys(Au).find(n=>Au[n]===e),Eie=e=>Object.keys(Es).find(n=>Es[n]===e);function fL(e){pL=e||"all"}function ju(){return pL||"all"}function _ie(){return We.slice(0)}function kie(){return We.map(e=>Iie(e)||Eie(e)||String.fromCharCode(e))}function Tie(){const e=[];return Object.keys(dt).forEach(n=>{dt[n].forEach(t=>{let{key:r,scope:s,mods:o,shortcut:i}=t;e.push({scope:s,shortcut:i,mods:o,keys:r.split("+").map(a=>ld(a))})})}),e}function Mie(e){const n=e.target||e.srcElement,{tagName:t}=n;let r=!0;const s=t==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(n.type);return(n.isContentEditable||(s||t==="TEXTAREA"||t==="SELECT")&&!n.readOnly)&&(r=!1),r}function Aie(e){return typeof e=="string"&&(e=ld(e)),We.indexOf(e)!==-1}function jie(e,n){let t,r;e||(e=ju());for(const s in dt)if(Object.prototype.hasOwnProperty.call(dt,s))for(t=dt[s],r=0;r{let{element:a}=i;return C1(a)}):r++;ju()===e&&fL(n||"all")}function Oie(e){let n=e.keyCode||e.which||e.charCode;const t=We.indexOf(n);if(t>=0&&We.splice(t,1),e.key&&e.key.toLowerCase()==="meta"&&We.splice(0,We.length),(n===93||n===224)&&(n=91),n in Bt){Bt[n]=!1;for(const r in Es)Es[r]===n&&(Fn[r]=!1)}}function gL(e){if(typeof e>"u")Object.keys(dt).forEach(s=>{Array.isArray(dt[s])&&dt[s].forEach(o=>vh(o)),delete dt[s]}),C1(null);else if(Array.isArray(e))e.forEach(s=>{s.key&&vh(s)});else if(typeof e=="object")e.key&&vh(e);else if(typeof e=="string"){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r{let{key:n,scope:t,method:r,splitKey:s="+"}=e;hL(n).forEach(i=>{const a=i.split(s),l=a.length,c=a[l-1],u=c==="*"?"*":ld(c);if(!dt[u])return;t||(t=ju());const h=l>1?dL(Es,a):[],p=[];dt[u]=dt[u].filter(f=>{const m=(r?f.method===r:!0)&&f.scope===t&&Cie(f.mods,h);return m&&p.push(f.element),!m}),p.forEach(f=>C1(f))})};function wE(e,n,t,r){if(n.element!==r)return;let s;if(n.scope===t||n.scope==="all"){s=n.mods.length>0;for(const o in Bt)Object.prototype.hasOwnProperty.call(Bt,o)&&(!Bt[o]&&n.mods.indexOf(+o)>-1||Bt[o]&&n.mods.indexOf(+o)===-1)&&(s=!1);(n.mods.length===0&&!Bt[16]&&!Bt[18]&&!Bt[17]&&!Bt[91]||s||n.shortcut==="*")&&(n.keys=[],n.keys=n.keys.concat(We),n.method(e,n)===!1&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0)))}}function bE(e,n){const t=dt["*"];let r=e.keyCode||e.which||e.charCode;if(!Fn.filter.call(this,e))return;if((r===93||r===224)&&(r=91),We.indexOf(r)===-1&&r!==229&&We.push(r),["ctrlKey","altKey","shiftKey","metaKey"].forEach(a=>{const l=ux[a];e[a]&&We.indexOf(l)===-1?We.push(l):!e[a]&&We.indexOf(l)>-1?We.splice(We.indexOf(l),1):a==="metaKey"&&e[a]&&We.length===3&&(e.ctrlKey||e.shiftKey||e.altKey||(We=We.slice(We.indexOf(l))))}),r in Bt){Bt[r]=!0;for(const a in Es)Es[a]===r&&(Fn[a]=!0);if(!t)return}for(const a in Bt)Object.prototype.hasOwnProperty.call(Bt,a)&&(Bt[a]=e[ux[a]]);e.getModifierState&&!(e.altKey&&!e.ctrlKey)&&e.getModifierState("AltGraph")&&(We.indexOf(17)===-1&&We.push(17),We.indexOf(18)===-1&&We.push(18),Bt[17]=!0,Bt[18]=!0);const s=ju();if(t)for(let a=0;a1&&(s=dL(Es,e)),e=e[e.length-1],e=e==="*"?"*":ld(e),e in dt||(dt[e]=[]),dt[e].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(!Ns.has(i)){const f=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return bE(m,i)},S=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;bE(m,i),Oie(m)};Ns.set(i,{keydownListener:f,keyupListenr:S,capture:h}),Fy(i,"keydown",f,h),Fy(i,"keyup",S,h)}if(!Zc){const f=()=>{We=[]};Zc={listener:f,capture:h},Fy(window,"focus",f,h)}}}function Die(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(dt).forEach(t=>{dt[t].filter(s=>s.scope===n&&s.shortcut===e).forEach(s=>{s&&s.method&&s.method()})})}function C1(e){const n=Object.values(dt).flat();if(n.findIndex(r=>{let{element:s}=r;return s===e})<0){const{keydownListener:r,keyupListenr:s,capture:o}=Ns.get(e)||{};r&&s&&(pc(e,"keyup",s,o),pc(e,"keydown",r,o),Ns.delete(e))}if((n.length<=0||Ns.size<=0)&&(Object.keys(Ns).forEach(s=>{const{keydownListener:o,keyupListenr:i,capture:a}=Ns.get(s)||{};o&&i&&(pc(s,"keyup",i,a),pc(s,"keydown",o,a),Ns.delete(s))}),Ns.clear(),Object.keys(dt).forEach(s=>delete dt[s]),Zc)){const{listener:s,capture:o}=Zc;pc(window,"focus",s,o),Zc=null}}const zy={getPressedKeyString:kie,setScope:fL,getScope:ju,deleteScope:jie,getPressedKeyCodes:_ie,getAllKeyCodes:Tie,isPressed:Aie,filter:Mie,trigger:Die,unbind:gL,keyMap:Au,modifier:Es,modifierMap:ux};for(const e in zy)Object.prototype.hasOwnProperty.call(zy,e)&&(Fn[e]=zy[e]);if(typeof window<"u"){const e=window.hotkeys;Fn.noConflict=n=>(n&&window.hotkeys===Fn&&(window.hotkeys=e),Fn),window.hotkeys=Fn}const PE=["copy","cut","paste","asset"];function Rie(){const e=F(),n=co(),t=ie(),r=Rg(),s=H("is focused",()=>e.getInstanceState().isFocused,[e]);P.useEffect(()=>{if(!s)return;const o=new Array,i=(l,c)=>{Fn(l,{element:document.body},c),o.push(()=>{Fn.unbind(l,c)})},a=(l,c)=>{Fn(l,{element:document.body,keyup:!0,keydown:!1},c),o.push(()=>{Fn.unbind(l,c)})};for(const l of Object.values(t))l.kbd&&(n&&!l.readonlyOk||PE.includes(l.id)||i(CE(l.kbd),c=>{Rc(e)||(Ie(c),l.onSelect("kbd"))}));for(const l of Object.values(r))!l.kbd||!l.readonlyOk&&e.getInstanceState().isReadonly||PE.includes(l.id)||i(CE(l.kbd),c=>{Rc(e)||(Ie(c),l.onSelect("kbd"))});return i(",",l=>{if(Rc(e)||e.inputs.keys.has("Comma"))return;Ie(l),e.focus(),e.inputs.keys.add("Comma");const{x:c,y:u,z:h}=e.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_down",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,pointerId:0,button:0,isPen:e.getInstanceState().isPenMode,target:"canvas"};e.dispatch(p)}),a(",",l=>{if(Rc(e)||!e.inputs.keys.has("Comma"))return;e.inputs.keys.delete("Comma");const{x:c,y:u,z:h}=e.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_up",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,pointerId:0,button:0,isPen:e.getInstanceState().isPenMode,target:"canvas"};e.dispatch(p)}),()=>{o.forEach(l=>l())}},[t,r,n,e,s])}function CE(e){return Lie(e).map(n=>{let t="";const r=n.split("");return r.length===1?t=r[0]:r[0]==="!"?t=`shift+${r[1]}`:r[0]==="?"?r.length===3&&r[1]==="!"?t=`alt+shift+${r[2]}`:t=`alt+${r[1]}`:r[0]==="$"?r[1]==="!"?t=`cmd+shift+${r[2]},ctrl+shift+${r[2]}`:r[1]==="?"?t=`cmd+⌥+${r[2]},ctrl+alt+${r[2]}`:t=`cmd+${r[1]},ctrl+${r[1]}`:t=n,t}).join(",")}function Lie(e){typeof e!="string"&&(e=""),e=e.replace(/\s/g,"");const n=e.split(",");let t=n.lastIndexOf("");for(;t>=0;)n[t-1]+=",",n.splice(t,1),t=n.lastIndexOf("");return n}function Rc(e){return e.getIsMenuOpen()||e.getEditingShapeId()!==null||e.getCrashingError()}const $ie=P.createContext(!1);function Nie({children:e}){const n=F(),t=IM(),r=Cn(),s=xe(),o=Math.min(8,5+r),[i,a]=P.useState(0),l=P.useRef(null),[c,u]=P.useState(null),h=P.useMemo(()=>{const f=c?`:not([data-value="${c}"])`:"";return` + }`,o=n.createShader(n.FRAGMENT_SHADER);if(!o)throw new Error("Failed to create fragment shader");if(n.shaderSource(o,s),n.compileShader(o),!n.getShaderParameter(o,n.COMPILE_STATUS))throw new Error("Failed to compile fragment shader");const i=n.createProgram();if(!i)throw new Error("Failed to create program");if(n.attachShader(i,r),n.attachShader(i,o),n.linkProgram(i),!n.getProgramParameter(i,n.LINK_STATUS))throw new Error("Failed to link program");n.useProgram(i);const a=n.getAttribLocation(i,"shapeVertexPosition");if(a<0)throw new Error("Failed to get shapeVertexPosition attribute location");n.enableVertexAttribArray(a);const l=n.getUniformLocation(i,"canvasPageBounds"),c=n.getUniformLocation(i,"fillColor");if(!n.createBuffer())throw new Error("Failed to create buffer");if(!n.createBuffer())throw new Error("Failed to create buffer");return{context:n,selectedShapes:Sh(n,1024),unselectedShapes:Sh(n,4096),viewport:Sh(n,XR),collaborators:Sh(n,1024),prepareTriangles(p,f){n.bindBuffer(n.ARRAY_BUFFER,p.buffer),n.bufferData(n.ARRAY_BUFFER,p.vertices,n.STATIC_DRAW,0,f),n.enableVertexAttribArray(a),n.vertexAttribPointer(a,2,n.FLOAT,!1,0,0)},drawTrianglesTransparently(p){n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.drawArrays(n.TRIANGLES,0,p/2),n.disable(n.BLEND)},drawTriangles(p){n.drawArrays(n.TRIANGLES,0,p/2)},setFillColor(p){n.uniform4fv(c,p)},setCanvasPageBounds(p){n.uniform4fv(l,p)}}}function Sh(e,n){const t=e.createBuffer();if(!t)throw new Error("Failed to create buffer");return{buffer:t,vertices:new Float32Array(n)}}function vE(e,n,t){let r=e.vertices.length;for(;r{for(var s=Jse(n,t),o=e.length-1,i;o>=0;o--)(i=e[o])&&(s=i(n,t,s)||s);return s&&Qse(n,t,s),s};class fo{constructor(n,t,r){g(this,"disposables",[]);g(this,"close",()=>this.disposables.forEach(n=>n()));g(this,"gl");g(this,"shapeGeometryCache");g(this,"colors");g(this,"id",ct());g(this,"canvasBoundingClientRect",Mt("canvasBoundingClientRect",new Q));g(this,"originPagePoint",new b);g(this,"originPageCenter",new b);g(this,"isInViewport",!1);g(this,"getMinimapPagePoint",(n,t)=>{const r=this.getCanvasPageBounds(),s=this.getCanvasScreenBounds();let o=n-s.x,i=t-s.y;return o*=r.width/s.width,i*=r.height/s.height,o+=r.minX,i+=r.minY,new b(o,i,1)});g(this,"minimapScreenPointToPagePoint",(n,t,r=!1,s=!1)=>{const{editor:o}=this,i=o.getViewportPageBounds();let{x:a,y:l}=this.getMinimapPagePoint(n,t);if(s){const c=this.editor.getCurrentPageBounds()??new Q,u=c.minX-i.width/2,h=c.maxX+i.width/2,p=c.minY-i.height/2,f=c.maxY+i.height/2,S=Math.max(0,u+i.width-a),y=Math.max(0,-(h-i.width-a)),x=Math.max(0,p+i.height-l),m=Math.max(0,-(f-i.height-l));a+=(S-y)/2,l+=(x-m)/2,a=kt(a,u,h),l=kt(l,p,f)}if(r){const{originPagePoint:c}=this,u=Math.abs(a-c.x),h=Math.abs(l-c.y);u>h?l=c.y:a=c.x}return new b(a,l)});g(this,"render",()=>{const n=this.gl.context,t=this.getCanvasSize();this.gl.setCanvasPageBounds(this.getCanvasPageBoundsArray()),this.elem.width=t.x,this.elem.height=t.y,n.viewport(0,0,t.x,t.y),n.clearColor(this.colors.background[0],this.colors.background[1],this.colors.background[2],1),n.clear(n.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 l=0,c=a.length;l{const o=n.getShapeMaskedPageBounds(s.id);if(!o)return null;const i=new Float32Array(12);return Ca(i,0,o.x,o.y,o.w,o.h),i}),this.colors=this._getColors(),this.disposables.push(this._listenForCanvasResize(),oa("minimap render",this.render))}_getColors(){const n=getComputedStyle(this.editor.getContainer());return{shapeFill:dc(n.getPropertyValue("--color-text-3").trim()),selectFill:dc(n.getPropertyValue("--color-selected").trim()),viewportFill:dc(n.getPropertyValue("--color-muted-1").trim()),background:dc(n.getPropertyValue("--color-low").trim())}}updateColors(){this.colors=this._getColors()}getDpr(){return this.editor.getInstanceState().devicePixelRatio}getContentPageBounds(){const n=this.editor.getViewportPageBounds(),t=this.editor.getCurrentPageBounds();return t?Q.Expand(t,n):n}getContentScreenBounds(){const n=this.getContentPageBounds(),t=this.editor.pageToScreen(n.point),r=this.editor.pageToScreen(new b(n.maxX,n.maxY));return new Q(t.x,t.y,r.x-t.x,r.y-t.y)}_getCanvasBoundingRect(){const{x:n,y:t,width:r,height:s}=this.elem.getBoundingClientRect();return new Q(n,t,r,s)}getCanvasScreenBounds(){return this.canvasBoundingClientRect.get()}_listenForCanvasResize(){const n=new ResizeObserver(()=>{const t=this._getCanvasBoundingRect();this.canvasBoundingClientRect.set(t)});return n.observe(this.elem),n.observe(this.container),()=>n.disconnect()}getCanvasSize(){const n=this.canvasBoundingClientRect.get(),t=this.getDpr();return new b(n.width*t,n.height*t)}getCanvasClientPosition(){return this.canvasBoundingClientRect.get().point}getCanvasPageBounds(){const n=this.getCanvasScreenBounds(),t=this.getContentPageBounds(),r=n.width/n.height;let s=t.width,o=s/r;o{try{const u=new fo(e,t.current,n);return s.current=u,s.current.close}catch(u){e.annotateError(u,{origin:"minimap",willCrashApp:!1}),e.timers.setTimeout(()=>{throw u})}},[e,n]);const o=P.useCallback(u=>{if(!e.getCurrentPageShapeIds().size||!s.current)return;const h=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),p=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);s.current.originPagePoint.setTo(p),s.current.originPageCenter.setTo(e.getViewportPageBounds().center),e.centerOnPoint(h,{animation:{duration:e.options.animationMediumMs}})},[e]),i=P.useCallback(u=>{if(!s.current)return;const h=u.currentTarget;if(Vu(h,u),!e.getCurrentPageShapeIds().size)return;r.current=!0,s.current.isInViewport=!1;const p=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),f=e.getViewportPageBounds(),S=s.current.getContentPageBounds();if(new Q(S.x-f.width/2,S.y-f.height/2,S.width+f.width,S.height+f.height).containsPoint(p)&&!f.containsPoint(p)){s.current.isInViewport=f.containsPoint(p);const m=b.Sub(f.center,f.point),v=b.Add(p,m);s.current.originPagePoint.setTo(v),s.current.originPageCenter.setTo(p),e.centerOnPoint(p,{animation:{duration:e.options.animationMediumMs}})}else{const m=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);s.current.isInViewport=f.containsPoint(m),s.current.originPagePoint.setTo(m),s.current.originPageCenter.setTo(f.center)}function x(m){h&&Yu(h,m),r.current=!1,document.body.removeEventListener("pointerup",x)}document.body.addEventListener("pointerup",x)},[e]),a=P.useCallback(u=>{if(!s.current)return;const h=s.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,u.shiftKey,!0);if(r.current){if(s.current.isInViewport){const y=s.current.originPagePoint.clone().sub(s.current.originPageCenter);e.centerOnPoint(b.Sub(h,y));return}e.centerOnPoint(h)}const p=s.current.getMinimapPagePoint(u.clientX,u.clientY),f=e.pageToScreen(p),S={type:"pointer",target:"canvas",name:"pointer_move",...Nn(u),point:f,isPen:e.getInstanceState().isPenMode};e.dispatch(S)},[e]),l=P.useCallback(u=>{const h=SM(u);e.dispatch({type:"wheel",name:"wheel",delta:h,point:new b(u.clientX,u.clientY),shiftKey:u.shiftKey,altKey:u.altKey,ctrlKey:u.metaKey||u.ctrlKey})},[e]),c=Ju();return P.useEffect(()=>{e.timers.setTimeout(()=>{var u,h;(u=s.current)==null||u.updateColors(),(h=s.current)==null||h.render()})},[c,e]),d.jsx("div",{className:"tlui-minimap",children:d.jsx("canvas",{role:"img","aria-label":"minimap",ref:t,className:"tlui-minimap__canvas",onDoubleClick:o,onPointerMove:a,onPointerDown:i,onWheel:l})})}function toe(e,n){const[t,r]=Ce.useState(n);Ce.useLayoutEffect(()=>{const o=N0(e);if(o)try{r(JSON.parse(o))}catch{console.error(`Could not restore value ${e} from local storage.`)}},[e]);const s=Ce.useCallback(o=>{r(i=>{const a=typeof o=="function"?o(i):o;return F0(e,JSON.stringify(a)),a})},[e]);return[t,s]}const noe=P.memo(function(){const n=ie(),t=xe(),r=Cn(),[s,o]=toe("minimap",!0),i=P.useCallback(()=>{o(c=>!c)},[o]),{ZoomMenu:a,Minimap:l}=pi();return rn["zoom-out"].onSelect("navigation-zone"),children:d.jsx(Se,{icon:"minus"})}),a&&d.jsx(a,{}),d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-in",title:`${t(Iu(n["zoom-in"].label))} ${sx(n["zoom-in"].kbd)}`,onClick:()=>n["zoom-in"].onSelect("navigation-zone"),children:d.jsx(Se,{icon:"plus"})}),l&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:t("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:i,children:d.jsx(Se,{icon:s?"chevrons-ne":"chevrons-sw"})})]})}),l&&r>=yt.TABLET&&!s&&d.jsx(l,{})]})}),roe=function({name:n,id:t,isCurrentPage:r}){const s=F(),o=qt(),i=P.useRef(null),a=P.useCallback(()=>{s.mark("rename page")},[s]),l=P.useCallback(c=>{s.renamePage(t,c||"New Page"),o("rename-page",{source:"page-menu"})},[s,t,o]);return d.jsx(Dg,{className:"tlui-page-menu__item__input",ref:c=>i.current=c,defaultValue:n,onValueChange:l,onFocus:a,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:r,autoSelect:!0})},ix=(e,n,t,r,s)=>{let o;const i=e.getPages(),a=t>r?i[r-1]:i[r],l=t>r?i[r]:i[r+1];a&&!l?o=Fr(a.index):!a&&l?o=R9(i[0].index):o=vu(a.index,l.index),o!==i[t].index&&(e.mark("moving page"),e.updatePage({id:n,index:o}),s("move-page",{source:"page-menu"}))},xE=Lt(function({index:n,listSize:t,item:r,onRename:s}){const o=F(),i=xe(),a=o.getPages(),l=qt(),c=P.useCallback(()=>{o.mark("creating page");const f=to.createId();o.duplicatePage(r.id,f),l("duplicate-page",{source:"page-menu"})},[o,r,l]),u=P.useCallback(()=>{ix(o,r.id,n,n-1,l)},[o,r,n,l]),h=P.useCallback(()=>{ix(o,r.id,n,n+1,l)},[o,r,n,l]),p=P.useCallback(()=>{o.mark("deleting page"),o.deletePage(r.id),l("delete-page",{source:"page-menu"})},[o,r,l]);return d.jsxs(qi,{id:`page item submenu ${n}`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon",title:i("page-menu.submenu.title"),children:d.jsx(Se,{icon:"dots-vertical"})})}),d.jsx(Qi,{alignOffset:0,side:"right",sideOffset:-4,children:d.jsxs(Tr,{type:"menu",sourceId:"page-menu",children:[d.jsxs(pe,{id:"modify",children:[s&&d.jsx(U,{id:"rename",label:"page-menu.submenu.rename",onSelect:s}),d.jsx(U,{id:"duplicate",label:"page-menu.submenu.duplicate-page",onSelect:c,disabled:a.length>=o.options.maxPages}),n>0&&d.jsx(U,{id:"move-up",onSelect:u,label:"page-menu.submenu.move-up"}),n1&&d.jsx(pe,{id:"delete",children:d.jsx(U,{id:"delete",onSelect:p,label:"page-menu.submenu.delete"})})]})})]})}),soe=P.memo(function(){const n=F(),t=qt(),r=xe(),s=Cn(),o=P.useCallback(()=>m(!1),[]),[i,a]=ho("page-menu",o),l=36,c=P.useRef(null),u=H("pages",()=>n.getPages(),[n]),h=H("currentPage",()=>n.getCurrentPage(),[n]),p=H("currentPageId",()=>n.getCurrentPageId(),[n]),f=co(),S=H("maxPageCountReached",()=>n.getPages().length>=n.options.maxPages,[n]),y=H("isCoarsePointer",()=>n.getInstanceState().isCoarsePointer,[n]),[x,m]=P.useState(!1),v=P.useCallback(()=>{f||m(j=>!j)},[f]),w=P.useRef({isPointing:!1,status:"idle",pointing:null,startY:0,startIndex:0,dragIndex:0}),[C,E]=P.useState(Object.fromEntries(u.map((j,O)=>[j.id,{y:O*l,offsetY:0,isSelected:!1}])));P.useLayoutEffect(()=>{E(Object.fromEntries(u.map((j,O)=>[j.id,{y:O*l,offsetY:0,isSelected:!1}])))},[l,u]),P.useEffect(()=>{i&&n.timers.requestAnimationFrame(()=>{const j=document.querySelector(`[data-testid="page-menu-item-${p}"]`);if(j){const O=c.current;if(!O)return;const R=j.offsetTop,K=O.scrollTop;Rz&&O.scrollTo({top:B-O.offsetHeight})}})},[l,p,i,n]);const k=P.useCallback(j=>{const{clientY:O,currentTarget:R}=j,{dataset:{id:K,index:B}}=R;if(!K||!B)return;const z=w.current;Vu(j.currentTarget,j),z.status="pointing",z.pointing={id:K,index:+B};const Y=C[K].y;z.startY=O,z.startIndex=Math.max(0,Math.min(Math.round(Y/l),u.length-1))},[l,u.length,C]),I=P.useCallback(j=>{const O=w.current;if(O.status==="pointing"){const{clientY:R}=j,K=R-O.startY;Math.abs(K)>5&&(O.status="dragging")}if(O.status==="dragging"){const{clientY:R}=j,K=R-O.startY,B=C[O.pointing.id],{startIndex:z,pointing:W}=O,Y=B.y+K,q=Math.max(0,Math.min(Math.round(Y/l),u.length-1)),ae={...C};if(ae[W.id]={y:B.y,offsetY:K,isSelected:!0},q!==O.dragIndex){O.dragIndex=q;for(let fe=0;fez&&(q>=fe&&fe>z?J=(fe-1)*l:J=fe*l),J!==ae[we.id].y&&(ae[we.id]={y:J,offsetY:0,isSelected:!0})}}E(ae)}},[l,u,C]),_=P.useCallback(j=>{const O=w.current;if(O.status==="dragging"){const{id:R,index:K}=O.pointing;ix(n,R,K,O.dragIndex,t)}Yu(j.currentTarget,j),O.status="idle"},[n,t]),T=P.useCallback(j=>{const O=w.current;j.key==="Escape"&&(O.status==="dragging"&&E(Object.fromEntries(u.map((R,K)=>[R.id,{y:K*l,offsetY:0,isSelected:!1}]))),O.status="idle")},[l,u]),M=P.useCallback(()=>{f||(n.run(()=>{n.mark("creating page");const j=to.createId();n.createPage({name:r("page-menu.new-page-initial-name"),id:j}),n.setCurrentPage(j),m(!0)}),t("new-page",{source:"page-menu"}))},[n,r,f,t]),D=P.useCallback(j=>{n.setCurrentPage(j),t("change-page",{source:"page-menu"})},[n,t]),$=P.useCallback((j,O)=>{n.renamePage(j,O),t("rename-page",{source:"page-menu"})},[n,t]);return d.jsxs(r1,{id:"pages",onOpenChange:a,open:i,children:[d.jsx(s1,{"data-testid":"main.page-menu",children:d.jsxs(ce,{type:"menu",title:h.name,"data-testid":"page-menu.button",className:"tlui-page-menu__trigger",children:[d.jsx("div",{className:"tlui-page-menu__name",children:h.name}),d.jsx(Se,{icon:"chevron-down",small:!0})]})}),d.jsx(o1,{side:"bottom",align:"start",sideOffset:6,children:d.jsxs("div",{className:"tlui-page-menu__wrapper",children:[d.jsxs("div",{className:"tlui-page-menu__header",children:[d.jsx("div",{className:"tlui-page-menu__header__title",children:r("page-menu.title")}),!f&&d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsx(ce,{type:"icon","data-testid":"page-menu.edit",title:r(x?"page-menu.edit-done":"page-menu.edit-start"),onClick:v,children:d.jsx(Se,{icon:x?"check":"edit"})}),d.jsx(ce,{type:"icon","data-testid":"page-menu.create",title:r(S?"page-menu.max-page-count-reached":"page-menu.create-new-page"),disabled:S,onClick:M,children:d.jsx(Se,{icon:"plus"})})]})]}),d.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((j,O)=>{const R=C[j.id]??{position:O*40,offsetY:0};return x?d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page_menu__item__sortable",style:{zIndex:j.id===h.id?888:O,transform:`translate(0px, ${R.y+R.offsetY}px)`},children:[d.jsx(ce,{type:"icon",tabIndex:-1,className:"tlui-page_menu__item__sortable__handle",onPointerDown:k,onPointerUp:_,onPointerMove:I,onKeyDown:T,"data-id":j.id,"data-index":O,children:d.jsx(Se,{icon:"drag-handle-dots"})}),s{const K=window.prompt("Rename page",j.name);K&&K!==j.name&&$(j.id,K)},onDoubleClick:v,children:[d.jsx(ox,{checked:j.id===h.id}),d.jsx(wt,{children:j.name})]}):d.jsx("div",{className:"tlui-page_menu__item__sortable__title",style:{height:l},children:d.jsx(roe,{id:j.id,name:j.name,isCurrentPage:j.id===h.id})}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu","data-isediting":x,children:d.jsx(xE,{index:O,item:j,listSize:u.length})})]},j.id+"_editing"):d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page-menu__item",children:[d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>D(j.id),onDoubleClick:v,title:r("page-menu.go-to-page"),children:[d.jsx(ox,{checked:j.id===h.id}),d.jsx(wt,{children:j.name})]}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu",children:d.jsx(xE,{index:O,item:j,listSize:u.length,onRename:()=>{if(n.environment.isIos){const K=window.prompt("Rename page",j.name);K&&K!==j.name&&$(j.id,K)}else m(!0),p!==j.id&&D(j.id)}})})]},j.id)})})]})})]})});function ooe(){const e=ie(),n=F(),t=uD(),r=cD(),s=In(1),o=co(),i=H("should display quick actions",()=>n.isInAny("select","hand","zoom"),[n]),a=po(),l=s&&a;if(!(o&&!i))return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e.undo,disabled:!t}),d.jsx(U,{...e.redo,disabled:!r}),d.jsx(U,{...e.delete,disabled:!l}),d.jsx(U,{...e.duplicate,disabled:!l})]})}const ioe=P.memo(function({children:n}){const t=n??d.jsx(ooe,{});return d.jsx(Tr,{type:"small-icons",sourceId:"quick-actions",children:t})});function aoe({userId:e}){const n=ug(e);return n?d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:n.color},children:n.userName==="New User"?"":n.userName[0]??""},e):null}const loe=Lt(function({userId:n}){const t=F(),r=xe(),s=qt(),o=ug(n),i=P.useCallback(()=>{t.getInstanceState().followingUserId===n?(t.stopFollowingUser(),s("stop-following",{source:"people-menu"})):(t.startFollowingUser(n),s("start-following",{source:"people-menu"}))},[t,n,s]),a=(o==null?void 0:o.followingUserId)===t.user.getId(),l=t.getInstanceState().followingUserId===n;return o?d.jsxs("div",{className:"tlui-people-menu__item tlui-buttons__horizontal",children:[d.jsxs(ce,{type:"menu",className:"tlui-people-menu__item__button",onClick:()=>t.zoomToUser(n),onDoubleClick:i,children:[d.jsx(Cs,{icon:"color",color:o.color}),d.jsx("div",{className:"tlui-people-menu__name",children:o.userName??"New User"})]}),d.jsx(ce,{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,"data-active":l||a,children:d.jsx(Se,{icon:a?"leading":l?"following":"follow"})})]}):null});function coe({count:e}){return d.jsx("div",{className:"tlui-people-menu__more",children:"+"+Math.abs(e)})}const uoe=Lt(function(){const n=F(),t=$t(),r=xe(),s=qt(),o=P.useRef(!1),[i,a]=P.useState(!1),l=P.useCallback(y=>{a(y)},[]),c=n.user.getColor(),u=P.useCallback(y=>{n.user.updateUserPreferences({color:y}),s("set-color",{source:"people-menu"})},[n,s]),{handleButtonClick:h,handleButtonPointerDown:p,handleButtonPointerEnter:f,handleButtonPointerUp:S}=Ce.useMemo(()=>{const y=()=>{o.current=!1,window.removeEventListener("pointerup",y)};return{handleButtonClick:C=>{const{id:E}=C.currentTarget.dataset;E&&c!==E&&u(E)},handleButtonPointerDown:C=>{const{id:E}=C.currentTarget.dataset;E&&(u(E),o.current=!0,window.addEventListener("pointerup",y))},handleButtonPointerEnter:C=>{if(!o.current)return;const{id:E}=C.currentTarget.dataset;E&&u(E)},handleButtonPointerUp:C=>{const{id:E}=C.currentTarget.dataset;E&&u(E)}}},[c,u]);return d.jsxs(Jw,{onOpenChange:l,open:i,children:[d.jsx(e1,{dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__color",style:{color:n.user.getColor()},title:r("people-menu.change-color"),children:d.jsx(Se,{icon:"color"})})}),d.jsx(t1,{container:t,children:d.jsx(n1,{dir:"ltr",className:"tlui-menu tlui-people-menu__user__color-picker",align:"start",side:"left",sideOffset:8,children:d.jsx("div",{className:"tlui-buttons__grid",children:_v.map(y=>d.jsx(ce,{type:"icon","data-id":y,"data-testid":y,"aria-label":y,"data-state":c===y?"hinted":void 0,title:y,className:"tlui-button-grid__button",style:{color:y},onPointerEnter:f,onPointerDown:p,onPointerUp:S,onClick:h,children:d.jsx(Se,{icon:"color"})},y))})})})]})});function doe(){const e=F(),n=qt(),t=H("userName",()=>e.user.getName(),[]),r=xe(),s=P.useRef(t),o=P.useRef(t),[i,a]=P.useState(!1),l=P.useCallback(()=>{a(h=>!h)},[]),c=P.useCallback(h=>{o.current=h,e.user.updateUserPreferences({name:h})},[e]),u=P.useCallback(()=>{s.current!==o.current&&(n("change-user-name",{source:"people-menu"}),s.current=o.current)},[n]);return d.jsxs("div",{className:"tlui-people-menu__user",children:[d.jsx(uoe,{}),i?d.jsx(Dg,{className:"tlui-people-menu__user__input",defaultValue:t,onValueChange:c,onComplete:l,onCancel:l,onBlur:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:!0,autoSelect:!0}):d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"tlui-people-menu__user__name",onDoubleClick:()=>{i||a(!0)},children:t}),t==="New User"?d.jsx("div",{className:"tlui-people-menu__user__label",children:r("people-menu.user")}):null]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__edit","data-testid":"people-menu.change-name",title:r("people-menu.change-name"),onClick:l,children:d.jsx(Se,{icon:i?"check":"edit"})})]})}const hoe=Lt(function({children:n}){const t=xe(),r=$t(),s=F(),o=PM(),i=H("user",()=>s.user.getColor(),[s]),a=H("user",()=>s.user.getName(),[s]),[l,c]=ho("people menu");return d.jsxs(Jw,{onOpenChange:c,open:l,children:[d.jsx(e1,{dir:"ltr",asChild:!0,children:d.jsxs("button",{className:"tlui-people-menu__avatars-button",title:t("people-menu.title"),children:[o.length>5&&d.jsx(coe,{count:o.length-5}),d.jsxs("div",{className:"tlui-people-menu__avatars",children:[o.slice(-5).map(u=>d.jsx(aoe,{userId:u},u)),d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:i},children:a==="New User"?"":a[0]??""})]})]})}),d.jsx(t1,{container:r,children:d.jsx(n1,{dir:"ltr",className:"tlui-menu",align:"end",side:"bottom",sideOffset:2,alignOffset:-5,children:d.jsxs("div",{className:"tlui-people-menu__wrapper",children:[d.jsx("div",{className:"tlui-people-menu__section",children:d.jsx(doe,{})}),o.length>0&&d.jsx("div",{className:"tlui-people-menu__section",children:o.map(u=>d.jsx(loe,{userId:u},u+"_presence"))}),n]})})})]})});function poe(){return d.jsx("div",{className:"tlui-share-zone",draggable:!1,children:d.jsx(hoe,{})})}const foe=Object.freeze([lr,Ui,Hi,ws]);function qR(e=foe){const n=F();return H("getRelevantStyles",()=>{var o;const t=new Tv(n.getSharedStyles()),r=!!((o=n.root.getCurrent())!=null&&o.shapeType),s=n.isIn("select")&&n.getSelectedShapeIds().length>0;if(t.size===0&&n.isIn("select")&&n.getSelectedShapeIds().length===0)for(const i of e)t.applyValue(i,n.getStyleForNextShape(i));return r||s||t.size>0?t:null},[n])}const Pr={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"},{value:"pattern",icon:"fill-pattern"}],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"}],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"}]},ki=P.memo(function(n){const{uiType:t,items:r,title:s,style:o,value:i,onValueChange:a,theme:l}=n,c=F(),u=xe(),h=P.useRef(!1),p=P.useRef(null),{handleButtonClick:f,handleButtonPointerDown:S,handleButtonPointerEnter:y,handleButtonPointerUp:x}=P.useMemo(()=>{const m=()=>{h.current=!1,window.removeEventListener("pointerup",m);const k=p.current;k&&["TEXTAREA","INPUT"].includes(k.nodeName)&&k.focus(),p.current=null};return{handleButtonClick:k=>{const{id:I}=k.currentTarget.dataset;i.type==="shared"&&i.value===I||(c.mark("point picker item"),a(o,I))},handleButtonPointerDown:k=>{const{id:I}=k.currentTarget.dataset;c.mark("point picker item"),a(o,I),h.current=!0,p.current=document.activeElement,window.addEventListener("pointerup",m)},handleButtonPointerEnter:k=>{if(!h.current)return;const{id:I}=k.currentTarget.dataset;a(o,I)},handleButtonPointerUp:k=>{const{id:I}=k.currentTarget.dataset;i.type==="shared"&&i.value===I||a(o,I)}}},[i,c,a,o]);return d.jsx("div",{"data-testid":`style.${t}`,className:le("tlui-buttons__grid"),children:r.map(m=>d.jsx(ce,{type:"icon","data-id":m.value,"data-testid":`style.${t}.${m.value}`,"aria-label":m.value,"data-state":i.type==="shared"&&i.value===m.value?"hinted":void 0,title:s+" — "+u(`${t}-style.${m.value}`),className:le("tlui-button-grid__button"),style:o===lr?{color:l[m.value].solid}:void 0,onPointerEnter:y,onPointerDown:S,onPointerUp:x,onClick:f,children:d.jsx(Se,{icon:m.icon})},m.value))})});function ZR(e,[n,t]){return Math.min(t,Math.max(n,e))}function goe(e){const n=P.useRef({value:e,previous:e});return P.useMemo(()=>(n.current.value!==e&&(n.current.previous=n.current.value,n.current.value=e),n.current.previous),[e])}var QR=["PageUp","PageDown"],JR=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],eL={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Ll="Slider",[ax,moe,yoe]=kg(Ll),[tL,Nae]=Ts(Ll,[yoe]),[Soe,Wg]=tL(Ll),nL=P.forwardRef((e,n)=>{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:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,...S}=e,y=P.useRef(new Set),x=P.useRef(0),v=i==="horizontal"?voe:xoe,[w=[],C]=ci({prop:u,defaultProp:c,onChange:M=>{var $;($=[...y.current][x.current])==null||$.focus(),h(M)}}),E=P.useRef(w);function k(M){const D=Ioe(w,M);T(M,D)}function I(M){T(M,x.current)}function _(){const M=E.current[x.current];w[x.current]!==M&&p(w)}function T(M,D,{commit:$}={commit:!1}){const j=Toe(o),O=Moe(Math.round((M-r)/o)*o+r,j),R=ZR(O,[r,s]);C((K=[])=>{const B=Poe(K,R,D);if(koe(B,l*o)){x.current=B.indexOf(R);const z=String(B)!==String(K);return z&&$&&p(B),z?B:K}else return K})}return d.jsx(Soe,{scope:e.__scopeSlider,name:t,disabled:a,min:r,max:s,valueIndexToChangeRef:x,thumbs:y.current,values:w,orientation:i,children:d.jsx(ax.Provider,{scope:e.__scopeSlider,children:d.jsx(ax.Slot,{scope:e.__scopeSlider,children:d.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...S,ref:n,onPointerDown:re(S.onPointerDown,()=>{a||(E.current=w)}),min:r,max:s,inverted:f,onSlideStart:a?void 0:k,onSlideMove:a?void 0:I,onSlideEnd:a?void 0:_,onHomeKeyDown:()=>!a&&T(r,0,{commit:!0}),onEndKeyDown:()=>!a&&T(s,w.length-1,{commit:!0}),onStepKeyDown:({event:M,direction:D})=>{if(!a){const O=QR.includes(M.key)||M.shiftKey&&JR.includes(M.key)?10:1,R=x.current,K=w[R],B=o*O*D;T(K+B,R,{commit:!0})}}})})})})});nL.displayName=Ll;var[rL,sL]=tL(Ll,{startEdge:"left",endEdge:"right",size:"width",direction:1}),voe=P.forwardRef((e,n)=>{const{min:t,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=e,[h,p]=P.useState(null),f=Xe(n,w=>p(w)),S=P.useRef(),y=i1(s),x=y==="ltr",m=x&&!o||!x&&o;function v(w){const C=S.current||h.getBoundingClientRect(),E=[0,C.width],I=b1(E,m?[t,r]:[r,t]);return S.current=C,I(w-C.left)}return d.jsx(rL,{scope:e.__scopeSlider,startEdge:m?"left":"right",endEdge:m?"right":"left",direction:m?1:-1,size:"width",children:d.jsx(oL,{dir:y,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=v(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=v(w.clientX);a==null||a(C)},onSlideEnd:()=>{S.current=void 0,l==null||l()},onStepKeyDown:w=>{const E=eL[m?"from-left":"from-right"].includes(w.key);c==null||c({event:w,direction:E?-1:1})}})})}),xoe=P.forwardRef((e,n)=>{const{min:t,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=e,u=P.useRef(null),h=Xe(n,u),p=P.useRef(),f=!s;function S(y){const x=p.current||u.current.getBoundingClientRect(),m=[0,x.height],w=b1(m,f?[r,t]:[t,r]);return p.current=x,w(y-x.top)}return d.jsx(rL,{scope:e.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:d.jsx(oL,{"data-orientation":"vertical",...c,ref:h,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const x=S(y.clientY);o==null||o(x)},onSlideMove:y=>{const x=S(y.clientY);i==null||i(x)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:y=>{const m=eL[f?"from-bottom":"from-top"].includes(y.key);l==null||l({event:y,direction:m?-1:1})}})})}),oL=P.forwardRef((e,n)=>{const{__scopeSlider:t,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=e,u=Wg(Ll,t);return d.jsx(_e.span,{...c,ref:n,onKeyDown:re(e.onKeyDown,h=>{h.key==="Home"?(i(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):QR.concat(JR).includes(h.key)&&(l(h),h.preventDefault())}),onPointerDown:re(e.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:re(e.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&s(h)}),onPointerUp:re(e.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),o(h))})})}),iL="SliderTrack",aL=P.forwardRef((e,n)=>{const{__scopeSlider:t,...r}=e,s=Wg(iL,t);return d.jsx(_e.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:n})});aL.displayName=iL;var lx="SliderRange",lL=P.forwardRef((e,n)=>{const{__scopeSlider:t,...r}=e,s=Wg(lx,t),o=sL(lx,t),i=P.useRef(null),a=Xe(n,i),l=s.values.length,c=s.values.map(p=>uL(p,s.min,s.max)),u=l>1?Math.min(...c):0,h=100-Math.max(...c);return d.jsx(_e.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:u+"%",[o.endEdge]:h+"%"}})});lL.displayName=lx;var cx="SliderThumb",cL=P.forwardRef((e,n)=>{const t=moe(e.__scopeSlider),[r,s]=P.useState(null),o=Xe(n,a=>s(a)),i=P.useMemo(()=>r?t().findIndex(a=>a.ref.current===r):-1,[t,r]);return d.jsx(woe,{...e,ref:o,index:i})}),woe=P.forwardRef((e,n)=>{const{__scopeSlider:t,index:r,name:s,...o}=e,i=Wg(cx,t),a=sL(cx,t),[l,c]=P.useState(null),u=Xe(n,v=>c(v)),h=l?!!l.closest("form"):!0,p=RO(l),f=i.values[r],S=f===void 0?0:uL(f,i.min,i.max),y=Coe(r,i.values.length),x=p==null?void 0:p[a.size],m=x?Eoe(x,S,a.direction):0;return P.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${S}% + ${m}px)`},children:[d.jsx(ax.ItemSlot,{scope:e.__scopeSlider,children:d.jsx(_e.span,{role:"slider","aria-label":e["aria-label"]||y,"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"}:e.style,onFocus:re(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),h&&d.jsx(boe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),value:f},r)]})});cL.displayName=cx;var boe=e=>{const{value:n,...t}=e,r=P.useRef(null),s=goe(n);return P.useEffect(()=>{const o=r.current,i=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(i,"value").set;if(s!==n&&l){const c=new Event("input",{bubbles:!0});l.call(o,n),o.dispatchEvent(c)}},[s,n]),d.jsx("input",{style:{display:"none"},...t,ref:r,defaultValue:n})};function Poe(e=[],n,t){const r=[...e];return r[t]=n,r.sort((s,o)=>s-o)}function uL(e,n,t){const o=100/(t-n)*(e-n);return ZR(o,[0,100])}function Coe(e,n){return n>2?`Value ${e+1} of ${n}`:n===2?["Minimum","Maximum"][e]:void 0}function Ioe(e,n){if(e.length===1)return 0;const t=e.map(s=>Math.abs(s-n)),r=Math.min(...t);return t.indexOf(r)}function Eoe(e,n,t){const r=e/2,o=b1([0,50],[0,r]);return(r-o(n)*t)*t}function _oe(e){return e.slice(0,-1).map((n,t)=>e[t+1]-n)}function koe(e,n){if(n>0){const t=_oe(e);return Math.min(...t)>=n}return!0}function b1(e,n){return t=>{if(e[0]===e[1]||n[0]===n[1])return n[0];const r=(n[1]-n[0])/(e[1]-e[0]);return n[0]+r*(t-e[0])}}function Toe(e){return(String(e).split(".")[1]||"").length}function Moe(e,n){const t=Math.pow(10,n);return Math.round(e*t)/t}var Aoe=nL,joe=aL,Ooe=lL,Doe=cL;const Roe=P.memo(function(n){const{title:t,steps:r,value:s,label:o,onValueChange:i}=n,a=F(),l=xe(),c=P.useCallback(p=>{i(p[0])},[i]),u=P.useCallback(()=>{a.mark("click slider")},[a]),h=P.useCallback(()=>{s&&i(s)},[s,i]);return d.jsx("div",{className:"tlui-slider__container",children:d.jsxs(Aoe,{"data-testid":n["data-testid"],className:"tlui-slider","area-label":"Opacity",dir:"ltr",min:0,max:r,step:1,value:s?[s]:void 0,onPointerDown:u,onValueChange:c,onPointerUp:h,title:t+" — "+l(o),children:[d.jsx(joe,{className:"tlui-slider__track",dir:"ltr",children:s!==null&&d.jsx(Ooe,{className:"tlui-slider__range",dir:"ltr"})}),s!==null&&d.jsx(Doe,{className:"tlui-slider__thumb",dir:"ltr"})]})})});function Loe({label:e,uiTypeA:n,uiTypeB:t,labelA:r,labelB:s,itemsA:o,itemsB:i,styleA:a,styleB:l,valueA:c,valueB:u,onValueChange:h}){const p=xe(),f=P.useMemo(()=>{var y;return((y=o.find(x=>c.type==="shared"&&c.value===x.value))==null?void 0:y.icon)??"mixed"},[o,c]),S=P.useMemo(()=>{var y;return((y=i.find(x=>u.type==="shared"&&u.value===x.value))==null?void 0:y.icon)??"mixed"},[i,u]);return c===void 0&&u===void 0?null:d.jsxs("div",{className:"tlui-style-panel__double-select-picker",children:[d.jsx("div",{title:p(e),className:"tlui-style-panel__double-select-picker-label",children:p(e)}),d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsxs(qi,{id:`style panel ${n} A`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}`,title:p(r)+" — "+(c===null||c.type==="mixed"?p("style-panel.mixed"):p(`${n}-style.${c.value}`)),children:d.jsx(Se,{icon:f,small:!0,invertIcon:!0})})}),d.jsx(Qi,{side:"left",align:"center",sideOffset:80,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:o.map((y,x)=>d.jsx(Mu,{"data-testid":`style.${n}.${y.value}`,children:d.jsx(ce,{type:"icon",onClick:()=>h(a,y.value),title:`${p(r)} — ${p(`${n}-style.${y.value}`)}`,children:d.jsx(Se,{icon:y.icon,invertIcon:!0})},y.value)},x))})})]}),d.jsxs(qi,{id:`style panel ${t}`,children:[d.jsx(Zi,{children:d.jsx(ce,{type:"icon","data-testid":`style.${t}`,title:p(s)+" — "+(u===null||u.type==="mixed"?p("style-panel.mixed"):p(`${t}-style.${u.value}`)),children:d.jsx(Se,{icon:S,small:!0})})}),d.jsx(Qi,{side:"left",align:"center",sideOffset:116,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:i.map(y=>d.jsx(Mu,{children:d.jsx(ce,{type:"icon",title:`${p(s)} — ${p(`${t}-style.${y.value}`)}`,"data-testid":`style.${t}.${y.value}`,onClick:()=>h(l,y.value),children:d.jsx(Se,{icon:y.icon})})},y.value))})})]})]})]})}const $oe=P.memo(Loe);function Noe({id:e,label:n,uiType:t,style:r,items:s,type:o,value:i,onValueChange:a}){const l=xe(),c=F(),u=P.useMemo(()=>{var f;return(f=s.find(S=>i.type==="shared"&&S.value===i.value))==null?void 0:f.icon},[s,i]),h=i.type==="mixed"?l("style-panel.mixed"):l(`${t}-style.${i.value}`),p=n?l(n):"";return d.jsxs(qi,{id:`style panel ${e}`,children:[d.jsx(Zi,{children:d.jsxs(ce,{type:o,"data-testid":`style.${t}`,title:h,children:[d.jsx(wt,{children:p}),d.jsx(Se,{icon:u??"mixed"})]})}),d.jsx(Qi,{side:"left",align:"center",alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map(f=>d.jsx(Mu,{children:d.jsx(ce,{type:"icon","data-testid":`style.${t}.${f.value}`,title:l(`${t}-style.${f.value}`),onClick:()=>{c.mark("select style dropdown item"),a(r,f.value)},children:d.jsx(Se,{icon:f.icon})})},f.value))})})]})}const P1=P.memo(Noe);function Foe({styles:e}){const n=Ju();if(!e)return null;const t=e.get(Br),r=e.get(sf),s=e.get(rf),o=e.get(cf),i=e.get(xs),a=t===void 0,l=r===void 0&&s===void 0,c=o===void 0,u=i===void 0,h=lo({isDarkMode:n});return d.jsxs(d.Fragment,{children:[d.jsx(zoe,{theme:h,styles:e}),!u&&d.jsx(Boe,{theme:h,styles:e}),!(a&&l&&c)&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[d.jsx(Uoe,{styles:e}),d.jsx(Koe,{styles:e}),d.jsx(Hoe,{styles:e})]})]})}function ad(){const e=F(),n=qt();return Ce.useMemo(()=>function(r,s){e.run(()=>{e.isIn("select")&&e.setStyleForSelectedShapes(r,s),e.setStyleForNextShapes(r,s),e.updateInstanceState({isChangingStyle:!0})}),n("set-style",{source:"style-panel",id:r.id,value:s})},[e,n])}function zoe({styles:e,theme:n}){const t=xe(),r=F(),s=ad(),o=e.get(lr),i=e.get(Hi),a=e.get(Ui),l=e.get(ws),c=i!==void 0||a!==void 0||l!==void 0;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{tabIndex:-1,className:"tlui-style-panel__section__common","aria-label":"style panel styles","data-testid":"style.panel",children:[o===void 0?null:d.jsx(ki,{title:t("style-panel.color"),uiType:"color",style:lr,items:Pr.color,value:o,onValueChange:s,theme:n}),d.jsx(Woe,{})]}),c&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[i===void 0?null:d.jsx(ki,{title:t("style-panel.fill"),uiType:"fill",style:Hi,items:Pr.fill,value:i,onValueChange:s,theme:n}),a===void 0?null:d.jsx(ki,{title:t("style-panel.dash"),uiType:"dash",style:Ui,items:Pr.dash,value:a,onValueChange:s,theme:n}),l===void 0?null:d.jsx(ki,{title:t("style-panel.size"),uiType:"size",style:ws,items:Pr.size,value:l,onValueChange:(u,h)=>{s(u,h);const p=r.getSelectedShapeIds();p.length>0&&Ke(r,p)},theme:n})]})]})}function Boe({theme:e,styles:n}){const t=xe(),r=ad(),s=n.get(xs),o=n.get(bv),i=n.get(af),a=n.get(lf);return s===void 0&&i===void 0?null:d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel text",children:[s===void 0?null:d.jsx(ki,{title:t("style-panel.font"),uiType:"font",style:xs,items:Pr.font,value:s,onValueChange:r,theme:e}),o===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(ki,{title:t("style-panel.align"),uiType:"align",style:bv,items:Pr.textAlign,value:o,onValueChange:r,theme:e}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:d.jsx(ce,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(Se,{icon:"vertical-align-middle"})})})]}),i===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(ki,{title:t("style-panel.align"),uiType:"align",style:af,items:Pr.horizontalAlign,value:i,onValueChange:r,theme:e}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:a===void 0?d.jsx(ce,{type:"icon",title:t("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(Se,{icon:"vertical-align-middle"})}):d.jsx(P1,{type:"icon",id:"geo-vertical-alignment",uiType:"verticalAlign",style:lf,items:Pr.verticalAlign,value:a,onValueChange:r})})]})]})}function Uoe({styles:e}){const n=ad(),t=e.get(Br);return t===void 0?null:d.jsx(P1,{id:"geo",type:"menu",label:"style-panel.geo",uiType:"geo",style:Br,items:Pr.geo,value:t,onValueChange:n})}function Hoe({styles:e}){const n=ad(),t=e.get(cf);return t===void 0?null:d.jsx(P1,{id:"spline",type:"menu",label:"style-panel.spline",uiType:"spline",style:cf,items:Pr.spline,value:t,onValueChange:n})}function Koe({styles:e}){const n=ad(),t=e.get(sf),r=e.get(rf);return!t||!r?null:d.jsx($oe,{label:"style-panel.arrowheads",uiTypeA:"arrowheadStart",styleA:rf,itemsA:Pr.arrowheadStart,valueA:r,uiTypeB:"arrowheadEnd",styleB:sf,itemsB:Pr.arrowheadEnd,valueB:t,onValueChange:n,labelA:"style-panel.arrowhead-start",labelB:"style-panel.arrowhead-end"})}const hc=[.1,.25,.5,.75,1];function Woe(){const e=F(),n=H("opacity",()=>e.getSharedOpacity(),[e]),t=qt(),r=xe(),s=Ce.useCallback(i=>{const a=hc[i];e.run(()=>{e.isIn("select")&&e.setOpacityForSelectedShapes(a),e.setOpacityForNextShapes(a),e.updateInstanceState({isChangingStyle:!0})}),t("set-style",{source:"style-panel",id:"opacity",value:i})},[e,t]);if(n===void 0)return null;const o=n.type==="mixed"?-1:hc.indexOf(b9(hc,i=>Math.abs(i-n.value)));return d.jsx(Roe,{"data-testid":"style.opacity",value:o>=0?o:hc.length-1,label:n.type==="mixed"?"style-panel.mixed":`opacity-style.${n.value}`,onValueChange:s,steps:hc.length-1,title:r("style-panel.opacity")})}const Goe=P.memo(function({isMobile:n,children:t}){const r=F(),s=qR(),o=P.useCallback(()=>{n||r.updateInstanceState({isChangingStyle:!1})},[r,n]),i=t??d.jsx(Foe,{styles:s});return d.jsx("div",{className:le("tlui-style-panel",{"tlui-style-panel__wrapper":!n}),"data-ismobile":n,onPointerLeave:o,children:i})});function Voe(){const e=F(),n=xe(),t=qR(),r=t==null?void 0:t.get(lr),s=lo({isDarkMode:e.user.getIsDarkMode()}),o=((r==null?void 0:r.type)==="shared"?s[r.value]:s.black).solid,i=H("disable style panel",()=>e.isInAny("hand","zoom","eraser","laser"),[e]),a=P.useCallback(c=>{c||e.updateInstanceState({isChangingStyle:!1})},[e]),{StylePanel:l}=pi();return l?d.jsxs(r1,{id:"mobile style menu",onOpenChange:a,children:[d.jsx(s1,{children:d.jsx(ce,{type:"tool","data-testid":"mobile-styles.button",style:{color:i?"var(--color-muted-1)":o},title:n("style-panel.title"),disabled:i,children:d.jsx(Se,{icon:i?"blob":(r==null?void 0:r.type)==="mixed"?"mixed":"blob"})})}),d.jsx(o1,{side:"top",align:"end",children:l&&d.jsx(l,{isMobile:!0})})]}):null}function Yoe(){return d.jsxs(d.Fragment,{children:[d.jsx(qoe,{}),d.jsx(Zoe,{}),d.jsx(Qoe,{}),d.jsx(Joe,{}),d.jsx(eie,{}),d.jsx(tie,{}),d.jsx(nie,{}),d.jsx(rie,{}),d.jsx(sie,{}),d.jsx(oie,{}),d.jsx(aie,{}),d.jsx(iie,{}),d.jsx(uie,{}),d.jsx(pie,{}),d.jsx(lie,{}),d.jsx(hie,{}),d.jsx(die,{}),d.jsx(cie,{}),d.jsx(fie,{}),d.jsx(gie,{}),d.jsx(mie,{}),d.jsx(yie,{}),d.jsx(Sie,{}),d.jsx(vie,{}),d.jsx(xie,{}),d.jsx(wie,{}),d.jsx(Pie,{}),d.jsx(bie,{})]})}function Xoe(e){var r;const n=F(),t=(r=e.meta)==null?void 0:r.geo;return H("is tool selected",()=>{const s=n.getCurrentToolId(),o=n.getSharedStyles().getAsKnownValue(Br);return t?s==="geo"&&o===t:s===e.id},[n,e.id,t])}function He({tool:e}){const n=Rg(),t=Xoe(n[e]);return d.jsx(U,{...n[e],isSelected:t})}function qoe(){return d.jsx(He,{tool:"select"})}function Zoe(){return d.jsx(He,{tool:"hand"})}function Qoe(){return d.jsx(He,{tool:"draw"})}function Joe(){return d.jsx(He,{tool:"eraser"})}function eie(){return d.jsx(He,{tool:"arrow"})}function tie(){return d.jsx(He,{tool:"text"})}function nie(){return d.jsx(He,{tool:"note"})}function rie(){const e=Rg();return d.jsx(U,{...e.asset})}function sie(){return d.jsx(He,{tool:"rectangle"})}function oie(){return d.jsx(He,{tool:"ellipse"})}function iie(){return d.jsx(He,{tool:"diamond"})}function aie(){return d.jsx(He,{tool:"triangle"})}function lie(){return d.jsx(He,{tool:"rhombus"})}function cie(){return d.jsx(He,{tool:"heart"})}function uie(){return d.jsx(He,{tool:"hexagon"})}function die(){return d.jsx(He,{tool:"cloud"})}function hie(){return d.jsx(He,{tool:"star"})}function pie(){return d.jsx(He,{tool:"oval"})}function fie(){return d.jsx(He,{tool:"x-box"})}function gie(){return d.jsx(He,{tool:"check-box"})}function mie(){return d.jsx(He,{tool:"arrow-left"})}function yie(){return d.jsx(He,{tool:"arrow-up"})}function Sie(){return d.jsx(He,{tool:"arrow-down"})}function vie(){return d.jsx(He,{tool:"arrow-right"})}function xie(){return d.jsx(He,{tool:"line"})}function wie(){return d.jsx(He,{tool:"highlight"})}function bie(){return d.jsx(He,{tool:"frame"})}function Pie(){return d.jsx(He,{tool:"laser"})}const Ny=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function Fy(e,n,t,r){e.addEventListener?e.addEventListener(n,t,r):e.attachEvent&&e.attachEvent("on".concat(n),t)}function pc(e,n,t,r){e.removeEventListener?e.removeEventListener(n,t,r):e.detachEvent&&e.detachEvent("on".concat(n),t)}function dL(e,n){const t=n.slice(0,n.length-1);for(let r=0;r=0;)n[t-1]+=",",n.splice(t,1),t=n.lastIndexOf("");return n}function Cie(e,n){const t=e.length>=n.length?e:n,r=e.length>=n.length?n:e;let s=!0;for(let o=0;oAu[e.toLowerCase()]||Es[e.toLowerCase()]||e.toUpperCase().charCodeAt(0),Iie=e=>Object.keys(Au).find(n=>Au[n]===e),Eie=e=>Object.keys(Es).find(n=>Es[n]===e);function fL(e){pL=e||"all"}function ju(){return pL||"all"}function _ie(){return We.slice(0)}function kie(){return We.map(e=>Iie(e)||Eie(e)||String.fromCharCode(e))}function Tie(){const e=[];return Object.keys(dt).forEach(n=>{dt[n].forEach(t=>{let{key:r,scope:s,mods:o,shortcut:i}=t;e.push({scope:s,shortcut:i,mods:o,keys:r.split("+").map(a=>ld(a))})})}),e}function Mie(e){const n=e.target||e.srcElement,{tagName:t}=n;let r=!0;const s=t==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(n.type);return(n.isContentEditable||(s||t==="TEXTAREA"||t==="SELECT")&&!n.readOnly)&&(r=!1),r}function Aie(e){return typeof e=="string"&&(e=ld(e)),We.indexOf(e)!==-1}function jie(e,n){let t,r;e||(e=ju());for(const s in dt)if(Object.prototype.hasOwnProperty.call(dt,s))for(t=dt[s],r=0;r{let{element:a}=i;return C1(a)}):r++;ju()===e&&fL(n||"all")}function Oie(e){let n=e.keyCode||e.which||e.charCode;const t=We.indexOf(n);if(t>=0&&We.splice(t,1),e.key&&e.key.toLowerCase()==="meta"&&We.splice(0,We.length),(n===93||n===224)&&(n=91),n in Bt){Bt[n]=!1;for(const r in Es)Es[r]===n&&(Fn[r]=!1)}}function gL(e){if(typeof e>"u")Object.keys(dt).forEach(s=>{Array.isArray(dt[s])&&dt[s].forEach(o=>vh(o)),delete dt[s]}),C1(null);else if(Array.isArray(e))e.forEach(s=>{s.key&&vh(s)});else if(typeof e=="object")e.key&&vh(e);else if(typeof e=="string"){for(var n=arguments.length,t=new Array(n>1?n-1:0),r=1;r{let{key:n,scope:t,method:r,splitKey:s="+"}=e;hL(n).forEach(i=>{const a=i.split(s),l=a.length,c=a[l-1],u=c==="*"?"*":ld(c);if(!dt[u])return;t||(t=ju());const h=l>1?dL(Es,a):[],p=[];dt[u]=dt[u].filter(f=>{const y=(r?f.method===r:!0)&&f.scope===t&&Cie(f.mods,h);return y&&p.push(f.element),!y}),p.forEach(f=>C1(f))})};function wE(e,n,t,r){if(n.element!==r)return;let s;if(n.scope===t||n.scope==="all"){s=n.mods.length>0;for(const o in Bt)Object.prototype.hasOwnProperty.call(Bt,o)&&(!Bt[o]&&n.mods.indexOf(+o)>-1||Bt[o]&&n.mods.indexOf(+o)===-1)&&(s=!1);(n.mods.length===0&&!Bt[16]&&!Bt[18]&&!Bt[17]&&!Bt[91]||s||n.shortcut==="*")&&(n.keys=[],n.keys=n.keys.concat(We),n.method(e,n)===!1&&(e.preventDefault?e.preventDefault():e.returnValue=!1,e.stopPropagation&&e.stopPropagation(),e.cancelBubble&&(e.cancelBubble=!0)))}}function bE(e,n){const t=dt["*"];let r=e.keyCode||e.which||e.charCode;if(!Fn.filter.call(this,e))return;if((r===93||r===224)&&(r=91),We.indexOf(r)===-1&&r!==229&&We.push(r),["ctrlKey","altKey","shiftKey","metaKey"].forEach(a=>{const l=ux[a];e[a]&&We.indexOf(l)===-1?We.push(l):!e[a]&&We.indexOf(l)>-1?We.splice(We.indexOf(l),1):a==="metaKey"&&e[a]&&We.length===3&&(e.ctrlKey||e.shiftKey||e.altKey||(We=We.slice(We.indexOf(l))))}),r in Bt){Bt[r]=!0;for(const a in Es)Es[a]===r&&(Fn[a]=!0);if(!t)return}for(const a in Bt)Object.prototype.hasOwnProperty.call(Bt,a)&&(Bt[a]=e[ux[a]]);e.getModifierState&&!(e.altKey&&!e.ctrlKey)&&e.getModifierState("AltGraph")&&(We.indexOf(17)===-1&&We.push(17),We.indexOf(18)===-1&&We.push(18),Bt[17]=!0,Bt[18]=!0);const s=ju();if(t)for(let a=0;a1&&(s=dL(Es,e)),e=e[e.length-1],e=e==="*"?"*":ld(e),e in dt||(dt[e]=[]),dt[e].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(!Ns.has(i)){const f=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return bE(y,i)},S=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;bE(y,i),Oie(y)};Ns.set(i,{keydownListener:f,keyupListenr:S,capture:h}),Fy(i,"keydown",f,h),Fy(i,"keyup",S,h)}if(!Zc){const f=()=>{We=[]};Zc={listener:f,capture:h},Fy(window,"focus",f,h)}}}function Die(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(dt).forEach(t=>{dt[t].filter(s=>s.scope===n&&s.shortcut===e).forEach(s=>{s&&s.method&&s.method()})})}function C1(e){const n=Object.values(dt).flat();if(n.findIndex(r=>{let{element:s}=r;return s===e})<0){const{keydownListener:r,keyupListenr:s,capture:o}=Ns.get(e)||{};r&&s&&(pc(e,"keyup",s,o),pc(e,"keydown",r,o),Ns.delete(e))}if((n.length<=0||Ns.size<=0)&&(Object.keys(Ns).forEach(s=>{const{keydownListener:o,keyupListenr:i,capture:a}=Ns.get(s)||{};o&&i&&(pc(s,"keyup",i,a),pc(s,"keydown",o,a),Ns.delete(s))}),Ns.clear(),Object.keys(dt).forEach(s=>delete dt[s]),Zc)){const{listener:s,capture:o}=Zc;pc(window,"focus",s,o),Zc=null}}const zy={getPressedKeyString:kie,setScope:fL,getScope:ju,deleteScope:jie,getPressedKeyCodes:_ie,getAllKeyCodes:Tie,isPressed:Aie,filter:Mie,trigger:Die,unbind:gL,keyMap:Au,modifier:Es,modifierMap:ux};for(const e in zy)Object.prototype.hasOwnProperty.call(zy,e)&&(Fn[e]=zy[e]);if(typeof window<"u"){const e=window.hotkeys;Fn.noConflict=n=>(n&&window.hotkeys===Fn&&(window.hotkeys=e),Fn),window.hotkeys=Fn}const PE=["copy","cut","paste","asset"];function Rie(){const e=F(),n=co(),t=ie(),r=Rg(),s=H("is focused",()=>e.getInstanceState().isFocused,[e]);P.useEffect(()=>{if(!s)return;const o=new Array,i=(l,c)=>{Fn(l,{element:document.body},c),o.push(()=>{Fn.unbind(l,c)})},a=(l,c)=>{Fn(l,{element:document.body,keyup:!0,keydown:!1},c),o.push(()=>{Fn.unbind(l,c)})};for(const l of Object.values(t))l.kbd&&(n&&!l.readonlyOk||PE.includes(l.id)||i(CE(l.kbd),c=>{Rc(e)||(Ie(c),l.onSelect("kbd"))}));for(const l of Object.values(r))!l.kbd||!l.readonlyOk&&e.getInstanceState().isReadonly||PE.includes(l.id)||i(CE(l.kbd),c=>{Rc(e)||(Ie(c),l.onSelect("kbd"))});return i(",",l=>{if(Rc(e)||e.inputs.keys.has("Comma"))return;Ie(l),e.focus(),e.inputs.keys.add("Comma");const{x:c,y:u,z:h}=e.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_down",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,pointerId:0,button:0,isPen:e.getInstanceState().isPenMode,target:"canvas"};e.dispatch(p)}),a(",",l=>{if(Rc(e)||!e.inputs.keys.has("Comma"))return;e.inputs.keys.delete("Comma");const{x:c,y:u,z:h}=e.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_up",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,pointerId:0,button:0,isPen:e.getInstanceState().isPenMode,target:"canvas"};e.dispatch(p)}),()=>{o.forEach(l=>l())}},[t,r,n,e,s])}function CE(e){return Lie(e).map(n=>{let t="";const r=n.split("");return r.length===1?t=r[0]:r[0]==="!"?t=`shift+${r[1]}`:r[0]==="?"?r.length===3&&r[1]==="!"?t=`alt+shift+${r[2]}`:t=`alt+${r[1]}`:r[0]==="$"?r[1]==="!"?t=`cmd+shift+${r[2]},ctrl+shift+${r[2]}`:r[1]==="?"?t=`cmd+⌥+${r[2]},ctrl+alt+${r[2]}`:t=`cmd+${r[1]},ctrl+${r[1]}`:t=n,t}).join(",")}function Lie(e){typeof e!="string"&&(e=""),e=e.replace(/\s/g,"");const n=e.split(",");let t=n.lastIndexOf("");for(;t>=0;)n[t-1]+=",",n.splice(t,1),t=n.lastIndexOf("");return n}function Rc(e){return e.getIsMenuOpen()||e.getEditingShapeId()!==null||e.getCrashingError()}const $ie=P.createContext(!1);function Nie({children:e}){const n=F(),t=IM(),r=Cn(),s=xe(),o=Math.min(8,5+r),[i,a]=P.useState(0),l=P.useRef(null),[c,u]=P.useState(null),h=P.useMemo(()=>{const f=c?`:not([data-value="${c}"])`:"";return` #${t}_main > *:nth-child(n + ${o+(c?1:2)})${f} { display: none; } #${t}_more > *:nth-child(-n + ${o}) { display: none; } - `},[c,t,o]),p=nA(()=>{if(!l.current)return;const f=Array.from(l.current.children);a(f.length),f.findIndex(x=>x.getAttribute("data-value")===c)<=o&&u(null);const m=Array.from(l.current.children).findIndex(x=>x.getAttribute("aria-checked")==="true");m!==-1&&m>=o&&u(f[m].getAttribute("data-value"))});return P.useLayoutEffect(()=>{p()}),P.useLayoutEffect(()=>{if(!l.current)return;const f=new MutationObserver(p);return f.observe(l.current,{childList:!0,subtree:!0,attributeFilter:["data-value","aria-checked"]}),()=>{f.disconnect()}},[p]),P.useEffect(()=>{const f=[["1",0],["2",1],["3",2],["4",3],["5",4],["6",5],["7",6],["8",7],["9",8],["0",9]];for(const[S,m]of f)Fn(S,x=>{var w;if(Rc(n))return;Ie(x);const v=Array.from(((w=l.current)==null?void 0:w.children)??[]).filter(C=>!(C instanceof HTMLElement)||C.tagName.toLowerCase()!=="button"?!1:!!(C.offsetWidth||C.offsetHeight))[m];v&&v.click()});return()=>{Fn.unbind("1,2,3,4,5,6,7,8,9,0")}},[n]),d.jsxs(d.Fragment,{children:[d.jsx("style",{children:h}),d.jsxs("div",{className:le("tlui-toolbar__tools",{"tlui-toolbar__tools__mobile":ro+1&&d.jsx($ie.Provider,{value:!0,children:d.jsxs(qi,{id:"toolbar overflow",modal:!1,children:[d.jsx(Zi,{children:d.jsx(ce,{title:s("tool-panel.more"),type:"tool",className:"tlui-toolbar__overflow","data-testid":"tools.more-button",children:d.jsx(Se,{icon:"chevron-up"})})}),d.jsx(Qi,{side:"top",align:"center",children:d.jsx("div",{className:"tlui-buttons__grid","data-testid":"tools.more-content",id:`${t}_more`,children:d.jsx(Tr,{type:"toolbar-overflow",sourceId:"toolbar",children:e})})})]})})]})]})}function Fie({activeToolId:e}){const n=F(),t=Cn(),r=xe(),s=H("is tool locked",()=>n.getInstanceState().isToolLocked,[n]),o=H("current tool",()=>n.getCurrentTool(),[n]);return!e||!o.isLockable?null:d.jsx(ce,{type:"normal",title:r("action.toggle-tool-lock"),"data-testid":"tool-lock",className:le("tlui-toolbar__lock-button",{"tlui-toolbar__lock-button__mobile":tn.updateInstanceState({isToolLocked:!s}),children:d.jsx(Se,{icon:s?"lock":"unlock",small:!0})})}const zie=P.memo(function({children:n}){const t=F(),r=Cn(),s=co(),o=H("current tool id",()=>t.getCurrentToolId(),[t]),{ActionsMenu:i,QuickActions:a}=pi();return d.jsx("div",{className:"tlui-toolbar",children:d.jsxs("div",{className:"tlui-toolbar__inner",children:[d.jsxs("div",{className:"tlui-toolbar__left",children:[!s&&d.jsxs("div",{className:"tlui-toolbar__extras",children:[r{const c=i.current;if(!c)return;const u=c.parentElement.parentElement,h=u.querySelector(".tlui-layout__top__left"),p=u.querySelector(".tlui-layout__top__right"),f=u.offsetWidth,S=h.offsetWidth,m=p.offsetWidth,x=c.offsetWidth-n;let y=(f-x)/2;f%2!==0&&(y-=.5);const v=S+r,w=c.offsetLeft,C=Math.min(f-m-S-2*r,e),E=Math.max(y,v)-w;p.offsetWidth>t&&a<=6?c.style.setProperty("max-width",C-s+"px"):c.style.setProperty("max-width",C+"px"),c.style.setProperty("transform",`translate(${E}px, 0px)`)},[a,n,r,e,s,t]);return P.useLayoutEffect(()=>{const c=i.current;if(!c)return;const u=c.parentElement.parentElement,h=u.querySelector(".tlui-layout__top__left"),p=u.querySelector(".tlui-layout__top__right"),f=new ResizeObserver(l);return f.observe(h),f.observe(p),f.observe(u),f.observe(c),l(),()=>{f.disconnect()}},[l]),P.useLayoutEffect(()=>{l()}),d.jsx("div",{ref:i,className:"tlui-top-panel__container",children:o})}function Hie(){const e=fee()==="offline";return d.jsx(Uie,{children:e&&d.jsx(Bie,{})})}function Kie(){const e=ie();return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["zoom-in"],noClose:!0}),d.jsx(U,{...e["zoom-out"],noClose:!0}),d.jsx($R,{}),d.jsx(NR,{}),d.jsx(FR,{})]})}const Wie=P.memo(function({children:n}){const t=$t(),[r,s]=ho("zoom menu"),o=n??d.jsx(Kie,{});return d.jsxs(S1,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[d.jsx(v1,{asChild:!0,dir:"ltr",children:d.jsx(Gie,{})}),d.jsx(Kg,{container:t,children:d.jsx(x1,{className:"tlui-menu",side:"top",align:"start",alignOffset:0,sideOffset:8,collisionPadding:4,children:d.jsx(Tr,{type:"menu",sourceId:"zoom-menu",children:o})})})]})}),Gie=P.forwardRef(function(n,t){const r=F(),s=Cn(),o=H("zoom",()=>r.getZoomLevel(),[r]),i=xe(),a=P.useCallback(()=>{r.resetZoom(r.getViewportScreenCenter(),{animation:{duration:r.options.animationMediumMs}})},[r]);return d.jsx(ce,{ref:t,...n,type:"icon",title:`${i("navigation-zone.zoom")}`,"data-testid":"minimap.zoom-menu-button",className:s({ContextMenu:hse,ActionsMenu:Fre,HelpMenu:null,ZoomMenu:Wie,MainMenu:Xse,Minimap:eoe,StylePanel:Goe,PageMenu:soe,NavigationPanel:noe,Toolbar:zie,KeyboardShortcutsDialog:Rse,QuickActions:ioe,HelperButtons:Ose,DebugPanel:Cse,DebugMenu:Pse,MenuPanel:kse,SharePanel:r?poe:null,CursorChatBubble:r?gse:null,TopPanel:r?Hie:null,...t}),[t,r]),children:n})}function pi(){const e=P.useContext(mL);if(!e)throw new Error("useTldrawUiComponents must be used within a TldrawUiComponentsProvider");return e}function Yie({overrides:e,components:n,assetUrls:t,onUiEvent:r,forceMobile:s,children:o}){return d.jsx(Lq,{assetUrls:CJ(t),children:d.jsx(Fq,{overrides:TJ(e),children:d.jsx(UQ,{onEvent:r,children:d.jsx(yJ,{children:d.jsx(HQ,{children:d.jsx(EJ,{forceMobile:s,children:d.jsx(Vie,{overrides:n,children:d.jsx(Xie,{overrides:e,children:o})})})})})})})})}function Xie({overrides:e,children:n}){const t=MJ(e);return d.jsx(yee,{overrides:t.actions,children:d.jsx(IJ,{overrides:t.tools,children:n})})}function qie(){const e=F(),{addToast:n}=Qr();P.useEffect(()=>{function t({name:r,count:s}){n({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 e.addListener("max-shapes",t),()=>{e.removeListener("max-shapes",t)}},[e,n])}const Zie=Ce.memo(function({renderDebugMenuItems:n,children:t,hideUi:r,components:s,...o}){return d.jsx(Yie,{...o,components:s,children:d.jsx(Qie,{hideUi:r,renderDebugMenuItems:n,children:t})})}),Qie=Ce.memo(function({children:n,hideUi:t,...r}){return d.jsxs(d.Fragment,{children:[n,t?null:d.jsx(Jie,{...r})]})}),Jie=Ce.memo(function(){const n=F(),t=xe(),r=Cn(),s=co(),o=H("focus",()=>n.getInstanceState().isFocusMode,[n]),i=H("debug",()=>n.getInstanceState().isDebugMode,[n]),{SharePanel:a,TopPanel:l,MenuPanel:c,StylePanel:u,Toolbar:h,HelpMenu:p,NavigationPanel:f,HelperButtons:S,DebugPanel:m,CursorChatBubble:x}=pi();Rie(),see(),qie();const{"toggle-focus-mode":y}=ie();return d.jsxs("div",{className:le("tlui-layout",{"tlui-layout__mobile":ry.onSelect("menu"),children:d.jsx(Se,{icon:"dot"})})}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"tlui-layout__top",children:[d.jsxs("div",{className:"tlui-layout__top__left",children:[c&&d.jsx(c,{}),S&&d.jsx(S,{})]}),d.jsx("div",{className:"tlui-layout__top__center",children:l&&d.jsx(l,{})}),d.jsxs("div",{className:"tlui-layout__top__right",children:[a&&d.jsx(a,{}),u&&r>=yt.TABLET_SM&&!s&&d.jsx(u,{})]})]}),d.jsxs("div",{className:"tlui-layout__bottom",children:[d.jsxs("div",{className:"tlui-layout__bottom__main",children:[f&&d.jsx(f,{}),h&&d.jsx(h,{}),p&&d.jsx(p,{})]}),i&&m&&d.jsx(m,{})]})]}),d.jsx(wJ,{}),d.jsx(GQ,{}),d.jsx(bJ,{}),d.jsx(VQ,{}),x&&d.jsx(x,{})]})});async function eae(e,n){const{url:t,style:r="normal",weight:s="500",display:o,featureSettings:i,stretch:a,unicodeRange:l,variant:c,format:u}=n,h={style:r,weight:s,display:o,featureSettings:i,stretch:a,unicodeRange:l,variant:c},p=new FontFace(e,`url(${t})`,h);return await p.load(),document.fonts.add(p),p.$$_url=t,p.$$_fontface=` + `},[c,t,o]),p=nA(()=>{if(!l.current)return;const f=Array.from(l.current.children);a(f.length),f.findIndex(x=>x.getAttribute("data-value")===c)<=o&&u(null);const y=Array.from(l.current.children).findIndex(x=>x.getAttribute("aria-checked")==="true");y!==-1&&y>=o&&u(f[y].getAttribute("data-value"))});return P.useLayoutEffect(()=>{p()}),P.useLayoutEffect(()=>{if(!l.current)return;const f=new MutationObserver(p);return f.observe(l.current,{childList:!0,subtree:!0,attributeFilter:["data-value","aria-checked"]}),()=>{f.disconnect()}},[p]),P.useEffect(()=>{const f=[["1",0],["2",1],["3",2],["4",3],["5",4],["6",5],["7",6],["8",7],["9",8],["0",9]];for(const[S,y]of f)Fn(S,x=>{var w;if(Rc(n))return;Ie(x);const v=Array.from(((w=l.current)==null?void 0:w.children)??[]).filter(C=>!(C instanceof HTMLElement)||C.tagName.toLowerCase()!=="button"?!1:!!(C.offsetWidth||C.offsetHeight))[y];v&&v.click()});return()=>{Fn.unbind("1,2,3,4,5,6,7,8,9,0")}},[n]),d.jsxs(d.Fragment,{children:[d.jsx("style",{children:h}),d.jsxs("div",{className:le("tlui-toolbar__tools",{"tlui-toolbar__tools__mobile":ro+1&&d.jsx($ie.Provider,{value:!0,children:d.jsxs(qi,{id:"toolbar overflow",modal:!1,children:[d.jsx(Zi,{children:d.jsx(ce,{title:s("tool-panel.more"),type:"tool",className:"tlui-toolbar__overflow","data-testid":"tools.more-button",children:d.jsx(Se,{icon:"chevron-up"})})}),d.jsx(Qi,{side:"top",align:"center",children:d.jsx("div",{className:"tlui-buttons__grid","data-testid":"tools.more-content",id:`${t}_more`,children:d.jsx(Tr,{type:"toolbar-overflow",sourceId:"toolbar",children:e})})})]})})]})]})}function Fie({activeToolId:e}){const n=F(),t=Cn(),r=xe(),s=H("is tool locked",()=>n.getInstanceState().isToolLocked,[n]),o=H("current tool",()=>n.getCurrentTool(),[n]);return!e||!o.isLockable?null:d.jsx(ce,{type:"normal",title:r("action.toggle-tool-lock"),"data-testid":"tool-lock",className:le("tlui-toolbar__lock-button",{"tlui-toolbar__lock-button__mobile":tn.updateInstanceState({isToolLocked:!s}),children:d.jsx(Se,{icon:s?"lock":"unlock",small:!0})})}const zie=P.memo(function({children:n}){const t=F(),r=Cn(),s=co(),o=H("current tool id",()=>t.getCurrentToolId(),[t]),{ActionsMenu:i,QuickActions:a}=pi();return d.jsx("div",{className:"tlui-toolbar",children:d.jsxs("div",{className:"tlui-toolbar__inner",children:[d.jsxs("div",{className:"tlui-toolbar__left",children:[!s&&d.jsxs("div",{className:"tlui-toolbar__extras",children:[r{const c=i.current;if(!c)return;const u=c.parentElement.parentElement,h=u.querySelector(".tlui-layout__top__left"),p=u.querySelector(".tlui-layout__top__right"),f=u.offsetWidth,S=h.offsetWidth,y=p.offsetWidth,x=c.offsetWidth-n;let m=(f-x)/2;f%2!==0&&(m-=.5);const v=S+r,w=c.offsetLeft,C=Math.min(f-y-S-2*r,e),E=Math.max(m,v)-w;p.offsetWidth>t&&a<=6?c.style.setProperty("max-width",C-s+"px"):c.style.setProperty("max-width",C+"px"),c.style.setProperty("transform",`translate(${E}px, 0px)`)},[a,n,r,e,s,t]);return P.useLayoutEffect(()=>{const c=i.current;if(!c)return;const u=c.parentElement.parentElement,h=u.querySelector(".tlui-layout__top__left"),p=u.querySelector(".tlui-layout__top__right"),f=new ResizeObserver(l);return f.observe(h),f.observe(p),f.observe(u),f.observe(c),l(),()=>{f.disconnect()}},[l]),P.useLayoutEffect(()=>{l()}),d.jsx("div",{ref:i,className:"tlui-top-panel__container",children:o})}function Hie(){const e=fee()==="offline";return d.jsx(Uie,{children:e&&d.jsx(Bie,{})})}function Kie(){const e=ie();return d.jsxs(d.Fragment,{children:[d.jsx(U,{...e["zoom-in"],noClose:!0}),d.jsx(U,{...e["zoom-out"],noClose:!0}),d.jsx($R,{}),d.jsx(NR,{}),d.jsx(FR,{})]})}const Wie=P.memo(function({children:n}){const t=$t(),[r,s]=ho("zoom menu"),o=n??d.jsx(Kie,{});return d.jsxs(S1,{dir:"ltr",open:r,onOpenChange:s,modal:!1,children:[d.jsx(v1,{asChild:!0,dir:"ltr",children:d.jsx(Gie,{})}),d.jsx(Kg,{container:t,children:d.jsx(x1,{className:"tlui-menu",side:"top",align:"start",alignOffset:0,sideOffset:8,collisionPadding:4,children:d.jsx(Tr,{type:"menu",sourceId:"zoom-menu",children:o})})})]})}),Gie=P.forwardRef(function(n,t){const r=F(),s=Cn(),o=H("zoom",()=>r.getZoomLevel(),[r]),i=xe(),a=P.useCallback(()=>{r.resetZoom(r.getViewportScreenCenter(),{animation:{duration:r.options.animationMediumMs}})},[r]);return d.jsx(ce,{ref:t,...n,type:"icon",title:`${i("navigation-zone.zoom")}`,"data-testid":"minimap.zoom-menu-button",className:s({ContextMenu:hse,ActionsMenu:Fre,HelpMenu:null,ZoomMenu:Wie,MainMenu:Xse,Minimap:eoe,StylePanel:Goe,PageMenu:soe,NavigationPanel:noe,Toolbar:zie,KeyboardShortcutsDialog:Rse,QuickActions:ioe,HelperButtons:Ose,DebugPanel:Cse,DebugMenu:Pse,MenuPanel:kse,SharePanel:r?poe:null,CursorChatBubble:r?gse:null,TopPanel:r?Hie:null,...t}),[t,r]),children:n})}function pi(){const e=P.useContext(mL);if(!e)throw new Error("useTldrawUiComponents must be used within a TldrawUiComponentsProvider");return e}function Yie({overrides:e,components:n,assetUrls:t,onUiEvent:r,forceMobile:s,children:o}){return d.jsx(Lq,{assetUrls:CJ(t),children:d.jsx(Fq,{overrides:TJ(e),children:d.jsx(UQ,{onEvent:r,children:d.jsx(yJ,{children:d.jsx(HQ,{children:d.jsx(EJ,{forceMobile:s,children:d.jsx(Vie,{overrides:n,children:d.jsx(Xie,{overrides:e,children:o})})})})})})})})}function Xie({overrides:e,children:n}){const t=MJ(e);return d.jsx(yee,{overrides:t.actions,children:d.jsx(IJ,{overrides:t.tools,children:n})})}function qie(){const e=F(),{addToast:n}=Qr();P.useEffect(()=>{function t({name:r,count:s}){n({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 e.addListener("max-shapes",t),()=>{e.removeListener("max-shapes",t)}},[e,n])}const Zie=Ce.memo(function({renderDebugMenuItems:n,children:t,hideUi:r,components:s,...o}){return d.jsx(Yie,{...o,components:s,children:d.jsx(Qie,{hideUi:r,renderDebugMenuItems:n,children:t})})}),Qie=Ce.memo(function({children:n,hideUi:t,...r}){return d.jsxs(d.Fragment,{children:[n,t?null:d.jsx(Jie,{...r})]})}),Jie=Ce.memo(function(){const n=F(),t=xe(),r=Cn(),s=co(),o=H("focus",()=>n.getInstanceState().isFocusMode,[n]),i=H("debug",()=>n.getInstanceState().isDebugMode,[n]),{SharePanel:a,TopPanel:l,MenuPanel:c,StylePanel:u,Toolbar:h,HelpMenu:p,NavigationPanel:f,HelperButtons:S,DebugPanel:y,CursorChatBubble:x}=pi();Rie(),see(),qie();const{"toggle-focus-mode":m}=ie();return d.jsxs("div",{className:le("tlui-layout",{"tlui-layout__mobile":rm.onSelect("menu"),children:d.jsx(Se,{icon:"dot"})})}):d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"tlui-layout__top",children:[d.jsxs("div",{className:"tlui-layout__top__left",children:[c&&d.jsx(c,{}),S&&d.jsx(S,{})]}),d.jsx("div",{className:"tlui-layout__top__center",children:l&&d.jsx(l,{})}),d.jsxs("div",{className:"tlui-layout__top__right",children:[a&&d.jsx(a,{}),u&&r>=yt.TABLET_SM&&!s&&d.jsx(u,{})]})]}),d.jsxs("div",{className:"tlui-layout__bottom",children:[d.jsxs("div",{className:"tlui-layout__bottom__main",children:[f&&d.jsx(f,{}),h&&d.jsx(h,{}),p&&d.jsx(p,{})]}),i&&y&&d.jsx(y,{})]})]}),d.jsx(wJ,{}),d.jsx(GQ,{}),d.jsx(bJ,{}),d.jsx(VQ,{}),x&&d.jsx(x,{})]})});async function eae(e,n){const{url:t,style:r="normal",weight:s="500",display:o,featureSettings:i,stretch:a,unicodeRange:l,variant:c,format:u}=n,h={style:r,weight:s,display:o,featureSettings:i,stretch:a,unicodeRange:l,variant:c},p=new FontFace(e,`url(${t})`,h);return await p.load(),document.fonts.add(p),p.$$_url=t,p.$$_fontface=` @font-face { font-family: ${p.family}; font-stretch: ${p.stretch}; font-weight: ${p.weight}; font-style: ${p.style}; src: url("${t}") format("${u}") -}`,p}const xh=(e,n)=>{const[t,r]=P.useState(2);return P.useEffect(()=>{let s=!1;return r(2),eae(e,n).then(()=>{s||r(0)}).catch(o=>{s||(console.error(o),r(1))}),()=>{s=!0}},[e,n]),t};function tae(e){return{draw:{url:e.fonts.draw,format:e.fonts.draw.split(".").pop()},serif:{url:e.fonts.serif,format:e.fonts.serif.split(".").pop()},sansSerif:{url:e.fonts.sansSerif,format:e.fonts.sansSerif.split(".").pop()},monospace:{url:e.fonts.monospace,format:e.fonts.monospace.split(".").pop()}}}function yL(e){const n=P.useMemo(()=>tae(e),[e]),t=[xh("tldraw_draw",n.draw),xh("tldraw_serif",n.serif),xh("tldraw_sans",n.sansSerif),xh("tldraw_mono",n.monospace)];return{error:t.some(r=>r===1),done:!t.some(r=>r===2)}}function nae(e){const{children:n,maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:s,acceptedVideoMimeTypes:o,onMount:i,components:a={},shapeUtils:l=[],bindingUtils:c=[],tools:u=[],...h}=e,p=dg(a),f=P.useMemo(()=>({Scribble:oI,ShapeIndicators:vY,CollaboratorScribble:oI,SelectionForeground:mY,SelectionBackground:fY,Handles:cY,...p}),[p]),S=Yc(l),m=P.useMemo(()=>[...ZA,...S],[S]),x=Yc(c),y=P.useMemo(()=>[...yA,...x],[x]),v=Yc(u),w=P.useMemo(()=>[...dZ,...vX,...v],[v]),C=hO(h.assetUrls),{done:E,error:k}=yL(C);return k?d.jsx(pA,{children:"Could not load assets. Please refresh the page."}):E?d.jsx(XV,{initialState:"select",...h,components:f,shapeUtils:m,bindingUtils:y,tools:w,children:d.jsxs(Zie,{...h,components:f,children:[d.jsx(rae,{maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:s,acceptedVideoMimeTypes:o,onMount:i}),n]})}):d.jsx(pw,{children:d.jsx(nw,{})})}function rae({maxImageDimension:e=5e3,maxAssetSize:n=10*1024*1024,acceptedImageMimeTypes:t=$0,acceptedVideoMimeTypes:r=Q2,onMount:s}){const o=F(),i=Qr(),a=xe();fA(()=>{const u=[];return u.push(Xq(o)),tX(o,{maxImageDimension:e,maxAssetSize:n,acceptedImageMimeTypes:t,acceptedVideoMimeTypes:r},{toasts:i,msg:a}),u.push(o.store.props.onMount(o)),u.push(s==null?void 0:s(o)),()=>{u.forEach(h=>h==null?void 0:h())}});const{Canvas:l}=st(),{ContextMenu:c}=pi();return c?d.jsx(c,{}):l?d.jsx(l,{}):null}P.memo(function(n){const[t,r]=P.useState(null),[s,o]=P.useState(null),i=Yc(n.shapeUtils??[]),a=P.useMemo(()=>[...ZA,...i],[i]),l=Yc(n.bindingUtils??[]),c=P.useMemo(()=>[...yA,...l],[l]),u=tY({snapshot:n.snapshot,shapeUtils:a}),h=hO(),{done:p,error:f}=yL(h),{pageId:S,bounds:m,scale:x,background:y,padding:v,darkMode:w,preserveAspectRatio:C,format:E="svg",licenseKey:k}=n;return P.useLayoutEffect(()=>{if(!s||!u||!p)return;let I=!1;const _=document.createElement("div");s.appendChild(_),s.classList.add("tl-container","tl-theme__light");const T=new Z({store:u,shapeUtils:a,bindingUtils:c,tools:[],getContainer:()=>_,licenseKey:k});S&&T.setCurrentPage(S);const M=T.getCurrentPageShapeIds();async function D(){const $=await T.getSvgString([...M],{bounds:m,scale:x,background:y,padding:v,darkMode:w,preserveAspectRatio:C});if($&&!I){if(E==="svg"){if(!I){const j=new Blob([$.svg],{type:"image/svg+xml"}),O=URL.createObjectURL(j);r(O)}}else if(E==="png"){const j=await wO(T,$.svg,{type:E,quality:1,scale:2,width:$.width,height:$.height});if(j&&!I){const O=URL.createObjectURL(j);r(O)}}}T.dispose()}return D(),()=>{I=!0}},[E,s,u,a,c,S,m,x,y,v,w,C,p,f,k]),f?d.jsx(pA,{children:"Could not load assets."}):p?d.jsx("div",{ref:o,style:{position:"relative",width:"100%",height:"100%"},children:t&&d.jsx("img",{src:t,referrerPolicy:"strict-origin-when-cross-origin",style:{width:"100%",height:"100%"}})}):d.jsx(pw,{children:d.jsx(nw,{})})});P.memo(function({children:n}){const t=xe(),r=Cn(),s=n??d.jsx(Nse,{});return r{const c=r.getShape(l);if(!c)return;const u=r.getShapeUtil(c);if(t.nearest){const h=u.getGeometry(c).nearestPoint(s);a.push(h)}else if(t.end){const h=u.getGeometry(c).vertices??[],p=this.getWeightedPoints(h,i);a.push(...p)}else if(t.middle){const h=u.getGeometry(c);let p;if(h instanceof at){const f=h.segments.map(m=>m.center),S=this.getWeightedPoints(f,i);a.push(...S)}else if(h instanceof ia&&h.segments.length===1){p=u.getGeometry(c).center;const f=this.getWeightedPoints([p],i);a.push(...f)}}}),a}getWeightedPoints(n,t){return n==null?void 0:n.filter(r=>t.distanceToPoint(r){let x=m.dist(p);return isNaN(x)&&(x=1/0),x}),S=Math.min(...f);if(r.grid&&o)if(p.dist(c[0]),S!0,this.hideRotateHandle=()=>!0,this.onHandleDrag=(n,{handle:t})=>{var u,h,p,f,S,m,x,y,v,w;const r=Be(n),{inputs:{currentPagePoint:s,ctrlKey:o}}=this.editor,{x:i,y:a}=s,l=new dx(this.editor,Number((h=(u=this.editor)==null?void 0:u.customSnapping)==null?void 0:h.weight));let c={...t,x:i,y:a};return o||(c=l.snap(t,c,{middle:(f=(p=this.editor)==null?void 0:p.customSnapping)==null?void 0:f.middle,end:(m=(S=this.editor)==null?void 0:S.customSnapping)==null?void 0:m.end,grid:(y=(x=this.editor)==null?void 0:x.customSnapping)==null?void 0:y.grid,nearest:(w=(v=this.editor)==null?void 0:v.customSnapping)==null?void 0:w.nearest})),r.props.points[Number(t.id)]=[c.x,c.y],r},this.onTranslateEnd=(n,t)=>{const{x:r,y:s}=t,{x:o,y:i}=n,a=r-o,l=s-i,c=Be(t),u=c.props.points.map(([p,f])=>[p+a,f+l]),h={...c,x:0,y:0,props:{...c.props,points:u}};this.editor.updateShape(h)}}getDefaultProps(){return{name:"Polygon",points:[[0,0],[100,0],[100,100],[0,100]]}}getGeometry(n){return new at({points:n.props.points.map(b.FromArray),isFilled:!1})}getHandles(n){return this.editor.getShapeGeometry(n).vertices.map((s,o)=>({id:`${o}`,type:"vertex",canBind:!1,canSnap:!0,index:`p${o}`,x:s.x,y:s.y}))}component(n){const r=this.editor.getShapeGeometry(n).toSimpleSvgPath();return d.jsx(bs,{children:d.jsx("path",{d:r,stroke:"black",fill:"none",strokeWidth:2})})}indicator(n){const r=this.editor.getShapeGeometry(n).toSimpleSvgPath();return d.jsx(bs,{children:d.jsx("path",{d:r,stroke:"blue",strokeWidth:1})})}};jf.type="custom-polygon",jf.props=iae;let hx=jf;const aae=[hx];function lae(){const[e,n]=P.useState(null);return d.jsxs("div",{style:{fontFamily:"Arial, Helvetica, sans-serif"},children:[d.jsx("div",{className:"tldraw__editor",style:{position:"absolute",inset:0},children:d.jsx(nae,{persistenceKey:"example",onMount:t=>{t.customSnapping={weight:.5},n(t),t.createShapes([{id:je("a1"),type:"custom-polygon"},{id:je("a2"),type:"custom-polygon",props:{points:[[150,0],[250,0],[250,100],[150,100]]}}])},shapeUtils:aae})}),e&&d.jsxs("div",{style:{position:"absolute",zIndex:10,top:40,left:20},children:[d.jsx("h3",{children:"Custom Snapping"}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"end",name:"scales",onChange:t=>e.customSnapping.end=t.target.checked}),d.jsx("label",{htmlFor:"end",children:"End"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"middle",name:"scales",onChange:t=>e.customSnapping.middle=t.target.checked}),d.jsx("label",{htmlFor:"middle",children:"Middle"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"grid",name:"scales",onChange:t=>{e.customSnapping.grid=t.target.checked,e.updateInstanceState({isGridMode:t.target.checked})}}),d.jsx("label",{htmlFor:"grid",children:"Grid"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"nearest",name:"scales",onChange:t=>e.customSnapping.nearest=t.target.checked}),d.jsx("label",{htmlFor:"nearest",children:"Nearest"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"number",id:"weight",min:.1,step:.1,max:1,defaultValue:e.customSnapping.weight,onChange:t=>e.customSnapping.weight=Number(t.target.value)}),d.jsx("label",{htmlFor:"weight",children:"Weight"})]})]})]})}a0(document.getElementById("root")).render(d.jsx(P.StrictMode,{children:d.jsx(lae,{})})); +}`,p}const xh=(e,n)=>{const[t,r]=P.useState(2);return P.useEffect(()=>{let s=!1;return r(2),eae(e,n).then(()=>{s||r(0)}).catch(o=>{s||(console.error(o),r(1))}),()=>{s=!0}},[e,n]),t};function tae(e){return{draw:{url:e.fonts.draw,format:e.fonts.draw.split(".").pop()},serif:{url:e.fonts.serif,format:e.fonts.serif.split(".").pop()},sansSerif:{url:e.fonts.sansSerif,format:e.fonts.sansSerif.split(".").pop()},monospace:{url:e.fonts.monospace,format:e.fonts.monospace.split(".").pop()}}}function yL(e){const n=P.useMemo(()=>tae(e),[e]),t=[xh("tldraw_draw",n.draw),xh("tldraw_serif",n.serif),xh("tldraw_sans",n.sansSerif),xh("tldraw_mono",n.monospace)];return{error:t.some(r=>r===1),done:!t.some(r=>r===2)}}function nae(e){const{children:n,maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:s,acceptedVideoMimeTypes:o,onMount:i,components:a={},shapeUtils:l=[],bindingUtils:c=[],tools:u=[],...h}=e,p=dg(a),f=P.useMemo(()=>({Scribble:oI,ShapeIndicators:vY,CollaboratorScribble:oI,SelectionForeground:mY,SelectionBackground:fY,Handles:cY,...p}),[p]),S=Yc(l),y=P.useMemo(()=>[...ZA,...S],[S]),x=Yc(c),m=P.useMemo(()=>[...yA,...x],[x]),v=Yc(u),w=P.useMemo(()=>[...dZ,...vX,...v],[v]),C=hO(h.assetUrls),{done:E,error:k}=yL(C);return k?d.jsx(pA,{children:"Could not load assets. Please refresh the page."}):E?d.jsx(XV,{initialState:"select",...h,components:f,shapeUtils:y,bindingUtils:m,tools:w,children:d.jsxs(Zie,{...h,components:f,children:[d.jsx(rae,{maxImageDimension:t,maxAssetSize:r,acceptedImageMimeTypes:s,acceptedVideoMimeTypes:o,onMount:i}),n]})}):d.jsx(pw,{children:d.jsx(nw,{})})}function rae({maxImageDimension:e=5e3,maxAssetSize:n=10*1024*1024,acceptedImageMimeTypes:t=$0,acceptedVideoMimeTypes:r=Q2,onMount:s}){const o=F(),i=Qr(),a=xe();fA(()=>{const u=[];return u.push(Xq(o)),tX(o,{maxImageDimension:e,maxAssetSize:n,acceptedImageMimeTypes:t,acceptedVideoMimeTypes:r},{toasts:i,msg:a}),u.push(o.store.props.onMount(o)),u.push(s==null?void 0:s(o)),()=>{u.forEach(h=>h==null?void 0:h())}});const{Canvas:l}=st(),{ContextMenu:c}=pi();return c?d.jsx(c,{}):l?d.jsx(l,{}):null}P.memo(function(n){const[t,r]=P.useState(null),[s,o]=P.useState(null),i=Yc(n.shapeUtils??[]),a=P.useMemo(()=>[...ZA,...i],[i]),l=Yc(n.bindingUtils??[]),c=P.useMemo(()=>[...yA,...l],[l]),u=tY({snapshot:n.snapshot,shapeUtils:a}),h=hO(),{done:p,error:f}=yL(h),{pageId:S,bounds:y,scale:x,background:m,padding:v,darkMode:w,preserveAspectRatio:C,format:E="svg",licenseKey:k}=n;return P.useLayoutEffect(()=>{if(!s||!u||!p)return;let I=!1;const _=document.createElement("div");s.appendChild(_),s.classList.add("tl-container","tl-theme__light");const T=new Z({store:u,shapeUtils:a,bindingUtils:c,tools:[],getContainer:()=>_,licenseKey:k});S&&T.setCurrentPage(S);const M=T.getCurrentPageShapeIds();async function D(){const $=await T.getSvgString([...M],{bounds:y,scale:x,background:m,padding:v,darkMode:w,preserveAspectRatio:C});if($&&!I){if(E==="svg"){if(!I){const j=new Blob([$.svg],{type:"image/svg+xml"}),O=URL.createObjectURL(j);r(O)}}else if(E==="png"){const j=await wO(T,$.svg,{type:E,quality:1,scale:2,width:$.width,height:$.height});if(j&&!I){const O=URL.createObjectURL(j);r(O)}}}T.dispose()}return D(),()=>{I=!0}},[E,s,u,a,c,S,y,x,m,v,w,C,p,f,k]),f?d.jsx(pA,{children:"Could not load assets."}):p?d.jsx("div",{ref:o,style:{position:"relative",width:"100%",height:"100%"},children:t&&d.jsx("img",{src:t,referrerPolicy:"strict-origin-when-cross-origin",style:{width:"100%",height:"100%"}})}):d.jsx(pw,{children:d.jsx(nw,{})})});P.memo(function({children:n}){const t=xe(),r=Cn(),s=n??d.jsx(Nse,{});return r{const c=r.getShape(l);if(!c)return;const u=r.getShapeUtil(c);if(t.nearest){const h=u.getGeometry(c).nearestPoint(s);a.push(h)}else if(t.end){const h=u.getGeometry(c).vertices??[],p=this.getWeightedPoints(h,i);a.push(...p)}else if(t.middle){const h=u.getGeometry(c);let p=[];h instanceof at?p=h.segments.map(S=>S.center):h instanceof ia&&h.segments.length===1&&(p=[u.getGeometry(c).center]);const f=this.getWeightedPoints(p,i);a.push(...f)}}),a}getWeightedPoints(n,t){return n==null?void 0:n.filter(r=>t.distanceToPoint(r){let x=y.dist(p);return isNaN(x)&&(x=1/0),x}),S=Math.min(...f);if(r.grid&&o)if(p.dist(c[0]),S!0,this.hideRotateHandle=()=>!0,this.onHandleDrag=(n,{handle:t})=>{var u,h,p,f,S,y,x,m,v,w;const r=Be(n),{inputs:{currentPagePoint:s,ctrlKey:o}}=this.editor,{x:i,y:a}=s,l=new dx(this.editor,Number((h=(u=this.editor)==null?void 0:u.customSnapping)==null?void 0:h.weight));let c={...t,x:i,y:a};return o||(c=l.snap(t,c,{middle:(f=(p=this.editor)==null?void 0:p.customSnapping)==null?void 0:f.middle,end:(y=(S=this.editor)==null?void 0:S.customSnapping)==null?void 0:y.end,grid:(m=(x=this.editor)==null?void 0:x.customSnapping)==null?void 0:m.grid,nearest:(w=(v=this.editor)==null?void 0:v.customSnapping)==null?void 0:w.nearest})),r.props.points[Number(t.id)]=[c.x,c.y],r},this.onTranslateEnd=(n,t)=>{const{x:r,y:s}=t,{x:o,y:i}=n,a=r-o,l=s-i,c=Be(t),u=c.props.points.map(([p,f])=>[p+a,f+l]),h={...c,x:0,y:0,props:{...c.props,points:u}};this.editor.updateShape(h)}}getDefaultProps(){return{name:"Polygon",points:[[0,0],[100,0],[100,100],[0,100]]}}getGeometry(n){return new at({points:n.props.points.map(b.FromArray),isFilled:!1})}getHandles(n){return this.editor.getShapeGeometry(n).vertices.map((s,o)=>({id:`${o}`,type:"vertex",canBind:!1,canSnap:!0,index:`p${o}`,x:s.x,y:s.y}))}component(n){const r=this.editor.getShapeGeometry(n).toSimpleSvgPath();return d.jsx(bs,{children:d.jsx("path",{d:r,stroke:"black",fill:"none",strokeWidth:2})})}indicator(n){const r=this.editor.getShapeGeometry(n).toSimpleSvgPath();return d.jsx(bs,{children:d.jsx("path",{d:r,stroke:"blue",strokeWidth:1})})}};jf.type="custom-polygon",jf.props=iae;let hx=jf;const aae=[hx];function lae(){const[e,n]=P.useState(null);return d.jsxs("div",{style:{fontFamily:"Arial, Helvetica, sans-serif"},children:[d.jsx("div",{className:"tldraw__editor",style:{position:"absolute",inset:0},children:d.jsx(nae,{persistenceKey:"example",onMount:t=>{t.customSnapping={weight:.5},n(t),t.createShapes([{id:je("a1"),type:"custom-polygon"},{id:je("a2"),type:"custom-polygon",props:{points:[[150,0],[250,0],[250,100],[150,100]]}}])},shapeUtils:aae})}),e&&d.jsxs("div",{style:{position:"absolute",zIndex:10,top:40,left:20},children:[d.jsx("h3",{children:"Custom Snapping"}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"end",name:"scales",onChange:t=>e.customSnapping.end=t.target.checked}),d.jsx("label",{htmlFor:"end",children:"End"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"middle",name:"scales",onChange:t=>e.customSnapping.middle=t.target.checked}),d.jsx("label",{htmlFor:"middle",children:"Middle"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"grid",name:"scales",onChange:t=>{e.customSnapping.grid=t.target.checked,e.updateInstanceState({isGridMode:t.target.checked})}}),d.jsx("label",{htmlFor:"grid",children:"Grid"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"checkbox",id:"nearest",name:"scales",onChange:t=>e.customSnapping.nearest=t.target.checked}),d.jsx("label",{htmlFor:"nearest",children:"Nearest"})]}),d.jsxs("div",{children:[d.jsx("input",{type:"number",id:"weight",min:.1,step:.1,max:1,defaultValue:e.customSnapping.weight,onChange:t=>e.customSnapping.weight=Number(t.target.value)}),d.jsx("label",{htmlFor:"weight",children:"Weight"})]})]})]})}a0(document.getElementById("root")).render(d.jsx(P.StrictMode,{children:d.jsx(lae,{})})); diff --git a/index.html b/index.html index ca674a7..2f0a897 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ Snapping - +