var FO=Object.defineProperty;var NO=(e,t,n)=>t in e?FO(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var m=(e,t,n)=>(NO(e,typeof t!="symbol"?t+"":t,n),n);function zO(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const s of o)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const s={};return o.integrity&&(s.integrity=o.integrity),o.referrerPolicy&&(s.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?s.credentials="include":o.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(o){if(o.ep)return;o.ep=!0;const s=n(o);fetch(o.href,s)}})();var tn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function pc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var xI={exports:{}},ff={},wI={exports:{}},xe={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Cu=Symbol.for("react.element"),BO=Symbol.for("react.portal"),UO=Symbol.for("react.fragment"),HO=Symbol.for("react.strict_mode"),KO=Symbol.for("react.profiler"),WO=Symbol.for("react.provider"),VO=Symbol.for("react.context"),GO=Symbol.for("react.forward_ref"),YO=Symbol.for("react.suspense"),XO=Symbol.for("react.memo"),qO=Symbol.for("react.lazy"),Bw=Symbol.iterator;function ZO(e){return e===null||typeof e!="object"?null:(e=Bw&&e[Bw]||e["@@iterator"],typeof e=="function"?e:null)}var bI={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},PI=Object.assign,CI={};function fc(e,t,n){this.props=e,this.context=t,this.refs=CI,this.updater=n||bI}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function II(){}II.prototype=fc.prototype;function Nv(e,t,n){this.props=e,this.context=t,this.refs=CI,this.updater=n||bI}var zv=Nv.prototype=new II;zv.constructor=Nv;PI(zv,fc.prototype);zv.isPureReactComponent=!0;var Uw=Array.isArray,EI=Object.prototype.hasOwnProperty,Bv={current:null},_I={key:!0,ref:!0,__self:!0,__source:!0};function kI(e,t,n){var r,o={},s=null,i=null;if(t!=null)for(r in t.ref!==void 0&&(i=t.ref),t.key!==void 0&&(s=""+t.key),t)EI.call(t,r)&&!_I.hasOwnProperty(r)&&(o[r]=t[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1>>1,le=H[Z];if(0>>1;Zo(ae,W))Aeo(Re,ae)?(H[Z]=Re,H[Ae]=W,Z=Ae):(H[Z]=ae,H[Me]=W,Z=Me);else if(Aeo(Re,W))H[Z]=Re,H[Ae]=W,Z=Ae;else break e}}return U}function o(H,U){var W=H.sortIndex-U.sortIndex;return W!==0?W:H.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;e.unstable_now=function(){return s.now()}}else{var i=Date,a=i.now();e.unstable_now=function(){return i.now()-a}}var c=[],l=[],u=1,d=null,p=3,f=!1,y=!1,g=!1,w=typeof setTimeout=="function"?setTimeout:null,S=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 b(H){for(var U=n(l);U!==null;){if(U.callback===null)r(l);else if(U.startTime<=H)r(l),U.sortIndex=U.expirationTime,t(c,U);else break;U=n(l)}}function E(H){if(g=!1,b(H),!y)if(n(c)!==null)y=!0,q(C);else{var U=n(l);U!==null&&Q(E,U.startTime-H)}}function C(H,U){y=!1,g&&(g=!1,S(k),k=-1),f=!0;var W=p;try{for(b(U),d=n(c);d!==null&&(!(d.expirationTime>U)||H&&!O());){var Z=d.callback;if(typeof Z=="function"){d.callback=null,p=d.priorityLevel;var le=Z(d.expirationTime<=U);U=e.unstable_now(),typeof le=="function"?d.callback=le:d===n(c)&&r(c),b(U)}else r(c);d=n(c)}if(d!==null)var be=!0;else{var Me=n(l);Me!==null&&Q(E,Me.startTime-U),be=!1}return be}finally{d=null,p=W,f=!1}}var I=!1,_=null,k=-1,$=5,T=-1;function O(){return!(e.unstable_now()-T<$)}function N(){if(_!==null){var H=e.unstable_now();T=H;var U=!0;try{U=_(!0,H)}finally{U?F():(I=!1,_=null)}}else I=!1}var F;if(typeof v=="function")F=function(){v(N)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,B=L.port2;L.port1.onmessage=N,F=function(){B.postMessage(null)}}else F=function(){w(N,0)};function q(H){_=H,I||(I=!0,F())}function Q(H,U){k=w(function(){H(e.unstable_now())},U)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_continueExecution=function(){y||f||(y=!0,q(C))},e.unstable_forceFrameRate=function(H){0>H||125Z?(H.sortIndex=W,t(l,H),n(c)===null&&H===n(l)&&(g?(S(k),k=-1):g=!0,Q(E,W-Z))):(H.sortIndex=le,t(c,H),y||f||(y=!0,q(C))),H},e.unstable_shouldYield=O,e.unstable_wrapCallback=function(H){var U=p;return function(){var W=p;p=U;try{return H.apply(this,arguments)}finally{p=W}}}})(jI);AI.exports=jI;var lD=AI.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var uD=x,Jn=lD;function Y(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ny=Object.prototype.hasOwnProperty,dD=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Kw={},Ww={};function hD(e){return Ny.call(Ww,e)?!0:Ny.call(Kw,e)?!1:dD.test(e)?Ww[e]=!0:(Kw[e]=!0,!1)}function pD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function fD(e,t,n,r){if(t===null||typeof t>"u"||pD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function yn(e,t,n,r,o,s,i){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=s,this.removeEmptyString=i}var Kt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Kt[e]=new yn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Kt[t]=new yn(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Kt[e]=new yn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Kt[e]=new yn(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Kt[e]=new yn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Kt[e]=new yn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Kt[e]=new yn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Kt[e]=new yn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Kt[e]=new yn(e,5,!1,e.toLowerCase(),null,!1,!1)});var Hv=/[\-:]([a-z])/g;function Kv(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Hv,Kv);Kt[t]=new yn(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Hv,Kv);Kt[t]=new yn(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Hv,Kv);Kt[t]=new yn(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Kt[e]=new yn(e,1,!1,e.toLowerCase(),null,!1,!1)});Kt.xlinkHref=new yn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Kt[e]=new yn(e,1,!1,e.toLowerCase(),null,!0,!0)});function Wv(e,t,n,r){var o=Kt.hasOwnProperty(t)?Kt[t]:null;(o!==null?o.type!==0:r||!(2a||o[i]!==s[a]){var c=` `+o[i].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=i&&0<=a);break}}}finally{Ag=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ll(e):""}function gD(e){switch(e.tag){case 5:return ll(e.type);case 16:return ll("Lazy");case 13:return ll("Suspense");case 19:return ll("SuspenseList");case 0:case 2:case 15:return e=jg(e.type,!1),e;case 11:return e=jg(e.type.render,!1),e;case 1:return e=jg(e.type,!0),e;default:return""}}function Hy(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 ya:return"Fragment";case ma:return"Portal";case zy:return"Profiler";case Vv:return"StrictMode";case By:return"Suspense";case Uy:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case RI:return(e.displayName||"Context")+".Consumer";case DI:return(e._context.displayName||"Context")+".Provider";case Gv:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Yv:return t=e.displayName||null,t!==null?t:Hy(e.type)||"Memo";case gs:t=e._payload,e=e._init;try{return Hy(e(t))}catch{}}return null}function mD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Hy(t);case 8:return t===Vv?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ds(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function FI(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function yD(e){var t=FI(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,s=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(i){r=""+i,s.call(this,i)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function rd(e){e._valueTracker||(e._valueTracker=yD(e))}function NI(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=FI(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function op(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 Ky(e,t){var n=t.checked;return ut({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Gw(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ds(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function zI(e,t){t=t.checked,t!=null&&Wv(e,"checked",t,!1)}function Wy(e,t){zI(e,t);var n=Ds(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Vy(e,t.type,n):t.hasOwnProperty("defaultValue")&&Vy(e,t.type,Ds(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Yw(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Vy(e,t,n){(t!=="number"||op(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ul=Array.isArray;function La(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=od.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fl(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vl={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},SD=["Webkit","ms","Moz","O"];Object.keys(vl).forEach(function(e){SD.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vl[t]=vl[e]})});function KI(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vl.hasOwnProperty(e)&&vl[e]?(""+t).trim():t+"px"}function WI(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=KI(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var vD=ut({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 Xy(e,t){if(t){if(vD[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Y(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Y(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Y(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Y(62))}}function qy(e,t){if(e.indexOf("-")===-1)return typeof t.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 Zy=null;function Xv(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Qy=null,Fa=null,Na=null;function Zw(e){if(e=_u(e)){if(typeof Qy!="function")throw Error(Y(280));var t=e.stateNode;t&&(t=vf(t),Qy(e.stateNode,e.type,t))}}function VI(e){Fa?Na?Na.push(e):Na=[e]:Fa=e}function GI(){if(Fa){var e=Fa,t=Na;if(Na=Fa=null,Zw(e),t)for(e=0;e>>=0,e===0?32:31-($D(e)/MD|0)|0}var sd=64,id=4194304;function dl(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 cp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,s=e.pingedLanes,i=n&268435455;if(i!==0){var a=i&~o;a!==0?r=dl(a):(s&=i,s!==0&&(r=dl(s)))}else i=n&~o,i!==0?r=dl(i):s!==0&&(r=dl(s));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,s=t&-t,o>=s||o===16&&(s&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Iu(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Dr(t),e[t]=n}function DD(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wl),ib=" ",ab=!1;function pE(e,t){switch(e){case"keyup":return lR.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fE(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Sa=!1;function dR(e,t){switch(e){case"compositionend":return fE(t);case"keypress":return t.which!==32?null:(ab=!0,ib);case"textInput":return e=t.data,e===ib&&ab?null:e;default:return null}}function hR(e,t){if(Sa)return e==="compositionend"||!r0&&pE(e,t)?(e=dE(),sh=e0=ws=null,Sa=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=db(n)}}function SE(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?SE(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vE(){for(var e=window,t=op();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=op(e.document)}return t}function o0(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function wR(e){var t=vE(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&SE(n.ownerDocument.documentElement,n)){if(r!==null&&o0(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,s=Math.min(r.start,o);r=r.end===void 0?s:Math.min(r.end,o),!e.extend&&s>r&&(o=r,r=s,s=o),o=hb(n,s);var i=hb(n,r);o&&i&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),s>r?(e.addRange(t),e.extend(i.node,i.offset)):(t.setEnd(i.node,i.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,va=null,oS=null,Pl=null,sS=!1;function pb(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;sS||va==null||va!==op(r)||(r=va,"selectionStart"in r&&o0(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}),Pl&&Kl(Pl,r)||(Pl=r,r=dp(oS,"onSelect"),0ba||(e.current=dS[ba],dS[ba]=null,ba--)}function Ge(e,t){ba++,dS[ba]=e.current,e.current=t}var Rs={},rn=Ws(Rs),Tn=Ws(!1),Ci=Rs;function Qa(e,t){var n=e.type.contextTypes;if(!n)return Rs;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},s;for(s in n)o[s]=t[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function $n(e){return e=e.childContextTypes,e!=null}function pp(){tt(Tn),tt(rn)}function xb(e,t,n){if(rn.current!==Rs)throw Error(Y(168));Ge(rn,t),Ge(Tn,n)}function kE(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(Y(108,mD(e)||"Unknown",o));return ut({},n,r)}function fp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Rs,Ci=rn.current,Ge(rn,e),Ge(Tn,Tn.current),!0}function wb(e,t,n){var r=e.stateNode;if(!r)throw Error(Y(169));n?(e=kE(e,t,Ci),r.__reactInternalMemoizedMergedChildContext=e,tt(Tn),tt(rn),Ge(rn,e)):tt(Tn),Ge(Tn,n)}var To=null,xf=!1,Gg=!1;function TE(e){To===null?To=[e]:To.push(e)}function jR(e){xf=!0,TE(e)}function Vs(){if(!Gg&&To!==null){Gg=!0;var e=0,t=Fe;try{var n=To;for(Fe=1;e>=i,o-=i,Mo=1<<32-Dr(t)+o|n<k?($=_,_=null):$=_.sibling;var T=p(S,_,b[k],E);if(T===null){_===null&&(_=$);break}e&&_&&T.alternate===null&&t(S,_),v=s(T,v,k),I===null?C=T:I.sibling=T,I=T,_=$}if(k===b.length)return n(S,_),rt&&ui(S,k),C;if(_===null){for(;kk?($=_,_=null):$=_.sibling;var O=p(S,_,T.value,E);if(O===null){_===null&&(_=$);break}e&&_&&O.alternate===null&&t(S,_),v=s(O,v,k),I===null?C=O:I.sibling=O,I=O,_=$}if(T.done)return n(S,_),rt&&ui(S,k),C;if(_===null){for(;!T.done;k++,T=b.next())T=d(S,T.value,E),T!==null&&(v=s(T,v,k),I===null?C=T:I.sibling=T,I=T);return rt&&ui(S,k),C}for(_=r(S,_);!T.done;k++,T=b.next())T=f(_,S,k,T.value,E),T!==null&&(e&&T.alternate!==null&&_.delete(T.key===null?k:T.key),v=s(T,v,k),I===null?C=T:I.sibling=T,I=T);return e&&_.forEach(function(N){return t(S,N)}),rt&&ui(S,k),C}function w(S,v,b,E){if(typeof b=="object"&&b!==null&&b.type===ya&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case nd:e:{for(var C=b.key,I=v;I!==null;){if(I.key===C){if(C=b.type,C===ya){if(I.tag===7){n(S,I.sibling),v=o(I,b.props.children),v.return=S,S=v;break e}}else if(I.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===gs&&Cb(C)===I.type){n(S,I.sibling),v=o(I,b.props),v.ref=Hc(S,I,b),v.return=S,S=v;break e}n(S,I);break}else t(S,I);I=I.sibling}b.type===ya?(v=bi(b.props.children,S.mode,E,b.key),v.return=S,S=v):(E=ph(b.type,b.key,b.props,null,S.mode,E),E.ref=Hc(S,v,b),E.return=S,S=E)}return i(S);case ma:e:{for(I=b.key;v!==null;){if(v.key===I)if(v.tag===4&&v.stateNode.containerInfo===b.containerInfo&&v.stateNode.implementation===b.implementation){n(S,v.sibling),v=o(v,b.children||[]),v.return=S,S=v;break e}else{n(S,v);break}else t(S,v);v=v.sibling}v=tm(b,S.mode,E),v.return=S,S=v}return i(S);case gs:return I=b._init,w(S,v,I(b._payload),E)}if(ul(b))return y(S,v,b,E);if(Fc(b))return g(S,v,b,E);pd(S,b)}return typeof b=="string"&&b!==""||typeof b=="number"?(b=""+b,v!==null&&v.tag===6?(n(S,v.sibling),v=o(v,b),v.return=S,S=v):(n(S,v),v=em(b,S.mode,E),v.return=S,S=v),i(S)):n(S,v)}return w}var ec=jE(!0),OE=jE(!1),yp=Ws(null),Sp=null,Ia=null,c0=null;function l0(){c0=Ia=Sp=null}function u0(e){var t=yp.current;tt(yp),e._currentValue=t}function fS(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Ba(e,t){Sp=e,c0=Ia=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(En=!0),e.firstContext=null)}function yr(e){var t=e._currentValue;if(c0!==e)if(e={context:e,memoizedValue:t,next:null},Ia===null){if(Sp===null)throw Error(Y(308));Ia=e,Sp.dependencies={lanes:0,firstContext:e}}else Ia=Ia.next=e;return t}var fi=null;function d0(e){fi===null?fi=[e]:fi.push(e)}function DE(e,t,n,r){var o=t.interleaved;return o===null?(n.next=n,d0(t)):(n.next=o.next,o.next=n),t.interleaved=n,Bo(e,r)}function Bo(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var ms=!1;function h0(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function RE(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Oo(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Ts(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,_e&2){var o=r.pending;return o===null?t.next=t:(t.next=o.next,o.next=t),r.pending=t,Bo(e,n)}return o=r.interleaved,o===null?(t.next=t,d0(r)):(t.next=o.next,o.next=t),r.interleaved=t,Bo(e,n)}function ah(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zv(e,n)}}function Ib(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var o=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var i={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?o=s=i:s=s.next=i,n=n.next}while(n!==null);s===null?o=s=t:s=s.next=t}else o=s=t;n={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function vp(e,t,n,r){var o=e.updateQueue;ms=!1;var s=o.firstBaseUpdate,i=o.lastBaseUpdate,a=o.shared.pending;if(a!==null){o.shared.pending=null;var c=a,l=c.next;c.next=null,i===null?s=l:i.next=l,i=c;var u=e.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==i&&(a===null?u.firstBaseUpdate=l:a.next=l,u.lastBaseUpdate=c))}if(s!==null){var d=o.baseState;i=0,u=l=c=null,a=s;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 y=e,g=a;switch(p=t,f=n,g.tag){case 1:if(y=g.payload,typeof y=="function"){d=y.call(f,d,p);break e}d=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=g.payload,p=typeof y=="function"?y.call(f,d,p):y,p==null)break e;d=ut({},d,p);break e;case 2:ms=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,p=o.effects,p===null?o.effects=[a]:p.push(a))}else f={eventTime:f,lane:p,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(l=u=f,c=d):u=u.next=f,i|=p;if(a=a.next,a===null){if(a=o.shared.pending,a===null)break;p=a,a=p.next,p.next=null,o.lastBaseUpdate=p,o.shared.pending=null}}while(!0);if(u===null&&(c=d),o.baseState=c,o.firstBaseUpdate=l,o.lastBaseUpdate=u,t=o.shared.interleaved,t!==null){o=t;do i|=o.lane,o=o.next;while(o!==t)}else s===null&&(o.shared.lanes=0);_i|=i,e.lanes=i,e.memoizedState=d}}function Eb(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Xg.transition;Xg.transition={};try{e(!1),t()}finally{Fe=n,Xg.transition=r}}function JE(){return Sr().memoizedState}function LR(e,t,n){var r=Ms(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},e_(e))t_(t,n);else if(n=DE(e,t,n,r),n!==null){var o=gn();Rr(n,e,r,o),n_(n,t,r)}}function FR(e,t,n){var r=Ms(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(e_(e))t_(t,o);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var i=t.lastRenderedState,a=s(i,n);if(o.hasEagerState=!0,o.eagerState=a,zr(a,i)){var c=t.interleaved;c===null?(o.next=o,d0(t)):(o.next=c.next,c.next=o),t.interleaved=o;return}}catch{}finally{}n=DE(e,t,o,r),n!==null&&(o=gn(),Rr(n,e,r,o),n_(n,t,r))}}function e_(e){var t=e.alternate;return e===lt||t!==null&&t===lt}function t_(e,t){Cl=wp=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function n_(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Zv(e,n)}}var bp={readContext:yr,useCallback:Vt,useContext:Vt,useEffect:Vt,useImperativeHandle:Vt,useInsertionEffect:Vt,useLayoutEffect:Vt,useMemo:Vt,useReducer:Vt,useRef:Vt,useState:Vt,useDebugValue:Vt,useDeferredValue:Vt,useTransition:Vt,useMutableSource:Vt,useSyncExternalStore:Vt,useId:Vt,unstable_isNewReconciler:!1},NR={readContext:yr,useCallback:function(e,t){return Yr().memoizedState=[e,t===void 0?null:t],e},useContext:yr,useEffect:kb,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,lh(4194308,4,YE.bind(null,t,e),n)},useLayoutEffect:function(e,t){return lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return lh(4,2,e,t)},useMemo:function(e,t){var n=Yr();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Yr();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=LR.bind(null,lt,e),[r.memoizedState,e]},useRef:function(e){var t=Yr();return e={current:e},t.memoizedState=e},useState:_b,useDebugValue:x0,useDeferredValue:function(e){return Yr().memoizedState=e},useTransition:function(){var e=_b(!1),t=e[0];return e=RR.bind(null,e[1]),Yr().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=lt,o=Yr();if(rt){if(n===void 0)throw Error(Y(407));n=n()}else{if(n=t(),At===null)throw Error(Y(349));Ei&30||zE(r,t,n)}o.memoizedState=n;var s={value:n,getSnapshot:t};return o.queue=s,kb(UE.bind(null,r,s,e),[e]),r.flags|=2048,Ql(9,BE.bind(null,r,s,n,t),void 0,null),n},useId:function(){var e=Yr(),t=At.identifierPrefix;if(rt){var n=Ao,r=Mo;n=(r&~(1<<32-Dr(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ql++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(n,{is:r.is}):(e=i.createElement(n),n==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,n),e[qr]=t,e[Gl]=r,h_(e,t,!1,!1),t.stateNode=e;e:{switch(i=qy(n,r),n){case"dialog":Qe("cancel",e),Qe("close",e),o=r;break;case"iframe":case"object":case"embed":Qe("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,Kc(s,!1),t.lanes=4194304)}else{if(!r)if(e=xp(i),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Kc(s,!0),s.tail===null&&s.tailMode==="hidden"&&!i.alternate&&!rt)return Gt(t),null}else 2*St()-s.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,Kc(s,!1),t.lanes=4194304);s.isBackwards?(i.sibling=t.child,t.child=i):(n=s.last,n!==null?n.sibling=i:t.child=i,s.last=i)}return s.tail!==null?(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=St(),t.sibling=null,n=it.current,Ge(it,r?n&1|2:n&1),t):(Gt(t),null);case 22:case 23:return E0(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Hn&1073741824&&(Gt(t),t.subtreeFlags&6&&(t.flags|=8192)):Gt(t),null;case 24:return null;case 25:return null}throw Error(Y(156,t.tag))}function GR(e,t){switch(i0(t),t.tag){case 1:return $n(t.type)&&pp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),tt(Tn),tt(rn),g0(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return f0(t),null;case 13:if(tt(it),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Y(340));Ja()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return tt(it),null;case 4:return tc(),null;case 10:return u0(t.type._context),null;case 22:case 23:return E0(),null;case 24:return null;default:return null}}var gd=!1,Qt=!1,YR=typeof WeakSet=="function"?WeakSet:Set,te=null;function Ea(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ft(e,t,r)}else n.current=null}function PS(e,t,n){try{n()}catch(r){ft(e,t,r)}}var Nb=!1;function XR(e,t){if(iS=lp,e=vE(),o0(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var o=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var i=0,a=-1,c=-1,l=0,u=0,d=e,p=null;t:for(;;){for(var f;d!==n||o!==0&&d.nodeType!==3||(a=i+o),d!==s||r!==0&&d.nodeType!==3||(c=i+r),d.nodeType===3&&(i+=d.nodeValue.length),(f=d.firstChild)!==null;)p=d,d=f;for(;;){if(d===e)break t;if(p===n&&++l===o&&(a=i),p===s&&++u===r&&(c=i),(f=d.nextSibling)!==null)break;d=p,p=d.parentNode}d=f}n=a===-1||c===-1?null:{start:a,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(aS={focusedElem:e,selectionRange:n},lp=!1,te=t;te!==null;)if(t=te,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,te=e;else for(;te!==null;){t=te;try{var y=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var g=y.memoizedProps,w=y.memoizedState,S=t.stateNode,v=S.getSnapshotBeforeUpdate(t.elementType===t.type?g:Ir(t.type,g),w);S.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var b=t.stateNode.containerInfo;b.nodeType===1?b.textContent="":b.nodeType===9&&b.documentElement&&b.removeChild(b.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Y(163))}}catch(E){ft(t,t.return,E)}if(e=t.sibling,e!==null){e.return=t.return,te=e;break}te=t.return}return y=Nb,Nb=!1,y}function Il(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var s=o.destroy;o.destroy=void 0,s!==void 0&&PS(t,n,s)}o=o.next}while(o!==r)}}function Pf(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function CS(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function g_(e){var t=e.alternate;t!==null&&(e.alternate=null,g_(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[qr],delete t[Gl],delete t[uS],delete t[MR],delete t[AR])),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 m_(e){return e.tag===5||e.tag===3||e.tag===4}function zb(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||m_(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 IS(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=hp));else if(r!==4&&(e=e.child,e!==null))for(IS(e,t,n),e=e.sibling;e!==null;)IS(e,t,n),e=e.sibling}function ES(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ES(e,t,n),e=e.sibling;e!==null;)ES(e,t,n),e=e.sibling}var Rt=null,Er=!1;function ls(e,t,n){for(n=n.child;n!==null;)y_(e,t,n),n=n.sibling}function y_(e,t,n){if(to&&typeof to.onCommitFiberUnmount=="function")try{to.onCommitFiberUnmount(gf,n)}catch{}switch(n.tag){case 5:Qt||Ea(n,t);case 6:var r=Rt,o=Er;Rt=null,ls(e,t,n),Rt=r,Er=o,Rt!==null&&(Er?(e=Rt,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Rt.removeChild(n.stateNode));break;case 18:Rt!==null&&(Er?(e=Rt,n=n.stateNode,e.nodeType===8?Vg(e.parentNode,n):e.nodeType===1&&Vg(e,n),Ul(e)):Vg(Rt,n.stateNode));break;case 4:r=Rt,o=Er,Rt=n.stateNode.containerInfo,Er=!0,ls(e,t,n),Rt=r,Er=o;break;case 0:case 11:case 14:case 15:if(!Qt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var s=o,i=s.destroy;s=s.tag,i!==void 0&&(s&2||s&4)&&PS(n,t,i),o=o.next}while(o!==r)}ls(e,t,n);break;case 1:if(!Qt&&(Ea(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){ft(n,t,a)}ls(e,t,n);break;case 21:ls(e,t,n);break;case 22:n.mode&1?(Qt=(r=Qt)||n.memoizedState!==null,ls(e,t,n),Qt=r):ls(e,t,n);break;default:ls(e,t,n)}}function Bb(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new YR),t.forEach(function(r){var o=o3.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function Cr(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=i),r&=~s}if(r=o,r=St()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*ZR(r/1960))-r,10e?16:e,bs===null)var r=!1;else{if(e=bs,bs=null,Ip=0,_e&6)throw Error(Y(331));var o=_e;for(_e|=4,te=e.current;te!==null;){var s=te,i=s.child;if(te.flags&16){var a=s.deletions;if(a!==null){for(var c=0;cSt()-C0?wi(e,0):P0|=n),Mn(e,t)}function I_(e,t){t===0&&(e.mode&1?(t=id,id<<=1,!(id&130023424)&&(id=4194304)):t=1);var n=gn();e=Bo(e,t),e!==null&&(Iu(e,t,n),Mn(e,n))}function r3(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),I_(e,n)}function o3(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Y(314))}r!==null&&r.delete(t),I_(e,n)}var E_;E_=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Tn.current)En=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return En=!1,WR(e,t,n);En=!!(e.flags&131072)}else En=!1,rt&&t.flags&1048576&&$E(t,mp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;uh(e,t),e=t.pendingProps;var o=Qa(t,rn.current);Ba(t,n),o=y0(null,t,r,e,o,n);var s=S0();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,$n(r)?(s=!0,fp(t)):s=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,h0(t),o.updater=bf,t.stateNode=o,o._reactInternals=t,mS(t,r,e,n),t=vS(null,t,r,!0,s,n)):(t.tag=0,rt&&s&&s0(t),un(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(uh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=i3(r),e=Ir(r,e),o){case 0:t=SS(null,t,r,e,n);break e;case 1:t=Rb(null,t,r,e,n);break e;case 11:t=Ob(null,t,r,e,n);break e;case 14:t=Db(null,t,r,Ir(r.type,e),n);break e}throw Error(Y(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Ir(r,o),SS(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Ir(r,o),Rb(e,t,r,o,n);case 3:e:{if(l_(t),e===null)throw Error(Y(387));r=t.pendingProps,s=t.memoizedState,o=s.element,RE(e,t),vp(t,r,null,n);var i=t.memoizedState;if(r=i.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},t.updateQueue.baseState=s,t.memoizedState=s,t.flags&256){o=nc(Error(Y(423)),t),t=Lb(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(Y(424)),t),t=Lb(e,t,r,n,o);break e}else for(Yn=ks(t.stateNode.containerInfo.firstChild),Xn=t,rt=!0,$r=null,n=OE(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ja(),r===o){t=Uo(e,t,n);break e}un(e,t,r,n)}t=t.child}return t;case 5:return LE(t),e===null&&pS(t),r=t.type,o=t.pendingProps,s=e!==null?e.memoizedProps:null,i=o.children,cS(r,o)?i=null:s!==null&&cS(r,s)&&(t.flags|=32),c_(e,t),un(e,t,i,n),t.child;case 6:return e===null&&pS(t),null;case 13:return u_(e,t,n);case 4:return p0(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):un(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Ir(r,o),Ob(e,t,r,o,n);case 7:return un(e,t,t.pendingProps,n),t.child;case 8:return un(e,t,t.pendingProps.children,n),t.child;case 12:return un(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,s=t.memoizedProps,i=o.value,Ge(yp,r._currentValue),r._currentValue=i,s!==null)if(zr(s.value,i)){if(s.children===o.children&&!Tn.current){t=Uo(e,t,n);break e}}else for(s=t.child,s!==null&&(s.return=t);s!==null;){var a=s.dependencies;if(a!==null){i=s.child;for(var c=a.firstContext;c!==null;){if(c.context===r){if(s.tag===1){c=Oo(-1,n&-n),c.tag=2;var l=s.updateQueue;if(l!==null){l=l.shared;var u=l.pending;u===null?c.next=c:(c.next=u.next,u.next=c),l.pending=c}}s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),fS(s.return,n,t),a.lanes|=n;break}c=c.next}}else if(s.tag===10)i=s.type===t.type?null:s.child;else if(s.tag===18){if(i=s.return,i===null)throw Error(Y(341));i.lanes|=n,a=i.alternate,a!==null&&(a.lanes|=n),fS(i,n,t),i=s.sibling}else i=s.child;if(i!==null)i.return=s;else for(i=s;i!==null;){if(i===t){i=null;break}if(s=i.sibling,s!==null){s.return=i.return,i=s;break}i=i.return}s=i}un(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Ba(t,n),o=yr(o),r=r(o),t.flags|=1,un(e,t,r,n),t.child;case 14:return r=t.type,o=Ir(r,t.pendingProps),o=Ir(r.type,o),Db(e,t,r,o,n);case 15:return i_(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:Ir(r,o),uh(e,t),t.tag=1,$n(r)?(e=!0,fp(t)):e=!1,Ba(t,n),r_(t,r,o),mS(t,r,o,n),vS(null,t,r,!0,e,n);case 19:return d_(e,t,n);case 22:return a_(e,t,n)}throw Error(Y(156,t.tag))};function __(e,t){return eE(e,t)}function s3(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 fr(e,t,n,r){return new s3(e,t,n,r)}function k0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function i3(e){if(typeof e=="function")return k0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Gv)return 11;if(e===Yv)return 14}return 2}function As(e,t){var n=e.alternate;return n===null?(n=fr(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function ph(e,t,n,r,o,s){var i=2;if(r=e,typeof e=="function")k0(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case ya:return bi(n.children,o,s,t);case Vv:i=8,o|=8;break;case zy:return e=fr(12,n,t,o|2),e.elementType=zy,e.lanes=s,e;case By:return e=fr(13,n,t,o),e.elementType=By,e.lanes=s,e;case Uy:return e=fr(19,n,t,o),e.elementType=Uy,e.lanes=s,e;case LI:return If(n,o,s,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case DI:i=10;break e;case RI:i=9;break e;case Gv:i=11;break e;case Yv:i=14;break e;case gs:i=16,r=null;break e}throw Error(Y(130,e==null?e:typeof e,""))}return t=fr(i,n,t,o),t.elementType=e,t.type=r,t.lanes=s,t}function bi(e,t,n,r){return e=fr(7,e,r,t),e.lanes=n,e}function If(e,t,n,r){return e=fr(22,e,r,t),e.elementType=LI,e.lanes=n,e.stateNode={isHidden:!1},e}function em(e,t,n){return e=fr(6,e,null,t),e.lanes=n,e}function tm(e,t,n){return t=fr(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function a3(e,t,n,r,o){this.tag=t,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=Dg(0),this.expirationTimes=Dg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Dg(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function T0(e,t,n,r,o,s,i,a,c){return e=new a3(e,t,n,a,c),t===1?(t=1,s===!0&&(t|=8)):t=0,s=fr(3,null,null,t),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},h0(s),e}function c3(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(M_)}catch(e){console.error(e)}}M_(),MI.exports=nr;var Ui=MI.exports;const p3=pc(Ui);var A_,Xb=Ui;A_=Fy.createRoot=Xb.createRoot,Fy.hydrateRoot=Xb.hydrateRoot;async function f3(e,t){const{url:n,style:r="normal",weight:o="500",display:s,featureSettings:i,stretch:a,unicodeRange:c,variant:l,format:u}=t,d={style:r,weight:o,display:s,featureSettings:i,stretch:a,unicodeRange:c,variant:l},p=new FontFace(e,`url(${n})`,d);return await p.load(),document.fonts.add(p),p.$$_url=n,p.$$_fontface=` @font-face { font-family: ${p.family}; font-stretch: ${p.stretch}; font-weight: ${p.weight}; font-style: ${p.style}; src: url("${n}") format("${u}") }`,p}function j_(e){return e&&typeof e=="object"&&"parents"in e}function O_(e){for(let t=0,n=e.parents.length;t{if(e.children.remove(t)&&e.children.isEmpty&&j_(e))for(let n=0,r=e.parents.length;n{if(e.children.add(t)&&j_(e))for(let n=0,r=e.parents.length;nObject.freeze([])),qb=8;class Tp{constructor(){m(this,"arraySize",0);m(this,"array",Array(qb));m(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(t){if(this.array)return this.array.indexOf(t)!==-1?!1:this.arraySize=l)return[];if(c<=t&&t({stack:null}));function L_(e){yt.stack=new g3(yt.stack,e),e.parentSet.clear()}function F_(){const e=yt.stack;if(yt.stack=e.below,e.offset{this._isActivelyListening&&this.execute()});this.name=t,this.runEffect=n,this._scheduleEffect=r==null?void 0:r.scheduleEffect}get isActivelyListening(){return this._isActivelyListening}get scheduleCount(){return this._scheduleCount}maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==dn()){if(this.parents.length&&!O_(this)){this.lastReactedEpoch=dn();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let t=0,n=this.parents.length;tm3);function Sc(e,t,n){const r=new yc(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function y3(e,t,n){const r=new yc(e,t,n);return{scheduler:r,start:o=>{const s=(o==null?void 0:o.force)??!1;r.attach(),s?r.scheduleEffect():r.maybeScheduleEffect()},stop:()=>{r.detach()}}}class S3{constructor(t){m(this,"initialAtomValues",new Map);this.parent=t}get isRoot(){return this.parent===null}commit(){if(this.isRoot){const t=this.initialAtomValues;this.initialAtomValues=new Map,N_(t.keys())}else this.initialAtomValues.forEach((t,n)=>{this.parent.initialAtomValues.has(n)||this.parent.initialAtomValues.set(n,t)})}abort(){Jt.globalEpoch++,this.initialAtomValues.forEach((t,n)=>{var r;n.set(t),(r=n.historyBuffer)==null||r.clear()}),this.commit()}}const Jt=Gs("transactions",()=>({globalEpoch:mi+1,globalIsReacting:!1,currentTransaction:null}));function dn(){return Jt.globalEpoch}function N_(e){if(Jt.globalIsReacting)throw new Error("cannot change atoms during reaction cycle");try{Jt.globalIsReacting=!0;const t=new Set,n=r=>{r.lastTraversedEpoch!==Jt.globalEpoch&&(r.lastTraversedEpoch=Jt.globalEpoch,r instanceof yc?t.add(r):r.children.visit(n))};for(const r of e)r.children.visit(n);for(const r of t)r.maybeScheduleEffect()}finally{Jt.globalIsReacting=!1}}function v3(e,t){Jt.currentTransaction?Jt.currentTransaction.initialAtomValues.has(e)||Jt.currentTransaction.initialAtomValues.set(e,t):N_([e])}function x3(){Jt.globalEpoch++}function w3(e){const t=new S3(Jt.currentTransaction);Jt.currentTransaction=t;try{let n=!1;const r=e(()=>n=!0);return n?t.abort():t.commit(),r}catch(n){throw t.abort(),n}finally{Jt.currentTransaction=Jt.currentTransaction.parent}}function Mr(e){return Jt.currentTransaction?e():w3(e)}class b3{constructor(t,n,r){m(this,"isEqual");m(this,"computeDiff");m(this,"lastChangedEpoch",dn());m(this,"children",new Tp);m(this,"historyBuffer");this.name=t,this.current=n,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new R_(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(t){return this.current}get(){return $p(this),this.current}set(t,n){var o,s;if(((o=this.isEqual)==null?void 0:o.call(this,this.current,t))??D_(this.current,t))return this.current;x3(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,dn(),n??((s=this.computeDiff)==null?void 0:s.call(this,this.current,t,this.lastChangedEpoch,dn()))??qn),this.lastChangedEpoch=dn();const r=this.current;return this.current=t,v3(this,r),t}update(t){return this.set(t(this.current))}getDiffSince(t){var n;return $p(this),t>=this.lastChangedEpoch?Do:((n=this.historyBuffer)==null?void 0:n.getChangesSince(t))??qn}}const P3=Gs("Atom",()=>b3);function fn(e,t,n){return new P3(e,t,n)}let Zb=!1;function C3(){Zb||(Zb=!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 get foo() { return 'foo' } // After @computed getFoo() { return 'foo' } `))}const pl=Symbol.for("com.tldraw.state/UNINITIALIZED"),Pi=e=>e===pl,MS=Gs("WithDiff",()=>class{constructor(t,n){this.value=t,this.diff=n}});function fl(e,t){return new MS(e,t)}class I3{constructor(t,n,r){m(this,"lastChangedEpoch",mi);m(this,"lastTraversedEpoch",mi);m(this,"lastCheckedEpoch",mi);m(this,"parentSet",new Tp);m(this,"parents",[]);m(this,"parentEpochs",[]);m(this,"children",new Tp);m(this,"historyBuffer");m(this,"state",pl);m(this,"error",null);m(this,"computeDiff");m(this,"isEqual");this.name=t,this.derive=n,r!=null&&r.historyLength&&(this.historyBuffer=new R_(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??D_}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(t){var r;if(!(this.lastChangedEpoch===mi)&&(this.lastCheckedEpoch===dn()||!O_(this)))if(this.lastCheckedEpoch=dn(),this.error){if(t)return this.state;throw this.error.thrownValue}else return this.state;try{L_(this);const o=this.derive(this.state,this.lastCheckedEpoch),s=o instanceof MS?o.value:o,i=this.state===pl;if(i||!this.isEqual(s,this.state)){if(this.historyBuffer&&!i){const a=o instanceof MS?o.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,dn(),a??((r=this.computeDiff)==null?void 0:r.call(this,this.state,s,this.lastCheckedEpoch,dn()))??qn)}this.lastChangedEpoch=dn(),this.state=s}return this.error=null,this.lastCheckedEpoch=dn(),this.state}catch(o){if(this.state!==pl&&(this.state=pl,this.lastChangedEpoch=dn()),this.lastCheckedEpoch=dn(),this.historyBuffer&&this.historyBuffer.clear(),this.error={thrownValue:o},!t)throw o;return this.state}finally{F_()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{$p(this)}}getDiffSince(t){var n;return this.__unsafe__getWithoutCapture(!0),$p(this),t>=this.lastChangedEpoch?Do:((n=this.historyBuffer)==null?void 0:n.getChangesSince(t))??qn}}const O0=Gs("Computed",()=>I3);function E3(e={},t,n,r){const o=r.value,s=Symbol.for("__@tldraw/state__computed__"+n);return r.value=function(){let i=this[s];return i||(i=new O0(n,o.bind(this),e),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[k3]=!0,r}function Qb(e={},t,n,r){return r.get?(C3(),_3(e,t,n,r)):E3(e,t,n,r)}function _3(e={},t,n,r){const o=r.get,s=Symbol.for("__@tldraw/state__computed__"+n);return r.get=function(){let i=this[s];return i||(i=new O0(n,o.bind(this),e),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}const k3="@@__isComputedMethod__@@";function V(){if(arguments.length===1){const e=arguments[0];return(t,n,r)=>Qb(e,t,n,r)}else return typeof arguments[0]=="string"?new O0(arguments[0],arguments[1],arguments[2]):Qb(void 0,arguments[0],arguments[1],arguments[2])}const z_=1,T3=Gs("apiVersion",()=>z_);if(T3!==z_)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");function $f(e,t){const n=Se.useRef(t);n.current=t;const[r,o,s]=Se.useMemo(()=>{let i=null;const a=u=>(i=u,()=>{i=null}),c=new yc(`useStateTracking(${e})`,()=>{var u;return(u=n.current)==null?void 0:u.call(n)},{scheduleEffect(){i==null||i()}});return[c,a,()=>c.scheduleCount]},[e]);return Se.useSyncExternalStore(o,s,s),Se.useEffect(()=>(r.attach(),r.maybeScheduleEffect(),()=>{r.detach()}),[r]),r.execute()}const Jb={apply(e,t,n){return $f(e.displayName??e.name??"tracked(???)",()=>e.apply(t,n))}},$3=Symbol.for("react.memo"),M3=Symbol.for("react.forward_ref");function or(e){let t=null;const n=e.$$typeof;return n===$3&&(e=e.type,t=e.compare),n===M3?x.memo(x.forwardRef(new Proxy(e.render,Jb))):x.memo(new Proxy(e,Jb),t)}function A3(){const e=arguments[0],t=arguments[1],n=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return x.useMemo(()=>V(`useComputed(${e})`,t,n),r)}function js(e,t,n=Do){x.useEffect(()=>{const r=new yc(e,t);return r.attach(),r.execute(),()=>{r.detach()}},n)}function K(){const e=arguments,t=e.length===3?e[2]:[e[0]],n=e.length===3?e[0]:`useValue(${e[0].name})`,r=x.useRef(!0);r.current=!0;const o=x.useMemo(()=>e.length===1?e[0]:V(n,()=>{if(r.current)return e[1]();try{return e[1]()}catch{return{}}}),t);try{const{subscribe:s,getSnapshot:i}=x.useMemo(()=>({subscribe:a=>Sc(`useValue(${n})`,()=>{o.get(),a()}),getSnapshot:()=>o.get()}),[o]);return x.useSyncExternalStore(s,i,i)}finally{r.current=!1}}class fh{constructor(t){m(this,"nextValue");m(this,"diff");this.previousValue=t}get(){var r,o,s,i;const t=((o=(r=this.diff)==null?void 0:r.removed)==null?void 0:o.size)??0,n=((i=(s=this.diff)==null?void 0:s.added)==null?void 0:i.size)??0;if(!(t===0&&n===0))return{value:this.nextValue,diff:this.diff}}_add(t,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(t),this.diff??(this.diff={}),n?(r=this.diff.removed)==null||r.delete(t):((o=this.diff).added??(o.added=new Set),this.diff.added.add(t))}add(t){var o,s,i;const n=this.previousValue.has(t);if(n)return((s=(o=this.diff)==null?void 0:o.removed)==null?void 0:s.has(t))?this._add(t,n):void 0;(i=this.nextValue)!=null&&i.has(t)||this._add(t,n)}_remove(t,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(t),this.diff??(this.diff={}),n?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(t)):(o=this.diff.added)==null||o.delete(t)}remove(t){var o,s,i,a;const n=this.previousValue.has(t);if(!n)return((s=(o=this.diff)==null?void 0:o.added)==null?void 0:s.has(t))?this._remove(t,n):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(t)||this._remove(t,n)}}function Mp(e,t){const n=[];e:for(const r of e){for(const o of n)if(t?t(r,o):r===o)continue e;n.push(r)}return n}function fe(e){return e.filter(t=>t!=null)}function Wn(e){return e[e.length-1]}function j3(e,t){let n,r=1/0;for(const o of e){const s=t(o);sn=!1,t),r=e(...o)),r}}function U_(e){const t=(...n)=>{try{return e(...n)}catch(r){throw r instanceof Error&&Error.captureStackTrace&&Error.captureStackTrace(r,t),r}};return t}const Ha={ok(e){return{ok:!0,value:e}},err(e){return{ok:!1,error:e}}};function qo(e,t){const n=t&&e&&typeof e=="object"&&t in e?e[t]:e;throw new Error(`Unknown switch case ${n}`)}const _t=U_((e,t)=>{if(!e)throw new Error(t||"Assertion Error")}),yi=U_((e,t)=>{if(e==null)throw new Error(t??"value must be defined");return e});function H_(e,t){let n;const r=(...o)=>(n||(n={},n.promise=new Promise((s,i)=>{n.resolve=s,n.reject=i})),clearTimeout(n.timeout),n.latestArgs=o,n.timeout=setTimeout(()=>{const s=n;n=void 0;try{s.resolve(e(...s.latestArgs))}catch(i){s.reject(i)}},t),n.promise);return r.cancel=()=>{n&&clearTimeout(n.timeout)},r}const e1=new WeakMap;function D0(e,t){if(typeof e!="object"||e===null)return;let n=e1.get(e);n||(n={tags:{},extras:{}},e1.set(e,n)),t.tags&&(n.tags={...n.tags,...t.tags}),t.extras&&(n.extras={...n.extras,...t.extras})}class Ka{static async dataUrlToArrayBuffer(t){return fetch(t).then(function(n){return n.arrayBuffer()})}static async blobToDataUrl(t){return await new Promise((n,r)=>{if(t){const o=new FileReader;o.onload=()=>n(o.result),o.onerror=s=>r(s),o.onabort=s=>r(s),o.readAsDataURL(t)}})}static async blobToText(t){return await new Promise((n,r)=>{if(t){const o=new FileReader;o.onload=()=>n(o.result),o.onerror=s=>r(s),o.onabort=s=>r(s),o.readAsText(t)}})}}function AS(e){let t=0;for(let n=0;n{let n=~~t^-1;for(let r=0;r>>8;return n^-1},t1=4,n1=4;class Zr{static isPng(t,n){return t.getUint8(n+0)===137&&t.getUint8(n+1)===80&&t.getUint8(n+2)===78&&t.getUint8(n+3)===71&&t.getUint8(n+4)===13&&t.getUint8(n+5)===10&&t.getUint8(n+6)===26&&t.getUint8(n+7)===10}static getChunkType(t,n){return[String.fromCharCode(t.getUint8(n)),String.fromCharCode(t.getUint8(n+1)),String.fromCharCode(t.getUint8(n+2)),String.fromCharCode(t.getUint8(n+3))].join("")}static readChunks(t,n=0){const r={};if(!Zr.isPng(t,n))throw new Error("Not a PNG");for(n+=8;n<=t.buffer.byteLength;){const o=n,s=t.getInt32(n);n+=4;const i=Zr.getChunkType(t,n);if(i==="IDAT"&&r[i]){n+=s+t1+n1;continue}if(i==="IEND")break;r[i]={start:o,dataOffset:n+4,size:s},n+=s+t1+n1}return r}static parsePhys(t,n){return{ppux:t.getUint32(n),ppuy:t.getUint32(n+4),unit:t.getUint8(n+4)}}static findChunk(t,n){return Zr.readChunks(t)[n]}static setPhysChunk(t,n=1,r){let o=46,s=0;const i=Zr.findChunk(t,"pHYs");i&&(o=i.start,s=i.size);const a=Zr.findChunk(t,"IDAT");a&&(o=a.start,s=0);const c=new ArrayBuffer(21),l=new DataView(c);l.setUint32(0,9),l.setUint8(4,112),l.setUint8(5,72),l.setUint8(6,89),l.setUint8(7,115);const u=2835.5;l.setInt32(8,u*n),l.setInt32(12,u*n),l.setInt8(16,1);const d=new Uint8Array(c.slice(4,17));l.setInt32(17,R3(d));const p=t.buffer.slice(0,o),f=t.buffer.slice(o+s);return new Blob([p,c,f],r)}}class jo{static loadVideo(t){return new Promise((n,r)=>{const o=document.createElement("video");o.onloadeddata=()=>n(o),o.onerror=s=>{console.error(s),r(new Error("Could not load video"))},o.crossOrigin="anonymous",o.src=t})}static loadImage(t){return new Promise((n,r)=>{const o=new Image;o.onload=()=>n(o),o.onerror=s=>{console.error(s),r(new Error("Could not load image"))},o.crossOrigin="anonymous",o.src=t})}static async getVideoSize(t){return jo.usingObjectURL(t,async n=>{const r=await jo.loadVideo(n);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(t){const n=await jo.usingObjectURL(t,jo.loadImage);try{if(t.type==="image/png"){const r=new DataView(await t.arrayBuffer());if(Zr.isPng(r,0)){const o=Zr.findChunk(r,"pHYs");if(o){const s=Zr.parsePhys(r,o.dataOffset);if(s.unit===0&&s.ppux===s.ppuy){const i=Math.max(s.ppux/2834.5,1);return{w:Math.round(n.naturalWidth/i),h:Math.round(n.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:n.naturalWidth,h:n.naturalHeight}}return{w:n.naturalWidth,h:n.naturalHeight}}static async usingObjectURL(t,n){const r=URL.createObjectURL(t);try{return await n(r)}finally{URL.revokeObjectURL(r)}}}function Ys(e=""){let t=0,n=0,r=0,o=0;function s(){const i=t^t<<11;return t=n,n=r,r=o,o^=(o>>>19^i^i>>>8)>>>0,o/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 Y_(e){if(e.length!==G_(e.charAt(0)))throw new Error("invalid integer part of index key: "+e)}function o1(e){if(e===void 0)throw Error("n is undefined")}function s1(e){Y_(e);const[t,...n]=e.split("");let r=!0;for(let o=n.length-1;r&&o>=0;o--){const s=Gn.indexOf(n[o])+1;s===Gn.length?n[o]="0":(n[o]=Gn.charAt(s),r=!1)}if(r){if(t==="Z")return"a0";if(t==="z")return;const o=String.fromCharCode(t.charCodeAt(0)+1);return o>"a"?n.push("0"):n.pop(),o+n.join("")}else return t+n.join("")}function L3(e){Y_(e);const[t,...n]=e.split("");let r=!0;for(let o=n.length-1;r&&o>=0;o--){const s=Gn.indexOf(n[o])-1;s===-1?n[o]=Gn.slice(-1):(n[o]=Gn.charAt(s),r=!1)}if(r){if(t==="a")return"Z"+Gn.slice(-1);if(t==="A")return;const o=String.fromCharCode(t.charCodeAt(0)-1);return o<"Z"?n.push(Gn.slice(-1)):n.pop(),o+n.join("")}else return t+n.join("")}function ka(e,t){if(t!==void 0&&e>=t)throw new Error(e+" >= "+t);if(e.slice(-1)==="0"||t&&t.slice(-1)==="0")throw new Error("trailing zero");if(t){let o=0;for(;(e.charAt(o)||"0")===t.charAt(o);)o++;if(o>0)return t.slice(0,o)+ka(e.slice(o),t.slice(o))}const n=e?Gn.indexOf(e.charAt(0)):0,r=t!==void 0?Gn.indexOf(t.charAt(0)):Gn.length;if(r-n>1){const o=Math.round(.5*(n+r));return Gn.charAt(o)}else return t&&t.length>1?t.slice(0,1):Gn.charAt(n)+ka(e.slice(1),void 0)}function gl(e){const t=G_(e.charAt(0));if(t>e.length)throw new Error("invalid index: "+e);return e.slice(0,t)}function OS(e){if(e===V_)throw new Error("invalid index: "+e);const t=gl(e);if(e.slice(t.length).slice(-1)==="0")throw new Error("invalid index: "+e)}function Ji(e,t){if(e!==void 0&&OS(e),t!==void 0&&OS(t),e!==void 0&&t!==void 0&&e>=t)throw new Error(e+" >= "+t);if(e===void 0&&t===void 0)return W_;if(e===void 0){if(t===void 0)throw Error("b is undefined");const a=gl(t),c=t.slice(a.length);if(a===V_)return a+ka("",c);if(at.index?1:0}function B3(e,t){return e.id>t.id?1:-1}function L0(e){try{return localStorage.getItem(e)}catch{return null}}function F0(e,t){try{localStorage.setItem(e,t)}catch{}}function U3(){try{localStorage.clear()}catch{}}function X_(e){try{return sessionStorage.getItem(e)}catch{return null}}function N0(e,t){try{sessionStorage.setItem(e,t)}catch{}}function q_(e){try{sessionStorage.removeItem(e)}catch{}}function H3(){try{sessionStorage.clear()}catch{}}const K3=()=>typeof process<"u"&&!1,Ta=[],W3=60,gh=Math.ceil(1e3/W3);let Vc,om=0,DS=0;const V3=()=>{const e=Ta.splice(0,Ta.length);for(const t of e)t()};function Z_(){if(Vc)return;const e=Date.now(),t=e-DS;if(om+t{Vc=void 0,Z_()});return}Vc=requestAnimationFrame(()=>{Vc=void 0,DS=e,om=Math.min(om+t-gh,gh*10),V3()})}let i1=!1;function Q_(e){return K3()?(e(),()=>{}):(Ta.includes(e)||(Ta.push(e),i1||(i1=!0,DS=Date.now()-gh-1),Z_()),()=>{const t=Ta.indexOf(e);t>-1&&Ta.splice(t,1)})}function G3(e){return e!==null}function Y3(){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 J_=Y3(),Ye=J_[0];J_[1];const X3=Object.getPrototypeOf(Ye({}));let ek=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");class z0{constructor(t,n){m(this,"createDefaultProperties");m(this,"validator");m(this,"scope");m(this,"isInstance",t=>(t==null?void 0:t.typeName)===this.typeName);this.typeName=t,this.createDefaultProperties=n.createDefaultProperties,this.validator=n.validator??{validate:r=>r},this.scope=n.scope??"document"}create(t){const n={...this.createDefaultProperties(),id:this.createId()};for(const[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n.typeName=this.typeName,n}clone(t){return{...Ye(t),id:this.createId()}}createId(t){return this.typeName+":"+(t??ek())}createCustomId(t){return this.typeName+":"+t}parseId(t){if(!this.isId(t))throw new Error(`ID "${t}" is not a valid ID for type "${this.typeName}"`);return t.slice(this.typeName.length+1)}isId(t){if(!t)return!1;for(let n=0;n({}),validator:t.validator,scope:t.scope})}class a1{constructor(){m(this,"items",new WeakMap)}get(t,n){return this.items.has(t)||this.items.set(t,n(t)),this.items.get(t)}}var jp={exports:{}};jp.exports;(function(e,t){var n=200,r="__lodash_hash_undefined__",o=1,s=2,i=9007199254740991,a="[object Arguments]",c="[object Array]",l="[object AsyncFunction]",u="[object Boolean]",d="[object Date]",p="[object Error]",f="[object Function]",y="[object GeneratorFunction]",g="[object Map]",w="[object Number]",S="[object Null]",v="[object Object]",b="[object Promise]",E="[object Proxy]",C="[object RegExp]",I="[object Set]",_="[object String]",k="[object Symbol]",$="[object Undefined]",T="[object WeakMap]",O="[object ArrayBuffer]",N="[object DataView]",F="[object Float32Array]",L="[object Float64Array]",B="[object Int8Array]",q="[object Int16Array]",Q="[object Int32Array]",H="[object Uint8Array]",U="[object Uint8ClampedArray]",W="[object Uint16Array]",Z="[object Uint32Array]",le=/[\\^$.*+?()[\]{}|]/g,be=/^\[object .+?Constructor\]$/,Me=/^(?:0|[1-9]\d*)$/,ae={};ae[F]=ae[L]=ae[B]=ae[q]=ae[Q]=ae[H]=ae[U]=ae[W]=ae[Z]=!0,ae[a]=ae[c]=ae[O]=ae[u]=ae[N]=ae[d]=ae[p]=ae[f]=ae[g]=ae[w]=ae[v]=ae[C]=ae[I]=ae[_]=ae[T]=!1;var Ae=typeof tn=="object"&&tn&&tn.Object===Object&&tn,Re=typeof self=="object"&&self&&self.Object===Object&&self,ot=Ae||Re||Function("return this")(),Ie=t&&!t.nodeType&&t,ht=Ie&&!0&&e&&!e.nodeType&&e,He=ht&&ht.exports===Ie,ir=He&&Ae.process,Ln=function(){try{return ir&&ir.binding&&ir.binding("util")}catch{}}(),Fn=Ln&&Ln.isTypedArray;function qe(M,D){for(var G=-1,ee=M==null?0:M.length,Ze=0,me=[];++G-1}function oO(M,D){var G=this.__data__,ee=qu(G,M);return ee<0?(++this.size,G.push([M,D])):G[ee][1]=D,this}bo.prototype.clear=eO,bo.prototype.delete=tO,bo.prototype.get=nO,bo.prototype.has=rO,bo.prototype.set=oO;function oi(M){var D=-1,G=M==null?0:M.length;for(this.clear();++Dkt))return!1;var st=me.get(M);if(st&&me.get(D))return st==D;var Nn=-1,Pr=!0,Wt=G&s?new Xu:void 0;for(me.set(M,D),me.set(D,M);++Nn-1&&M%1==0&&M-1&&M%1==0&&M<=i}function Fw(M){var D=typeof M;return M!=null&&(D=="object"||D=="function")}function Lc(M){return M!=null&&typeof M=="object"}var Nw=Fn?jc(Fn):wO;function DO(M){return jO(M)?yO(M):bO(M)}function RO(){return[]}function LO(){return!1}e.exports=OO})(jp,jp.exports);var q3=jp.exports;const Z3=pc(q3);function Q3(e){if(e.length===0)return new Set;const t=e[0],n=e.slice(1),r=new Set;for(const o of t)n.every(s=>s.has(o))&&r.add(o);return r}function J3(e,t){const n={};for(const r of t)e.has(r)||(n.added??(n.added=new Set),n.added.add(r));for(const r of e)t.has(r)||(n.removed??(n.removed=new Set),n.removed.add(r));return n.added||n.removed?n:void 0}function c1(e,t){for(const[n,r]of Object.entries(e)){const o=r,s=t[n];if("eq"in o&&s!==o.eq||"neq"in o&&s===o.neq||"gt"in o&&(typeof s!="number"||s<=o.gt))return!1}return!0}function l1(e,t,n){const r=Object.fromEntries(Object.keys(n).map(o=>[o,new Set]));for(const[o,s]of Object.entries(n))if("eq"in s){const a=e.index(t,o).get().get(s.eq);if(a)for(const c of a)r[o].add(c)}else if("neq"in s){const i=e.index(t,o);for(const[a,c]of i.get())if(a!==s.neq)for(const l of c)r[o].add(l)}else if("gt"in s){const i=e.index(t,o);for(const[a,c]of i.get())if(a>s.gt)for(const l of c)r[o].add(l)}return Q3(Object.values(r))}class eL{constructor(t,n){m(this,"indexCache",new Map);m(this,"historyCache",new Map);this.atoms=t,this.history=n}filterHistory(t){if(this.historyCache.has(t))return this.historyCache.get(t);const n=V("filterHistory:"+t,(r,o)=>{if(Pi(r))return this.history.get();const s=this.history.getDiffSince(o);if(s===qn)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,c=0,l=0;for(const u of s){for(const d of bt(u.added))if(d.typeName===t)if(i.removed[d.id]){const p=i.removed[d.id];delete i.removed[d.id],c--,p!==d&&(i.updated[d.id]=[p,d],l++)}else i.added[d.id]=d,a++;for(const[d,p]of bt(u.updated))p.typeName===t&&(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]=[d,p],l++));for(const d of bt(u.removed))d.typeName===t&&(i.added[d.id]?(delete i.added[d.id],a--):i.updated[d.id]?(i.removed[d.id]=i.updated[d.id][0],delete i.updated[d.id],l--,c++):(i.removed[d.id]=d,c++))}return a||c||l?fl(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(t,n),n}index(t,n){const r=t+":"+n;if(this.indexCache.has(r))return this.indexCache.get(r);const o=this.__uncached_createIndex(t,n);return this.indexCache.set(r,o),o}__uncached_createIndex(t,n){const r=this.filterHistory(t),o=()=>{r.get();const s=new Map;for(const i of bt(this.atoms.get())){const a=i.get();if(a.typeName===t){const c=a[n];s.has(c)||s.set(c,new Set),s.get(c).add(a.id)}}return s};return V("index:"+t+":"+n,(s,i)=>{if(Pi(s))return o();const a=r.getDiffSince(i);if(a===qn)return o();const c=new Map,l=(f,y)=>{let g=c.get(f);g||(g=new fh(s.get(f)??new Set)),g.add(y),c.set(f,g)},u=(f,y)=>{let g=c.get(f);g||(g=new fh(s.get(f)??new Set)),g.remove(y),c.set(f,g)};for(const f of a){for(const y of bt(f.added))if(y.typeName===t){const g=y[n];l(g,y.id)}for(const[y,g]of bt(f.updated))if(g.typeName===t){const w=y[n],S=g[n];w!==S&&(u(w,g.id),l(S,g.id))}for(const y of bt(f.removed))if(y.typeName===t){const g=y[n];u(g,y.id)}}let d,p;for(const[f,y]of c){const g=y.get();g&&(d||(d=new Map(s)),p||(p=new Map),g.value.size===0?d.delete(f):d.set(f,g.value),p.set(f,g.diff))}return d&&p?fl(d,p):s},{historyLength:100})}record(t,n=()=>({}),r="record:"+t+(n?":"+n.toString():"")){const o=this.ids(t,n,r);return V(r,()=>{var s;for(const i of o.get())return(s=this.atoms.get()[i])==null?void 0:s.get()})}records(t,n=()=>({}),r="records:"+t+(n?":"+n.toString():"")){const o=this.ids(t,n,"ids:"+r);return V(r,()=>[...o.get()].map(s=>{const i=this.atoms.get()[s];if(!i)throw new Error("no atom found for record id: "+s);return i.get()}))}ids(t,n=()=>({}),r="ids:"+t+(n?":"+n.toString():"")){const o=this.filterHistory(t),s=()=>{o.get();const c=n();return Object.keys(c).length===0?new Set(bt(this.atoms.get()).flatMap(l=>{const u=l.get();return u.typeName===t?u.id:[]})):l1(this,t,c)},i=c=>{const l=s(),u=J3(c,l);return u?fl(l,u):c},a=V("ids_query:"+r,n,{isEqual:Z3});return V("query:"+r,(c,l)=>{const u=a.get();if(Pi(c))return s();if(lo[s].get())}}class tk{constructor(t){m(this,"id",ek());m(this,"atoms",fn("store_atoms",{}));m(this,"history",fn("history",0,{historyLength:1e3}));m(this,"query",new eL(this.atoms,this.history));m(this,"listeners",new Set);m(this,"historyAccumulator",new nL);m(this,"historyReactor");m(this,"schema");m(this,"props");m(this,"scopedTypes");m(this,"onBeforeCreate");m(this,"onAfterCreate");m(this,"onBeforeChange");m(this,"onAfterChange");m(this,"onBeforeDelete");m(this,"onAfterDelete");m(this,"_runCallbacks",!0);m(this,"put",(t,n)=>{Mr(()=>{const r={},o={},s=this.atoms.__unsafe__getWithoutCapture();let i=null,a,c=!1;const l=this.onBeforeCreate&&this._runCallbacks?this.onBeforeCreate:null,u=this.onBeforeChange&&this._runCallbacks?this.onBeforeChange:null,d=this.isMergingRemoteChanges?"remote":"user";for(let p=0,f=t.length;p{p(y,d)}),f&&Object.values(r).forEach(([y,g])=>{f(y,g,d)})}})});m(this,"remove",t=>{Mr(()=>{const n=[],r=this.isMergingRemoteChanges?"remote":"user";if(this.onBeforeDelete&&this._runCallbacks)for(const s of t){const i=this.atoms.__unsafe__getWithoutCapture()[s];i&&this.onBeforeDelete(i.get(),r)===!1&&n.push(s)}let o;if(this.atoms.update(s=>{let i;for(const a of t)n.includes(a)||a in s&&(i||(i={...s}),o||(o={}),delete i[a],o[a]=s[a].get());return i??s}),!!o&&(this.updateHistory({added:{},updated:{},removed:o}),this.onAfterDelete&&this._runCallbacks)){let s;for(let i=0,a=t.length;i{var n;return(n=this.atoms.get()[t])==null?void 0:n.get()});m(this,"unsafeGetWithoutCapture",t=>{var n;return(n=this.atoms.get()[t])==null?void 0:n.__unsafe__getWithoutCapture()});m(this,"serialize",(t="document")=>{const n={};for(const[r,o]of An(this.atoms.get())){const s=o.get();(t==="all"||this.scopedTypes[t].has(s.typeName))&&(n[r]=s)}return n});m(this,"allRecords",()=>bt(this.atoms.get()).map(t=>t.get()));m(this,"clear",()=>{this.remove(r1(this.atoms.get()))});m(this,"update",(t,n)=>{const r=this.atoms.get()[t];if(!r){console.error(`Record ${t} not found. This is probably an error`);return}this.put([n(r.__unsafe__getWithoutCapture())])});m(this,"has",t=>!!this.atoms.get()[t]);m(this,"listen",(t,n)=>{this._flushHistory();const r={onHistory:t,filters:{source:(n==null?void 0:n.source)??"all",scope:(n==null?void 0:n.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()}});m(this,"isMergingRemoteChanges",!1);m(this,"mergeRemoteChanges",t=>{if(this.isMergingRemoteChanges)return t();try{this.isMergingRemoteChanges=!0,Mr(t)}finally{this.isMergingRemoteChanges=!1}});m(this,"createComputedCache",(t,n,r)=>{const o=new a1;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=r?V(i.name+":equals",()=>i.get(),{isEqual:r}):i;return V(t+":"+s,()=>n(a.get()))}).get()}}});m(this,"createSelectedComputedCache",(t,n,r)=>{const o=new a1;return{get:s=>{const i=this.atoms.get()[s];if(!i)return;const a=V(t+":"+s+":selector",()=>n(i.get()));return o.get(i,()=>V(t+":"+s,()=>r(a.get()))).get()}}});m(this,"getRecordType",t=>{const n=this.schema.types[t.typeName];if(!n)throw new Error(`Record type ${t.typeName} not found`);return n});m(this,"_integrityChecker");m(this,"_isPossiblyCorrupted",!1);const{initialData:n,schema:r}=t;this.schema=r,this.props=t.props,n&&this.atoms.set(R0(An(n).map(([o,s])=>[o,fn("atom:"+o,this.schema.validateRecord(this,s,"initialize",null))]))),this.historyReactor=y3("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:o=>Q_(o)}),this.scopedTypes={document:new Set(bt(this.schema.types).filter(o=>o.scope==="document").map(o=>o.typeName)),session:new Set(bt(this.schema.types).filter(o=>o.scope==="session").map(o=>o.typeName)),presence:new Set(bt(this.schema.types).filter(o=>o.scope==="presence").map(o=>o.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){const t=this.historyAccumulator.flush();for(const{changes:n,source:r}of t){let o=null,s=null,i=null;for(const{onHistory:a,filters:c}of this.listeners)if(!(c.source!=="all"&&c.source!==r))if(c.scope!=="all")if(c.scope==="document"){if(s??(s=this.filterChangesByScope(n,"document")),!s)continue;a({changes:s,source:r})}else if(c.scope==="session"){if(o??(o=this.filterChangesByScope(n,"session")),!o)continue;a({changes:o,source:r})}else{if(i??(i=this.filterChangesByScope(n,"presence")),!i)continue;a({changes:i,source:r})}else a({changes:n,source:r})}}}filterChangesByScope(t,n){const r={added:nm(t.added,(o,s)=>this.scopedTypes[n].has(s.typeName)),updated:nm(t.updated,(o,s)=>this.scopedTypes[n].has(s[1].typeName)),removed:nm(t.removed,(o,s)=>this.scopedTypes[n].has(s.typeName))};return Object.keys(r.added).length===0&&Object.keys(r.updated).length===0&&Object.keys(r.removed).length===0?null:r}updateHistory(t){this.historyAccumulator.add({changes:t,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,t)}validate(t){this.allRecords().forEach(n=>this.schema.validateRecord(this,n,t,null))}getSnapshot(t="document"){return{store:this.serialize(t),schema:this.schema.serialize()}}migrateSnapshot(t){const n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);return{store:n.value,schema:this.schema.serialize()}}loadSnapshot(t){const n=this.schema.migrateStoreSnapshot(t);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);const r=this._runCallbacks;try{this._runCallbacks=!1,Mr(()=>{this.clear(),this.put(Object.values(n.value)),this.ensureStoreIsUsable()})}finally{this._runCallbacks=r}}extractingChanges(t){const n=[],r=this.historyAccumulator.intercepting(o=>n.push(o.changes));try{return Mr(t),Af(n)}finally{r()}}applyDiff(t,n=!0){const r=this._runCallbacks;try{this._runCallbacks=n,Mr(()=>{const o=bt(t.added).concat(bt(t.updated).map(([i,a])=>a)),s=r1(t.removed);o.length&&this.put(o),s.length&&this.remove(s)})}finally{this._runCallbacks=r}}ensureStoreIsUsable(){var t;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(t=this._integrityChecker)==null||t.call(this)}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}}function Af(e){const t={added:{},removed:{},updated:{}};for(const n of e){for(const[r,o]of An(n.added))if(t.removed[r]){const s=t.removed[r];delete t.removed[r],s!==o&&(t.updated[r]=[s,o])}else t.added[r]=o;for(const[r,[o,s]]of An(n.updated)){if(t.added[r]){t.added[r]=s,delete t.updated[r],delete t.removed[r];continue}if(t.updated[r]){t.updated[r]=[t.updated[r][0],s],delete t.removed[r];continue}t.updated[r]=n.updated[r],delete t.removed[r]}for(const[r,o]of An(n.removed))t.added[r]?delete t.added[r]:t.updated[r]?(t.removed[r]=t.updated[r][0],delete t.updated[r]):t.removed[r]=o}return t}function tL(e){if(e.length===0)return[];const t=[];let n=[e[0]],r;for(let o=1,s=e.length;o({source:o[0].source,changes:Af(o.map(s=>s.changes))}))}class nL{constructor(){m(this,"_history",[]);m(this,"_interceptors",new Set)}intercepting(t){return this._interceptors.add(t),()=>{this._interceptors.delete(t)}}add(t){this._history.push(t);for(const n of this._interceptors)n(t)}flush(){const t=tL(this._history);return this._history=[],t}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function rL(e){const t=[];for(let n=e.length-1;n>=0;n--){const r=e[n];if("id"in r)t.unshift(r);else{const o=r.dependsOn,s=t[0];s&&(t[0]={...s,dependsOn:o.concat(s.dependsOn??[])})}}return t}function Tl({sequence:e,sequenceId:t,retroactive:n=!0}){const r={sequenceId:t,retroactive:n,sequence:rL(e)};return nk(r),r}function sr(e,t){return Object.fromEntries(An(t).map(([n,r])=>[n,`${e}/${r}`]))}function xr(e){const t=e.sequenceId;return Tl({sequenceId:t,retroactive:e.retroactive??!0,sequence:e.sequence.map(n=>"id"in n?{...n,scope:"record",filter:r=>{var o,s;return r.typeName===e.recordType&&(((o=n.filter)==null?void 0:o.call(n,r))??!0)&&(((s=e.filter)==null?void 0:s.call(e,r))??!0)}}:n)})}function oL(e){const t=new Map(e.map(s=>[s.id,s])),n=new Set,r=[];function o(s){_t(!n.has(s.id),`Circular dependency in migrations: ${s.id}`),n.add(s.id);const{version:i,sequenceId:a}=Op(s.id),c=t.get(`${a}/${i-1}`);if(c&&o(c),s.dependsOn)for(const l of s.dependsOn){const u=t.get(l);u&&o(u)}t.delete(s.id),r.push(s)}for(const s of t.values())o(s);return r}function Op(e){const[t,n]=e.split("/");return{sequenceId:t,version:parseInt(n)}}function u1(e,t){t&&_t(e.startsWith(t+"/"),`Every migration in sequence '${t}' must have an id starting with '${t}/'. Got invalid id: '${e}'`),_t(e.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${e}'`)}function nk(e){if(_t(!e.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${e.sequenceId}`),_t(e.sequenceId.length,"sequenceId must be a non-empty string"),e.sequence.length===0)return;u1(e.sequence[0].id,e.sequenceId);let t=Op(e.sequence[0].id).version;_t(t===1,`Expected the first migrationId to be '${e.sequenceId}/1' but got '${e.sequence[0].id}'`);for(let n=1;n(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))(ps||{});function sL(e){if(e.schemaVersion>2||e.schemaVersion<1)return Ha.err("Bad schema version");if(e.schemaVersion===2)return Ha.ok(e);const t={schemaVersion:2,sequences:{}};for(const[n,r]of Object.entries(e.recordVersions))if(t.sequences[`com.tldraw.${n}`]=r.version,"subTypeKey"in r)for(const[o,s]of Object.entries(r.subTypeVersions))t.sequences[`com.tldraw.${n}.${o}`]=s;return Ha.ok(t)}class B0{constructor(t,n){m(this,"migrations",{});m(this,"sortedMigrations");var o;this.types=t,this.options=n;for(const s of n.migrations??[])_t(!this.migrations[s.sequenceId],`Duplicate migration sequenceId ${s.sequenceId}`),nk(s),this.migrations[s.sequenceId]=s;const r=Object.values(this.migrations).flatMap(s=>s.sequence);this.sortedMigrations=oL(r);for(const s of this.sortedMigrations)if((o=s.dependsOn)!=null&&o.length)for(const i of s.dependsOn){const a=r.find(c=>c.id===i);_t(a,`Migration '${s.id}' depends on missing migration '${i}'`)}}static create(t,n){return new B0(t,n??{})}validateRecord(t,n,r,o){try{const s=Lr(this.types,n.typeName);if(!s)throw new Error(`Missing definition for record type ${n.typeName}`);return s.validate(n,o??void 0)}catch(s){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:t,record:n,phase:r,recordBefore:o,error:s});throw s}}getMigrationsSince(t){const n=sL(t);if(!n.ok)return n;const r=n.value,o=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&&o.add(i);if(o.size===0)return Ha.ok([]);const s=new Set;for(const i of o){const a=r.sequences[i];if(typeof a!="number"&&this.migrations[i].retroactive||a===0){for(const u of this.migrations[i].sequence)s.add(u.id);continue}const c=`${i}/${a}`,l=this.migrations[i].sequence.findIndex(u=>u.id===c);if(l===-1)return Ha.err("Incompatible schema?");for(const u of this.migrations[i].sequence.slice(l+1))s.add(u.id)}return Ha.ok(this.sortedMigrations.filter(({id:i})=>s.has(i)))}migratePersistedRecord(t,n,r="up"){const o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:ps.MigrationError};let s=o.value;if(s.length===0)return{type:"success",value:t};if(s.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?ps.TargetVersionTooOld:ps.TargetVersionTooNew};if(r==="down"){if(!s.every(i=>i.down))return{type:"error",reason:ps.TargetVersionTooOld};s=s.slice().reverse()}t=Ye(t);try{for(const i of s){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(t):!0))continue;const c=i[r](t);c&&(t=Ye(c))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:ps.MigrationError}}return{type:"success",value:t}}migrateStoreSnapshot(t){let{store:n}=t;const r=this.getMigrationsSince(t.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:ps.MigrationError};const o=r.value;if(o.length===0)return{type:"success",value:n};n=Ye(n);try{for(const s of o)if(s.scope==="record")for(const[i,a]of Object.entries(n)){if(!(s.filter?s.filter(a):!0))continue;const l=s.up(a);l&&(n[i]=Ye(l))}else if(s.scope==="store"){const i=s.up(n);i&&(n=Ye(i))}else qo(s)}catch(s){return console.error("Error migrating store",s),{type:"error",reason:ps.MigrationError}}return{type:"success",value:n}}createIntegrityChecker(t){var n,r;return((r=(n=this.options).createIntegrityChecker)==null?void 0:r.call(n,t))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t,sequence:n})=>[t,n.length?Op(n.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:t})=>[t,0]))}}}function iL(e){if(!e.length)return null;let t="";for(const n of e)typeof n=="number"?t+=`.${n}`:n.startsWith("(")?t.endsWith(")")?t=`${t.slice(0,-1)}, ${n.slice(1)}`:t+=n:t+=`.${n}`;return t=t.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),t.startsWith(".")?t.slice(1):t}class Ce extends Error{constructor(n,r=[]){const o=iL(r),s=n.split(` `).map((i,a)=>a===0?i:` ${i}`).join(` `);super(r?`At ${o}: ${s}`:s);m(this,"name","ValidationError");this.rawMessage=n,this.path=r}}function jn(e,t){try{return t()}catch(n){throw n instanceof Ce?new Ce(n.rawMessage,[e,...n.path]):new Ce(n.toString(),[e])}}function Fs(e){if(e===null)return"null";if(Array.isArray(e))return"an array";const t=typeof e;switch(t){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${t}`;case"object":return`an ${t}`;case"undefined":return"undefined";default:qo(t)}}class Sn{constructor(t,n){this.validationFn=t,this.validateUsingKnownGoodVersionFn=n}validate(t){return this.validationFn(t)}validateUsingKnownGoodVersion(t,n){return Object.is(t,n)?t:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(t,n):this.validate(n)}isValid(t){try{return this.validate(t),!0}catch{return!1}}nullable(){return hL(this)}optional(){return ok(this)}refine(t){return new Sn(n=>t(this.validate(n)),(n,r)=>{const o=this.validateUsingKnownGoodVersion(n,r);return Object.is(n,o)?n:t(o)})}check(t,n){return typeof t=="string"?this.refine(r=>(jn(`(check ${t})`,()=>n(r)),r)):this.refine(r=>(t(r),r))}}class aL extends Sn{constructor(t){super(n=>{const r=d1.validate(n);for(let o=0;ot.validate(r[o]));return r},(n,r)=>{if(!t.validateUsingKnownGoodVersion)return this.validate(r);const o=d1.validate(r);let s=n.length!==o.length;for(let i=0;i=n.length){s=!0,jn(i,()=>t.validate(a));continue}if(Object.is(n[i],a))continue;const c=jn(i,()=>t.validateUsingKnownGoodVersion(n[i],a));Object.is(c,n[i])||(s=!0)}return s?r:n}),this.itemValidator=t}nonEmpty(){return this.check(t=>{if(t.length===0)throw new Ce("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(t=>{if(t.length<=1)throw new Ce("Expected an array with length greater than 1")})}}class Dp extends Sn{constructor(t,n=!1){super(r=>{if(typeof r!="object"||r===null)throw new Ce(`Expected object, got ${Fs(r)}`);for(const[o,s]of Object.entries(t))jn(o,()=>{s.validate(Lr(r,o))});if(!n){for(const o of Object.keys(r))if(!ro(t,o))throw new Ce("Unexpected property",[o])}return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Ce(`Expected object, got ${Fs(o)}`);let s=!1;for(const[i,a]of Object.entries(t)){const c=Lr(r,i),l=Lr(o,i);if(Object.is(c,l))continue;const u=jn(i,()=>{const d=a;return d.validateUsingKnownGoodVersion?d.validateUsingKnownGoodVersion(c,l):d.validate(l)});Object.is(u,c)||(s=!0)}if(!n){for(const i of Object.keys(o))if(!ro(t,i))throw new Ce("Unexpected property",[i])}for(const i of Object.keys(r))if(!ro(o,i)){s=!0;break}return s?o:r}),this.config=t,this.shouldAllowUnknownProperties=n}allowUnknownProperties(){return new Dp(this.config,!0)}extend(t){return new Dp({...this.config,...t})}}class jf extends Sn{constructor(t,n,r,o){super(s=>{this.expectObject(s);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(s);return i===void 0?this.unknownValueValidation(s,a):jn(`(${t} = ${a})`,()=>i.validate(s))},(s,i)=>{this.expectObject(i),this.expectObject(s);const{matchingSchema:a,variant:c}=this.getMatchingSchemaAndVariant(i);return a===void 0?this.unknownValueValidation(i,c):Lr(s,t)!==Lr(i,t)?jn(`(${t} = ${c})`,()=>a.validate(i)):jn(`(${t} = ${c})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(s,i):a.validate(i))}),this.key=t,this.config=n,this.unknownValueValidation=r,this.useNumberKeys=o}expectObject(t){if(typeof t!="object"||t===null)throw new Ce(`Expected an object, got ${Fs(t)}`,[])}getMatchingSchemaAndVariant(t){const n=Lr(t,this.key);if(!this.useNumberKeys&&typeof n!="string")throw new Ce(`Expected a string for key "${this.key}", got ${Fs(n)}`);if(this.useNumberKeys&&!Number.isFinite(Number(n)))throw new Ce(`Expected a number for key "${this.key}", got "${n}"`);return{matchingSchema:ro(this.config,n)?this.config[n]:void 0,variant:n}}validateUnknownVariants(t){return new jf(this.key,this.config,t,this.useNumberKeys)}}class cL extends Sn{constructor(t,n){super(r=>{if(typeof r!="object"||r===null)throw new Ce(`Expected object, got ${Fs(r)}`);for(const[o,s]of Object.entries(r))jn(o,()=>{t.validate(o),n.validate(s)});return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Ce(`Expected object, got ${Fs(o)}`);let s=!1;for(const[i,a]of Object.entries(o)){if(!ro(r,i)){s=!0,jn(i,()=>{t.validate(i),n.validate(a)});continue}const c=Lr(r,i),l=a;if(Object.is(c,l))continue;const u=jn(i,()=>n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(c,l):n.validate(l));Object.is(u,c)||(s=!0)}for(const i of Object.keys(r))if(!ro(o,i)){s=!0;break}return s?o:r}),this.keyValidator=t,this.valueValidator=n}}function U0(e){return new Sn(t=>{if(typeof t!==e)throw new Ce(`Expected ${e}, got ${Fs(t)}`);return t})}const lL=new Sn(e=>e),ge=U0("string"),he=U0("number").check(e=>{if(Number.isNaN(e))throw new Ce("Expected a number, got NaN");if(!Number.isFinite(e))throw new Ce(`Expected a finite number, got ${e}`)}),Rp=he.check(e=>{if(e<0)throw new Ce(`Expected a positive number, got ${e}`)}),On=he.check(e=>{if(e<=0)throw new Ce(`Expected a non-zero positive number, got ${e}`)}),rk=he.check(e=>{if(!Number.isInteger(e))throw new Ce(`Expected an integer, got ${e}`)}),mh=rk.check(e=>{if(e<0)throw new Ce(`Expected a positive integer, got ${e}`)}),uL=rk.check(e=>{if(e<=0)throw new Ce(`Expected a non-zero positive integer, got ${e}`)}),we=U0("boolean");function on(e){return new Sn(t=>{if(t!==e)throw new Ce(`Expected ${e}, got ${JSON.stringify(t)}`);return e})}const d1=new Sn(e=>{if(!Array.isArray(e))throw new Ce(`Expected an array, got ${Fs(e)}`);return e});function Nt(e){return new aL(e)}function ve(e){return new Dp(e)}function RS(e){return typeof e=="object"&&e!==null&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===X3)}function LS(e){return e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(LS):RS(e)?Object.values(e).every(LS):!1}const pn=new Sn(e=>{if(LS(e))return e;throw new Ce(`Expected json serializable value, got ${typeof e}`)},(e,t)=>{if(Array.isArray(e)&&Array.isArray(t)){let n=e.length!==t.length;for(let r=0;r=e.length){n=!0,pn.validate(t[r]);continue}const o=e[r],s=t[r];if(Object.is(o,s))continue;const i=pn.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}return n?t:e}else if(RS(e)&&RS(t)){let n=!1;for(const r of Object.keys(t)){if(!ro(e,r)){n=!0,pn.validate(t[r]);continue}const o=e[r],s=t[r];if(Object.is(o,s))continue;const i=pn.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}for(const r of Object.keys(e))if(!ro(t,r)){n=!0;break}return n?t:e}else return pn.validate(t)});function Lp(e,t){return new cL(e,t)}function H0(e,t){return new jf(e,t,(n,r)=>{throw new Ce(`Expected one of ${Object.keys(t).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!1)}function dL(e,t){return new jf(e,t,(n,r)=>{throw new Ce(`Expected one of ${Object.keys(t).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!0)}function Qo(e,t){return new Sn(n=>jn(e,()=>t.validate(n)),(n,r)=>jn(e,()=>t.validateUsingKnownGoodVersion?t.validateUsingKnownGoodVersion(n,r):t.validate(r)))}function Of(e){return new Sn(t=>{if(!e.has(t)){const n=Array.from(e,r=>JSON.stringify(r)).join(" or ");throw new Ce(`Expected ${n}, got ${t}`)}return t})}function ok(e){return new Sn(t=>{if(t!==void 0)return e.validate(t)},(t,n)=>{if(!(t===void 0&&n===void 0)&&n!==void 0)return e.validateUsingKnownGoodVersion&&t!==void 0?e.validateUsingKnownGoodVersion(t,n):e.validate(n)})}function hL(e){return new Sn(t=>t===null?null:e.validate(t),(t,n)=>n===null?null:e.validateUsingKnownGoodVersion&&t!==null?e.validateUsingKnownGoodVersion(t,n):e.validate(n))}function sk(...e){return Of(new Set(e))}function ik(e){try{return new URL(e)}catch{if(e.startsWith("/")||e.startsWith("./"))try{return new URL(e,"http://example.com")}catch{throw new Ce(`Expected a valid url, got ${JSON.stringify(e)}`)}throw new Ce(`Expected a valid url, got ${JSON.stringify(e)}`)}}const pL=new Set(["http:","https:","mailto:"]),er=ge.check(e=>{if(e==="")return;const t=ik(e);if(!pL.has(t.protocol.toLowerCase()))throw new Ce(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)}),fL=new Set(["http:","https:","data:"]),vc=ge.check(e=>{if(e==="")return;const t=ik(e);if(!fL.has(t.protocol.toLowerCase()))throw new Ce(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)}),K0=ge.refine(e=>{try{return N3(e),e}catch{throw new Ce(`Expected an index key, got ${JSON.stringify(e)}`)}});function mr(e){return ge.refine(t=>{if(!t.startsWith(`${e}:`))throw new Error(`${e} ID must start with "${e}:"`);return t})}const Df=mr("asset");function W0(e,t){return ve({id:Df,typeName:on("asset"),type:on(e),props:t,meta:pn})}const gL=Qo("camera",ve({typeName:on("camera"),id:mr("camera"),x:he,y:he,z:he,meta:pn})),mL=sr("com.tldraw.camera",{AddMeta:1}),yL=xr({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:mL.AddMeta,up:e=>{e.meta={}}}]}),hn=Zo("camera",{validator:gL,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),tu=ve({x:he,y:he,z:he.optional()}),$l=ve({x:he,y:he,w:he,h:he}),SL=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"]),ak=Of(SL),vL=ve({type:ak,rotation:he}),ck=he.check(e=>{if(e<0||e>1)throw new Ce("Opacity must be between 0 and 1")}),xL=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),wL=Of(xL),bL=new Set(["starting","paused","active","stopping"]),lk=ve({id:ge,points:Nt(tu),size:Rp,color:wL,opacity:he,state:Of(bL),delay:he,shrink:he,taper:we}),nu=mr("page"),PL=Qo("page",ve({typeName:on("page"),id:nu,name:ge,index:K0,meta:pn})),CL=sr("com.tldraw.page",{AddMeta:1}),IL=xr({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:CL.AddMeta,up:e=>{e.meta={}}}]}),Ho=Zo("page",{validator:PL,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function bn(e){return Ho.isId(e)}mr("instance");function EL(e){const t={};for(const[r,o]of e)t[r]=ok(o);const n=Qo("instance",ve({typeName:on("instance"),id:mr("instance"),currentPageId:nu,followingUserId:ge.nullable(),brush:$l.nullable(),opacityForNextShape:ck,stylesForNextShape:ve(t),cursor:vL,scribbles:Nt(lk),isFocusMode:we,isDebugMode:we,isToolLocked:we,exportBackground:we,screenBounds:$l,insets:Nt(we),zoomBrush:$l.nullable(),isPenMode:we,isGridMode:we,chatMessage:ge,isChatting:we,highlightedUserIds:Nt(ge),canMoveCamera:we,isFocused:we,devicePixelRatio:he,isCoarsePointer:we,isHoveringCanvas:we.nullable(),openMenus:Nt(ge),isChangingStyle:we,isReadonly:we,meta:pn,duplicateProps:ve({shapeIds:Nt(mr("shape")),offset:ve({x:he,y:he})}).nullable()}));return Zo("instance",{validator:n,scope:"session"}).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:[],canMoveCamera:!0,isFocused:!1,devicePixelRatio:typeof window>"u"?1:window.devicePixelRatio,isCoarsePointer:!1,isHoveringCanvas:null,openMenus:[],isChangingStyle:!1,isReadonly:!1,meta:{},duplicateProps:null}))}const nt=sr("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}),_L=xr({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:nt.AddTransparentExportBgs,up:e=>({...e,exportBackground:!0})},{id:nt.RemoveDialog,up:({dialog:e,...t})=>t},{id:nt.AddToolLockMode,up:e=>({...e,isToolLocked:!1})},{id:nt.RemoveExtraPropsForNextShape,up:({propsForNextShape:e,...t})=>({...t,propsForNextShape:Object.fromEntries(Object.entries(e).filter(([n])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(n)))})},{id:nt.AddLabelColor,up:({propsForNextShape:e,...t})=>({...t,propsForNextShape:{...e,labelColor:"black"}})},{id:nt.AddFollowingUserId,up:e=>({...e,followingUserId:null})},{id:nt.RemoveAlignJustify,up:e=>{let t=e.propsForNextShape.align;return t==="justify"&&(t="start"),{...e,propsForNextShape:{...e.propsForNextShape,align:t}}}},{id:nt.AddZoom,up:e=>({...e,zoomBrush:null})},{id:nt.AddVerticalAlign,up:e=>({...e,propsForNextShape:{...e.propsForNextShape,verticalAlign:"middle"}})},{id:nt.AddScribbleDelay,up:e=>e.scribble!==null?{...e,scribble:{...e.scribble,delay:0}}:{...e}},{id:nt.RemoveUserId,up:({userId:e,...t})=>t},{id:nt.AddIsPenModeAndIsGridMode,up:e=>({...e,isPenMode:!1,isGridMode:!1})},{id:nt.HoistOpacity,up:({propsForNextShape:{opacity:e,...t},...n})=>({...n,opacityForNextShape:Number(e??"1"),propsForNextShape:t})},{id:nt.AddChat,up:e=>({...e,chatMessage:"",isChatting:!1})},{id:nt.AddHighlightedUserIds,up:e=>({...e,highlightedUserIds:[]})},{id:nt.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:e,...t})=>({...t,stylesForNextShape:{}})},{id:nt.AddMeta,up:e=>({...e,meta:{}})},{id:nt.RemoveCursorColor,up:e=>{const{color:t,...n}=e.cursor;return{...e,cursor:n}}},{id:nt.AddLonelyProperties,up:e=>({...e,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:nt.ReadOnlyReadonly,up:({isReadOnly:e,...t})=>({...t,isReadonly:e})},{id:nt.AddHoveringCanvas,up:e=>({...e,isHoveringCanvas:null})},{id:nt.AddScribbles,up:({scribble:e,...t})=>({...t,scribbles:[]})},{id:nt.AddInset,up:e=>({...e,insets:[!1,!1,!1,!1]}),down:({insets:e,...t})=>({...t})},{id:nt.AddDuplicateProps,up:e=>({...e,duplicateProps:null}),down:({duplicateProps:e,...t})=>({...t})}]}),In="instance:instance",kL=ge.refine(e=>{if(!e.startsWith("page:")&&!e.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return e}),_r=mr("shape");function TL(e,t,n){return ve({id:_r,typeName:on("shape"),x:he,y:he,rotation:he,index:K0,parentId:kL,type:on(e),isLocked:we,opacity:ck,props:t?ve(t):pn,meta:n?ve(n):pn})}const $L=Qo("instance_page_state",ve({typeName:on("instance_page_state"),id:mr("instance_page_state"),pageId:nu,selectedShapeIds:Nt(_r),hintingShapeIds:Nt(_r),erasingShapeIds:Nt(_r),hoveredShapeId:_r.nullable(),editingShapeId:_r.nullable(),croppingShapeId:_r.nullable(),focusedGroupId:_r.nullable(),meta:pn})),Gc=sr("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),ML=xr({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:Gc.AddCroppingId,up(e){e.croppingShapeId=null}},{id:Gc.RemoveInstanceIdAndCameraId,up(e){delete e.instanceId,delete e.cameraId}},{id:Gc.AddMeta,up:e=>{e.meta={}}},{id:Gc.RenameProperties,up:e=>{},down:e=>{}},{id:Gc.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}}]}),Zt=Zo("instance_page_state",{validator:$L,scope:"session"}).withDefaultProperties(()=>({editingShapeId:null,croppingShapeId:null,selectedShapeIds:[],hoveredShapeId:null,erasingShapeIds:[],hintingShapeIds:[],focusedGroupId:null,meta:{}})),AL=Qo("pointer",ve({typeName:on("pointer"),id:mr("pointer"),x:he,y:he,lastActivityTimestamp:he,meta:pn})),jL=sr("com.tldraw.pointer",{AddMeta:1}),OL=xr({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:jL.AddMeta,up:e=>{e.meta={}}}]}),V0=Zo("pointer",{validator:AL,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),Fp=V0.createId("pointer"),DL=Qo("instance_presence",ve({typeName:on("instance_presence"),id:mr("instance_presence"),userId:ge,userName:ge,lastActivityTimestamp:he,followingUserId:ge.nullable(),cursor:ve({x:he,y:he,type:ak,rotation:he}),color:ge,camera:ve({x:he,y:he,z:he}),screenBounds:$l,selectedShapeIds:Nt(mr("shape")),currentPageId:mr("page"),brush:$l.nullable(),scribbles:Nt(lk),chatMessage:ge,meta:pn})),Yc=sr("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5}),RL=xr({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:Yc.AddScribbleDelay,up:e=>{e.scribble!==null&&(e.scribble.delay=0)}},{id:Yc.RemoveInstanceId,up:e=>{delete e.instanceId}},{id:Yc.AddChatMessage,up:e=>{e.chatMessage=""}},{id:Yc.AddMeta,up:e=>{e.meta={}}},{id:Yc.RenameSelectedShapeIds,up:e=>{}}]}),LL=Zo("instance_presence",{validator:DL,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:{}})),FL=Qo("document",ve({typeName:on("document"),id:on("document:document"),gridSize:he,name:ge,meta:pn})),h1=sr("com.tldraw.document",{AddName:1,AddMeta:2}),NL=xr({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:h1.AddName,up:e=>{e.name=""},down:e=>{delete e.name}},{id:h1.AddMeta,up:e=>{e.meta={}}}]}),G0=Zo("document",{validator:FL,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),FS=G0.createId("document");function zL(e,t){return e.indext.index?1:0}function p1(e){e.typeName==="asset"&&("src"in e&&(e.src=""),"src"in e.props&&(e.props.src=""))}const BL=({error:e,phase:t,record:n,recordBefore:r})=>{throw D0(e,{tags:{origin:"store.validateRecord",storePhase:t,isExistingValidationIssue:t==="initialize"},extras:{recordBefore:r?p1(Ye(r)):void 0,recordAfter:p1(Ye(n))}}),e};function UL(){return[Ho.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function HL(e){const t=e.query.ids("page"),n=()=>{if(!e.has(FS))return e.put([G0.create({id:FS,name:e.props.defaultName})]),n();if(!e.has(Fp))return e.put([V0.create({id:Fp})]),n();const r=t.get();if(r.size===0)return e.put(UL()),n();const o=()=>[...r].map(c=>e.get(c)).sort(zL)[0].id,s=e.get(In);if(s){if(!r.has(s.currentPageId))return e.put([{...s,currentPageId:o()}]),n()}else return e.put([e.schema.types.instance.create({id:In,currentPageId:o(),exportBackground:!0})]),n();const i=new Set,a=new Set;for(const c of r){const l=Zt.createId(c);e.has(l)||i.add(l);const u=hn.createId(c);e.has(u)||a.add(u)}i.size>0&&e.put([...i].map(c=>Zt.create({id:c,pageId:Zt.parseId(c)}))),a.size>0&&e.put([...a].map(c=>hn.create({id:c})))};return n}const KL=W0("bookmark",ve({title:ge,description:ge,image:ge,src:vc.nullable()})),WL=sr("com.tldraw.asset.bookmark",{MakeUrlsValid:1}),VL=xr({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:e=>e.type==="bookmark",sequence:[{id:WL.MakeUrlsValid,up:e=>{vc.isValid(e.props.src)||(e.props.src="")},down:e=>{}}]}),GL=W0("image",ve({w:he,h:he,name:ge,isAnimated:we,mimeType:ge.nullable(),src:vc.nullable()})),sm=sr("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3}),YL=xr({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:e=>e.type==="image",sequence:[{id:sm.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:sm.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:sm.MakeUrlsValid,up:e=>{vc.isValid(e.props.src)||(e.props.src="")},down:e=>{}}]}),XL=W0("video",ve({w:he,h:he,name:ge,isAnimated:we,mimeType:ge.nullable(),src:vc.nullable()})),im=sr("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3}),qL=xr({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:e=>e.type==="video",sequence:[{id:im.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:im.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:im.MakeUrlsValid,up:e=>{vc.isValid(e.props.src)||(e.props.src="")},down:e=>{}}]}),ZL=Qo("asset",H0("type",{image:GL,video:XL,bookmark:KL})),QL=sr("com.tldraw.asset",{AddMeta:1}),JL=xr({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:QL.AddMeta,up:e=>{e.meta={}}}]}),Si=Zo("asset",{validator:ZL,scope:"document"}).withDefaultProperties(()=>({meta:{}}));let e5=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");class an{constructor(t,n,r){this.id=t,this.defaultValue=n,this.type=r}static define(t,n){const{defaultValue:r,type:o=lL}=n;return new an(t,r,o)}static defineEnum(t,n){const{defaultValue:r,values:o}=n;return new t5(t,r,o)}validate(t){return this.type.validate(t)}validateUsingKnownGoodVersion(t,n){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(t,n):this.validate(n)}}class t5 extends an{constructor(t,n,r){super(t,n,sk(...r)),this.values=r}}const Sd=sr("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),n5=xr({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:Sd.AddIsLocked,up:e=>{e.isLocked=!1},down:e=>{delete e.isLocked}},{id:Sd.HoistOpacity,up:e=>{e.opacity=Number(e.props.opacity??"1"),delete e.props.opacity},down:e=>{const t=e.opacity;delete e.opacity,e.props.opacity=t<.175?"0.1":t<.375?"0.25":t<.625?"0.5":t<.875?"0.75":"1"}},{id:Sd.AddMeta,up:e=>{e.meta={}}},{id:Sd.AddWhite,up:e=>{},down:e=>{e.props.color==="white"&&(e.props.color="black")}}]});function $a(e){return e?e.typeName==="shape":!1}function Kn(e){return e?e.startsWith("shape:"):!1}function Be(e){return`shape:${e??e5()}`}function uk(e){const t=new Map;for(const[n,r]of Object.entries(e))if(r instanceof an){if(t.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);t.set(r,n)}return t}const gt="retired";function fo(e,t){return Mf(t,(n,r)=>`com.tldraw.shape.${e}/${r}`)}function r5(e){const t=[];for(const[n,{migrations:r}]of Object.entries(e)){const o=`com.tldraw.shape.${n}`;r?"sequenceId"in r?(_t(o===r.sequenceId,`sequenceId mismatch for ${n} shape migrations. Expected '${o}', got '${r.sequenceId}'`),t.push(r)):"sequence"in r?t.push(Tl({sequenceId:o,retroactive:!1,sequence:r.sequence.map(s=>"id"in s?{id:s.id,scope:"record",filter:i=>i.typeName==="shape"&&i.type===n,dependsOn:s.dependsOn,up:i=>{const a=s.up(i.props);a&&(i.props=a)},down:typeof s.down=="function"?i=>{const a=s.down(i.props);a&&(i.props=a)}:void 0}:s)})):t.push(Tl({sequenceId:o,retroactive:!1,sequence:Object.keys(r.migrators).map(s=>Number(s)).sort((s,i)=>s-i).map(s=>({id:`${o}/${s}`,scope:"record",filter:i=>i.typeName==="shape"&&i.type===n,up:i=>{const a=r.migrators[s].up(i);if(a)return a},down:i=>{const a=r.migrators[s].down(i);if(a)return a}}))})):t.push(Tl({sequenceId:o,retroactive:!1,sequence:[]}))}return t}function o5(e){return Zo("shape",{scope:"document",validator:Qo("shape",H0("type",Mf(e,(t,{props:n,meta:r})=>TL(t,n,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}const dk=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Np={lightMode:{id:"light",text:"#000000",background:"rgb(249, 250, 251)",solid:"#fcfffe",black:{solid:"#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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",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",semi:"#f5f5f5",pattern:"#f9f9f9",note:{fill:"#eaeaea",text:"#1d1d1d"},highlight:{srgb:"#ffffff",p3:"color(display-p3 1 1 1)"}}}};function Jo(e){return e.isDarkMode?Np.darkMode:Np.lightMode}const tr=an.defineEnum("tldraw:color",{defaultValue:"black",values:dk}),hk=an.defineEnum("tldraw:labelColor",{defaultValue:"black",values:dk}),Ti=an.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),sc=an.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern"]}),ao=an.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),pk={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},co=an.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),fk=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],zp=an.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:fk}),Bp=an.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:fk}),f1=H0("type",{binding:ve({type:on("binding"),boundShapeId:_r,normalizedAnchor:tu,isExact:we,isPrecise:we}),point:ve({type:on("point"),x:he,y:he})}),gk={labelColor:hk,color:tr,fill:sc,dash:Ti,size:co,arrowheadStart:zp,arrowheadEnd:Bp,font:ao,start:f1,end:f1,bend:he,text:ge,labelPosition:he},am=fo("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3}),mk={sequence:[{id:am.AddLabelColor,up:e=>{e.labelColor="black"},down:gt},{id:am.AddIsPrecise,up:({start:e,end:t})=>{e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5)),t.type==="binding"&&(t.isPrecise=!(t.normalizedAnchor.x===.5&&t.normalizedAnchor.y===.5))},down:({start:e,end:t})=>{e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise),t.type==="binding"&&(t.isPrecise||(t.normalizedAnchor={x:.5,y:.5}),delete t.isPrecise)}},{id:am.AddLabelPosition,up:e=>{e.labelPosition=.5},down:e=>{delete e.labelPosition}}]},yk={w:On,h:On,assetId:Df.nullable(),url:er},g1=fo("bookmark",{NullAssetId:1,MakeUrlsValid:2}),Sk={sequence:[{id:g1.NullAssetId,up:e=>{e.assetId===void 0&&(e.assetId=null)},down:gt},{id:g1.MakeUrlsValid,up:e=>{er.isValid(e.url)||(e.url="")},down:e=>{}}]},vk=ve({type:sk("free","straight"),points:Nt(tu)}),xk={color:tr,fill:sc,dash:Ti,size:co,segments:Nt(vk),isComplete:we,isClosed:we,isPen:we},s5=fo("draw",{AddInPen:1}),wk={sequence:[{id:s5.AddInPen,up:e=>{const{points:t}=e.segments[0];if(t.length===0){e.isPen=!1;return}let n=!(t[0].z===0||t[0].z===.5);t[1]&&(n=n&&!(t[1].z===0||t[1].z===.5)),e.isPen=n},down:gt}]};var i5={};const m1=/(^\/r\/[^/]+\/?$)/,Ne=e=>{try{return new URL(e)}catch{return}},Tu=[{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 t=Ne(e);if(t&&t.pathname.match(m1))return e},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(m1))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 t=Ne(e);if(t&&t.pathname.match(/^\/embed\/?$/)){const n=t.searchParams.get("url");if(n)return n}}},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{if(e.includes("/maps/")){const t=e.match(/@(.*),(.*),(.*)z/);let n;if(t){const[,r,o,s]=t;n=`https://${new URL(e).host.replace("www.","")}/maps/embed/v1/view?key=${i5.NEXT_PUBLIC_GC_API_KEY}¢er=${r},${o}&zoom=${s}`}else n="";return n}},fromEmbedUrl:e=>{const t=Ne(e);if(!t)return;if(t.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&t.searchParams.has("center")&&t.searchParams.get("zoom")){const r=t.searchParams.get("zoom"),[o,s]=t.searchParams.get("center").split(",");return`https://www.google.com/maps/@${o},${s},${r}z`}}},{type:"val_town",title:"Val Town",hostnames:["val.town"],minWidth:260,minHeight:100,width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e),n=t&&t.pathname.match(/\/v\/([^/]+)\/?/);if(n)return`https://www.val.town/embed/${n[1]}`},fromEmbedUrl:e=>{const t=Ne(e),n=t&&t.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://www.val.town/v/${n[1]}`}},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e),n=t&&t.pathname.match(/\/s\/([^/]+)\/?/);if(n)return`https://codesandbox.io/embed/${n[1]}`},fromEmbedUrl:e=>{const t=Ne(e),n=t&&t.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://codesandbox.io/s/${n[1]}`}},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:e=>{const t=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,n=e.match(t);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/embed/${s}`}},fromEmbedUrl:e=>{const t=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,n=e.match(t);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/pen/${s}`}}},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,toEmbedUrl:e=>{const t=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,n=e.match(t);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/embed/${o}`}},fromEmbedUrl:e=>{const t=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,n=e.match(t);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/${o}`}}},{type:"youtube",title:"YouTube",hostnames:["*.youtube.com","youtube.com","youtu.be"],width:800,height:450,doesResize:!0,overridePermissions:{"allow-presentation":!0},isAspectRatioLocked:!0,toEmbedUrl:e=>{const t=Ne(e);if(!t)return;const n=t.hostname.replace(/^www./,"");if(n==="youtu.be")return`https://www.youtube.com/embed/${t.pathname.split("/").filter(Boolean)[0]}`;if((n==="youtube.com"||n==="m.youtube.com")&&t.pathname.match(/^\/watch/))return`https://www.youtube.com/embed/${t.searchParams.get("v")}`},fromEmbedUrl:e=>{const t=Ne(e);if(!t)return;if(t.hostname.replace(/^www./,"")==="youtube.com"){const r=t.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",toEmbedUrl:e=>{const t=Ne(e),n=t==null?void 0:t.searchParams.get("cid");if(t!=null&&t.pathname.match(/\/calendar\/u\/0/)&&n){t.pathname="/calendar/embed";const r=Array.from(t.searchParams.keys());for(const o of r)t.searchParams.delete(o);return t.searchParams.set("src",n),t.href}},fromEmbedUrl:e=>{const t=Ne(e),n=t==null?void 0:t.searchParams.get("src");if(t!=null&&t.pathname.match(/\/calendar\/embed/)&&n){t.pathname="/calendar/u/0";const r=Array.from(t.searchParams.keys());for(const o of r)t.searchParams.delete(o);return t.searchParams.set("cid",n),t.href}}},{type:"google_slides",title:"Google Slides",hostnames:["docs.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e);if(t!=null&&t.pathname.match(/^\/presentation/)&&(t!=null&&t.pathname.match(/\/pub\/?$/))){t.pathname=t.pathname.replace(/\/pub$/,"/embed");const n=Array.from(t.searchParams.keys());for(const r of n)t.searchParams.delete(r);return t.href}},fromEmbedUrl:e=>{const t=Ne(e);if(t!=null&&t.pathname.match(/^\/presentation/)&&(t!=null&&t.pathname.match(/\/embed\/?$/))){t.pathname=t.pathname.replace(/\/embed$/,"/pub");const n=Array.from(t.searchParams.keys());for(const r of n)t.searchParams.delete(r);return t.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/\/([^/]+)\/([^/]+)/))return e.split("/").pop()?e:void 0},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.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 t=Ne(e);if(t&&t.pathname.match(/\/@([^/]+)\/([^/]+)/))return`${e}?embed=true`},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/\/@([^/]+)\/([^/]+)/)&&t.searchParams.has("embed"))return t.searchParams.delete("embed"),t.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/^\/map\//))return t.origin+"/embed"+t.pathname},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/^\/embed\/map\//))return t.pathname=t.pathname.replace(/^\/embed/,""),t.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,toEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/^\/(artist|album)\//))return t.origin+"/embed"+t.pathname},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/^\/embed\/(artist|album)\//))return t.origin+t.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const t=Ne(e);if(t&&t.hostname==="vimeo.com"&&t.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+t.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.hostname==="player.vimeo.com"){const n=t.pathname.match(/^\/video\/([^/]+)\/?$/);if(n)return"https://vimeo.com/"+n[1]}}},{type:"excalidraw",title:"Excalidraw",hostnames:["excalidraw.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const t=Ne(e);if(t&&t.hash.match(/#room=/))return e},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.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 t=Ne(e);if(t&&t.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${t.origin}/embed${t.pathname}?cell=*`;if(t&&t.pathname.match(/^\/d\/([^/]+)\/?$/)){const n=t.pathname.replace(/^\/d/,"");return`${t.origin}/embed${n}?cell=*`}},fromEmbedUrl:e=>{const t=Ne(e);if(t&&t.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${t.origin}${t.pathname.replace("/embed","")}#cell-*`;if(t&&t.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${t.origin}${t.pathname.replace("/embed","/d")}#cell-*`}}],a5={"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},bk={w:On,h:On,url:ge},vd=fo("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),Pk={sequence:[{id:vd.GenOriginalUrlInEmbed,up:e=>{try{const t=e.url,n=new URL(t).host.replace("www.","");let r;for(const o of Tu)if(o.hostnames.includes(n))try{r=o.fromEmbedUrl(t)}catch(s){console.warn(s)}e.tmpOldUrl=e.url,e.url=r??""}catch{e.url="",e.tmpOldUrl=e.url}},down:gt},{id:vd.RemoveDoesResize,up:e=>{delete e.doesResize},down:gt},{id:vd.RemoveTmpOldUrl,up:e=>{delete e.tmpOldUrl},down:gt},{id:vd.RemovePermissionOverrides,up:e=>{delete e.overridePermissions},down:gt}]},Ck={w:On,h:On,name:ge},Ik={sequence:[]},ru=an.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),Up=an.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),oo=an.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"]}),Ek={geo:oo,labelColor:hk,color:tr,fill:sc,dash:Ti,size:co,font:ao,align:ru,verticalAlign:Up,url:er,w:On,h:On,growY:Rp,text:ge},us=fo("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8}),_k={sequence:[{id:us.AddUrlProp,up:e=>{e.url=""},down:gt},{id:us.AddLabelColor,up:e=>{e.labelColor="black"},down:gt},{id:us.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:gt},{id:us.AddCheckBox,up:e=>{},down:gt},{id:us.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:gt},{id:us.MigrateLegacyAlign,up:e=>{let t;switch(e.align){case"start":t="start-legacy";break;case"end":t="end-legacy";break;default:t="middle-legacy";break}e.align=t},down:gt},{id:us.AddCloud,up:e=>{},down:gt},{id:us.MakeUrlsValid,up:e=>{er.isValid(e.url)||(e.url="")},down:e=>{}}]},kk={},Tk={sequence:[]},$k={color:tr,size:co,segments:Nt(vk),isComplete:we,isPen:we},Mk={sequence:[]},c5=ve({topLeft:tu,bottomRight:tu}),Ak={w:On,h:On,playing:we,url:er,assetId:Df.nullable(),crop:c5.nullable()},cm=fo("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3}),jk={sequence:[{id:cm.AddUrlProp,up:e=>{e.url=""},down:gt},{id:cm.AddCropProp,up:e=>{e.crop=null},down:e=>{delete e.crop}},{id:cm.MakeUrlsValid,up:e=>{er.isValid(e.url)||(e.url="")},down:e=>{}}]},Hp=an.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),l5=ve({id:ge,index:K0,x:he,y:he}),Ok={color:tr,dash:Ti,size:co,spline:Hp,points:Lp(ge,l5)},xd=fo("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4}),Dk={sequence:[{id:xd.AddSnapHandles,up:e=>{for(const t of Object.values(e.handles))t.canSnap=!0},down:gt},{id:xd.RemoveExtraHandleProps,up:e=>{e.handles=R0(Object.values(e.handles).map(t=>[t.index,{x:t.x,y:t.y}]))},down:e=>{const t=Object.entries(e.handles).map(([n,r])=>({index:n,...r})).sort(en);e.handles=Object.fromEntries(t.map((n,r)=>{const o=r===0?"start":r===t.length-1?"end":`handle:${n.index}`;return[o,{id:o,type:"vertex",canBind:!1,canSnap:!0,index:n.index,x:n.x,y:n.y}]}))}},{id:xd.HandlesToPoints,up:e=>{const t=Object.entries(e.handles).map(([n,{x:r,y:o}])=>({x:r,y:o,index:n})).sort(en);e.points=t.map(({x:n,y:r})=>({x:n,y:r})),delete e.handles},down:e=>{const t=eu(e.points.length);e.handles=Object.fromEntries(e.points.map((n,r)=>[t[r],{x:n.x,y:n.y}])),delete e.points}},{id:xd.PointIndexIds,up:e=>{const t=eu(e.points.length);e.points=Object.fromEntries(e.points.map((n,r)=>{const o=t[r];return[o,{id:o,index:o,x:n.x,y:n.y}]}))},down:e=>{const t=Object.values(e.points).sort(en);e.points=t.map(({x:n,y:r})=>({x:n,y:r}))}}]},Rk={color:tr,size:co,font:ao,fontSizeAdjustment:Rp,align:ru,verticalAlign:Up,growY:Rp,url:er,text:ge},ea=fo("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6}),Lk={sequence:[{id:ea.AddUrlProp,up:e=>{e.url=""},down:gt},{id:ea.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:gt},{id:ea.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:gt},{id:ea.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:gt},{id:ea.MakeUrlsValid,up:e=>{er.isValid(e.url)||(e.url="")},down:e=>{}},{id:ea.AddFontSizeAdjustment,up:e=>{e.fontSizeAdjustment=0},down:e=>{delete e.fontSizeAdjustment}}]},Fk={color:tr,size:co,font:ao,align:ru,w:On,text:ge,scale:On,autoSize:we},u5=fo("text",{RemoveJustify:1}),Nk={sequence:[{id:u5.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:gt}]},zk={w:On,h:On,time:he,playing:we,url:er,assetId:Df.nullable()},y1=fo("video",{AddUrlProp:1,MakeUrlsValid:2}),Bk={sequence:[{id:y1.AddUrlProp,up:e=>{e.url=""},down:gt},{id:y1.MakeUrlsValid,up:e=>{er.isValid(e.url)||(e.url="")},down:e=>{}}]},wd=sr("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4}),d5=Tl({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:wd.RemoveCodeAndIconShapeTypes,scope:"store",up:e=>{for(const[t,n]of An(e))n.typeName==="shape"&&(n.type==="icon"||n.type==="code")&&delete e[t]}},{id:wd.AddInstancePresenceType,scope:"store",up(e){}},{id:wd.RemoveTLUserAndPresenceAndAddPointer,scope:"store",up:e=>{for(const[t,n]of An(e))n.typeName.match(/^(user|user_presence)$/)&&delete e[t]}},{id:wd.RemoveUserDocument,scope:"store",up:e=>{for(const[t,n]of An(e))n.typeName.match("user_document")&&delete e[t]}}]}),h5={arrow:{migrations:mk,props:gk},bookmark:{migrations:Sk,props:yk},draw:{migrations:wk,props:xk},embed:{migrations:Pk,props:bk},frame:{migrations:Ik,props:Ck},geo:{migrations:_k,props:Ek},group:{migrations:Tk,props:kk},highlight:{migrations:Mk,props:$k},image:{migrations:jk,props:Ak},line:{migrations:Dk,props:Ok},note:{migrations:Lk,props:Rk},text:{migrations:Nk,props:Fk},video:{migrations:Bk,props:zk}};function p5({shapes:e=h5,migrations:t}={}){const n=new Map;for(const s of bt(e))for(const i of uk(s.props??{}).keys()){if(n.has(i.id)&&n.get(i.id)!==i)throw new Error(`Multiple StyleProp instances with the same id: ${i.id}`);n.set(i.id,i)}const r=o5(e),o=EL(n);return B0.create({asset:Si,camera:hn,document:G0,instance:o,instance_page_state:Zt,page:Ho,instance_presence:LL,pointer:V0,shape:r},{migrations:[d5,JL,yL,NL,_L,ML,IL,RL,OL,n5,VL,YL,qL,...r5(e),...t??[]],onValidationFailure:BL,createIntegrityChecker:HL})}const ou=[{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 f5(){const e=typeof window<"u"?window.navigator.languages??["en"]:["en"];return g5(e)}function g5(e){for(const t of e){const n=m5(t);if(n)return n}return"en"}const S1={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function m5(e){const t=ou.find(o=>o.locale===e.toLowerCase());if(t)return t.locale;const[n,r]=e.split(/[-_]/).map(o=>o.toLowerCase());if(r){const o=ou.find(s=>s.locale===n);if(o)return o.locale}return n in S1?S1[n]:null}var Uk={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var s="",i=0;i{const i=e.current;if(!i||t===void 0)return;let a=`translate(${t}px, ${n}px)`;r!==void 0&&(a+=` scale(${r})`),o!==void 0&&(a+=` rotate(${o}rad)`),s&&(a+=` translate(${s.x}px, ${s.y}px)`),i.style.transform=a})}const nn={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 P{constructor(t=0,n=0,r=1){this.x=t,this.y=n,this.z=r}get pressure(){return this.z}set(t=this.x,n=this.y,r=this.z){return this.x=t,this.y=n,this.z=r,this}setTo({x:t=0,y:n=0,z:r=1}){return this.x=t,this.y=n,this.z=r,this}rot(t){if(t===0)return this;const{x:n,y:r}=this,o=Math.sin(t),s=Math.cos(t);return this.x=n*s-r*o,this.y=n*o+r*s,this}rotWith(t,n){if(n===0)return this;const r=this.x-t.x,o=this.y-t.y,s=Math.sin(n),i=Math.cos(n);return this.x=t.x+(r*i-o*s),this.y=t.y+(r*s+o*i),this}clone(){const{x:t,y:n,z:r}=this;return new P(t,n,r)}sub(t){return this.x-=t.x,this.y-=t.y,this}subXY(t,n){return this.x-=t,this.y-=n,this}subScalar(t){return this.x-=t,this.y-=t,this}add(t){return this.x+=t.x,this.y+=t.y,this}addXY(t,n){return this.x+=t,this.y+=n,this}addScalar(t){return this.x+=t,this.y+=t,this}clamp(t,n){return this.x=Math.max(this.x,t),this.y=Math.max(this.y,t),n!==void 0&&(this.x=Math.min(this.x,n),this.y=Math.min(this.y,n)),this}div(t){return this.x/=t,this.y/=t,this}divV(t){return this.x/=t.x,this.y/=t.y,this}mul(t){return this.x*=t,this.y*=t,this}mulV(t){return this.x*=t.x,this.y*=t.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(t,n){const r=P.Tan(t,this);return this.add(r.mul(n))}neg(){return this.x*=-1,this.y*=-1,this}cross(t){return this.x=this.y*t.z-this.z*t.y,this.y=this.z*t.x-this.x*t.z,this}dpr(t){return P.Dpr(this,t)}cpr(t){return P.Cpr(this,t)}len2(){return P.Len2(this)}len(){return P.Len(this)}pry(t){return P.Pry(this,t)}per(){const{x:t,y:n}=this;return this.x=n,this.y=-t,this}uni(){return P.Uni(this)}tan(t){return P.Tan(this,t)}dist(t){return P.Dist(this,t)}distanceToLineSegment(t,n){return P.DistanceToLineSegment(t,n,this)}slope(t){return P.Slope(this,t)}snapToGrid(t){return this.x=Math.round(this.x/t)*t,this.y=Math.round(this.y/t)*t,this}angle(t){return P.Angle(this,t)}toAngle(){return P.ToAngle(this)}lrp(t,n){return this.x=this.x+(t.x-this.x)*n,this.y=this.y+(t.y-this.y)*n,this}equals(t){return P.Equals(this,t)}equalsXY(t,n){return P.EqualsXY(this,t,n)}norm(){const t=this.len();return this.x=t===0?0:this.x/t,this.y=t===0?0:this.y/t,this}toFixed(){return P.ToFixed(this)}toString(){return P.ToString(P.ToFixed(this))}toJson(){return P.ToJson(this)}toArray(){return P.ToArray(this)}static Add(t,n){return new P(t.x+n.x,t.y+n.y)}static AddXY(t,n,r){return new P(t.x+n,t.y+r)}static Sub(t,n){return new P(t.x-n.x,t.y-n.y)}static SubXY(t,n,r){return new P(t.x-n,t.y-r)}static AddScalar(t,n){return new P(t.x+n,t.y+n)}static SubScalar(t,n){return new P(t.x-n,t.y-n)}static Div(t,n){return new P(t.x/n,t.y/n)}static Mul(t,n){return new P(t.x*n,t.y*n)}static DivV(t,n){return new P(t.x/n.x,t.y/n.y)}static MulV(t,n){return new P(t.x*n.x,t.y*n.y)}static Neg(t){return new P(-t.x,-t.y)}static Per(t){return new P(t.y,-t.x)}static Abs(t){return new P(Math.abs(t.x),Math.abs(t.y))}static Dist(t,n){return((t.y-n.y)**2+(t.x-n.x)**2)**.5}static DistMin(t,n,r){return(t.x-n.x)*(t.x-n.x)+(t.y-n.y)*(t.y-n.y)Math.max(t.x,n.x))return P.Cast(t.x>n.x?t:n);if(i.yMath.max(t.y,n.y))return P.Cast(t.y>n.y?t:n)}return i}static DistanceToLineThroughPoint(t,n,r){return P.Dist(r,P.NearestPointOnLineThroughPoint(t,n,r))}static DistanceToLineSegment(t,n,r,o=!0){return P.Dist(r,P.NearestPointOnLineSegment(t,n,r,o))}static Snap(t,n=1){return new P(Math.round(t.x/n)*n,Math.round(t.y/n)*n)}static Cast(t){return t instanceof P?t:P.From(t)}static Slope(t,n){return t.x===n.y?NaN:(t.y-n.y)/(t.x-n.x)}static IsNaN(t){return isNaN(t.x)||isNaN(t.y)}static Angle(t,n){return Math.atan2(n.y-t.y,n.x-t.x)}static Lrp(t,n,r){return P.Sub(n,t).mul(r).add(t)}static Med(t,n){return new P((t.x+n.x)/2,(t.y+n.y)/2)}static Equals(t,n){return Math.abs(t.x-n.x)<1e-4&&Math.abs(t.y-n.y)<1e-4}static EqualsXY(t,n,r){return t.x===n&&t.y===r}static Clockwise(t,n,r){return(r.x-t.x)*(n.y-t.y)-(n.x-t.x)*(r.y-t.y)<0}static Rescale(t,n){const r=P.Len(t);return new P(n*t.x/r,n*t.y/r)}static ScaleWithOrigin(t,n,r){return P.Sub(t,r).mul(n).add(r)}static ToFixed(t,n=2){return new P(+t.x.toFixed(n),+t.y.toFixed(n),+t.z.toFixed(n))}static Nudge(t,n,r){return P.Add(t,P.Tan(n,t).mul(r))}static ToString(t){return`${t.x}, ${t.y}`}static ToAngle(t){let n=Math.atan2(t.y,t.x);return n<0&&(n+=Math.PI*2),n}static FromAngle(t,n=1){return new P(Math.cos(t)*n,Math.sin(t)*n)}static ToArray(t){return[t.x,t.y,t.z]}static ToJson(t){const{x:n,y:r,z:o}=t;return{x:n,y:r,z:o}}static Average(t){const n=t.length,r=new P(0,0);if(n===0)return r;for(let o=0;oe<.5?2*e*e:-1+(4-2*e)*e;function Ft(e){return`${j(e.x)},${j(e.y)} `}function Cn(e,t){return`${j((e.x+t.x)/2)},${j((e.y+t.y)/2)} `}const Pe=Math.PI,ze=Pe/2,Oe=Pe*2,w5=Math.sin;function Ns(e,t,n){return Math.max(t,typeof n<"u"?Math.min(e,n):e)}function bd(e,t=1e10){return e?Math.round(e*t)/t:0}function Ml(e,t,n=1e-6){return Math.abs(e-t)<=n}function Kp(e,t){const n=Math.pow(e-t,2)/Math.pow(e+t,2);return Pe*(e+t)*(1+3*n/(10+Math.sqrt(4-3*n)))}function Os(e){return e=e%Oe,e<0?e=e+Oe:e===0&&(e=0),e}function $u(e,t){return e=Os(e),t=Os(t),e>t&&(t+=Oe),t-e}function Kk(e,t){return Oe-$u(e,t)}function yh(e,t){const n=(t-e)%Oe;return 2*n%Oe-n}function NS(e){return(Oe+e)%Oe}function Wp(e,t){const n=Oe/t;let r=Math.floor((NS(e)+n/2)/n)*n%Oe;return rPe&&(r-=Oe),r}function Wk(e,t){return e===t||Ml(e%(Math.PI/2)-t%(Math.PI/2),0)}function b5(e){return e*Pe/180}function P5(e){return e*180/Pe}function $i(e,t,n){return new P(e.x,e.y).add(P.FromAngle(n,t))}function lm(e,t,n){const r=e/2,o=t/2,s=[];let i=1/0,a=-1/0,c=1/0,l=-1/0;for(let y=0;ya&&(a=S),v>l&&(l=v),s.push(new P(S,v))}const u=a-i,d=l-c,p=e-u,f=t-d;if(p!==0||f!==0)for(let y=0;ye.y&&v1(r,o,e)>0&&(n+=1):o.y<=e.y&&v1(r,o,e)<0&&(n-=1)}return n!==0}function j(e){return Math.round(e*1e4)/1e4}function Vp(e){return Math.round(e*100)/100}const x1=e=>Math.abs(e)Pe){o=yh(t,r);const s=yh(r,n);return Math.abs(o).5?1:0:s}}function C5(e,t,n,r){const o=2*((t-e)%Oe)%Oe-(t-e)%Oe;return r?(Oe-Math.abs(o))*(n?1:-1):o}const Pd=({brush:e,color:t,opacity:n,className:r})=>{const o=x.useRef(null);xc(o,e.x,e.y);const s=j(Math.max(1,e.w)),i=j(Math.max(1,e.h));return h.jsx("svg",{className:"tl-overlays__item",ref:o,children:t?h.jsxs("g",{className:"tl-brush",opacity:n,children:[h.jsx("rect",{width:s,height:i,fill:t,opacity:.75}),h.jsx("rect",{width:s,height:i,fill:"none",stroke:t,opacity:.1})]}):h.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:s,height:i})})},Io=2e3,Gp=40,Qr=320,ta=[.1,.25,.5,1,2,4,8],qc=.1,xs=8,I5=.5,E5=.1,_5=.2,k5=.005,T5=.05,$5=450,M5=200,BS=36,iu=16,A5=32,ic={};for(let e=1;e<=Math.ceil(xs);e++)ic[e+"_dark"]=`hash_pattern_zoom_${e}_dark`,ic[e+"_light"]=`hash_pattern_zoom_${e}_light`;const j5={duration:0,easing:nn.easeInOutCubic},Sh=.09,w1=[{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}],O5=6e4,Vk=3e3,D5=1200,b1={CAMERA_MOVE:-10},R5=64,Ko=8,L5=20,F5=8,N5=12,Gk=20,Yk=12,z5=["top","right","bottom","left"],B5=500,P1=.35;var um={};const U5={},Xk=zn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),$t={logPreventDefaults:zn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:zn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:zn("logElementRemoves",{defaults:{all:!1}}),debugSvg:zn("debugSvg",{defaults:{all:!1}}),showFps:zn("showFps",{defaults:{all:!1}}),throwToBlob:zn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:zn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:zn("debugCursors",{defaults:{all:!1}}),forceSrgb:zn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:zn("debugGeometry",{defaults:{all:!1}}),hideShapes:zn("hideShapes",{defaults:{all:!1}}),editOnType:zn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const e=Element.prototype.removeChild;Sc("element removal logging",()=>{$t.logElementRemoves.get()?Element.prototype.removeChild=function(t){return console.warn("[tldraw] removing child:",t),e.call(this,t)}:Element.prototype.removeChild=e})}function zn(e,{defaults:t,shouldStoreForSession:n=!0}){return H5({name:e,defaults:t,shouldStoreForSession:n})}function H5(e){const t=W5(e),n=e.shouldStoreForSession?K5(e.name):null,r=fn(`debug:${e.name}`,n??t);return typeof window<"u"&&(e.shouldStoreForSession&&Sc(`debug:${e.name}`,()=>{const o=r.get();o===t?q_(`tldraw_debug:${e.name}`):N0(`tldraw_debug:${e.name}`,JSON.stringify(o))}),Object.defineProperty(window,`tldraw${e.name.replace(/^[a-z]/,o=>o.toUpperCase())}`,{get(){return r.get()},set(o){r.set(o)},configurable:!0})),Object.assign(r,e)}function K5(e){try{return JSON.parse(X_(`tldraw_debug:${e}`)??"null")}catch{return null}}function dm(e){try{return e()}catch{return null}}function W5(e){switch(dm(()=>um.TLDRAW_ENV)??dm(()=>um.VERCEL_PUBLIC_TLDRAW_ENV)??dm(()=>um.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}}function Yp(e){if(e instanceof HTMLElement)return e;if(e.parentElement)return Yp(e.parentElement);throw Error("Could not find a parent element of an HTML type!")}function Ee(e){e.preventDefault(),$t.logPreventDefaults.get()&&console.warn("preventDefault called on event:",e)}function Mu(e,t){if(e.setPointerCapture(t.pointerId),$t.logPointerCaptures.get()){const n=Xk.get();n.set(e,(n.get(e)??0)+1),console.warn("setPointerCapture called on element:",e,t)}}function Au(e,t){if(e.hasPointerCapture(t.pointerId)&&(e.releasePointerCapture(t.pointerId),$t.logPointerCaptures.get())){const n=Xk.get();n.get(e)===1?n.delete(e):n.has(e)?n.set(e,n.get(e)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",e,t)}}const Ut=e=>e.stopPropagation(),Yt=(e,t,n)=>{e&&e.style.setProperty(t,n)};function _n(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 V5(){const e=z();return x.useMemo(function(){let r,o;function s(g){if(!g.isKilled){if(g.button===2){e.dispatch({type:"pointer",target:"canvas",name:"right_click",..._n(g)});return}g.button!==0&&g.button!==1&&g.button!==5||(Mu(g.currentTarget,g),e.dispatch({type:"pointer",target:"canvas",name:"pointer_down",..._n(g)}),e.getOpenMenus().length>0&&(e.updateInstanceState({openMenus:[]}),document.body.click(),e.getContainer().focus()))}}function i(g){g.isKilled||g.clientX===r&&g.clientY===o||(r=g.clientX,o=g.clientY,e.dispatch({type:"pointer",target:"canvas",name:"pointer_move",..._n(g)}))}function a(g){g.isKilled||g.button!==0&&g.button!==1&&g.button!==2&&g.button!==5||(r=g.clientX,o=g.clientY,Au(g.currentTarget,g),e.dispatch({type:"pointer",target:"canvas",name:"pointer_up",..._n(g)}))}function c(g){if(g.isKilled||e.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const w=g.pointerType==="mouse"||g.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:w?!0:null})}function l(g){if(g.isKilled||e.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const w=g.pointerType==="mouse"||g.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:w?!1:null})}function u(g){g.isKilled=!0,document.body.click(),Ee(g)}function d(g){g.isKilled=!0,g.target.tagName!=="A"&&g.target.tagName!=="TEXTAREA"&&!(e.getEditingShape()&&g.target.className.includes("tl-text-content"))&&Ee(g)}function p(g){Ee(g)}async function f(g){var S,v;if(Ee(g),!((v=(S=g.dataTransfer)==null?void 0:S.files)!=null&&v.length))return;const w=Array.from(g.dataTransfer.files);await e.putExternalContent({type:"files",files:w,point:e.screenToPage({x:g.clientX,y:g.clientY}),ignoreParent:!1})}function y(g){Ut(g)}return{onPointerDown:s,onPointerMove:i,onPointerUp:a,onPointerEnter:c,onPointerLeave:l,onDragOver:p,onDrop:f,onTouchStart:u,onTouchEnd:d,onClick:y}},[e])}function G5(){const e=z();x.useEffect(()=>{if(e.environment.isFirefox&&!e.environment.isAndroid&&!e.environment.isIos){e.updateInstanceState({isCoarsePointer:!1});return}if(window.matchMedia){const t=window.matchMedia("(pointer: coarse)"),n=()=>{e.updateInstanceState({isCoarsePointer:!!t.matches})};if(n(),t)return t.addEventListener("change",n),()=>t.removeEventListener("change",n)}},[e])}const qk=x.createContext(null);function Y5({container:e,children:t}){return h.jsx(qk.Provider,{value:e,children:t})}function cn(){return yi(x.useContext(qk),"useContainer used outside of ")}function X5(){const e=z(),t=cn(),n=K("isFocused",()=>e.getInstanceState().isFocused,[e]);x.useEffect(()=>{if(typeof matchMedia===void 0)return;let r=null;const o=()=>{r!=null&&r();const s=`(resolution: ${window.devicePixelRatio}dppx)`,i=matchMedia(s),a=c=>{c.type==="change"&&o()};i.addEventListener?i.addEventListener("change",o):i.addListener&&i.addListener(a),r=()=>{i.removeEventListener?i.removeEventListener("change",o):i.removeListener&&i.removeListener(a)},e.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return o(),()=>{r==null||r()}},[e]),x.useEffect(()=>{if(!n)return;const r=a=>{if(a.altKey&&(e.isIn("zoom")||!e.getPath().endsWith(".idle"))&&!Cd()&&Ee(a),a.isKilled)return;switch(a.isKilled=!0,a.key){case"=":case"-":case"0":{if(a.metaKey||a.ctrlKey){Ee(a);return}break}case"Tab":{if(Cd()||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(),t.focus());return}default:if(Cd()||e.getIsMenuOpen())return}const c={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(c)},o=a=>{if(a.isKilled||(a.isKilled=!0,Cd()||e.getIsMenuOpen())||a.key===",")return;const c={type:"keyboard",name:"key_up",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(c)};function s(a){var c,l;if(t.contains(a.target)){const u=a.touches[0].pageX,d=a.touches[0].radiusX||0;(u-d<10||u+d>e.getViewportScreenBounds().width-10)&&(((c=a.target)==null?void 0:c.tagName)==="BUTTON"&&((l=a.target)==null||l.click()),Ee(a))}}const i=a=>{t.contains(a.target)&&(a.ctrlKey||a.metaKey)&&Ee(a)};return t.addEventListener("touchstart",s,{passive:!1}),t.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",Ee),document.addEventListener("gesturechange",Ee),document.addEventListener("gestureend",Ee),t.addEventListener("keydown",r),t.addEventListener("keyup",o),()=>{t.removeEventListener("touchstart",s),t.removeEventListener("wheel",i),document.removeEventListener("gesturestart",Ee),document.removeEventListener("gesturechange",Ee),document.removeEventListener("gestureend",Ee),t.removeEventListener("keydown",r),t.removeEventListener("keyup",o)}},[e,t,n])}const q5=["input","select","button","textarea"];function Cd(){const{activeElement:e}=document;return!!(e&&(e.getAttribute("contenteditable")||q5.indexOf(e.tagName.toLowerCase())>-1))}const Z5=["textarea","input"];function Q5(e){const t=z();x.useEffect(()=>{const n=e.current;if(!n)return;const r=o=>{var s;if(o instanceof PointerEvent&&o.pointerType==="pen"){o.isKilled=!0;const{target:i}=o;if(Z5.includes((s=i.tagName)==null?void 0:s.toLocaleLowerCase())||t.isIn("select.editing_shape"))return;Ee(o)}};return n.addEventListener("touchstart",r),n.addEventListener("touchend",r),()=>{n.removeEventListener("touchstart",r),n.removeEventListener("touchend",r)}},[t,e])}function J5(e,t,n){return Math.max(t,Math.min(e,n))}const zt={toVector(e,t){return e===void 0&&(e=t),Array.isArray(e)?e:[e,e]},add(e,t){return[e[0]+t[0],e[1]+t[1]]},sub(e,t){return[e[0]-t[0],e[1]-t[1]]},addTo(e,t){e[0]+=t[0],e[1]+=t[1]},subTo(e,t){e[0]-=t[0],e[1]-=t[1]}};function C1(e,t,n){return t===0||Math.abs(t)===1/0?Math.pow(e,n*5):e*t*n/(t+n*e)}function I1(e,t,n,r=.15){return r===0?J5(e,t,n):en?+C1(e-n,n-t,r)+n:e}function e6(e,[t,n],[r,o]){const[[s,i],[a,c]]=e;return[I1(t,s,i,r),I1(n,a,c,o)]}function t6(e,t){if(typeof e!="object"||e===null)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function n6(e){var t=t6(e,"string");return typeof t=="symbol"?t:String(t)}function qt(e,t,n){return t=n6(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function at(e){for(var t=1;t{var n,r;return t.target===e.currentTarget||((n=e.currentTarget)===null||n===void 0||(r=n.contains)===null||r===void 0?void 0:r.call(n,t.target))})}function US(e,t){try{const n=t.clientX-e.clientX,r=t.clientY-e.clientY,o=(t.clientX+e.clientX)/2,s=(t.clientY+e.clientY)/2,i=Math.hypot(n,r);return{angle:-(Math.atan2(n,r)*180)/Math.PI,distance:i,origin:[o,s]}}catch{}return null}function d6(e){return u6(e).map(t=>t.identifier)}function k1(e,t){const[n,r]=Array.from(e.touches).filter(o=>t.includes(o.identifier));return US(n,r)}const T1=40,$1=800;function Jk(e){let{deltaX:t,deltaY:n,deltaMode:r}=e;return r===1?(t*=T1,n*=T1):r===2&&(t*=$1,n*=$1),[t,n]}function h6(e){const t={};if("buttons"in e&&(t.buttons=e.buttons),"shiftKey"in e){const{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s}=e;Object.assign(t,{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s})}return t}function Xp(e,...t){return typeof e=="function"?e(...t):e}function p6(){}function f6(...e){return e.length===0?p6:e.length===1?e[0]:function(){let t;for(const n of e)t=n.apply(this,arguments)||t;return t}}function M1(e,t){return Object.assign({},t,e||{})}const g6=32;class e2{constructor(t,n,r){this.ctrl=t,this.args=n,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(t){this.ctrl.state[this.key]=t}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:t,shared:n,ingKey:r,args:o}=this;n[r]=t._active=t.active=t._blocked=t._force=!1,t._step=[!1,!1],t.intentional=!1,t._movement=[0,0],t._distance=[0,0],t._direction=[0,0],t._delta=[0,0],t._bounds=[[-1/0,1/0],[-1/0,1/0]],t.args=o,t.axis=void 0,t.memo=void 0,t.elapsedTime=t.timeDelta=0,t.direction=[0,0],t.distance=[0,0],t.overflow=[0,0],t._movementBound=[!1,!1],t.velocity=[0,0],t.movement=[0,0],t.delta=[0,0],t.timeStamp=0}start(t){const n=this.state,r=this.config;n._active||(this.reset(),this.computeInitial(),n._active=!0,n.target=t.target,n.currentTarget=t.currentTarget,n.lastOffset=r.from?Xp(r.from,n):n.offset,n.offset=n.lastOffset,n.startTime=n.timeStamp=t.timeStamp)}computeValues(t){const n=this.state;n._values=t,n.values=this.config.transform(t)}computeInitial(){const t=this.state;t._initial=t._values,t.initial=t.values}compute(t){const{state:n,config:r,shared:o}=this;n.args=this.args;let s=0;if(t&&(n.event=t,r.preventDefault&&t.cancelable&&n.event.preventDefault(),n.type=t.type,o.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,o.locked=!!document.pointerLockElement,Object.assign(o,h6(t)),o.down=o.pressed=o.buttons%2===1||o.touches>0,s=t.timeStamp-n.timeStamp,n.timeStamp=t.timeStamp,n.elapsedTime=n.timeStamp-n.startTime),n._active){const I=n._delta.map(Math.abs);zt.addTo(n._distance,I)}this.axisIntent&&this.axisIntent(t);const[i,a]=n._movement,[c,l]=r.threshold,{_step:u,values:d}=n;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=c&&d[0]),u[1]===!1&&(u[1]=Math.abs(a)>=l&&d[1])):(u[0]===!1&&(u[0]=Math.abs(i)>=c&&Math.sign(i)*c),u[1]===!1&&(u[1]=Math.abs(a)>=l&&Math.sign(a)*l)),n.intentional=u[0]!==!1||u[1]!==!1,!n.intentional)return;const p=[0,0];if(r.hasCustomTransform){const[I,_]=d;p[0]=u[0]!==!1?I-u[0]:0,p[1]=u[1]!==!1?_-u[1]:0}else p[0]=u[0]!==!1?i-u[0]:0,p[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!n._blocked&&this.restrictToAxis(p);const f=n.offset,y=n._active&&!n._blocked||n.active;y&&(n.first=n._active&&!n.active,n.last=!n._active&&n.active,n.active=o[this.ingKey]=n._active,t&&(n.first&&("bounds"in r&&(n._bounds=Xp(r.bounds,n)),this.setup&&this.setup()),n.movement=p,this.computeOffset()));const[g,w]=n.offset,[[S,v],[b,E]]=n._bounds;n.overflow=[gv?1:0,wE?1:0],n._movementBound[0]=n.overflow[0]?n._movementBound[0]===!1?n._movement[0]:n._movementBound[0]:!1,n._movementBound[1]=n.overflow[1]?n._movementBound[1]===!1?n._movement[1]:n._movementBound[1]:!1;const C=n._active?r.rubberband||[0,0]:[0,0];if(n.offset=e6(n._bounds,n.offset,C),n.delta=zt.sub(n.offset,f),this.computeMovement(),y&&(!n.last||s>g6)){n.delta=zt.sub(n.offset,f);const I=n.delta.map(Math.abs);zt.addTo(n.distance,I),n.direction=n.delta.map(Math.sign),n._direction=n._delta.map(Math.sign),!n.first&&s>0&&(n.velocity=[I[0]/s,I[1]/s],n.timeDelta=s)}}emit(){const t=this.state,n=this.shared,r=this.config;if(t._active||this.clean(),(t._blocked||!t.intentional)&&!t._force&&!r.triggerAllEvents)return;const o=this.handler(at(at(at({},n),t),{},{[this.aliasKey]:t.values}));o!==void 0&&(t.memo=o)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function m6([e,t],n){const r=Math.abs(e),o=Math.abs(t);if(r>o&&r>n)return"x";if(o>r&&o>n)return"y"}class y6 extends e2{constructor(...t){super(...t),qt(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=zt.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=zt.sub(this.state.offset,this.state.lastOffset)}axisIntent(t){const n=this.state,r=this.config;if(!n.axis&&t){const o=typeof r.axisThreshold=="object"?r.axisThreshold[l6(t)]:r.axisThreshold;n.axis=m6(n._movement,o)}n._blocked=(r.lockDirection||!!r.axis)&&!n.axis||!!r.axis&&r.axis!==n.axis}restrictToAxis(t){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":t[1]=0;break;case"y":t[0]=0;break}}}const S6=e=>e,A1=.15,t2={enabled(e=!0){return e},eventOptions(e,t,n){return at(at({},n.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[A1,A1];case!1:return[0,0];default:return zt.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return zt.toVector(e)},transform(e,t,n){const r=e||n.shared.transform;return this.hasCustomTransform=!!r,r||S6},threshold(e){return zt.toVector(e,0)}},v6=0,ju=at(at({},t2),{},{axis(e,t,{axis:n}){if(this.lockDirection=n==="lock",!this.lockDirection)return n},axisThreshold(e=v6){return e},bounds(e={}){if(typeof e=="function")return s=>ju.bounds(e(s));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:t=-1/0,right:n=1/0,top:r=-1/0,bottom:o=1/0}=e;return[[t,n],[r,o]]}}),Ou=typeof window<"u"&&window.document&&window.document.createElement;function n2(){return Ou&&"ontouchstart"in window}function x6(){return n2()||Ou&&window.navigator.maxTouchPoints>1}function w6(){return Ou&&"onpointerdown"in window}function b6(){return Ou&&"exitPointerLock"in window.document}function P6(){try{return"constructor"in GestureEvent}catch{return!1}}const pr={isBrowser:Ou,gesture:P6(),touch:n2(),touchscreen:x6(),pointer:w6(),pointerLock:b6()},C6=250,I6=180,E6=.5,_6=50,k6=250,T6=10,j1={mouse:0,touch:0,pen:8};at(at({},ju),{},{device(e,t,{pointer:{touch:n=!1,lock:r=!1,mouse:o=!1}={}}){return this.pointerLock=r&&pr.pointerLock,pr.touch&&n?"touch":this.pointerLock?"mouse":pr.pointer&&!o?"pointer":pr.touch?"touch":"mouse"},preventScrollAxis(e,t,{preventScroll:n}){if(this.preventScrollDelay=typeof n=="number"?n:n||n===void 0&&e?C6:void 0,!(!pr.touchscreen||n===!1))return e||(n!==void 0?"y":void 0)},pointerCapture(e,t,{pointer:{capture:n=!0,buttons:r=1,keys:o=!0}={}}){return this.pointerButtons=r,this.keys=o,!this.pointerLock&&this.device==="pointer"&&n},threshold(e,t,{filterTaps:n=!1,tapsThreshold:r=3,axis:o=void 0}){const s=zt.toVector(e,n?r:o?1:0);return this.filterTaps=n,this.tapsThreshold=r,s},swipe({velocity:e=E6,distance:t=_6,duration:n=k6}={}){return{velocity:this.transform(zt.toVector(e)),distance:this.transform(zt.toVector(t)),duration:n}},delay(e=0){switch(e){case!0:return I6;case!1:return 0;default:return e}},axisThreshold(e){return e?at(at({},j1),e):j1},keyboardDisplacement(e=T6){return e}});function r2(e){const[t,n]=e.overflow,[r,o]=e._delta,[s,i]=e._direction;(t<0&&r>0&&s<0||t>0&&r<0&&s>0)&&(e._movement[0]=e._movementBound[0]),(n<0&&o>0&&i<0||n>0&&o<0&&i>0)&&(e._movement[1]=e._movementBound[1])}const $6=30,M6=100;class A6 extends e2{constructor(...t){super(...t),qt(this,"ingKey","pinching"),qt(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const t=this.state;t._touchIds=[],t.canceled=!1,t.cancel=this.cancel.bind(this),t.turns=0}computeOffset(){const{type:t,movement:n,lastOffset:r}=this.state;t==="wheel"?this.state.offset=zt.add(n,r):this.state.offset=[(1+n[0])*r[0],n[1]+r[1]]}computeMovement(){const{offset:t,lastOffset:n}=this.state;this.state.movement=[t[0]/n[0],t[1]-n[1]]}axisIntent(){const t=this.state,[n,r]=t._movement;if(!t.axis){const o=Math.abs(n)*$6-Math.abs(r);o<0?t.axis="angle":o>0&&(t.axis="scale")}}restrictToAxis(t){this.config.lockDirection&&(this.state.axis==="scale"?t[1]=0:this.state.axis==="angle"&&(t[0]=0))}cancel(){const t=this.state;t.canceled||setTimeout(()=>{t.canceled=!0,t._active=!1,this.compute(),this.emit()},0)}touchStart(t){this.ctrl.setEventIds(t);const n=this.state,r=this.ctrl.touchIds;if(n._active&&n._touchIds.every(s=>r.has(s))||r.size<2)return;this.start(t),n._touchIds=Array.from(r).slice(0,2);const o=k1(t,n._touchIds);o&&this.pinchStart(t,o)}pointerStart(t){if(t.buttons!=null&&t.buttons%2!==1)return;this.ctrl.setEventIds(t),t.target.setPointerCapture(t.pointerId);const n=this.state,r=n._pointerEvents,o=this.ctrl.pointerIds;if(n._active&&Array.from(r.keys()).every(i=>o.has(i))||(r.size<2&&r.set(t.pointerId,t),n._pointerEvents.size<2))return;this.start(t);const s=US(...Array.from(r.values()));s&&this.pinchStart(t,s)}pinchStart(t,n){const r=this.state;r.origin=n.origin,this.computeValues([n.distance,n.angle]),this.computeInitial(),this.compute(t),this.emit()}touchMove(t){if(!this.state._active)return;const n=k1(t,this.state._touchIds);n&&this.pinchMove(t,n)}pointerMove(t){const n=this.state._pointerEvents;if(n.has(t.pointerId)&&n.set(t.pointerId,t),!this.state._active)return;const r=US(...Array.from(n.values()));r&&this.pinchMove(t,r)}pinchMove(t,n){const r=this.state,o=r._values[1],s=n.angle-o;let i=0;Math.abs(s)>270&&(i+=Math.sign(s)),this.computeValues([n.distance,n.angle-360*i]),r.origin=n.origin,r.turns=i,r._movement=[r._values[0]/r._initial[0]-1,r._values[1]-r._initial[1]],this.compute(t),this.emit()}touchEnd(t){this.ctrl.setEventIds(t),this.state._active&&this.state._touchIds.some(n=>!this.ctrl.touchIds.has(n))&&(this.state._active=!1,this.compute(t),this.emit())}pointerEnd(t){const n=this.state;this.ctrl.setEventIds(t);try{t.target.releasePointerCapture(t.pointerId)}catch{}n._pointerEvents.has(t.pointerId)&&n._pointerEvents.delete(t.pointerId),n._active&&n._pointerEvents.size<2&&(n._active=!1,this.compute(t),this.emit())}gestureStart(t){t.cancelable&&t.preventDefault();const n=this.state;n._active||(this.start(t),this.computeValues([t.scale,t.rotation]),n.origin=[t.clientX,t.clientY],this.compute(t),this.emit())}gestureMove(t){if(t.cancelable&&t.preventDefault(),!this.state._active)return;const n=this.state;this.computeValues([t.scale,t.rotation]),n.origin=[t.clientX,t.clientY];const r=n._movement;n._movement=[t.scale-1,t.rotation],n._delta=zt.sub(n._movement,r),this.compute(t),this.emit()}gestureEnd(t){this.state._active&&(this.state._active=!1,this.compute(t),this.emit())}wheel(t){const n=this.config.modifierKey;n&&(Array.isArray(n)?!n.find(r=>t[r]):!t[n])||(this.state._active?this.wheelChange(t):this.wheelStart(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(t){this.start(t),this.wheelChange(t)}wheelChange(t){"uv"in t||t.cancelable&&t.preventDefault();const r=this.state;r._delta=[-Jk(t)[1]/M6*r.offset[0],0],zt.addTo(r._movement,r._delta),r2(r),this.state.origin=[t.clientX,t.clientY],this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){const n=this.config.device;n&&(t(n,"start",this[n+"Start"].bind(this)),t(n,"change",this[n+"Move"].bind(this)),t(n,"end",this[n+"End"].bind(this)),t(n,"cancel",this[n+"End"].bind(this)),t("lostPointerCapture","",this[n+"End"].bind(this))),this.config.pinchOnWheel&&t("wheel","",this.wheel.bind(this),{passive:!1})}}const j6=at(at({},t2),{},{device(e,t,{shared:n,pointer:{touch:r=!1}={}}){if(n.target&&!pr.touch&&pr.gesture)return"gesture";if(pr.touch&&r)return"touch";if(pr.touchscreen){if(pr.pointer)return"pointer";if(pr.touch)return"touch"}},bounds(e,t,{scaleBounds:n={},angleBounds:r={}}){const o=i=>{const a=M1(Xp(n,i),{min:-1/0,max:1/0});return[a.min,a.max]},s=i=>{const a=M1(Xp(r,i),{min:-1/0,max:1/0});return[a.min,a.max]};return typeof n!="function"&&typeof r!="function"?[o(),s()]:i=>[o(i),s(i)]},threshold(e,t,n){return this.lockDirection=n.axis==="lock",zt.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});at(at({},ju),{},{mouseOnly:(e=!0)=>e});class O6 extends y6{constructor(...t){super(...t),qt(this,"ingKey","wheeling")}wheel(t){this.state._active||this.start(t),this.wheelChange(t),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(t){const n=this.state;n._delta=Jk(t),zt.addTo(n._movement,n._delta),r2(n),this.compute(t),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(t){t("wheel","",this.wheel.bind(this))}}const D6=ju;at(at({},ju),{},{mouseOnly:(e=!0)=>e});const Y0=new Map,HS=new Map;function R6(e){Y0.set(e.key,e.engine),HS.set(e.key,e.resolver)}const L6={key:"pinch",engine:A6,resolver:j6},F6={key:"wheel",engine:O6,resolver:D6};function N6(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,s;for(s=0;s=0)&&(n[o]=e[o]);return n}function z6(e,t){if(e==null)return{};var n=N6(e,t),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}const B6={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=pr.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:t=!1}={}){return{passive:e,capture:t}},transform(e){return e}},U6=["target","eventOptions","window","enabled","transform"];function vh(e={},t){const n={};for(const[r,o]of Object.entries(t))switch(typeof o){case"function":n[r]=o.call(n,e[r],r,e);break;case"object":n[r]=vh(e[r],o);break;case"boolean":o&&(n[r]=e[r]);break}return n}function H6(e,t,n={}){const r=e,{target:o,eventOptions:s,window:i,enabled:a,transform:c}=r,l=z6(r,U6);if(n.shared=vh({target:o,eventOptions:s,window:i,enabled:a,transform:c},B6),t){const u=HS.get(t);n[t]=vh(at({shared:n.shared},l),u)}else for(const u in l){const d=HS.get(u);d&&(n[u]=vh(at({shared:n.shared},l[u]),d))}return n}class o2{constructor(t,n){qt(this,"_listeners",new Set),this._ctrl=t,this._gestureKey=n}add(t,n,r,o,s){const i=this._listeners,a=c6(n,r),c=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},l=at(at({},c),s);t.addEventListener(a,o,l);const u=()=>{t.removeEventListener(a,o,l),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(t=>t()),this._listeners.clear()}}class K6{constructor(){qt(this,"_timeouts",new Map)}add(t,n,r=140,...o){this.remove(t),this._timeouts.set(t,window.setTimeout(n,r,...o))}remove(t){const n=this._timeouts.get(t);n&&window.clearTimeout(n)}clean(){this._timeouts.forEach(t=>void window.clearTimeout(t)),this._timeouts.clear()}}class W6{constructor(t){qt(this,"gestures",new Set),qt(this,"_targetEventStore",new o2(this)),qt(this,"gestureEventStores",{}),qt(this,"gestureTimeoutStores",{}),qt(this,"handlers",{}),qt(this,"config",{}),qt(this,"pointerIds",new Set),qt(this,"touchIds",new Set),qt(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),V6(this,t)}setEventIds(t){if(Qk(t))return this.touchIds=new Set(d6(t)),this.touchIds;if("pointerId"in t)return t.type==="pointerup"||t.type==="pointercancel"?this.pointerIds.delete(t.pointerId):t.type==="pointerdown"&&this.pointerIds.add(t.pointerId),this.pointerIds}applyHandlers(t,n){this.handlers=t,this.nativeHandlers=n}applyConfig(t,n){this.config=H6(t,n,this.config)}clean(){this._targetEventStore.clean();for(const t of this.gestures)this.gestureEventStores[t].clean(),this.gestureTimeoutStores[t].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...t){const n=this.config.shared,r={};let o;if(!(n.target&&(o=n.target(),!o))){if(n.enabled){for(const i of this.gestures){const a=this.config[i],c=O1(r,a.eventOptions,!!o);if(a.enabled){const l=Y0.get(i);new l(this,t,i).bind(c)}}const s=O1(r,n.eventOptions,!!o);for(const i in this.nativeHandlers)s(i,"",a=>this.nativeHandlers[i](at(at({},this.state.shared),{},{event:a,args:t})),void 0,!0)}for(const s in r)r[s]=f6(...r[s]);if(!o)return r;for(const s in r){const{device:i,capture:a,passive:c}=a6(s);this._targetEventStore.add(o,i,"",r[s],{capture:a,passive:c})}}}}function na(e,t){e.gestures.add(t),e.gestureEventStores[t]=new o2(e,t),e.gestureTimeoutStores[t]=new K6}function V6(e,t){t.drag&&na(e,"drag"),t.wheel&&na(e,"wheel"),t.scroll&&na(e,"scroll"),t.move&&na(e,"move"),t.pinch&&na(e,"pinch"),t.hover&&na(e,"hover")}const O1=(e,t,n)=>(r,o,s,i={},a=!1)=>{var c,l;const u=(c=i.capture)!==null&&c!==void 0?c:t.capture,d=(l=i.passive)!==null&&l!==void 0?l:t.passive;let p=a?r:s6(r,o,u);n&&d&&(p+="Passive"),e[p]=e[p]||[],e[p].push(s)},G6=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function Y6(e){const t={},n={},r=new Set;for(let o in e)G6.test(o)?(r.add(RegExp.lastMatch),n[o]=e[o]):t[o]=e[o];return[n,t,r]}function ra(e,t,n,r,o,s){if(!e.has(n)||!Y0.has(r))return;const i=n+"Start",a=n+"End",c=l=>{let u;return l.first&&i in t&&t[i](l),n in t&&(u=t[n](l)),l.last&&a in t&&t[a](l),u};o[r]=c,s[r]=s[r]||{}}function X6(e,t){const[n,r,o]=Y6(e),s={};return ra(o,n,"onDrag","drag",s,t),ra(o,n,"onWheel","wheel",s,t),ra(o,n,"onScroll","scroll",s,t),ra(o,n,"onPinch","pinch",s,t),ra(o,n,"onMove","move",s,t),ra(o,n,"onHover","hover",s,t),{handlers:s,config:t,nativeHandlers:r}}function q6(e,t={},n,r){const o=Se.useMemo(()=>new W6(e),[]);if(o.applyHandlers(e,r),o.applyConfig(t,n),Se.useEffect(o.effect.bind(o)),Se.useEffect(()=>o.clean.bind(o),[]),t.target===void 0)return o.bind.bind(o)}function Z6(e){return e.forEach(R6),function(n,r){const{handlers:o,nativeHandlers:s,config:i}=X6(n,r||{});return q6(o,i,void 0,s)}}const D1=10,Q6=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function s2(e){let{deltaY:t,deltaX:n}=e,r=0;if(e.ctrlKey||e.altKey||e.metaKey){const o=Math.sign(e.deltaY),s=Math.abs(e.deltaY);let i=t;s>D1&&(i=D1*o),r=i/100}else e.shiftKey&&!Q6&&(n=t,t=0);return{x:-n,y:-t,z:-r}}const J6=Z6([F6,L6]);let oa;const eF=e=>oa===void 0?(oa=e,!1):e-oa>120&&e-oa<160?(oa=e,!0):(oa=e,!1);function tF(e){const t=z(),n=x.useMemo(()=>{let r="not sure";const o=({event:g})=>{if(!t.getInstanceState().isFocused||(r="not sure",eF(Date.now())))return;const w=t.getEditingShapeId();if(w){const b=t.getShape(w);if(b&&t.getShapeUtil(b).canScroll(b)){const C=t.getShapePageBounds(w);if(C!=null&&C.containsPoint(t.inputs.currentPagePoint))return}}Ee(g),Ut(g);const S=s2(g);if(S.x===0&&S.y===0)return;const v={type:"wheel",name:"wheel",delta:S,point:new P(g.clientX,g.clientY),shiftKey:g.shiftKey,altKey:g.altKey,ctrlKey:g.metaKey||g.ctrlKey};t.dispatch(v)};let s=1,i=1,a=1,c=0;const l=new P,u=new P,d=g=>{const w=e.current;r="not sure";const{event:S,origin:v,da:b}=g;S instanceof WheelEvent||(S.target===w||w!=null&&w.contains(S.target))&&(u.x=v[0],u.y=v[1],l.x=v[0],l.y=v[1],s=b[0],i=t.getZoomLevel(),t.dispatch({type:"pinch",name:"pinch_start",point:{x:v[0],y:v[1],z:t.getZoomLevel()},delta:{x:0,y:0},shiftKey:S.shiftKey,altKey:S.altKey,ctrlKey:S.metaKey||S.ctrlKey}))},p=g=>{if(g&&(r="zooming"),r==="zooming")return;const w=Math.abs(c-s),S=P.Dist(l,u);switch(r){case"not sure":{w>24?r="zooming":S>16&&(r="panning");break}case"panning":{w>64&&(r="zooming");break}}};return{onWheel:o,onPinchStart:d,onPinchEnd:g=>{const w=e.current,{event:S,origin:v,offset:b}=g;if(S instanceof WheelEvent||!(S.target===w||w!=null&&w.contains(S.target)))return;const E=b[0];r="not sure",requestAnimationFrame(()=>{t.dispatch({type:"pinch",name:"pinch_end",point:{x:v[0],y:v[1],z:E},delta:{x:v[0],y:v[1]},shiftKey:S.shiftKey,altKey:S.altKey,ctrlKey:S.metaKey||S.ctrlKey})})},onPinch:g=>{const w=e.current,{event:S,origin:v,offset:b,da:E}=g;if(S instanceof WheelEvent||!(S.target===w||w!=null&&w.contains(S.target)))return;const C=g.type==="gesturechange"||g.type==="gestureend";c=E[0];const I=v[0]-u.x,_=v[1]-u.y;switch(u.x=v[0],u.y=v[1],p(C),r){case"zooming":{a=b[0],t.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:a},delta:{x:I,y:_},shiftKey:S.shiftKey,altKey:S.altKey,ctrlKey:S.metaKey||S.ctrlKey});break}case"panning":{t.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:i},delta:{x:I,y:_},shiftKey:S.shiftKey,altKey:S.altKey,ctrlKey:S.metaKey||S.ctrlKey});break}}}}},[t,e]);J6(n,{target:e,eventOptions:{passive:!1},pinch:{from:()=>[t.getZoomLevel(),0],scaleBounds:()=>({from:t.getZoomLevel(),max:8,min:.05})}})}function hm(e,t,n){const r=e.getShape(t),o=e.getShapeHandles(r);return{shape:r,handle:o.find(s=>s.id===n)}}function nF(e,t){const n=z();return x.useMemo(()=>{const r=c=>{if(c.isKilled)return;const l=Yp(c.currentTarget);Mu(l,c);const{shape:u,handle:d}=hm(n,e,t);d&&n.dispatch({type:"pointer",target:"handle",handle:d,shape:u,name:"pointer_down",..._n(c)})};let o,s;return{onPointerDown:r,onPointerMove:c=>{if(c.isKilled||c.clientX===o&&c.clientY===s)return;o=c.clientX,s=c.clientY;const{shape:l,handle:u}=hm(n,e,t);u&&n.dispatch({type:"pointer",target:"handle",handle:u,shape:l,name:"pointer_move",..._n(c)})},onPointerUp:c=>{if(c.isKilled)return;const l=Yp(c.currentTarget);Au(l,c);const{shape:u,handle:d}=hm(n,e,t);d&&n.dispatch({type:"pointer",target:"handle",handle:d,shape:u,name:"pointer_up",..._n(c)})}}},[n,e,t])}var i2="Expected a function",R1=NaN,rF="[object Symbol]",oF=/^\s+|\s+$/g,sF=/^[-+]0x[0-9a-f]+$/i,iF=/^0b[01]+$/i,aF=/^0o[0-7]+$/i,cF=parseInt,lF=typeof tn=="object"&&tn&&tn.Object===Object&&tn,uF=typeof self=="object"&&self&&self.Object===Object&&self,dF=lF||uF||Function("return this")(),hF=Object.prototype,pF=hF.toString,fF=Math.max,gF=Math.min,pm=function(){return dF.Date.now()};function mF(e,t,n){var r,o,s,i,a,c,l=0,u=!1,d=!1,p=!0;if(typeof e!="function")throw new TypeError(i2);t=L1(t)||0,qp(n)&&(u=!!n.leading,d="maxWait"in n,s=d?fF(L1(n.maxWait)||0,t):s,p="trailing"in n?!!n.trailing:p);function f(I){var _=r,k=o;return r=o=void 0,l=I,i=e.apply(k,_),i}function y(I){return l=I,a=setTimeout(S,t),u?f(I):i}function g(I){var _=I-c,k=I-l,$=t-_;return d?gF($,s-k):$}function w(I){var _=I-c,k=I-l;return c===void 0||_>=t||_<0||d&&k>=s}function S(){var I=pm();if(w(I))return v(I);a=setTimeout(S,g(I))}function v(I){return a=void 0,p&&r?f(I):(r=o=void 0,i)}function b(){a!==void 0&&clearTimeout(a),l=0,r=c=o=a=void 0}function E(){return a===void 0?i:v(pm())}function C(){var I=pm(),_=w(I);if(r=arguments,o=this,c=I,_){if(a===void 0)return y(c);if(d)return a=setTimeout(S,t),f(c)}return a===void 0&&(a=setTimeout(S,t)),i}return C.cancel=b,C.flush=E,C}function yF(e,t,n){var r=!0,o=!0;if(typeof e!="function")throw new TypeError(i2);return qp(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),mF(e,t,{leading:r,maxWait:t,trailing:o})}function qp(e){var t=typeof e;return!!e&&(t=="object"||t=="function")}function SF(e){return!!e&&typeof e=="object"}function vF(e){return typeof e=="symbol"||SF(e)&&pF.call(e)==rF}function L1(e){if(typeof e=="number")return e;if(vF(e))return R1;if(qp(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=qp(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=e.replace(oF,"");var n=iF.test(e);return n||aF.test(e)?cF(e.slice(2),n?2:8):sF.test(e)?R1:+e}var xF=yF;const wF=pc(xF),Je=class Je{constructor(t=0,n=0,r=0,o=0){m(this,"x",0);m(this,"y",0);m(this,"w",0);m(this,"h",0);this.x=t,this.y=n,this.w=r,this.h=o}get point(){return new P(this.x,this.y)}set point(t){this.x=t.x,this.y=t.y}get minX(){return this.x}set minX(t){this.x=t}get midX(){return this.x+this.w/2}get maxX(){return this.x+this.w}get minY(){return this.y}set minY(t){this.y=t}get midY(){return this.y+this.h/2}get maxY(){return this.y+this.h}get width(){return this.w}set width(t){this.w=t}get height(){return this.h}set height(t){this.h=t}get aspectRatio(){return this.width/this.height}get center(){return new P(this.midX,this.midY)}set center(t){this.minX=t.x-this.width/2,this.minY=t.y-this.height/2}get corners(){return[new P(this.minX,this.minY),new P(this.maxX,this.minY),new P(this.maxX,this.maxY),new P(this.minX,this.maxY)]}get cornersAndCenter(){return[new P(this.minX,this.minY),new P(this.maxX,this.minY),new P(this.maxX,this.maxY),new P(this.minX,this.maxY),this.center]}get sides(){const{corners:t}=this;return[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]]}get size(){return new P(this.w,this.h)}toFixed(){return this.x=bd(this.x),this.y=bd(this.y),this.w=bd(this.w),this.h=bd(this.h),this}setTo(t){return this.x=t.x,this.y=t.y,this.w=t.w,this.h=t.h,this}set(t=0,n=0,r=0,o=0){return this.x=t,this.y=n,this.w=r,this.h=o,this}expand(t){const n=Math.min(this.minX,t.minX),r=Math.min(this.minY,t.minY),o=Math.max(this.maxX,t.maxX),s=Math.max(this.maxY,t.maxY);return this.x=n,this.y=r,this.w=o-n,this.h=s-r,this}expandBy(t){return this.x-=t,this.y-=t,this.w+=t*2,this.h+=t*2,this}scale(t){return this.x/=t,this.y/=t,this.w/=t,this.h/=t,this}clone(){const{x:t,y:n,w:r,h:o}=this;return new Je(t,n,r,o)}translate(t){return this.x+=t.x,this.y+=t.y,this}snapToGrid(t){const n=Math.round(this.minX/t)*t,r=Math.round(this.minY/t)*t,o=Math.round(this.maxX/t)*t,s=Math.round(this.maxY/t)*t;this.minX=n,this.minY=r,this.width=Math.max(1,o-n),this.height=Math.max(1,s-r)}collides(t){return Je.Collides(this,t)}contains(t){return Je.Contains(this,t)}includes(t){return Je.Includes(this,t)}containsPoint(t,n=0){return Je.ContainsPoint(this,t,n)}getHandlePoint(t){switch(t){case"top_left":return new P(this.minX,this.minY);case"top_right":return new P(this.maxX,this.minY);case"bottom_left":return new P(this.minX,this.maxY);case"bottom_right":return new P(this.maxX,this.maxY);case"top":return new P(this.midX,this.minY);case"right":return new P(this.maxX,this.midY);case"bottom":return new P(this.midX,this.maxY);case"left":return new P(this.minX,this.midY)}}toJson(){return{x:this.minX,y:this.minY,w:this.w,h:this.h}}resize(t,n,r){const{minX:o,minY:s,maxX:i,maxY:a}=this;let{minX:c,minY:l,maxX:u,maxY:d}=this;switch(t){case"left":case"top_left":case"bottom_left":{c+=n;break}case"right":case"top_right":case"bottom_right":{u+=n;break}}switch(t){case"top":case"top_left":case"top_right":{l+=r;break}case"bottom":case"bottom_left":case"bottom_right":{d+=r;break}}const p=(u-c)/(i-o),f=(d-l)/(a-s),y=p<0,g=f<0;if(y){const w=u;u=c,c=w}if(g){const w=d;d=l,l=w}this.minX=c,this.minY=l,this.width=Math.abs(u-c),this.height=Math.abs(d-l)}union(t){const n=Math.min(this.minX,t.x),r=Math.min(this.minY,t.y),o=Math.max(this.maxX,t.w+t.x),s=Math.max(this.maxY,t.h+t.y);return this.x=n,this.y=r,this.width=o-n,this.height=s-r,this}static From(t){return new Je(t.x,t.y,t.w,t.h)}static FromCenter(t,n){return new Je(t.x-n.x/2,t.y-n.y/2,n.x,n.y)}static FromPoints(t){if(t.length===0)return new Je;let n=1/0,r=1/0,o=-1/0,s=-1/0,i;for(let a=0,c=t.length;a0?1:-1)).toFixed(5),scaleY:+(v.height/t.height*(g>0?1:-1)).toFixed(5)}}equals(t){return Je.Equals(this,t)}static Equals(t,n){return n.x===t.x&&n.y===t.y&&n.w===t.w&&n.h===t.h}zeroFix(){return this.w=Math.max(1,this.w),this.h=Math.max(1,this.h),this}static ZeroFix(t){return new Je(t.x,t.y,Math.max(1,t.w),Math.max(1,t.h))}};m(Je,"Collides",(t,n)=>!(t.maxXn.maxX||t.maxYn.maxY)),m(Je,"Contains",(t,n)=>t.minXn.maxY&&t.maxX>n.maxX),m(Je,"Includes",(t,n)=>Je.Collides(t,n)||Je.Contains(t,n)),m(Je,"ContainsPoint",(t,n,r=0)=>!(n.xt.maxX+r||n.y>t.maxY+r)),m(Je,"Common",t=>{let n=1/0,r=1/0,o=-1/0,s=-1/0;for(let i=0;i{const{corners:r}=t;return[[r[0],r[1]],[r[1],r[2]],[r[2],r[3]],[r[3],r[0]]]});let ne=Je;function bF(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 PF(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 CF(e){return e==="top_left"||e==="top_right"||e==="bottom_right"||e==="bottom_left"}function IF(e){const t=z();x.useLayoutEffect(()=>{let n=new ne;function r(){const l=e.current;if(!l)return null;const u=l.getBoundingClientRect(),d=new ne(u.left||u.x,u.top||u.y,Math.max(u.width,1),Math.max(u.height,1));n.equals(d)||(t.updateViewportScreenBounds(d),n=d)}r();const o=wF(r,200,{trailing:!0}),s=setInterval(o,1e3);window.addEventListener("resize",o);const i=new ResizeObserver(l=>{l[0].contentRect&&o()}),a=e.current;let c=null;return a&&(i.observe(a),c=EF(a),c.addEventListener("scroll",o)),()=>{clearInterval(s),window.removeEventListener("resize",o),i.disconnect(),c==null||c.removeEventListener("scroll",o)}},[t,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 EF=e=>{let t=e.parentElement;for(;t;){if(t===document.body)return document;const{overflowY:n}=window.getComputedStyle(t);if(t.scrollHeight>t.clientHeight&&(n==="auto"||n==="scroll"||n==="overlay"))return t;t=t.parentElement}return document},je=class je{constructor(t,n,r,o,s,i){m(this,"a",1);m(this,"b",0);m(this,"c",0);m(this,"d",1);m(this,"e",0);m(this,"f",0);this.a=t,this.b=n,this.c=r,this.d=o,this.e=s,this.f=i}equals(t){return this===t||this.a===t.a&&this.b===t.b&&this.c===t.c&&this.d===t.d&&this.e===t.e&&this.f===t.f}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this}multiply(t){const n=t,{a:r,b:o,c:s,d:i,e:a,f:c}=this;return this.a=r*n.a+s*n.b,this.c=r*n.c+s*n.d,this.e=r*n.e+s*n.f+a,this.b=o*n.a+i*n.b,this.d=o*n.c+i*n.d,this.f=o*n.e+i*n.f+c,this}rotate(t,n,r){return t===0?this:n===void 0?this.multiply(je.Rotate(t)):this.translate(n,r).multiply(je.Rotate(t)).translate(-n,-r)}translate(t,n){return this.multiply(je.Translate(t,n))}scale(t,n){return this.multiply(je.Scale(t,n))}invert(){const{a:t,b:n,c:r,d:o,e:s,f:i}=this,a=t*o-n*r;return this.a=o/a,this.b=n/-a,this.c=r/-a,this.d=t/a,this.e=(o*s-r*i)/-a,this.f=(n*s-t*i)/a,this}applyToPoint(t){return je.applyToPoint(this,t)}applyToPoints(t){return je.applyToPoints(this,t)}rotation(){return je.Rotation(this)}point(){return je.Point(this)}decomposed(){return je.Decompose(this)}toCssString(){return je.toCssString(this)}setTo(t){return Object.assign(this,t),this}decompose(){return je.Decompose(this)}clone(){return new je(this.a,this.b,this.c,this.d,this.e,this.f)}static Identity(){return new je(1,0,0,1,0,0)}static Translate(t,n){return new je(1,0,0,1,t,n)}static Rotate(t,n,r){if(t===0)return je.Identity();const o=Math.cos(t),s=Math.sin(t),i=new je(o,s,-s,o,0,0);return n===void 0?i:je.Compose(je.Translate(n,r),i,je.Translate(-n,-r))}static Multiply(t,n){return{a:t.a*n.a+t.c*n.b,c:t.a*n.c+t.c*n.d,e:t.a*n.e+t.c*n.f+t.e,b:t.b*n.a+t.d*n.b,d:t.b*n.c+t.d*n.d,f:t.b*n.e+t.d*n.f+t.f}}static Inverse(t){const n=t.a*t.d-t.b*t.c;return{a:t.d/n,b:t.b/-n,c:t.c/-n,d:t.a/n,e:(t.d*t.e-t.c*t.f)/-n,f:(t.b*t.e-t.a*t.f)/n}}static Absolute(t){const n=t.a*t.d-t.b*t.c;return{a:t.d/n,b:t.b/-n,c:t.c/-n,d:t.a/n,e:(t.d*t.e-t.c*t.f)/n,f:(t.b*t.e-t.a*t.f)/-n}}static Compose(...t){const n=je.Identity();for(let r=0,o=t.length;r0?-1:1)}else if(t.b!==0||t.d!==0){const r=(t.b*t.b+t.d*t.d)**.5;n=ze+Math.acos(t.b/r)*(t.d>0?-1:1)}else n=0;return NS(n)}static Decompose(t){let n,r,o;if(t.a!==0||t.c!==0){const s=(t.a*t.a+t.c*t.c)**.5;n=s,r=(t.a*t.d-t.b*t.c)/s,o=Math.acos(t.a/s)*(t.c>0?-1:1)}else if(t.b!==0||t.d!==0){const s=(t.b*t.b+t.d*t.d)**.5;n=(t.a*t.d-t.b*t.c)/s,r=s,o=ze+Math.acos(t.b/s)*(t.d>0?-1:1)}else n=0,r=0,o=0;return{x:t.e,y:t.f,scaleX:n,scaleY:r,rotation:NS(o)}}static Smooth(t,n=1e10){return t.a=Math.round(t.a*n)/n,t.b=Math.round(t.b*n)/n,t.c=Math.round(t.c*n)/n,t.d=Math.round(t.d*n)/n,t.e=Math.round(t.e*n)/n,t.f=Math.round(t.f*n)/n,t}static toCssString(t){return`matrix(${j(t.a)}, ${j(t.b)}, ${j(t.c)}, ${j(t.d)}, ${j(t.e)}, ${j(t.f)})`}static applyToPoint(t,n){return new P(t.a*n.x+t.c*n.y+t.e,t.b*n.x+t.d*n.y+t.f,n.z)}static applyToXY(t,n,r){return[t.a*n+t.c*r+t.e,t.b*n+t.d*r+t.f]}static applyToPoints(t,n){return n.map(r=>new P(t.a*r.x+t.c*r.y+t.e,t.b*r.x+t.d*r.y+t.f,r.z))}static applyToBounds(t,n){return new ne(t.e+n.minX,t.f+n.minY,n.width,n.height)}static From(t){return new je(t.a,t.b,t.c,t.d,t.e,t.f)}static Cast(t){return t instanceof je?t:je.From(t)}};m(je,"Scale",(t,n,r,o)=>{const s=new je(t,0,0,n,0,0);return r===void 0?s:je.Compose(je.Translate(r,o),s,je.Translate(-r,-o))});let oe=je;function a2(e,t){return t===0?e:a2(t,e%t)}function c2(e){const t=e.toString().split(".")[1];if(!t)return 1;const n=Math.pow(10,t.length),r=parseInt(t,10);return n/a2(r,n)}class Hi{constructor(t){m(this,"isFilled",!1);m(this,"isClosed",!0);m(this,"isLabel",!1);m(this,"debugColor");m(this,"ignore");m(this,"_vertices");m(this,"_bounds");m(this,"_area");this.isFilled=t.isFilled,this.isClosed=t.isClosed,this.isLabel=t.isLabel??!1,this.debugColor=t.debugColor,this.ignore=t.ignore}hitTestPoint(t,n=0,r=!1){return this.isClosed&&(this.isFilled||r)&&Zn(t,this.vertices)?!0:P.Dist2(t,this.nearestPoint(t))<=n*n}distanceToPoint(t,n=!1){return t.dist(this.nearestPoint(t))*(this.isClosed&&(this.isFilled||n)&&Zn(t,this.vertices)?-1:1)}distanceToLineSegment(t,n){if(t.equals(n))return this.distanceToPoint(t);const{vertices:r}=this;let o,s=1/0,i,a,c;for(let l=0;lr.maxX+n||t.y>r.maxY+n)}get vertices(){return this._vertices||(this._vertices=this.getVertices()),this._vertices}getBounds(){return ne.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:t}=this;let n=0;for(let r=0,o=t.length;r!n.isLabel).flatMap(n=>n.vertices)}nearestPoint(n){let r=1/0,o;const{children:s}=this;if(s.length===0)throw Error("no children");let i,a;for(const c of s)i=c.nearestPoint(n),a=P.Dist2(i,n),ao.distanceToPoint(n,r||s>0)))}hitTestPoint(n,r,o){return!!this.children.filter(s=>!s.isLabel).find(s=>s.hitTestPoint(n,r,o))}hitTestLineSegment(n,r,o){return!!this.children.filter(s=>!s.isLabel).find(s=>s.hitTestLineSegment(n,r,o))}getArea(){return this.children[0].area}toSimpleSvgPath(){let n="";for(const o of this.children)n+=o.toSimpleSvgPath();const r=ne.FromPoints(this.vertices).corners;for(let o=0,s=r.length;o{if(!e)return;const o=()=>n(s=>s+1);return r.on("tick",o),()=>{r.off("tick",o)}},[r,e])}const kF=or(function({showStroke:t=!0,showVertices:n=!0,showClosestPointOnOutline:r=!0}){const o=z();_F(r);const s=o.getZoomLevel(),i=o.getRenderingShapes(),{inputs:{currentPagePoint:a}}=o;return h.jsx("svg",{style:{position:"absolute",pointerEvents:"none",zIndex:999999999,top:0,left:0,overflow:"visible"},children:i.map(c=>{const l=o.getShape(c.id);if(l.type==="group")return null;const u=o.getShapeGeometry(l),d=o.getShapePageTransform(l),p=o.getPointInShapeSpace(l,a),f=u.nearestPoint(p),y=u.distanceToPoint(p,!0),g=Math.abs(y)*s,w=y<0,{vertices:S}=u;return h.jsxs("g",{transform:d.toCssString(),strokeLinecap:"round",strokeLinejoin:"round",children:[t&&h.jsx(l2,{geometry:u}),n&&S.map((v,b)=>h.jsx("circle",{cx:v.x,cy:v.y,r:"2",fill:`hsl(${Ap(b,[0,S.length-1],[120,200])}, 100%, 50%)`,stroke:"black",strokeWidth:"1"},`v${b}`)),r&&g<150&&h.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,opacity:1-g/150,stroke:w?"goldenrod":"dodgerblue",strokeWidth:"2"})]},c.id+"_outline")})})});function l2({geometry:e}){return e instanceof Br?h.jsx(h.Fragment,{children:[...e.children,...e.ignoredChildren].map((t,n)=>h.jsx(l2,{geometry:t},n))}):h.jsx("path",{stroke:e.debugColor??"red",strokeWidth:"2",fill:"none",opacity:"1",d:e.toSimpleSvgPath()})}var TF=200,X0="__lodash_hash_undefined__",$F=1/0,MF="[object Function]",AF="[object GeneratorFunction]",jF=/[\\^$.*+?()[\]{}|]/g,OF=/^\[object .+?Constructor\]$/,DF=typeof tn=="object"&&tn&&tn.Object===Object&&tn,RF=typeof self=="object"&&self&&self.Object===Object&&self,q0=DF||RF||Function("return this")();function LF(e,t){var n=e?e.length:0;return!!n&&NF(e,t,0)>-1}function FF(e,t,n,r){for(var o=e.length,s=n+-1;++s-1}function sN(e,t){var n=this.__data__,r=Lf(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}wc.prototype.clear=tN;wc.prototype.delete=nN;wc.prototype.get=rN;wc.prototype.has=oN;wc.prototype.set=sN;function bc(e){var t=-1,n=e?e.length:0;for(this.clear();++t=TF){var l=gN(e);if(l)return u2(l);i=!1,o=BF,c=new Zp}else c=a;e:for(;++rf2(e.getCollaborators().map(n=>n.userId)).sort(),{isEqual:(n,r)=>{var o;return n.join(",")===((o=r.join)==null?void 0:o.call(r,","))}},[e]);return K(t)}function g2(e){const t=z();return K(`latestPresence:${e}`,()=>t.getCollaborators().find(r=>r.userId===e),[t])??null}const EN=or(function(){const t=IN();return h.jsx(h.Fragment,{children:t.map(n=>h.jsx(_N,{collaboratorId:n},n))})}),_N=or(function({collaboratorId:t}){const n=z(),r=g2(t),o=TN(r);if(!(r&&r.currentPageId===n.getCurrentPageId()))return null;switch(o){case"inactive":{const{followingUserId:s,highlightedUserIds:i}=n.getInstanceState();if(!(s===r.userId||i.includes(r.userId)))return null;break}case"idle":{const{highlightedUserIds:s}=n.getInstanceState();if(r.followingUserId===n.user.getId()&&!(r.chatMessage||s.includes(r.userId)))return null;break}}return h.jsx(kN,{latestPresence:r})}),kN=or(function({latestPresence:t}){const n=z(),{CollaboratorBrush:r,CollaboratorScribble:o,CollaboratorCursor:s,CollaboratorHint:i,CollaboratorShapeIndicator:a}=dt(),c=n.getZoomLevel(),l=n.getViewportPageBounds(),{userId:u,chatMessage:d,brush:p,scribbles:f,selectedShapeIds:y,userName:g,cursor:w,color:S}=t,v=!(w.xl.maxX-12/c||w.y>l.maxY-16/c);return h.jsxs(h.Fragment,{children:[p&&r?h.jsx(r,{className:"tl-collaborator__brush",brush:p,color:S,opacity:.1},u+"_brush"):null,v&&s?h.jsx(s,{className:"tl-collaborator__cursor",point:w,color:S,zoom:c,name:g!=="New User"?g:null,chatMessage:d},u+"_cursor"):i?h.jsx(i,{className:"tl-collaborator__cursor-hint",point:w,color:S,zoom:c,viewport:l},u+"_cursor_hint"):null,o&&f.length?h.jsx(h.Fragment,{children:f.map(b=>h.jsx(o,{className:"tl-collaborator__scribble",scribble:b,color:S,zoom:c,opacity:b.color==="laser"?.5:.1},u+"_scribble_"+b.id))}):null,a&&y.map(b=>h.jsx(a,{className:"tl-collaborator__shape-indicator",shapeId:b,color:S,opacity:.5},u+"_"+b))]})});function N1(e){return e>O5?"inactive":e>Vk?"idle":"active"}function TN(e){const t=x.useRef((e==null?void 0:e.lastActivityTimestamp)??-1),[n,r]=x.useState(()=>N1(Date.now()-t.current));return x.useEffect(()=>{const o=setInterval(()=>{r(N1(Date.now()-t.current))},D5);return()=>clearInterval(o)},[]),e&&(t.current=e.lastActivityTimestamp),n}const m2=x.memo(function({id:t,shape:n,util:r,index:o,backgroundIndex:s,opacity:i,dprMultiple:a}){const c=z(),{ShapeErrorFallback:l}=dt(),u=x.useRef(null),d=x.useRef(null),p=x.useRef({transform:"",clipPath:"none",width:0,height:0,x:0,y:0,isCulled:!1});js("set shape stuff",()=>{const g=c.getShape(t);if(!g)return;const w=p.current,S=c.getShapeClipPath(t)??"none";S!==w.clipPath&&(Yt(u.current,"clip-path",S),Yt(d.current,"clip-path",S),w.clipPath=S);const v=c.getShapePageTransform(t),b=oe.toCssString(v),E=c.getShapeGeometry(g).bounds;b!==w.transform&&(Yt(u.current,"transform",b),Yt(d.current,"transform",b),w.transform=b);const C=E.w%a,I=E.h%a,_=C===0?E.w:E.w+(a-C),k=I===0?E.h:E.h+(a-I);(_!==w.width||k!==w.height)&&(Yt(u.current,"width",Math.max(_,a)+"px"),Yt(u.current,"height",Math.max(k,a)+"px"),Yt(d.current,"width",Math.max(_,a)+"px"),Yt(d.current,"height",Math.max(k,a)+"px"),w.width=_,w.height=k)},[c]),js("set opacity and z-index",()=>{const g=u.current,w=d.current;Yt(g,"opacity",i),Yt(w,"opacity",i),Yt(g,"z-index",o),Yt(w,"z-index",s)},[i,o,s]),js("set display",()=>{if(!c.getShape(t))return;const S=c.getCulledShapes().has(t);S!==p.current.isCulled&&(Yt(u.current,"display",S?"none":"block"),Yt(d.current,"display",S?"none":"block"),p.current.isCulled=S)},[c]);const f=x.useCallback(g=>c.annotateError(g,{origin:"shape",willCrashApp:!1}),[c]);if(!n)return null;const y="fill"in n.props&&n.props.fill!=="none";return h.jsxs(h.Fragment,{children:[r.backgroundComponent&&h.jsx("div",{ref:d,className:"tl-shape tl-shape-background","data-shape-type":n.type,draggable:!1,children:h.jsx(su,{fallback:l,onError:f,children:h.jsx(MN,{shape:n,util:r})})}),h.jsx("div",{ref:u,className:"tl-shape","data-shape-type":n.type,"data-shape-is-filled":y,draggable:!1,children:h.jsx(su,{fallback:l,onError:f,children:h.jsx($N,{shape:n,util:r})})})]})}),$N=x.memo(function({shape:t,util:n}){return $f("InnerShape:"+t.type,()=>n.component(t))},(e,t)=>e.shape.props===t.shape.props&&e.shape.meta===t.shape.meta),MN=x.memo(function({shape:t,util:n}){return $f("InnerShape:"+t.type,()=>{var r;return(r=n.backgroundComponent)==null?void 0:r.call(n,t)})},(e,t)=>e.shape.props===t.shape.props&&e.shape.meta===t.shape.meta);function AN({className:e}){const t=z(),{Background:n,SvgDefs:r}=dt(),o=x.useRef(null),s=x.useRef(null),i=x.useRef(null),a=cn();IF(o),X5(),G5(),tF(o),Q5(o);const c=x.useRef({lodDisableTextOutline:!1,allowTextOutline:!0});js("position layers",function(){const{x:S,y:v,z:b}=t.getCamera();if(c.current.allowTextOutline&&t.environment.isSafari&&(a.style.setProperty("--tl-text-outline","none"),c.current.allowTextOutline=!1),c.current.allowTextOutline&&b=1?Ap(b,[1,8],[.125,.5],!0):Ap(b,[.1,1],[-2,.125],!0),C=`scale(${j(b)}) translate(${j(S+E)}px,${j(v+E)}px)`;Yt(s.current,"transform",C),Yt(i.current,"transform",C)},[t,a]);const l=V5(),u=K("shapeSvgDefs",()=>{const w=new Map;for(const S of bt(t.shapeUtils)){if(!S)return;const v=S.getCanvasSvgDefs();for(const{key:b,component:E}of v)w.has(b)||w.set(b,h.jsx(E,{},b))}return[...w.values()]},[t]),d=K("debug_shapes",()=>$t.hideShapes.get(),[$t]),p=K("debug_svg",()=>$t.debugSvg.get(),[$t]),f=K("debug_geometry",()=>$t.debugGeometry.get(),[$t]),y=K("isEditingAnything",()=>t.getEditingShapeId()!==null,[t]),g=K("isSelectingAnything",()=>!!t.getSelectedShapeIds().length,[t]);return h.jsxs("div",{ref:o,draggable:!1,"data-iseditinganything":y,"data-isselectinganything":g,className:ue("tl-canvas",e),"data-testid":"canvas",...l,children:[h.jsx("svg",{className:"tl-svg-context",children:h.jsxs("defs",{children:[u,h.jsx(VN,{}),h.jsx(GN,{}),r&&h.jsx(r,{})]})}),n&&h.jsx("div",{className:"tl-background__wrapper",children:h.jsx(n,{})}),h.jsx(jN,{}),h.jsxs("div",{ref:s,className:"tl-html-layer tl-shapes",draggable:!1,children:[h.jsx(ZN,{}),h.jsx(qN,{}),d?null:p?h.jsx(BN,{}):h.jsx(HN,{})]}),h.jsxs("div",{className:"tl-overlays",children:[h.jsxs("div",{ref:i,className:"tl-html-layer",children:[f?h.jsx(kF,{}):null,h.jsx(FN,{}),h.jsx(DN,{}),h.jsx(ON,{}),h.jsx(RN,{}),h.jsx(KN,{}),h.jsx(WN,{}),h.jsx(LN,{}),h.jsx(XN,{}),h.jsx(EN,{})]}),h.jsx(QN,{})]}),h.jsx(JN,{})]})}function jN(){const e=z(),t=K("gridSize",()=>e.getDocumentSettings().gridSize,[e]),{x:n,y:r,z:o}=K("camera",()=>e.getCamera(),[e]),s=K("isGridMode",()=>e.getInstanceState().isGridMode,[e]),{Grid:i}=dt();return i&&s?h.jsx(i,{x:n,y:r,z:o,size:t}):null}function ON(){const e=z(),t=K("scribbles",()=>e.getInstanceState().scribbles,[e]),n=K("zoomLevel",()=>e.getZoomLevel(),[e]),{Scribble:r}=dt();return r&&t.length?h.jsx(h.Fragment,{children:t.map(o=>h.jsx(r,{className:"tl-user-scribble",scribble:o,zoom:n},o.id))}):null}function DN(){const e=z(),t=K("brush",()=>e.getInstanceState().brush,[e]),{Brush:n}=dt();return n&&t?h.jsx(n,{className:"tl-user-brush",brush:t}):null}function RN(){const e=z(),t=K("zoomBrush",()=>e.getInstanceState().zoomBrush,[e]),{ZoomBrush:n}=dt();return n&&t?h.jsx(n,{className:"tl-user-brush tl-zoom-brush",brush:t}):null}function LN(){const e=z(),t=K("snapLines",()=>e.snaps.getIndicators(),[e]),n=K("zoomLevel",()=>e.getZoomLevel(),[e]),{SnapIndicator:r}=dt();return r&&t.length>0?h.jsx(h.Fragment,{children:t.map(o=>h.jsx(r,{className:"tl-user-snapline",line:o,zoom:n},o.id))}):null}function FN(){const e=z(),t=K("handles shapeIdWithHandles",()=>{const{isReadonly:n,isChangingStyle:r}=e.getInstanceState();if(n||r)return!1;const o=e.getOnlySelectedShape();return!o||!e.getShapeHandles(o)?!1:o.id},[e]);return t?h.jsx(NN,{shapeId:t}):null}function NN({shapeId:e}){const t=z(),{Handles:n}=dt(),r=K("zoomLevel",()=>t.getZoomLevel(),[t]),o=K("coarse pointer",()=>t.getInstanceState().isCoarsePointer,[t]),s=K("handles transform",()=>t.getShapePageTransform(e),[t,e]),i=K("handles",()=>{const a=t.getShapeHandles(e);if(!a)return null;const c=(o?Gk:Yk)/r*2;return a.filter(l=>l.type!=="virtual"||!a.some(u=>u!==l&&u.type==="vertex"&&P.Dist(l,u)l.type==="vertex"?1:-1)},[t,r,o,e]);return!n||!i||!s?null:h.jsx(n,{children:h.jsx("g",{transform:oe.toCssString(s),children:i.map(a=>h.jsx(zN,{shapeId:e,handle:a,zoom:r,isCoarse:o},a.id))})})}function zN({shapeId:e,handle:t,zoom:n,isCoarse:r}){const o=nF(e,t.id),{Handle:s}=dt();return s?h.jsx("g",{"aria-label":"handle",transform:`translate(${t.x}, ${t.y})`,...o,children:h.jsx(s,{shapeId:e,handle:t,zoom:n,isCoarse:r})}):null}function BN(){const e=z(),t=K("rendering shapes",()=>e.getRenderingShapes(),[e]),n=K("dpr multiple",()=>c2(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return h.jsx(h.Fragment,{children:t.map(r=>h.jsxs(x.Fragment,{children:[h.jsx(m2,{...r,dprMultiple:n}),h.jsx(YN,{id:r.id})]},r.id+"_fragment"))})}function UN(){const e=z(),t=x.useRef(new Set);return js("reflow for culled shapes",()=>{const n=e.getCulledShapes();if(t.current.size===n.size&&[...n].every(o=>t.current.has(o)))return;t.current=n;const r=document.getElementsByClassName("tl-canvas");r.length!==0&&r[0].offsetHeight},[e]),null}function HN(){const e=z(),t=K("rendering shapes",()=>e.getRenderingShapes(),[e]),n=K("dpr multiple",()=>c2(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return h.jsxs(h.Fragment,{children:[t.map(r=>h.jsx(m2,{...r,dprMultiple:n},r.id+"_shape")),e.environment.isSafari&&h.jsx(UN,{})]})}function KN(){const e=z(),t=K("rendering shapes",()=>e.getRenderingShapes(),[e]),n=x.useRef(new Set),r=K("should display selected ids",()=>{const s=n.current,i=new Set;if(e.isInAny("select.idle","select.brushing","select.scribble_brushing","select.editing_shape","select.pointing_shape","select.pointing_selection","select.pointing_handle")&&!e.getInstanceState().isChangingStyle){const a=e.getSelectedShapeIds();for(const c of a)i.add(c);if(e.isInAny("select.idle","select.editing_shape")){const c=e.getInstanceState();if(c.isHoveringCanvas&&!c.isCoarsePointer){const l=e.getHoveredShapeId();l&&i.add(l)}}}if(s.size!==i.size)return n.current=i,i;for(const a of i)if(!s.has(a))return n.current=i,i;return s},[e]),{ShapeIndicator:o}=dt();return o?h.jsx(h.Fragment,{children:t.map(({id:s})=>h.jsx(o,{shapeId:s,hidden:!r.has(s)},s+"_indicator"))}):null}function WN(){const e=z(),{ShapeIndicator:t}=dt(),n=K("hinting shape ids",()=>Mp(e.getHintingShapeIds()),[e]);return!n.length||!t?null:h.jsx(h.Fragment,{children:n.map(r=>h.jsx(t,{className:"tl-user-indicator__hint",shapeId:r},r+"_hinting"))})}function VN(){return h.jsxs("g",{id:"cursor",children:[h.jsxs("g",{fill:"rgba(0,0,0,.2)",transform:"translate(-11,-11)",children:[h.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),h.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),h.jsxs("g",{fill:"white",transform:"translate(-12,-12)",children:[h.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),h.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),h.jsxs("g",{fill:"currentColor",transform:"translate(-12,-12)",children:[h.jsx("path",{d:"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z"}),h.jsx("path",{d:"m13 10.814v11.188l2.969-2.866.428-.139h4.768z"})]})]})}function GN(){return h.jsx("path",{id:"cursor_hint",fill:"currentColor",d:"M -2,-5 2,0 -2,5 Z"})}function YN({id:e}){const t=z(),[n,r]=x.useState(null),o=K("is in root",()=>{const s=t.getShape(e);return(s==null?void 0:s.parentId)===t.getCurrentPageId()},[t,e]);return x.useEffect(()=>{if(!o)return;let s=null;const i=Sc("shape to svg",async()=>{const a=Math.random();s=a;const l=t.isShapeOfType(e,"frame")?0:10;let u=t.getShapePageBounds(e);if(!u)return;u=u.clone().expandBy(l);const d=await t.getSvgString([e],{padding:l,background:t.getInstanceState().exportBackground});if(s!==a||!d)return;const p=`data:image/svg+xml;utf8,${encodeURIComponent(d.svg)}`;r({src:p,bounds:u})});return()=>{s=null,i()}},[t,e,o]),!o||!n?null:h.jsx("img",{src:n.src,width:n.bounds.width,height:n.bounds.height,style:{position:"absolute",top:0,left:0,transform:`translate(${n.bounds.x}px, ${n.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}})}function XN(){const e=z(),t=K("selection rotation",()=>e.getSelectionRotation(),[e]),n=K("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionForeground:r}=dt();return!n||!r?null:h.jsx(r,{bounds:n,rotation:t})}function qN(){const e=z(),t=K("selection rotation",()=>e.getSelectionRotation(),[e]),n=K("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionBackground:r}=dt();return!n||!r?null:h.jsx(r,{bounds:n,rotation:t})}function ZN(){const{OnTheCanvas:e}=dt();return e?h.jsx(e,{}):null}function QN(){const{InFrontOfTheCanvas:e}=dt();return e?h.jsx(e,{}):null}function JN(){const e=z(),t=K("camera state",()=>e.getCameraState(),[e]);return h.jsx("div",{className:ue("tl-hit-test-blocker",{"tl-hit-test-blocker__hidden":t==="idle"})})}function e4({className:e,zoom:t,point:n,color:r,viewport:o,opacity:s=1}){const i=x.useRef(null);return xc(i,Ns(n.x,o.minX+5/t,o.maxX-5/t),Ns(n.y,o.minY+5/t,o.maxY-5/t),1/t,P.Angle(o.center,n)),h.jsxs("svg",{ref:i,className:ue("tl-overlays__item",e),children:[h.jsx("use",{href:"#cursor_hint",color:r,strokeWidth:3,stroke:"var(--color-background)"}),h.jsx("use",{href:"#cursor_hint",color:r,opacity:s})]})}const z1=x.memo(function({className:t,zoom:n,point:r,color:o,name:s,chatMessage:i}){const a=x.useRef(null);return xc(a,r==null?void 0:r.x,r==null?void 0:r.y,1/n),r?h.jsxs("div",{ref:a,className:ue("tl-overlays__item",t),children:[h.jsx("svg",{className:"tl-cursor",children:h.jsx("use",{href:"#cursor",color:o})}),i?h.jsxs(h.Fragment,{children:[s&&h.jsx("div",{className:"tl-nametag-title",style:{color:o},children:s}),h.jsx("div",{className:"tl-nametag-chat",style:{backgroundColor:o},children:i})]}):s&&h.jsx("div",{className:"tl-nametag",style:{backgroundColor:o},children:s})]}):null});function t4({x:e,y:t,z:n,size:r}){return h.jsxs("svg",{className:"tl-grid",version:"1.1",xmlns:"http://www.w3.org/2000/svg",children:[h.jsx("defs",{children:w1.map(({min:o,mid:s,step:i},a)=>{const c=i*r*n,l=.5+e*n,u=.5+t*n,d=l>0?l%c:c+l%c,p=u>0?u%c:c+u%c,f=nh.jsx("rect",{width:"100%",height:"100%",fill:`url(#grid-${o})`},`grid-rect-${s}`))]})}function n4({handle:e,isCoarse:t,className:n,zoom:r}){const o=(t?Gk:Yk)/r;if(e.type==="clone"){const i=3/Math.max(r,.35),a=`M0,${-i} A${i},${i} 0 0,1 0,${i}`,c=z5.indexOf(e.id);return h.jsxs("g",{className:ue(`tl-handle tl-handle__${e.type}`,n),children:[h.jsx("circle",{className:"tl-handle__bg",r:o}),h.jsx("path",{className:"tl-handle__fg",d:a,transform:`rotate(${-90+90*c})`})]})}const s=(e.type==="create"&&t?3:4)/Math.max(r,.35);return h.jsxs("g",{className:ue(`tl-handle tl-handle__${e.type}`,n),children:[h.jsx("circle",{className:"tl-handle__bg",r:o}),h.jsx("circle",{className:"tl-handle__fg",r:s})]})}const r4=({children:e})=>h.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e});function J0(e,t=!0){const n=e.length;if(n<2)return"";let r=e[0],o=e[1];if(n===2)return`M${Ft(r)}L${Ft(o)}`;let s="";for(let i=2,a=n-1;i3?"T":""}${s}L${Ft(e[n-1])}`}function B1({scribble:e,zoom:t,color:n,opacity:r,className:o}){return e.points.length?h.jsx("svg",{className:o&&ue("tl-overlays__item",o),children:h.jsx("path",{className:"tl-scribble",d:J0(e.points,!1),stroke:n??`var(--color-${e.color})`,fill:"none",strokeWidth:8/t,opacity:r??e.opacity})}):null}function y2({bounds:e,rotation:t}){const n=x.useRef(null);return xc(n,e.x,e.y,1,t),x.useLayoutEffect(()=>{const r=n.current;r&&(r.style.width=j(Math.max(1,e.width))+"px",r.style.height=j(Math.max(1,e.height))+"px")},[e.width,e.height]),h.jsx("div",{ref:n,className:"tl-selection__bg",draggable:!1})}function o4({bounds:e,rotation:t}){const n=z(),r=x.useRef(null),o=K("only selected shape",()=>n.getOnlySelectedShape(),[n]),s=o?n.getShapeUtil(o).expandSelectionOutlinePx(o):0;return xc(r,e==null?void 0:e.x,e==null?void 0:e.y,1,t,{x:-s,y:-s}),e=e.clone().expandBy(s).zeroFix(),h.jsx("svg",{ref:r,className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:h.jsx("rect",{className:ue("tl-selection__fg__outline"),width:j(e.width),height:j(e.height)})})}const s4=()=>h.jsx("div",{className:"tl-shape-error-boundary"}),i4=({shape:e,util:t})=>$f("Indicator: "+e.type,()=>t.indicator(e)),a4=({editor:e,id:t})=>{const n=K("shape for indicator",()=>e.store.get(t),[e,t]),{ShapeIndicatorErrorFallback:r}=dt();return!n||n.isLocked?null:h.jsx(su,{fallback:r,onError:o=>e.annotateError(o,{origin:"react.shapeIndicator",willCrashApp:!1}),children:h.jsx(i4,{shape:n,util:e.getShapeUtil(n)},n.id)})},U1=x.memo(function({shapeId:t,className:n,color:r,hidden:o,opacity:s}){const i=z(),a=x.useRef(null);return js("indicator transform",()=>{const c=a.current;if(!c)return;const l=i.getShapePageTransform(t);l&&c.style.setProperty("transform",l.toCssString())},[i,t]),x.useLayoutEffect(()=>{const c=a.current;c&&c.style.setProperty("display",o?"none":"block")},[o]),h.jsx("svg",{ref:a,className:ue("tl-overlays__item",n),children:h.jsx("g",{className:"tl-shape-indicator",stroke:r??"var(--color-selected)",opacity:s,children:h.jsx(a4,{editor:i,id:t})})})}),c4=()=>h.jsx("circle",{cx:4,cy:4,r:8,strokeWidth:"1",stroke:"red"});function l4({points:e,zoom:t}){const n=2.5/t,r=e.reduce((p,f)=>Math.min(p,f.x),1/0),o=e.reduce((p,f)=>Math.max(p,f.x),-1/0),s=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===s);let c,l,u,d;return a?(c=r,l=s,u=o,d=i):(c=r,l=i,u=o,d=s),h.jsxs("g",{className:"tl-snap-indicator",stroke:"lime",children:[h.jsx("line",{x1:c,y1:l,x2:u,y2:d}),e.map((p,f)=>h.jsx("g",{transform:`translate(${p.x},${p.y})`,children:h.jsx("path",{className:"tl-snap-point",d:`M ${-n},${-n} L ${n},${n} M ${-n},${n} L ${n},${-n}`})},f))]})}function u4({gaps:e,direction:t,zoom:n}){const r=3.5/n;let o=[-1/0,1/0],s=null;const i=t==="horizontal";for(const c of e){if(s=kr(o[0],o[1],i?c.startEdge[0].y:c.startEdge[0].x,i?c.startEdge[1].y:c.startEdge[1].x),s)o=s;else continue;if(s=kr(o[0],o[1],i?c.endEdge[0].y:c.endEdge[0].x,i?c.endEdge[1].y:c.endEdge[1].x),s)o=s;else continue}if(o===null)return null;const a=(o[0]+o[1])/2;return h.jsx("g",{className:"tl-snap-indicator",stroke:"cyan",children:e.map(({startEdge:c,endEdge:l},u)=>h.jsx(x.Fragment,{children:i?h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:c[0].x,y1:a-2*r,x2:c[1].x,y2:a+2*r}),h.jsx("line",{x1:l[0].x,y1:a-2*r,x2:l[1].x,y2:a+2*r}),h.jsx("line",{x1:c[0].x,y1:a,x2:l[0].x,y2:a}),h.jsx("line",{x1:(c[0].x+l[0].x)/2,y1:a-r,x2:(c[0].x+l[0].x)/2,y2:a+r})]}):h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:a-2*r,y1:c[0].y,x2:a+2*r,y2:c[1].y}),h.jsx("line",{x1:a-2*r,y1:l[0].y,x2:a+2*r,y2:l[1].y}),h.jsx("line",{x1:a,y1:c[0].y,x2:a,y2:l[0].y}),h.jsx("line",{x1:a-r,y1:(c[0].y+l[0].y)/2,x2:a+r,y2:(c[0].y+l[0].y)/2})]})},u))})}function d4({className:e,line:t,zoom:n}){return h.jsx("svg",{className:ue("tl-overlays__item",e),children:t.type==="points"?h.jsx(l4,{...t,zoom:n}):t.type==="gaps"?h.jsx(u4,{...t,zoom:n}):null})}function h4(){return h.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",children:h.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[h.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"var(--color-text-1)"}),h.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"var(--color-text-1)",children:h.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}const p4=()=>null;function S2(e,t){const n=x.useRef(e);return t(e,n.current)?n.current:(n.current=e,e)}function KS(e){return S2(e,O3)}function ex(e){return S2(e,K_)}const v2=x.createContext({});function f4({overrides:e={},children:t}){const n=ex(e);return h.jsx(v2.Provider,{value:x.useMemo(()=>({Background:v5,SvgDefs:p4,Brush:Pd,ZoomBrush:Pd,ScreenshotBrush:Pd,CollaboratorBrush:Pd,Cursor:z1,CollaboratorCursor:z1,CollaboratorHint:e4,CollaboratorShapeIndicator:U1,Grid:t4,Scribble:B1,SnapIndicator:d4,Handles:r4,Handle:n4,CollaboratorScribble:B1,ErrorFallback:w2,ShapeErrorFallback:s4,ShapeIndicatorErrorFallback:c4,Spinner:h4,SelectionBackground:y2,SelectionForeground:o4,ShapeIndicator:U1,OnTheCanvas:null,InFrontOfTheCanvas:null,Canvas:AN,...n}),[n]),children:t})}function dt(){return x.useContext(v2)}const tx={openWindow:(e,t)=>window.open(e,t,"noopener noreferrer"),refreshPage:()=>window.location.reload(),hardReset:async()=>{var e;return await((e=window.__tldraw__hardReset)==null?void 0:e.call(window))}};function x2(){tx.hardReset()}function g4(){tx.refreshPage()}const m4="https://github.com/tldraw/tldraw/issues/new";function y4(){}const w2=({error:e,editor:t})=>{const n=x.useRef(null),[r,o]=x.useState(!1),[s,i]=x.useState(!1),[a,c]=x.useState(!1),{Canvas:l}=dt(),u=e instanceof Error?e.message:String(e),d=e instanceof Error?e.stack:null,p=K("isDarkMode",()=>{try{if(t)return t.user.getIsDarkMode()}catch{}return null},[t]),[f,y]=x.useState(null);x.useLayoutEffect(()=>{var C;p!==null&&y(p);let b=(C=n.current)==null?void 0:C.parentElement,E=!1;for(;b;){if(b.classList.contains("tl-theme__dark")||b.classList.contains("tl-theme__light")){E=!0;break}b=b.parentElement}if(E){y(null);return}y(window.matchMedia("(prefers-color-scheme: dark)").matches)},[p]),x.useEffect(()=>{if(s){const b=setTimeout(()=>{i(!1)},2e3);return()=>clearTimeout(b)}},[s]);const g=()=>{const b=document.createElement("textarea");b.value=d??u,document.body.appendChild(b),b.select(),document.execCommand("copy"),b.remove(),i(!0)},w=()=>{g4()},S=async()=>{x2()},v=new URL(m4);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 ${d??u} \`\`\` My browser: ${navigator.userAgent}`),h.jsxs("div",{ref:n,className:ue("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[h.jsx("div",{className:"tl-error-boundary__overlay"}),t&&h.jsx(Hk,{onError:y4,fallback:()=>null,children:h.jsx(Rf.Provider,{value:t,children:h.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:l?h.jsx(l,{}):null})})}),h.jsx("div",{className:ue("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?h.jsxs(h.Fragment,{children:[h.jsx("h2",{children:"Are you sure?"}),h.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),h.jsxs("div",{className:"tl-error-boundary__content__actions",children:[h.jsx("button",{onClick:()=>c(!1),children:"Cancel"}),h.jsx("button",{className:"tl-error-boundary__reset",onClick:S,children:"Reset data"})]})]}):h.jsxs(h.Fragment,{children:[h.jsx("h2",{children:"Something's gone wrong."}),h.jsxs("p",{children:["Sorry, we encountered an error. Please refresh the page to continue. If you keep seeing this error, you can ",h.jsx("a",{href:v.toString(),children:"create a GitHub issue"})," or"," ",h.jsx("a",{href:"https://discord.gg/Cq6cPsTfNy",children:"ask for help on Discord"}),"."]}),r&&h.jsxs(h.Fragment,{children:["Message:",h.jsx("h4",{children:h.jsx("code",{children:u})}),"Stack trace:",h.jsxs("div",{className:"tl-error-boundary__content__error",children:[h.jsx("pre",{children:h.jsx("code",{children:d??u})}),h.jsx("button",{onClick:g,children:s?"Copied!":"Copy"})]})]}),h.jsxs("div",{className:"tl-error-boundary__content__actions",children:[h.jsx("button",{onClick:()=>o(!r),children:r?"Hide details":"Show details"}),h.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[h.jsx("button",{className:"tl-error-boundary__reset",onClick:()=>c(!0),children:"Reset data"}),h.jsx("button",{className:"tl-error-boundary__refresh",onClick:w,children:"Refresh Page"})]})]})]})})]})};let S4=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");function et(){return S4()}const b2="TLDRAW_USER_DATA_v3",P2=ve({id:ge,name:ge.nullable().optional(),locale:ge.nullable().optional(),color:ge.nullable().optional(),isDarkMode:we.nullable().optional(),animationSpeed:he.nullable().optional(),edgeScrollSpeed:he.nullable().optional(),isSnapMode:we.nullable().optional(),isWrapMode:we.nullable().optional()}),pa={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5},nx=Math.max(...Object.values(pa));function v4(e){e.version"u"?!1:((t=(e=window.matchMedia)==null?void 0:e.call(window,"(prefers-color-scheme: dark)"))==null?void 0:t.matches)??!1}function b4(){var e,t;return typeof window>"u"?!1:((t=(e=window.matchMedia)==null?void 0:e.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:t.matches)??!1}const ai=Object.freeze({name:"New User",locale:f5(),color:x4(),isDarkMode:!1,edgeScrollSpeed:1,animationSpeed:b4()?0:1,isSnapMode:!1,isWrapMode:!1});function mm(){return{id:et()}}function C2(e){if(e===null||typeof e!="object"||!("version"in e)||!("user"in e)||typeof e.version!="number")return mm();const t=Ye(e);v4(t);try{return P2.validate(t.user)}catch{return mm()}}function P4(){const e=JSON.parse(L0(b2)||"null")??null;return C2(e)}const cu=fn("globalUserData",null);function C4(){F0(b2,JSON.stringify({version:nx,user:cu.get()}))}function I4(e){P2.validate(e),cu.set(e),C4(),_4()}const E4=typeof process<"u"&&!1,Wa=typeof BroadcastChannel<"u"&&!E4?new BroadcastChannel("tldraw-user-sync"):null;Wa==null||Wa.addEventListener("message",e=>{const t=e.data;(t==null?void 0:t.type)===E2&&(t==null?void 0:t.origin)!==I2()&&cu.set(C2(t.data))});let ym=null;function I2(){return ym===null&&(ym=et()),ym}const E2="tldraw-user-preferences-change";function _4(){Wa==null||Wa.postMessage({type:E2,origin:I2(),data:{user:_2(),version:nx}})}function _2(){let e=cu.get();return e||(e=P4(),cu.set(e)),e}function k2(e={}){return{derivePresenceState:e.derivePresenceState??(()=>V("presence",()=>null)),userPreferences:e.userPreferences??V("userPreferences",()=>_2()),setUserPreferences:e.setUserPreferences??I4}}var T2={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function s(c,l,u,d,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new o(u,d||c,p),y=n?n+l:l;return c._events[y]?c._events[y].fn?c._events[y]=[c._events[y],f]:c._events[y].push(f):(c._events[y]=f,c._eventsCount++),c}function i(c,l){--c._eventsCount===0?c._events=new r:delete c._events[l]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],u,d;if(this._eventsCount===0)return l;for(d in u=this._events)t.call(u,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},a.prototype.listeners=function(l){var u=n?n+l:l,d=this._events[u];if(!d)return[];if(d.fn)return[d.fn];for(var p=0,f=d.length,y=new Array(f);p1)&&(u<0||u>1))return null;const d=[];return 0<=l&&l<=1&&d.push(P.Lrp(e,t,l)),0<=u&&u<=1&&d.push(P.Lrp(e,t,u)),d.length===0?null:d}function T4(e,t,n){const r=[];let o;for(let s=0,i=n.length-1;s(t.y-e.y)*(n.x-e.x)}function sx(e,t,n,r){return Id(e,n,r)!==Id(t,n,r)&&Id(e,t,n)!==Id(e,t,r)}function W1(e,t){const n=new Map;let r,o,s,i;for(let a=0,c=e.length;aP.Angle(t,n)-P.Angle(t,r))}function $2(e,t){let n,r,o,s;for(let i=0,a=e.length;iMath.max(r.x,o.x))return r.x>o.x?r:o;const l=r.y+s.y*a;return lMath.max(r.y,o.y)?r.y>o.y?r:o:new P(c,l)}hitTestLineSegment(n,r,o=0){return sx(n,r,this.start,this.end)||this.distanceToLineSegment(n,r)<=o}}class Ki extends Hi{constructor(n){super({isClosed:!1,isFilled:!1,...n});m(this,"points");m(this,"_segments");m(this,"_length");const{points:r}=n;this.points=r}get segments(){if(!this._segments){this._segments=[];const{vertices:n}=this;for(let r=0,o=n.length-1;rn+r.length,0)),this._length}getVertices(){return this.points}nearestPoint(n){const{segments:r}=this;let o=this.points[0],s=1/0,i,a;for(let c=0;c!0);m(this,"canScroll",()=>!1);m(this,"canBind",(t,n)=>!0);m(this,"canEdit",()=>!1);m(this,"canResize",()=>!0);m(this,"canEditInReadOnly",()=>!1);m(this,"canCrop",()=>!1);m(this,"hideResizeHandles",()=>!1);m(this,"hideRotateHandle",()=>!1);m(this,"hideSelectionBoundsBg",()=>!1);m(this,"hideSelectionBoundsFg",()=>!1);m(this,"isAspectRatioLocked",()=>!1);m(this,"onBeforeCreate");m(this,"onBeforeUpdate");m(this,"onDragShapesOver");m(this,"onDragShapesOut");m(this,"onDropShapesOver");m(this,"onResizeStart");m(this,"onResize");m(this,"onResizeEnd");m(this,"onTranslateStart");m(this,"onTranslate");m(this,"onTranslateEnd");m(this,"onHandleDrag");m(this,"onRotateStart");m(this,"onRotate");m(this,"onRotateEnd");m(this,"onBindingChange");m(this,"onChildrenChange");m(this,"onDoubleClickHandle");m(this,"onDoubleClickEdge");m(this,"onDoubleClick");m(this,"onClick");m(this,"onEditEnd");this.editor=t}providesBackgroundForChildren(t){return!1}canReceiveNewChildrenOfType(t,n){return!1}canDropShapes(t,n){return!1}expandSelectionOutlinePx(t){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(t){return{}}getHandleSnapGeometry(t){return{}}}m(Fr,"props"),m(Fr,"migrations"),m(Fr,"type");function j4(e,t,n={}){const{closed:r=!1,snap:o=1,start:s="outset",end:i="outset",lengthRatio:a=2,style:c="dashed"}=n;let l=0,u=0,d=1,p=0,f=0;switch(c){case"dashed":{d=1,l=Math.min(t*a,e/4);break}case"dotted":{d=100,l=t/d;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(s==="outset"?(e+=l/2,f+=l/2):s==="skip"&&(e-=l,f-=l),i==="outset"?e+=l/2:i==="skip"&&(e-=l)),u=Math.floor(e/l/(2*d)),u-=u%o,u<3&&c==="dashed"?e/t<5?(l=e,u=1,p=0):(l=e*.333,p=e*.333):(u=Math.max(u,3),l=e/u/(2*d),r?(f=l/2,p=(e-u*l)/u):p=(e-u*l)/Math.max(1,u-1)),{strokeDasharray:[l,p].join(" "),strokeDashoffset:f.toString()}}function V1({bounds:e,className:t}){const n=z(),r=K("zoom level",()=>n.getZoomLevel(),[n]);return h.jsx("g",{className:t,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:e.sides.map((o,s)=>{const{strokeDasharray:i,strokeDashoffset:a}=j4(o[0].dist(o[1]),1/r,{style:"dashed",lengthRatio:4});return h.jsx("line",{x1:o[0].x,y1:o[0].y,x2:o[1].x,y2:o[1].y,strokeDasharray:i,strokeDashoffset:a},s)})})}class xh extends Fr{constructor(){super(...arguments);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"canBind",()=>!1);m(this,"onChildrenChange",n=>{const r=this.editor.getSortedChildIdsForParent(n.id);if(r.length===0){this.editor.getCurrentPageState().focusedGroupId===n.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([n.id]);return}else if(r.length===1){this.editor.getCurrentPageState().focusedGroupId===n.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(r,n.parentId),this.editor.deleteShapes([n.id]);return}})}getDefaultProps(){return{}}getGeometry(n){const r=this.editor.getSortedChildIdsForParent(n.id);return r.length===0?new Wo({width:1,height:1,isFilled:!1}):new Br({children:r.map(o=>{const s=this.editor.getShape(o),i=this.editor.getShapeGeometry(o),a=this.editor.getShapeLocalTransform(s).applyToPoints(i.vertices);return i.isClosed?new wt({points:a,isFilled:!0}):new Ki({points:a})})})}component(n){const r=this.editor.getErasingShapeIds().includes(n.id),{hintingShapeIds:o}=this.editor.getCurrentPageState(),s=o.length>0&&o.some(c=>c!==n.id&&this.editor.isShapeOfType(this.editor.getShape(c),"group")),i=this.editor.getCurrentPageState().focusedGroupId!==n.id;if(!r&&(i||s))return null;const a=this.editor.getShapeGeometry(n).bounds;return h.jsx(zs,{id:n.id,children:h.jsx(V1,{className:"tl-group",bounds:a})})}indicator(n){const r=this.editor.getShapeGeometry(n).bounds;return h.jsx(V1,{className:"",bounds:r})}}m(xh,"type","group"),m(xh,"props",kk),m(xh,"migrations",Tk);const M2=[xh],O4=new Set(M2.map(e=>e.type));function A2(e){const t=[...M2],n=new Set;for(const r of e){if(O4.has(r.type))throw new Error(`Shape type "${r.type}" is a core shapes type and cannot be overridden`);if(n.has(r.type))throw new Error(`Shape type "${r.type}" is defined more than once`);t.push(r),n.add(r.type)}return t}function G1(e,t){if(!t)return!1;switch(e.type){case"mixed":return t.type==="mixed";case"shared":return t.type==="shared"&&e.value===t.value;default:throw qo(e)}}class D4{constructor(t){m(this,"map");this.map=new Map(t)}get(t){return this.map.get(t)}getAsKnownValue(t){const n=this.get(t);if(n&&n.type!=="mixed")return n.value}get size(){return this.map.size}equals(t){if(this.size!==t.size)return!1;const n=new Set;for(const[r,o]of this){if(!G1(o,t.get(r)))return!1;n.add(r)}for(const[r,o]of t)if(!n.has(r)&&!G1(o,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 VS extends D4{set(t,n){this.map.set(t,n)}applyValue(t,n){const r=this.get(t);if(!r){this.set(t,{type:"shared",value:n});return}switch(r.type){case"mixed":return;case"shared":r.value!==n&&this.set(t,{type:"mixed"});return;default:qo(r,"type")}}}class zf{constructor(){m(this,"items",new WeakMap)}get(t,n){return this.items.has(t)||this.items.set(t,n(t)),this.items.get(t)}access(t){return this.items.get(t)}set(t,n){this.items.set(t,n)}has(t){return this.items.has(t)}invalidate(t){this.items.delete(t)}bust(){this.items=new WeakMap}}function R4(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}function L4(e,t){var o;let n=e;const r=new Set(t);for(;r.has(n);)n=(o=/^.*(\d+)$/.exec(n))!=null&&o[1]?n.replace(/(\d+)(?=\D?)$/,s=>(+s+1).toString()):`${n} 1`;return n}function Ed(e,t,n){if(n.length===0)return[];const r=new Map;for(const s of fe(n.map(i=>e.getShape(i)))){const{parentId:i}=s;r.has(i)||r.set(i,{children:fe(e.getSortedChildIdsForParent(i).map(a=>e.getShape(a))),moving:new Set}),r.get(i).moving.add(s)}const o=[];switch(t){case"toBack":{r.forEach(({moving:s,children:i})=>F4(s,i,o));break}case"toFront":{r.forEach(({moving:s,children:i})=>N4(s,i,o));break}case"forward":{r.forEach(({moving:s,children:i})=>z4(s,i,o));break}case"backward":{r.forEach(({moving:s,children:i})=>B4(s,i,o));break}}return o}function F4(e,t,n){const r=t.length;if(e.size===r)return;let o,s;for(let i=0;i({...a,index:i[c]})))}}function N4(e,t,n){const r=t.length;if(e.size===r)return;let o,s;for(let i=r-1;i>-1;i--){const a=t[i];if(e.has(a))s=a.index,e.delete(a);else{o=a.index;break}}if(e.size!==0){const i=oc(o,s,e.size);n.push(...Array.from(e.values()).sort(en).map((a,c)=>({...a,index:i[c]})))}}function z4(e,t,n){var s;const r=t.length;if(e.size===r)return;let o={name:"skipping"};for(let i=0;in.push({...t[c+u],index:l})),o={name:"skipping"};break}}}}function B4(e,t,n){var s;const r=t.length;if(e.size===r)return;let o={name:"skipping"};for(let i=r-1;i>-1;i--){const a=e.has(t[i]);switch(o.name){case"skipping":{if(!a)continue;o={name:"selecting",selectIndex:i};break}case"selecting":{if(a)continue;oc((s=t[i-1])==null?void 0:s.index,t[i].index,o.selectIndex-i).forEach((c,l)=>{n.push({...t[i+l+1],index:c})}),o={name:"skipping"};break}}}}function j2({editor:e}){const t=e.getSelectedShapes(),n=e.getSelectionRotation(),r=e.getSelectionRotatedPageBounds(),{inputs:{originPagePoint:o}}=e;if(!r)return null;const s=r.center.clone().rotWith(r.point,n);return{selectionPageCenter:s,initialCursorAngle:s.angle(o),initialSelectionRotation:n,shapeSnapshots:t.map(i=>({shape:Ye(i),initialPagePoint:e.getShapePageTransform(i.id).point()}))}}function wh({delta:e,editor:t,snapshot:n,stage:r}){const{selectionPageCenter:o,shapeSnapshots:s}=n;t.updateShapes(s.map(({shape:a,initialPagePoint:c})=>{const l=Kn(a.parentId)?t.getShapePageTransform(a.parentId):oe.Identity(),u=P.RotWith(c,o,e),d=oe.applyToPoint(oe.Inverse(l),u),p=Os(a.rotation+e);return{id:a.id,type:a.type,x:d.x,y:d.y,rotation:p}}));const i=[];s.forEach(({shape:a})=>{var d,p,f;const c=t.getShape(a.id);if(!c)return;const l=t.getShapeUtil(a);if(r==="start"||r==="one-off"){const y=(d=l.onRotateStart)==null?void 0:d.call(l,a);y&&i.push(y)}const u=(p=l.onRotate)==null?void 0:p.call(l,a,c);if(u&&i.push(u),r==="end"||r==="one-off"){const y=(f=l.onRotateEnd)==null?void 0:f.call(l,a,c);y&&i.push(y)}}),i.length>0&&t.updateShapes(i)}const U4=e=>{const{store:t}=e,n=t.query.filterHistory("shape"),r=t.query.records("shape",()=>({type:{eq:"arrow"}}));function o(){const s=r.get(),i={};for(const a of s){const{start:c,end:l}=a.props;if(c.type==="binding"){const u=i[c.boundShapeId];u?u.push({arrowId:a.id,handleId:"start"}):i[c.boundShapeId]=[{arrowId:a.id,handleId:"start"}]}if(l.type==="binding"){const u=i[l.boundShapeId];u?u.push({arrowId:a.id,handleId:"end"}):i[l.boundShapeId]=[{arrowId:a.id,handleId:"end"}]}}return i}return V("arrowBindingsIndex",(s,i)=>{if(Pi(s))return o();const a=s,c=n.getDiffSince(i);if(c===qn)return o();let l;function u(f){l||(l={...a}),l[f]?l[f]===a[f]&&(l[f]=[...l[f]]):l[f]=[]}function d(f,y,g){u(f),l[f]=l[f].filter(w=>w.arrowId!==y||w.handleId!==g),l[f].length===0&&delete l[f]}function p(f,y,g){u(f),l[f].push({arrowId:y,handleId:g})}for(const f of c){for(const y of Object.values(f.added))if(e.isShapeOfType(y,"arrow")){const{start:g,end:w}=y.props;g.type==="binding"&&p(g.boundShapeId,y.id,"start"),w.type==="binding"&&p(w.boundShapeId,y.id,"end")}for(const[y,g]of Object.values(f.updated))if(!(!e.isShapeOfType(y,"arrow")||!e.isShapeOfType(g,"arrow")))for(const w of["start","end"]){const S=y.props[w],v=g.props[w];S.type==="binding"&&v.type==="point"?d(S.boundShapeId,y.id,w):S.type==="point"&&v.type==="binding"?p(v.boundShapeId,g.id,w):S.type==="binding"&&v.type==="binding"&&S.boundShapeId!==v.boundShapeId&&(d(S.boundShapeId,y.id,w),p(v.boundShapeId,g.id,w))}for(const y of Object.values(f.removed))if(e.isShapeOfType(y,"arrow")){const{start:g,end:w}=y.props;g.type==="binding"&&d(g.boundShapeId,y.id,"start"),w.type==="binding"&&d(w.boundShapeId,y.id,"end")}}return l??a})};function H4(e,t,n){const r=e.getShapeMaskedPageBounds(t);return r===void 0?!0:!n.includes(r)}const K4=e=>{const t=Number.isFinite(e.renderingBoundsMargin);function n(r){const o=r.getCurrentPageShapeIds(),s=r.getViewportPageBounds(),i=new Set;return o.forEach(a=>{H4(r,a,s)&&i.add(a)}),i}return V("getCulledShapes",r=>{if(!t)return new Set;if(Pi(r))return n(e);const o=n(e);if(r.size!==o.size)return o;for(const s of r)if(!o.has(s))return o;return r})},W4=e=>{const t=e.query.ids("shape"),n=e.query.filterHistory("shape");function r(){const o={},s=t.get(),i=Array(s.size);return s.forEach(a=>i.push(e.get(a))),i.sort(en),i.forEach(a=>{o[a.parentId]||(o[a.parentId]=[]),o[a.parentId].push(a.id)}),o}return V("parentsToChildrenWithIndexes",(o,s)=>{if(Pi(o))return r();const i=n.getDiffSince(s);if(i===qn)return r();if(i.length===0)return o;let a=null;const c=d=>{a||(a={...o}),a[d]?a[d]===o[d]&&(a[d]=[...a[d]]):a[d]=[]},l=new Set;let u;for(let d=0,p=i.length;de.get(f)));p.sort(en),d.splice(0,d.length,...p.map(f=>f.id))}return a??o})},vm=(e,t,n)=>{for(;!bn(n.parentId);){const r=e.get(n.parentId);if(!r)return!1;n=r}return n.parentId===t},V4=(e,t)=>{const n=e.query.ids("shape");let r=null;function o(){const s=t();return r=s,new Set([...n.get()].filter(i=>vm(e,s,e.get(i))))}return V("_shapeIdsInCurrentPage",(s,i)=>{if(Pi(s))return o();const a=t();if(a!==r)return o();const c=e.history.getDiffSince(i);if(c===qn)return o();const l=new fh(s);for(const d of c){for(const p of Object.values(d.added))$a(p)&&vm(e,a,p)&&l.add(p.id);for(const[p,f]of Object.values(d.updated))$a(f)&&(vm(e,a,f)?l.add(f.id):l.remove(f.id));for(const p of Object.keys(d.removed))Kn(p)&&l.remove(p)}const u=l.get();return u?fl(u.value,u.diff):s})},O2=x.createContext(null);function G4({context:e,editor:t,children:n}){return h.jsx(Rf.Provider,{value:t,children:h.jsx(O2.Provider,{value:e,children:n})})}function D2(){const e=x.useContext(O2);return e?{isDarkMode:e.isDarkMode}:null}async function Y4(e,t,n={}){var C,I;const r=typeof t[0]=="string"?t:t.map(_=>_.id);if(r.length===0)return;if(!window.document)throw Error("No document");const{scale:o=1,background:s=!1,padding:i=A5,preserveAspectRatio:a=!1}=n,c=n.darkMode??e.user.getIsDarkMode(),l=Jo({isDarkMode:c}),u=e.getShapeAndDescendantIds(r),d=e.getUnorderedRenderingShapes(!1).filter(({id:_})=>u.has(_));let p=null;if(n.bounds)p=n.bounds;else for(const{id:_}of d){const k=e.getShapeMaskedPageBounds(_);k&&(p?p.union(k):p=k.clone())}if(!p)return;const f=r.length===1&&e.isShapeOfType(e.getShape(r[0]),"frame")?r[0]:null;f||p.expandBy(i);const y=p.width*o,g=p.height*o;try{(I=(C=document.body).focus)==null||I.call(C)}catch{}const w=[],S=new Map,v={isDarkMode:c,addExportDef:_=>{if(S.has(_.key))return;const k=(async()=>{const $=await _.getElement();$&&w.push(h.jsx(x.Fragment,{children:$},w.length))})();S.set(_.key,k)}},b=(await Promise.all(d.map(async({id:_,opacity:k,index:$,backgroundIndex:T})=>{var H,U;if(_===f)return[];const O=e.getShape(_);if(e.isShapeOfType(O,"group"))return[];const N=e.getShapeUtil(O);let F=await((H=N.toSvg)==null?void 0:H.call(N,O,v)),L=await((U=N.toBackgroundSvg)==null?void 0:U.call(N,O,v));if(!F&&!L){const W=e.getShapePageBounds(O);F=h.jsx("rect",{width:W.w,height:W.h,fill:l.solid,stroke:l.grey.pattern,strokeWidth:1})}let B=e.getShapePageTransform(O).toCssString();"scale"in O.props&&O.props.scale!==1&&(B=`${B} scale(${O.props.scale}, ${O.props.scale})`),F&&(F=h.jsx("g",{transform:B,opacity:k,children:F},O.id)),L&&(L=h.jsx("g",{transform:B,opacity:k,children:L},`bg_${O.id}`));const q=e.getShapeMask(O.id);if(q){const W=`mask_${O.id.replace(":","_")}`;w.push(h.jsx("clipPath",{id:W,children:h.jsx("path",{d:`M${q.map(({x:Z,y:le})=>`${Z},${le}`).join("L")}Z`})},w.length)),F&&(F=h.jsx("g",{clipPath:`url(#${W})`,children:F},O.id)),L&&(L=h.jsx("g",{clipPath:`url(#${W})`,children:L},`bg_${O.id}`))}const Q=[];return F&&Q.push({zIndex:$,element:F}),L&&Q.push({zIndex:T,element:L}),Q}))).flat();return await Promise.all(S.values()),{jsx:h.jsx(G4,{editor:e,context:v,children:h.jsxs("svg",{preserveAspectRatio:a||void 0,direction:"ltr",width:y,height:g,viewBox:`${p.minX} ${p.minY} ${p.width} ${p.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:s?f?l.solid:l.background:"transparent"},children:[h.jsx("defs",{children:w}),b.sort((_,k)=>_.zIndex-k.zIndex).map(({element:_})=>_)]})}),width:y,height:g}}const X4=40;class q4{constructor(t){m(this,"_clickId","");m(this,"_clickTimeout");m(this,"_clickScreenPoint");m(this,"_previousScreenPoint");m(this,"_getClickTimeout",(t,n=et())=>{this._clickId=n,clearTimeout(this._clickTimeout),this._clickTimeout=setTimeout(()=>{if(this._clickState===t&&this._clickId===n){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"}},t==="idle"||t==="pendingDouble"?$5:M5)});m(this,"_clickState","idle");m(this,"lastPointerInfo",{});m(this,"transformPointerDownEvent",t=>{if(!this._clickState)return t;switch(this._clickScreenPoint=P.From(t.point),this._previousScreenPoint&&this._previousScreenPoint.dist(this._clickScreenPoint)>X4&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=t,this._clickState){case"idle":return this._clickState="pendingDouble",this._clickTimeout=this._getClickTimeout(this._clickState),t;case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...t,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...t,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...t,type:"click",name:"quadruple_click",phase:"down"};case"pendingOverflow":return this._clickState="overflow",this._clickTimeout=this._getClickTimeout(this._clickState),t;default:return this._clickTimeout=this._getClickTimeout(this._clickState),t}});m(this,"transformPointerUpEvent",t=>{if(!this._clickState)return t;switch(this._clickScreenPoint=P.From(t.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"};default:return t}});m(this,"cancelDoubleClickTimeout",()=>{this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"});m(this,"handleMove",()=>{this._clickState!=="idle"&&this._clickScreenPoint&&P.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?BS:iu)&&this.cancelDoubleClickTimeout()});this.editor=t}get clickState(){return this._clickState}}class Z4{constructor(t){m(this,"isSafari");m(this,"isIos");m(this,"isChromeForIos");m(this,"isFirefox");m(this,"isAndroid");this.editor=t,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)}}function ci(e){return J4}class Q4{constructor(){m(this,"length",0);m(this,"head",null);m(this,"tail",this)}push(t){return new ix(t,this)}toArray(){return Do}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const J4=new Q4;class ix{constructor(t,n){m(this,"length");this.head=t,this.tail=n,this.length=n.length+1}push(t){return new ix(t,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let t=this;return{next(){if(t.length){const n=t.head;return t=t.tail,{value:n,done:!1}}else return{value:void 0,done:!0}}}}}class ez{constructor(t,n){m(this,"_undos",fn("HistoryManager.undos",ci()));m(this,"_redos",fn("HistoryManager.redos",ci()));m(this,"_batchDepth",0);m(this,"onBatchComplete",()=>{});m(this,"_commands",{});m(this,"createCommand",(t,n,r)=>{if(this._commands[t])throw new Error(`Duplicate command: ${t}`);this._commands[t]=r;const o=(...s)=>{if(!this._batchDepth)return this.batch(()=>o(...s)),this.ctx;const i=n(...s);if(!i)return this.ctx;const{data:a,ephemeral:c,squashing:l,preservesRedoStack:u}=i;if(this.ignoringUpdates((d,p)=>(r.do(a),{undos:d,redos:p})),!c){const d=this._undos.get().head;l&&d&&d.type==="command"&&d.name===t&&d.preservesRedoStack===u?this._undos.update(p=>p.tail.push({...d,data:r.squash(d.data,a)})):this._undos.update(p=>p.push({type:"command",name:t,data:a,preservesRedoStack:u})),i.preservesRedoStack||this._redos.set(ci()),this.ctx.emit("change-history",{reason:"push"})}return this.ctx};return o});m(this,"batch",t=>{try{this._batchDepth++,this._batchDepth===1?Mr(()=>{const n=this._undos.get().head;t(),n!==this._undos.get().head&&this.onBatchComplete()}):t()}catch(n){throw this.annotateError(n),n}finally{this._batchDepth--}return this});m(this,"ignoringUpdates",t=>{let n=this._undos.get(),r=this._redos.get();this._undos.set(ci()),this._redos.set(ci());try{({undos:n,redos:r}=Mr(()=>t(n,r)))}finally{this._undos.set(n),this._redos.set(r)}});m(this,"_undo",({pushToRedoStack:t,toMark:n=void 0})=>(this.ignoringUpdates((r,o)=>{var s;if(r.length===0)return{undos:r,redos:o};for(;((s=r.head)==null?void 0:s.type)==="STOP";){const i=r.head;if(r=r.tail,t&&(o=o.push(i)),i.id===n)return this.ctx.emit("change-history",t?{reason:"undo"}:{reason:"bail",markId:n}),{undos:r,redos:o}}if(r.length===0)return this.ctx.emit("change-history",t?{reason:"undo"}:{reason:"bail",markId:n}),{undos:r,redos:o};for(;r.head;){const i=r.head;if(r=r.tail,t&&(o=o.push(i)),i.type==="STOP"){if(i.onUndo&&(!n||i.id===n))return this.ctx.emit("change-history",t?{reason:"undo"}:{reason:"bail",markId:n}),{undos:r,redos:o}}else this._commands[i.name].undo(i.data)}return this.ctx.emit("change-history",t?{reason:"undo"}:{reason:"bail",markId:n}),{undos:r,redos:o}}),this));m(this,"undo",()=>(this._undo({pushToRedoStack:!0}),this));m(this,"redo",()=>(this.ignoringUpdates((t,n)=>{var r;if(n.length===0)return{undos:t,redos:n};for(;((r=n.head)==null?void 0:r.type)==="STOP";)t=t.push(n.head),n=n.tail;if(n.length===0)return this.ctx.emit("change-history",{reason:"redo"}),{undos:t,redos:n};for(;n.head;){const o=n.head;if(t=t.push(n.head),n=n.tail,o.type==="STOP"){if(o.onRedo)break}else{const s=this._commands[o.name];s.redo?s.redo(o.data):s.do(o.data)}}return this.ctx.emit("change-history",{reason:"redo"}),{undos:t,redos:n}}),this));m(this,"bail",()=>(this._undo({pushToRedoStack:!1}),this));m(this,"bailToMark",t=>(this._undo({pushToRedoStack:!1,toMark:t}),this));m(this,"mark",(t=et(),n=!0,r=!0)=>{const o=this._undos.get().head;return o&&o.type==="STOP"&&o.id===t&&o.onUndo===n&&o.onRedo===r?o.id:(this._undos.update(s=>s.push({type:"STOP",id:t,onUndo:n,onRedo:r})),this.ctx.emit("mark-history",{id:t}),t)});this.ctx=t,this.annotateError=n}getNumUndos(){return this._undos.get().length}getNumRedos(){return this._redos.get().length}clear(){this._undos.set(ci()),this._redos.set(ci())}}class tz{constructor(t){m(this,"scribbleItems",new Map);m(this,"state","paused");m(this,"addScribble",(t,n=et())=>{const r={id:n,scribble:{id:n,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...t,state:"starting"},timeoutMs:0,delayRemaining:t.delay??0,prev:null,next:null};return this.scribbleItems.set(n,r),r});m(this,"stop",t=>{const n=this.scribbleItems.get(t);if(!n)throw Error(`Scribble with id ${t} not found`);return n.delayRemaining=Math.min(n.delayRemaining,200),n.scribble.state="stopping",n});m(this,"addPoint",(t,n,r)=>{const o=this.scribbleItems.get(t);if(!o)throw Error(`Scribble with id ${t} not found`);const{prev:s}=o,i={x:n,y:r,z:.5};return(!s||P.Dist(s,i)>=1)&&(o.next=i),o});m(this,"tick",t=>{this.scribbleItems.size!==0&&this.editor.batch(()=>{this.scribbleItems.forEach(n=>{if(n.scribble.state==="starting"){const{next:c,prev:l}=n;c&&c!==l&&(n.prev=c,n.scribble.points.push(c)),n.scribble.points.length>8&&(n.scribble.state="active");return}n.delayRemaining>0&&(n.delayRemaining=Math.max(0,n.delayRemaining-t)),n.timeoutMs+=t,n.timeoutMs>=16&&(n.timeoutMs=0);const{delayRemaining:r,timeoutMs:o,prev:s,next:i,scribble:a}=n;switch(a.state){case"active":{i&&i!==s?(n.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):o===0&&(a.points.length>1?a.points.shift():n.delayRemaining=a.delay);break}case"stopping":{if(n.delayRemaining===0&&o===0){if(a.points.length===1){this.scribbleItems.delete(n.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:n})=>({...n,points:[...n.points]})).slice(-5)})})});this.editor=t}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}}class nz{constructor(t){m(this,"_beforeCreateHandlers",{});m(this,"_afterCreateHandlers",{});m(this,"_beforeChangeHandlers",{});m(this,"_afterChangeHandlers",{});m(this,"_beforeDeleteHandlers",{});m(this,"_afterDeleteHandlers",{});m(this,"_batchCompleteHandlers",[]);this.editor=t,t.store.onBeforeCreate=(r,o)=>{const s=this._beforeCreateHandlers[r.typeName];if(s){let i=r;for(const a of s)i=a(i,o);return i}return r},t.store.onAfterCreate=(r,o)=>{const s=this._afterCreateHandlers[r.typeName];if(s)for(const i of s)i(r,o)},t.store.onBeforeChange=(r,o,s)=>{const i=this._beforeChangeHandlers[o.typeName];if(i){let a=o;for(const c of i)a=c(r,a,s);return a}return o};let n=0;t.store.onAfterChange=(r,o,s)=>{if(n++,n>1e3)console.error("[CleanupManager.onAfterChange] Maximum update depth exceeded, bailing out.");else{const i=this._afterChangeHandlers[o.typeName];if(i)for(const a of i)a(r,o,s)}n--},t.store.onBeforeDelete=(r,o)=>{const s=this._beforeDeleteHandlers[r.typeName];if(s){for(const i of s)if(i(r,o)===!1)return!1}},t.store.onAfterDelete=(r,o)=>{const s=this._afterDeleteHandlers[r.typeName];if(s)for(const i of s)i(r,o)},t.history.onBatchComplete=()=>{this._batchCompleteHandlers.forEach(r=>r())}}registerBeforeCreateHandler(t,n){return this._beforeCreateHandlers[t]||(this._beforeCreateHandlers[t]=[]),this._beforeCreateHandlers[t].push(n),()=>li(this._beforeCreateHandlers[t],n)}registerAfterCreateHandler(t,n){return this._afterCreateHandlers[t]||(this._afterCreateHandlers[t]=[]),this._afterCreateHandlers[t].push(n),()=>li(this._afterCreateHandlers[t],n)}registerBeforeChangeHandler(t,n){return this._beforeChangeHandlers[t]||(this._beforeChangeHandlers[t]=[]),this._beforeChangeHandlers[t].push(n),()=>li(this._beforeChangeHandlers[t],n)}registerAfterChangeHandler(t,n){return this._afterChangeHandlers[t]||(this._afterChangeHandlers[t]=[]),this._afterChangeHandlers[t].push(n),()=>li(this._afterChangeHandlers[t],n)}registerBeforeDeleteHandler(t,n){return this._beforeDeleteHandlers[t]||(this._beforeDeleteHandlers[t]=[]),this._beforeDeleteHandlers[t].push(n),()=>li(this._beforeDeleteHandlers[t],n)}registerAfterDeleteHandler(t,n){return this._afterDeleteHandlers[t]||(this._afterDeleteHandlers[t]=[]),this._afterDeleteHandlers[t].push(n),()=>li(this._afterDeleteHandlers[t],n)}registerBatchCompleteHandler(t){return this._batchCompleteHandlers.push(t),()=>li(this._batchCompleteHandlers,t)}}function li(e,t){const n=e.indexOf(t);n>=0&&e.splice(n,1)}var rz=Object.defineProperty,oz=Object.getOwnPropertyDescriptor,Bf=(e,t,n,r)=>{for(var o=oz(t,n),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(t,n,o)||o);return o&&rz(t,n,o),o};const de=e=>Math.round(e*10**8)/10**8;function Eo(e,t,n,r,o){const s=e.filter(a=>(r==="forward"?a.startNode.id===t:a.endNode.id===t)&&de(a.length)===de(n)&&kr(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));if(s.length===0)return[];const i=new Set;return s.forEach(a=>{const c=r==="forward"?a.endNode.id:a.startNode.id;if(!i.has(c)){i.add(c);const l=Eo(e,c,n,r,kr(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));s.push(...l)}}),s}function sz(e){e.sort((t,n)=>n.gaps.length-t.gaps.length);for(let t=e.length-1;t>0;t--){const n=e[t];for(let r=t-1;r>=0;r--){const o=e[r];if(o.direction===n.direction&&n.gaps.every(s=>o.gaps.some(i=>de(s.startEdge[0].x)===de(i.startEdge[0].x)&&de(s.startEdge[0].y)===de(i.startEdge[0].y)&&de(s.startEdge[1].x)===de(i.startEdge[1].x)&&de(s.startEdge[1].y)===de(i.startEdge[1].y))&&o.gaps.some(i=>de(s.endEdge[0].x)===de(i.endEdge[0].x)&&de(s.endEdge[0].y)===de(i.endEdge[0].y)&&de(s.endEdge[1].x)===de(i.endEdge[1].x)&&de(s.endEdge[1].y)===de(i.endEdge[1].y)))){e.splice(t,1);break}}}}class Du{constructor(t){m(this,"editor");this.manager=t,this.editor=t.editor}getSnapPointsCache(){const{editor:t}=this;return t.store.createComputedCache("snapPoints",n=>{const r=t.getShapePageTransform(n.id);if(!r)return;const s=t.getShapeUtil(n).getBoundsSnapGeometry(n).points??t.getShapeGeometry(n).bounds.cornersAndCenter;if(!(!r||!s))return s.map((i,a)=>{const{x:c,y:l}=oe.applyToPoint(r,i);return{x:c,y:l,id:`${n.id}:${a}`}})})}getSnapPoints(t){return this.getSnapPointsCache().get(t)??[]}getSnappablePoints(){const t=this.getSnapPointsCache(),n=this.manager.getSnappableShapes(),r=[];for(const o of n){const s=t.get(o);s&&r.push(...s)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),t=>({id:t,pageBounds:yi(this.editor.getShapePageBounds(t))}))}getVisibleGaps(){const t=[],n=[];let r,o;const s=this.getSnappableGapNodes().sort((a,c)=>a.pageBounds.minX-c.pageBounds.minX);for(let a=0;aa.pageBounds.minY-c.pageBounds.minY);for(let a=0;a({id:"selection:"+E,x:v+o.x,y:b+o.y})),l=i,u=[],d=[],p=new P(s,s);this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:d,otherNodeSnapPoints:l,selectionSnapPoints:c}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d,minOffset:p});const f=new P(t==="x"?0:((w=u[0])==null?void 0:w.nudge)??0,t==="y"?0:((S=d[0])==null?void 0:S.nudge)??0);p.x=0,p.y=0,u.length=0,d.length=0,c.forEach(v=>{v.x+=f.x,v.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:d,otherNodeSnapPoints:l,selectionSnapPoints:c}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d,minOffset:p});const y=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:d}),g=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:d});return this.manager.setIndicators([...g,...y]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:t,dragDelta:n,handle:r,isAspectRatioLocked:o,isResizingFromCenter:s}){var _,k;const i=this.manager.getSnapThreshold(),{box:a,scaleX:c,scaleY:l}=ne.Resize(t,r,s?n.x*2:n.x,s?n.y*2:n.y,o);let u=r;c<0&&(u=PF(u)),l<0&&(u=bF(u)),s&&(a.center=t.center);const d=u==="top"||u==="bottom",p=u==="left"||u==="right",f=Y1(u,a),y=this.getSnappablePoints(),g=[],w=[],S=new P(i,i);this.collectPointSnaps({minOffset:S,nearestSnapsX:g,nearestSnapsY:w,otherNodeSnapPoints:y,selectionSnapPoints:f});const v=new P(d?0:((_=g[0])==null?void 0:_.nudge)??0,p?0:((k=w[0])==null?void 0:k.nudge)??0);if(o&&CF(u)&&v.len()!==0){const $=g.length&&w.length?Math.abs(v.x)t.width&&de(Math.abs(l))<=de(n.x)){de(Math.abs(l))E==="gap_center"),b=v&&kr(a.breadthIntersection[0],a.breadthIntersection[1],v.gap.breadthIntersection[0],v.gap.breadthIntersection[1]);v&&v.gap.length>a.length&&b?r[r.indexOf(v)]=S:(!v||!b)&&r.push(S)}const d=a.startNode.pageBounds.minX-a.length,p=t.maxX,f=d-p;de(Math.abs(f))<=de(n.x)&&(de(Math.abs(f))t.height&&de(Math.abs(l))<=de(n.y)){de(Math.abs(l))E==="gap_center"),b=v&&Xc(v.gap.breadthIntersection[0],v.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);v&&v.gap.length>a.length&&b?o[o.indexOf(v)]=S:(!v||!b)&&o.push(S);continue}const d=a.startNode.pageBounds.minY-a.length,p=t.maxY,f=d-p;de(Math.abs(f))<=de(n.y)&&(de(Math.abs(f))0){for(const s of t)if(s.type==="points"){const i=de(s.points.otherPoint.x);r[i]||(r[i]=[]),r[i].push(s.points)}}if(n.length>0){for(const s of n)if(s.type==="points"){const i=de(s.points.otherPoint.y);o[i]||(o[i]=[]),o[i].push(s.points)}}return Object.values(r).concat(Object.values(o)).map(s=>({id:et(),type:"points",points:Mp(s.map(i=>P.From(i.otherPoint)).concat(s.map(i=>P.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:t,nearestSnapsX:n,nearestSnapsY:r}){const{vertical:o,horizontal:s}=this.getVisibleGaps(),i={top:t.sides[0],right:t.sides[1],bottom:[t.corners[3],t.corners[2]],left:[t.corners[0],t.corners[3]]},a=[];if(n.length>0)for(const c of n){if(c.type==="points")continue;const{gap:{breadthIntersection:l,startEdge:u,startNode:d,endNode:p,length:f,endEdge:y}}=c;switch(c.type){case"gap_center":{const g=(f-t.width)/2,w=kr(l[0],l[1],t.minY,t.maxY);a.push({type:"gaps",direction:"horizontal",id:et(),gaps:[...Eo(s,d.id,g,"backward",w),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:y},...Eo(s,p.id,g,"forward",w)]});break}case"gap_duplicate":{const g=kr(l[0],l[1],t.minY,t.maxY);a.push({type:"gaps",direction:"horizontal",id:et(),gaps:c.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(w=>w.clone().addXY(-d.pageBounds.width,0))},{startEdge:u,endEdge:y},...Eo(s,p.id,f,"forward",g)]:[...Eo(s,d.id,f,"backward",g),{startEdge:u,endEdge:y},{startEdge:y.map(w=>w.clone().addXY(c.gap.endNode.pageBounds.width,0)),endEdge:i.left}]});break}}}if(r.length>0)for(const c of r){if(c.type==="points")continue;const{gap:{breadthIntersection:l,startEdge:u,startNode:d,endNode:p,length:f,endEdge:y}}=c;switch(c.type){case"gap_center":{const g=(f-t.height)/2,w=kr(l[0],l[1],t.minX,t.maxX);a.push({type:"gaps",direction:"vertical",id:et(),gaps:[...Eo(o,d.id,g,"backward",w),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:y},...Eo(o,c.gap.endNode.id,g,"forward",w)]});break}case"gap_duplicate":{const g=kr(l[0],l[1],t.minX,t.maxX);a.push({type:"gaps",direction:"vertical",id:et(),gaps:c.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(w=>w.clone().addXY(0,-d.pageBounds.height))},{startEdge:u,endEdge:y},...Eo(o,p.id,f,"forward",g)]:[...Eo(o,d.id,f,"backward",g),{startEdge:u,endEdge:y},{startEdge:y.map(w=>w.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return sz(a),a}}Bf([V],Du.prototype,"getSnapPointsCache");Bf([V],Du.prototype,"getSnappablePoints");Bf([V],Du.prototype,"getSnappableGapNodes");Bf([V],Du.prototype,"getVisibleGaps");function Y1(e,t){const{minX:n,maxX:r,minY:o,maxY:s}=t,i=[];switch(e){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:n,y:o})}switch(e){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:o})}switch(e){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:s})}switch(e){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:n,y:s})}return i}var iz=Object.defineProperty,az=Object.getOwnPropertyDescriptor,cz=(e,t,n,r)=>{for(var o=az(t,n),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(t,n,o)||o);return o&&iz(t,n,o),o};const lz=()=>null,uz=()=>[];class R2{constructor(t){m(this,"editor");this.manager=t,this.editor=t.editor}getSnapGeometryCache(){const{editor:t}=this;return t.store.createComputedCache("handle snap geometry",n=>{const r=t.getShapeUtil(n).getHandleSnapGeometry(n);return{outline:r.outline===void 0?t.getShapeGeometry(n):r.outline,points:r.points??[],getSelfSnapOutline:r.getSelfSnapOutline??lz,getSelfSnapPoints:r.getSelfSnapPoints??uz}})}*iterateSnapPointsInPageSpace(t,n){var o,s;const r=(o=this.getSnapGeometryCache().get(t))==null?void 0:o.getSelfSnapPoints(n);if(r&&r.length){const i=yi(this.editor.getShapePageTransform(t));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===t)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.points;if(!a||!a.length)continue;const c=yi(this.editor.getShapePageTransform(i));for(const l of a)yield c.applyToPoint(l)}}*iterateSnapOutlines(t,n){var o,s;const r=(o=this.getSnapGeometryCache().get(t))==null?void 0:o.getSelfSnapOutline(n);r&&(yield{shapeId:t,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===t)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:t,handle:n,handleInPageSpace:r}){const o=this.manager.getSnapThreshold();let s=o,i=null;for(const l of this.iterateSnapPointsInPageSpace(t,n))P.DistMin(r,l,s)&&(s=P.Dist(r,l),i=l);if(i)return i;let a=o,c=null;for(const{shapeId:l,outline:u}of this.iterateSnapOutlines(t,n)){const d=yi(this.editor.getShapePageTransform(l)),p=this.editor.getPointInShapeSpace(l,r),f=u.nearestPoint(p),y=d.applyToPoint(f);P.DistMin(r,y,a)&&(a=P.Dist(r,y),c=y)}return c||null}snapHandle({currentShapeId:t,handle:n}){const o=yi(this.editor.getShapePageTransform(t)).applyToPoint(n),s=this.getHandleSnapPosition({currentShapeId:t,handle:n,handleInPageSpace:o});return s?(this.manager.setIndicators([{id:et(),type:"points",points:[s]}]),{nudge:P.Sub(s,o)}):null}}cz([V],R2.prototype,"getSnapGeometryCache");var dz=Object.defineProperty,hz=Object.getOwnPropertyDescriptor,ax=(e,t,n,r)=>{for(var o=hz(t,n),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(t,n,o)||o);return o&&dz(t,n,o),o};class Uf{constructor(t){m(this,"shapeBounds");m(this,"handles");m(this,"_snapIndicators",fn("snapLines",void 0));this.editor=t,this.shapeBounds=new Du(this),this.handles=new R2(this)}getIndicators(){return this._snapIndicators.get()??Do}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(t){this._snapIndicators.set(t)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:t}=this,n=t.getRenderingBounds(),r=t.getSelectedShapeIds(),o=new Set,s=i=>{if(Kn(i)){const c=t.getShape(i);c&&t.isShapeOfType(c,"frame")&&o.add(i)}const a=t.getSortedChildIdsForParent(i);for(const c of a){if(r.includes(c))continue;const l=t.getShape(c);if(!l||!t.getShapeUtil(l).canSnap(l))continue;const d=t.getShapePageBounds(c);if(d&&n.includes(d)){if(t.isShapeOfType(l,"group")){s(c);continue}o.add(c)}}};return s(this.getCurrentCommonAncestor()??t.getCurrentPageId()),o}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}}ax([V],Uf.prototype,"getSnapThreshold");ax([V],Uf.prototype,"getSnappableShapes");ax([V],Uf.prototype,"getCurrentCommonAncestor");const pz=/\r?\n|\r/g;function X1(e){return e.replace(pz,` `).split(` `).map(t=>t||" ").join(` `)}const fz={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},gz=/\s/;class mz{constructor(t){m(this,"baseElm");m(this,"measureText",(t,n)=>{var i;const r=(i=this.baseElm)==null?void 0:i.cloneNode();this.baseElm.insertAdjacentElement("afterend",r),r.setAttribute("dir","ltr"),r.style.setProperty("font-family",n.fontFamily),r.style.setProperty("font-style",n.fontStyle),r.style.setProperty("font-weight",n.fontWeight),r.style.setProperty("font-size",n.fontSize+"px"),r.style.setProperty("line-height",n.lineHeight*n.fontSize+"px"),r.style.setProperty("max-width",n.maxWidth===null?null:n.maxWidth+"px"),r.style.setProperty("min-width",n.minWidth===null?null:n.minWidth+"px"),r.style.setProperty("padding",n.padding),r.style.setProperty("overflow-wrap",n.disableOverflowWrapBreaking?"normal":"break-word"),r.textContent=X1(t);const o=r.scrollWidth,s=r.getBoundingClientRect();return r.remove(),{x:0,y:0,w:s.width,h:s.height,scrollWidth:o}});var o;this.editor=t;const n=this.editor.getContainer();(o=n.querySelector("#tldraw_text_measure"))==null||o.remove();const r=document.createElement("div");r.id="tldraw_text_measure",r.classList.add("tl-text"),r.classList.add("tl-text-measure"),r.tabIndex=-1,n.appendChild(r),this.baseElm=r}measureElementTextNodeSpans(t,{shouldTruncateToFirstLine:n=!1}={}){const r=[],o=t.getBoundingClientRect(),s=-o.left,i=-o.top,a=new Range,c=t.childNodes[0];let l=0,u=null,d=null,p=0,f=!1;for(const y of t.childNodes)if(y.nodeType===Node.TEXT_NODE)for(const g of y.textContent??""){a.setStart(c,l),a.setEnd(c,l+g.length);const w=a.getClientRects(),S=w[w.length-1],v=S.top+i,b=S.left+s,E=S.right+s,C=gz.test(g);if(C!==d||v!==p||!u){if(u){if(n&&v!==p){f=!0;break}r.push(u)}u={box:{x:b,y:v,w:S.width,h:S.height},text:g}}else u.box.w=E-u.box.x,u.text+=g;d=C,p=v,l+=g.length}return u&&r.push(u),{spans:r,didTruncate:f}}measureTextSpans(t,n){var l;if(t==="")return[];const r=(l=this.baseElm)==null?void 0:l.cloneNode();this.baseElm.insertAdjacentElement("afterend",r);const o=Math.ceil(n.width-n.padding*2);r.style.setProperty("width",`${o}px`),r.style.setProperty("height","min-content"),r.style.setProperty("dir","ltr"),r.style.setProperty("font-size",`${n.fontSize}px`),r.style.setProperty("font-family",n.fontFamily),r.style.setProperty("font-weight",n.fontWeight),r.style.setProperty("line-height",`${n.lineHeight*n.fontSize}px`),r.style.setProperty("text-align",fz[n.textAlign]);const s=n.overflow==="truncate-ellipsis"||n.overflow==="truncate-clip";s&&(r.style.setProperty("overflow-wrap","anywhere"),r.style.setProperty("word-break","break-all"));const i=X1(t);r.textContent=i;const{spans:a,didTruncate:c}=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:s});if(n.overflow==="truncate-ellipsis"&&c){r.textContent="…";const u=Math.ceil(this.measureElementTextNodeSpans(r).spans[0].box.w);r.style.setProperty("width",`${o-u}px`),r.textContent=i;const d=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:!0}).spans,p=d[d.length-1];return d.push({text:"…",box:{x:Math.min(p.box.x+p.box.w,n.width-n.padding-u),y:p.box.y,w:u,h:p.box.h}}),d}return r.remove(),a}}const q1=(typeof process<"u",Q_);class yz{constructor(t){m(this,"cancelRaf");m(this,"isPaused",!0);m(this,"now",0);m(this,"start",()=>{var t;this.isPaused=!1,(t=this.cancelRaf)==null||t.call(this),this.cancelRaf=q1(this.tick),this.now=Date.now()});m(this,"tick",()=>{if(this.isPaused)return;const t=Date.now(),n=t-this.now;this.now=t,this.updatePointerVelocity(n),this.editor.emit("frame",n),this.editor.emit("tick",n),this.cancelRaf=q1(this.tick)});m(this,"dispose",()=>{var t;this.isPaused=!0,(t=this.cancelRaf)==null||t.call(this)});m(this,"prevPoint",new P);m(this,"updatePointerVelocity",t=>{const{prevPoint:n,editor:{inputs:{currentScreenPoint:r,pointerVelocity:o}}}=this;if(t===0)return;const s=P.Sub(r,n);this.prevPoint=r.clone();const i=s.len(),a=i?s.div(i):new P(0,0),c=o.clone().lrp(a.mul(i/t),.5);Math.abs(c.x)<.01&&(c.x=0),Math.abs(c.y)<.01&&(c.y=0),o.equals(c)||(this.editor.inputs.pointerVelocity=c)});this.editor=t,this.editor.disposables.add(this.dispose),this.start()}}var Sz=Object.defineProperty,vz=Object.getOwnPropertyDescriptor,go=(e,t,n,r)=>{for(var o=vz(t,n),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(t,n,o)||o);return o&&Sz(t,n,o),o};class Hr{constructor(t,n){m(this,"updateUserPreferences",t=>{this.user.setUserPreferences({...this.user.userPreferences.get(),...t})});this.user=t,this.inferDarkMode=n}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),isSnapMode:this.getIsSnapMode(),isDarkMode:this.getIsDarkMode(),isWrapMode:this.getIsWrapMode()}}getIsDarkMode(){return this.user.userPreferences.get().isDarkMode??(this.inferDarkMode?w4():!1)}getEdgeScrollSpeed(){return this.user.userPreferences.get().edgeScrollSpeed??ai.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??ai.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??ai.name}getLocale(){return this.user.userPreferences.get().locale??ai.locale}getColor(){return this.user.userPreferences.get().color??ai.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??ai.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??ai.isWrapMode}}go([V],Hr.prototype,"getUserPreferences");go([V],Hr.prototype,"getIsDarkMode");go([V],Hr.prototype,"getEdgeScrollSpeed");go([V],Hr.prototype,"getAnimationSpeed");go([V],Hr.prototype,"getId");go([V],Hr.prototype,"getName");go([V],Hr.prototype,"getLocale");go([V],Hr.prototype,"getColor");go([V],Hr.prototype,"getIsSnapMode");go([V],Hr.prototype,"getIsWrapMode");function Zc(e){return Math.abs(e.props.bend)<8}function Qp(e,t){if(t.type==="point")return;const n=e.getShape(t.boundShapeId),r=e.getShapePageTransform(n),o=e.getShapeGeometry(n),s=o instanceof Br?o.children[0].vertices:o.vertices;return{shape:n,transform:r,isClosed:o.isClosed,isExact:t.isExact,didIntersect:!1,outline:s}}function Z1(e,t,n,r){if(n.type==="point")return P.From(n);const o=e.getShape(n.boundShapeId);if(o){const{point:s,size:i}=e.getShapeGeometry(o).bounds,a=P.Add(s,P.MulV(n.isPrecise||r?n.normalizedAnchor:{x:.5,y:.5},i)),c=oe.applyToPoint(e.getShapePageTransform(o),a);return oe.applyToPoint(oe.Inverse(t),c)}else return new P(0,0)}function jr(e,t){const n=e.getShapePageTransform(t);let r,o;t.props.start.type==="binding"&&t.props.end.type==="binding"&&(r=t.props.start.boundShapeId,o=t.props.end.boundShapeId);const s=cx(e,r,o),i=Z1(e,n,t.props.start,s==="double-bound"||s==="start-contains-end"),a=Z1(e,n,t.props.end,s==="double-bound"||s==="end-contains-start");return{start:i,end:a}}const Ma=10,Jp=10,xz=10,Ps={s:2,m:3.5,l:5,xl:10};function cx(e,t,n){if(!t||!n)return"safe";if(t===n)return"double-bound";const r=e.getShapePageBounds(t),o=e.getShapePageBounds(n);if(r&&o){if(r.contains(o))return"start-contains-end";if(o.contains(r))return"end-contains-start"}return"safe"}function Al(e,t){const{start:n,end:r,arrowheadStart:o,arrowheadEnd:s}=t.props,i=jr(e,t),a=i.start.clone(),c=i.end.clone(),l=P.Med(a,c);if(P.Equals(a,c))return{isStraight:!0,start:{handle:a,point:a,arrowhead:t.props.arrowheadStart},end:{handle:c,point:c,arrowhead:t.props.arrowheadEnd},middle:l,isValid:!1,length:0};const u=P.Sub(c,a).uni(),d=Qp(e,n),p=Qp(e,r),f=e.getShapePageTransform(t);Q1(c,i.start,f,p),Q1(a,i.end,f,d);let y=0,g=0,w=0,S=0,v=Ma;const b=d&&p&&d.shape===p.shape,E=d&&p?cx(e,d.shape.id,p.shape.id):"safe";E==="safe"&&d&&p&&!b&&!d.isExact&&!p.isExact&&(p.didIntersect&&!d.didIntersect?d.isClosed&&a.setTo(c.clone().add(u.clone().mul(Ma))):p.didIntersect||p.isClosed&&c.setTo(a.clone().sub(u.clone().mul(Ma))));const C=P.Sub(c,a),I=P.Len(C)?C.uni():P.From(C),_=!P.Equals(I,u);b||(E!=="start-contains-end"&&d&&o!=="none"&&!d.isExact&&(w=Ps[t.props.size]/2+("size"in d.shape.props?Ps[d.shape.props.size]/2:0),y=Jp+w,v+=w),E!=="end-contains-start"&&p&&s!=="none"&&!p.isExact&&(S=Ps[t.props.size]/2+("size"in p.shape.props?Ps[p.shape.props.size]/2:0),g=Jp+S,v+=S));const k=a.clone().add(I.clone().mul(y*(_?-1:1))),$=c.clone().sub(I.clone().mul(g*(_?-1:1)));P.DistMin(k,$,v)&&(y!==0&&g!==0?(y*=-1.5,g*=-1.5):y!==0?y*=-1:g!==0&&(g*=-1)),a.add(I.clone().mul(y*(_?-1:1))),c.sub(I.clone().mul(g*(_?-1:1))),_?(d&&p&&c.setTo(P.Add(a,I.clone().mul(-Ma))),l.setTo(P.Med(i.start,i.end))):l.setTo(P.Med(a,c));const T=P.Dist(a,c);return{isStraight:!0,start:{handle:i.start,point:a,arrowhead:t.props.arrowheadStart},end:{handle:i.end,point:c,arrowhead:t.props.arrowheadEnd},middle:l,isValid:T>0,length:T}}function Q1(e,t,n,r){if(r===void 0||r.isExact)return;const o=oe.applyToPoint(n,t),s=oe.applyToPoint(n,e),i=oe.applyToPoint(oe.Inverse(r.transform),o),a=oe.applyToPoint(oe.Inverse(r.transform),s),c=r.isClosed,u=(c?ox:T4)(i,a,r.outline);let d;if(u!==null&&(d=u.sort((y,g)=>P.Dist2(y,i)-P.Dist2(g,i))[0]??(c?void 0:a)),d===void 0)return;const p=oe.applyToPoint(r.transform,d),f=oe.applyToPoint(oe.Inverse(n),p);e.setTo(f),r.didIntersect=!0}function xm(e,t,n=0){const{arrowheadEnd:r,arrowheadStart:o}=t.props,s=t.props.bend+n;if(Math.abs(s)>Math.abs(t.props.bend*xz))return Al(e,t);const i=jr(e,t),a=P.Med(i.start,i.end),c=P.Sub(i.end,i.start),l=P.Len(c)?c.uni():P.From(c),u=P.Add(a,l.per().mul(-s)),d=Qp(e,t.props.start),p=Qp(e,t.props.end),f=i.start.clone(),y=i.end.clone(),g=u.clone();if(P.Equals(f,y))return{isStraight:!0,start:{handle:f,point:f,arrowhead:t.props.arrowheadStart},end:{handle:y,point:y,arrowhead:t.props.arrowheadEnd},middle:g,isValid:!1,length:0};const w=t.props.bend<0,S=w?$u:Kk,v=J1(f,y,g),b=P.Angle(v.center,f),E=P.Angle(v.center,y),C=S(b,E);if(v.length===0||v.size===0||!x1(v.length)||!x1(v.size))return Al(e,t);const I=f.clone(),_=y.clone(),k=g.clone(),$=e.getShapePageTransform(t);let T=0,O=0,N=Ma;if(d&&!d.isExact){const W=oe.applyToPoint($,I),Z=oe.applyToPoint($,v.center),le=oe.applyToPoint($,_),be=oe.Inverse(d.transform),Me=oe.applyToPoint(be,W),ae=oe.applyToPoint(be,Z),Ae=oe.applyToPoint(be,le),{isClosed:Re}=d,ot=Re?WS:K1;let Ie,ht=ot(ae,v.radius,d.outline);if(ht){const He=ae.angle(Me),ir=ae.angle(Ae),Ln=S(He,ir);ht=ht.filter(qe=>S(He,ae.angle(qe))<=Ln);const Fn=Ln*.25;ht.sort(Re?(qe,Ot)=>Math.abs(S(He,ae.angle(qe))-Fn)S(He,ae.angle(qe))S(He,ae.angle(qe))<=Ln),ht.sort(Re?(qe,Ot)=>Math.abs(S(He,ae.angle(qe))-Fn)S(He,ae.angle(qe))S(b,L))){const Z=Math.min(.9,Ma/q)*(w?1:-1),le=P.FromAngle(F+B*Z);_.setTo(v.center).add(le.mul(v.radius))}}wz(v.center,v.radius,I,_,k,C,w),I.equals(_)&&(I.setTo(k.clone().addXY(1,1)),_.setTo(k.clone().subXY(1,1))),f.setTo(I),y.setTo(_),g.setTo(k);const U=J1(f,y,g);return{isStraight:!1,start:{point:f,handle:i.start,arrowhead:t.props.arrowheadStart},end:{point:y,handle:i.end,arrowhead:t.props.arrowheadEnd},middle:g,handleArc:v,bodyArc:U,isValid:U.length!==0&&isFinite(U.center.x)&&isFinite(U.center.y)}}function J1(e,t,n){const r=-2*(e.x*(t.y-n.y)-e.y*(t.x-n.x)+t.x*n.y-n.x*t.y),o={x:((e.x*e.x+e.y*e.y)*(n.y-t.y)+(t.x*t.x+t.y*t.y)*(e.y-n.y)+(n.x*n.x+n.y*n.y)*(t.y-e.y))/r,y:((e.x*e.x+e.y*e.y)*(t.x-n.x)+(t.x*t.x+t.y*t.y)*(n.x-e.x)+(n.x*n.x+n.y*n.y)*(e.x-t.x))/r},s=P.Dist(o,e),i=+P.Clockwise(e,n,t),a=((e.y-t.y)**2+(e.x-t.x)**2)**.5,c=((t.y-n.y)**2+(t.x-n.x)**2)**.5,l=((n.y-e.y)**2+(n.x-e.x)**2)**.5,u=Math.acos((c*c+l*l-a*a)/(2*c*l))*2,d=+(Pe>u),p=(Oe-u)*(i?1:-1),f=p*s;return{center:o,radius:s,size:p,length:f,largeArcFlag:d,sweepFlag:i}}function wz(e,t,n,r,o,s,i){const a=P.Angle(e,n),c=P.Angle(e,r);let l=$u(a,c);i||(l=Oe-l);const u=.5*(i?1:-1),d=P.FromAngle(a+l*u);if(o.setTo(e).add(d.mul(t)),l>s){o.rotWith(e,Pe);const p=r.clone();r.setTo(n),n.setTo(p)}}const bz={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"};class se{constructor(t,n){m(this,"id");m(this,"type");m(this,"shapeType");m(this,"initial");m(this,"children");m(this,"parent");m(this,"_path");m(this,"_current");m(this,"_isActive");m(this,"transition",(t,n={})=>{var s;const r=t.split(".");let o=this;for(let i=0;i{var o;const n=bz[t.name],r=this._current.__unsafe__getWithoutCapture();(o=this[n])==null||o.call(this,t),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(t)});m(this,"enter",(t,n)=>{var r;if(this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,t,n),this.children&&this.initial&&this.getIsActive()){const o=this.children[this.initial];this._current.set(o),o.enter(t,n)}});m(this,"exit",(t,n)=>{var r,o;this._isActive.set(!1),(r=this.onExit)==null||r.call(this,t,n),this.getIsActive()||(o=this.getCurrent())==null||o.exit(t,n)});m(this,"_currentToolIdMask",fn("curent tool id mask",void 0));m(this,"onWheel");m(this,"onPointerDown");m(this,"onPointerMove");m(this,"onLongPress");m(this,"onPointerUp");m(this,"onDoubleClick");m(this,"onTripleClick");m(this,"onQuadrupleClick");m(this,"onRightClick");m(this,"onMiddleClick");m(this,"onKeyDown");m(this,"onKeyUp");m(this,"onKeyRepeat");m(this,"onCancel");m(this,"onComplete");m(this,"onInterrupt");m(this,"onTick");m(this,"onEnter");m(this,"onExit");this.editor=t;const{id:r,children:o,initial:s}=this.constructor;this.id=r,this._isActive=fn("toolIsActive"+this.id,!1),this._current=fn("toolState"+this.id,void 0),this._path=V("toolPath"+this.id,()=>{const i=this.getCurrent();return this.id+(i?`.${i.getPath()}`:"")}),this.parent=n??{},this.parent?o&&s?(this.type="branch",this.initial=s,this.children=Object.fromEntries(o().map(i=>[i.id,new i(this.editor,this)])),this._current.set(this.children[this.initial])):this.type="leaf":(this.type="root",o&&s&&(this.initial=s,this.children=Object.fromEntries(o().map(i=>[i.id,new i(this.editor,this)])),this._current.set(this.children[this.initial])))}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(t){this._currentToolIdMask.set(t)}}m(se,"id"),m(se,"initial"),m(se,"children");class bh extends se{constructor(){super(...arguments);m(this,"onKeyDown",n=>{var r;switch(n.code){case"KeyZ":{if(!(n.shiftKey||n.ctrlKey)){const o=this.getCurrent();o&&((r=o.getCurrent())==null?void 0:r.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...n,onInteractionEnd:o.id})}break}}})}}m(bh,"id","root"),m(bh,"initial",""),m(bh,"children",()=>[]);var Pz=Object.defineProperty,Cz=Object.getOwnPropertyDescriptor,re=(e,t,n,r)=>{for(var o=Cz(t,n),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(t,n,o)||o);return o&&Pz(t,n,o),o};class J extends k4.EventEmitter{constructor({store:n,user:r,shapeUtils:o,tools:s,getContainer:i,initialState:a,inferDarkMode:c}){super();m(this,"store");m(this,"root");m(this,"disposables",new Set);m(this,"_tickManager");m(this,"snaps");m(this,"user");m(this,"textMeasure");m(this,"environment");m(this,"scribbles");m(this,"getContainer");m(this,"sideEffects");m(this,"shapeUtils");m(this,"styleProps");m(this,"history",new ez(this,n=>{this.annotateError(n,{origin:"history.batch",willCrashApp:!0}),this.crash(n)}));m(this,"_crashingError",null);m(this,"_updateInstanceState",this.history.createCommand("updateInstanceState",(n,r)=>{const o=this.store.get(this.getInstanceState().id),s={...o,...n};return{data:{prev:o,next:s},ephemeral:!1,squashing:!1,...r}},{do:({next:n})=>{this.store.put([n])},undo:({prev:n})=>{this.store.put([n])},squash({prev:n},{next:r}){return{prev:n,next:r}}}));m(this,"_isChangingStyleTimeout",-1);m(this,"setCursor",n=>(this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...n}},{ephemeral:!0}),this));m(this,"_setInstancePageState",this.history.createCommand("setInstancePageState",(n,r)=>({data:{prev:this.store.get(n.id??this.getCurrentPageState().id),partial:n},...r}),{do:({prev:n,partial:r})=>{this.store.update(n.id,o=>({...o,...r}))},undo:({prev:n})=>{this.store.update(n.id,()=>n)}}));m(this,"_setSelectedShapes",this.history.createCommand("setSelectedShapes",(n,r)=>{const{selectedShapeIds:o}=this.getCurrentPageState(),s=new Set(o);return n.length===s.size&&n.every(i=>s.has(i))?null:{data:{selectedShapeIds:n,prevSelectedShapeIds:o},preservesRedoStack:!0,...r}},{do:({selectedShapeIds:n})=>{this.store.put([{...this.getCurrentPageState(),selectedShapeIds:n}])},undo:({prevSelectedShapeIds:n})=>{this.store.put([{...this.getCurrentPageState(),selectedShapeIds:n}])},squash({prevSelectedShapeIds:n},{selectedShapeIds:r}){return{selectedShapeIds:r,prevSelectedShapeIds:n}}}));m(this,"_setFocusedGroupId",this.history.createCommand("setFocusedGroupId",n=>{const r=this.getCurrentPageState().focusedGroupId;if(r!==n)return{data:{prev:r,next:n},preservesRedoStack:!0,squashing:!0}},{do:({next:n})=>{this.store.update(this.getCurrentPageState().id,r=>({...r,focusedGroupId:n}))},undo:({prev:n})=>{this.store.update(this.getCurrentPageState().id,r=>({...r,focusedGroupId:n}))},squash({prev:n},{next:r}){return{prev:n,next:r}}}));m(this,"_viewportAnimation",null);m(this,"_willSetInitialBounds",!0);m(this,"_wasInset",!1);m(this,"_cameraState",fn("camera state","idle"));m(this,"_cameraStateTimeoutRemaining",0);m(this,"_lastUpdateRenderingBoundsTimestamp",Date.now());m(this,"_decayCameraStateTimeout",n=>{this._cameraStateTimeoutRemaining-=n,this._cameraStateTimeoutRemaining<=0&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"),this.updateRenderingBounds())});m(this,"_tickCameraState",()=>{this._cameraStateTimeoutRemaining=R5;const n=Date.now();this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._lastUpdateRenderingBoundsTimestamp=n,this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))});m(this,"_renderingBounds",fn("rendering viewport",new ne));m(this,"renderingBoundsMargin",100);m(this,"_currentPageShapeIds");m(this,"_setCurrentPageId",this.history.createCommand("setCurrentPage",(n,r)=>{if(!this.store.has(n)){console.error("Tried to set the current page id to a page that doesn't exist.");return}return this.stopFollowingUser(),{data:{toId:n,fromId:this.getCurrentPageId()},squashing:!0,preservesRedoStack:!0,...r}},{do:({toId:n})=>{if(this.store.has(n)){if(!this.getPageStates().find(r=>r.pageId===n)){const r=hn.create({id:hn.createId(n)});this.store.put([r,Zt.create({id:Zt.createId(n),pageId:n})])}this.store.put([{...this.getInstanceState(),currentPageId:n}]),this.updateRenderingBounds()}},undo:({fromId:n})=>{this.store.has(n)&&(this.store.put([{...this.getInstanceState(),currentPageId:n}]),this.updateRenderingBounds())},squash:({fromId:n},{toId:r})=>({toId:r,fromId:n})}));m(this,"_updatePage",this.history.createCommand("updatePage",(n,r)=>{if(this.getInstanceState().isReadonly)return null;const o=this.getPage(n.id);return o?{data:{prev:o,partial:n},...r}:null},{do:({partial:n})=>{this.store.update(n.id,r=>({...r,...n}))},undo:({prev:n,partial:r})=>{this.store.update(r.id,()=>n)},squash(n,r){return{prev:{...n.prev,...r.prev},partial:r.partial}}}));m(this,"_createPage",this.history.createCommand("createPage",n=>{if(this.getInstanceState().isReadonly||this.getPages().length>=Gp)return null;const r=this.getPages(),o=L4(n.name??"Page 1",r.map(l=>l.name));let s=n.index;(!s||r.some(l=>l.index===s))&&(s=$o(r[r.length-1].index));const i=Ho.create({meta:{},...n,name:o,index:s}),a=hn.create({id:hn.createId(i.id)}),c=Zt.create({id:Zt.createId(i.id),pageId:i.id});return{data:{newPage:i,newTabPageState:c,newCamera:a}}},{do:({newPage:n,newTabPageState:r,newCamera:o})=>{this.store.put([n,o,r])},undo:({newPage:n,newTabPageState:r,newCamera:o})=>{this.getPages().length!==1&&this.store.remove([r.id,n.id,o.id])}}));m(this,"_deletePage",this.history.createCommand("delete_page",n=>{if(this.getInstanceState().isReadonly)return null;const r=this.getPages();if(r.length===1)return null;const o=this.getPage(n),s=this.getPageStates().filter(i=>i.pageId===n);if(!o)return null;if(n===this.getCurrentPageId()){const i=r.findIndex(c=>c.id===n),a=r[i-1]??r[i+1];this.setCurrentPage(a.id)}return{data:{id:n,deletedPage:o,deletedPageStates:s}}},{do:({deletedPage:n,deletedPageStates:r})=>{const o=this.getPages();if(o.length!==1){if(n.id===this.getCurrentPageId()){const s=o.findIndex(a=>a.id===n.id),i=o[s-1]??o[s+1];this.setCurrentPage(i.id)}this.store.remove(r.map(s=>s.id)),this.store.remove([n.id]),this.updateRenderingBounds()}},undo:({deletedPage:n,deletedPageStates:r})=>{this.store.put([n]),this.store.put(r),this.updateRenderingBounds()}}));m(this,"_createAssets",this.history.createCommand("createAssets",n=>this.getInstanceState().isReadonly||n.length<=0?null:{data:{assets:n}},{do:({assets:n})=>{this.store.put(n)},undo:({assets:n})=>{this.store.remove(n.map(r=>r.id))}}));m(this,"_updateAssets",this.history.createCommand("updateAssets",n=>this.getInstanceState().isReadonly||n.length<=0?void 0:{data:{snapshots:{},assets:n}},{do:({assets:n,snapshots:r})=>{this.store.put(n.map(o=>{const s=this.store.get(o.id);return r[o.id]=s,{...s,...o}}))},undo:({snapshots:n})=>{this.store.put(Object.values(n))}}));m(this,"_deleteAssets",this.history.createCommand("deleteAssets",n=>{if(this.getInstanceState().isReadonly||n.length<=0)return;const r=fe(n.map(o=>this.store.get(o)));return{data:{ids:n,prev:r}}},{do:({ids:n})=>{this.store.remove(n)},undo:({prev:n})=>{this.store.put(n)}}));m(this,"_parentIdsToChildIds");m(this,"_childIdsCache",new zf);m(this,"_createShapes",this.history.createCommand("createShapes",n=>{if(this.getInstanceState().isReadonly||n.length<=0)return null;const r=this.getCurrentPageShapeIds();if(n.length+r.size>Io){_d(this);return}return n.length===0?null:{data:{currentPageId:this.getCurrentPageId(),partials:n.map(s=>s.id?s:{...s,id:Be()})}}},{do:({partials:n})=>{var a,c;const r=this.getFocusedGroupId(),o=this.getCurrentPageShapesSorted();n=n.map(l=>{if(!l.parentId||!(this.store.has(l.parentId)||n.some(u=>u.id===l.parentId))){let u=this.getFocusedGroupId();for(let p=o.length-1;p>=0;p--){const f=o[p];if(this.getShapeUtil(f).canReceiveNewChildrenOfType(f,l.type)&&this.isPointInShape(f,{x:l.x??0,y:l.y??0},{margin:0,hitInside:!0})){u=f.id;break}}const d=l.parentId;if(u===l.id&&(u=r),u!==d&&(l={...l},l.parentId=u,Kn(u))){const p=this.getPointInShapeSpace(this.getShape(u),{x:l.x??0,y:l.y??0});l.x=p.x,l.y=p.y,l.rotation=-this.getShapePageTransform(u).rotation()+(l.rotation??0)}}return l});const s=new Map,i=[];for(const l of n){const u=this.getShapeUtil(l);let d=l.index;if(!d){const g=l.parentId??r;s.has(g)||s.set(g,this.getHighestIndexForParent(g)),d=s.get(g),s.set(g,$o(d))}const p=u.getDefaultProps();for(const[g,w]of this.styleProps[l.type])p[w]=this.getStyleForNextShape(g);let f=this.store.schema.types.shape.create({...l,index:d,opacity:l.opacity??this.getInstanceState().opacityForNextShape,parentId:l.parentId??r,props:"props"in l?{...p,...l.props}:p});if(f.index===void 0)throw Error("no index!");const y=(c=(a=this.getShapeUtil(f)).onBeforeCreate)==null?void 0:c.call(a,f);y&&(f=y),i.push(f)}i.forEach(l=>{l.meta={...this.getInitialMetaForShape(l),...l.meta}}),this.store.put(i)},undo:({partials:n})=>{this.store.remove(n.map(r=>r.id))}}));m(this,"animatingShapes",new Map);m(this,"_updateShapes",this.history.createCommand("updateShapes",(n,r)=>{if(this.getInstanceState().isReadonly)return null;const o={},s={};let i,a;for(let c=0,l=n.length;c{this.store.put(bt(n).map(r=>{var s,i;const o=this.store.get(r.id);if(o){const a=(i=(s=this.getShapeUtil(r)).onBeforeUpdate)==null?void 0:i.call(s,o,r);if(a)return a}return r}))},undo:({snapshots:n})=>{this.store.put(Object.values(n))},squash(n,r){return{snapshots:{...r.snapshots,...n.snapshots},updates:{...n.updates,...r.updates}}}}));m(this,"_deleteShapes",this.history.createCommand("delete_shapes",n=>{if(this.getInstanceState().isReadonly||n.length===0)return null;const r=[...this.getCurrentPageState().selectedShapeIds],o=new Set(n);for(const l of n)this.visitDescendants(l,u=>{o.add(u)});const s=[...o],i=this._getArrowBindingsIndex().get(),a=fe(s.flatMap(l=>{const u=this.getShape(l),d=i[l];return d&&d.length>0?d.map(({arrowId:p})=>this.getShape(p)).concat(u):u})),c=r.filter(l=>!o.has(l));return{data:{deletedIds:s,snapshots:a,prevSelectedShapeIds:r,postSelectedShapeIds:c}}},{do:({deletedIds:n,postSelectedShapeIds:r})=>{this.store.remove(n),this.store.update(this.getCurrentPageState().id,o=>({...o,selectedShapeIds:r}))},undo:({snapshots:n,prevSelectedShapeIds:r})=>{this.store.put(n),this.store.update(this.getCurrentPageState().id,o=>({...o,selectedShapeIds:r}))}}));m(this,"externalAssetContentHandlers",{file:null,url:null});m(this,"externalContentHandlers",{text:null,files:null,embed:null,"svg-text":null,url:null});m(this,"inputs",{originPagePoint:new P,originScreenPoint:new P,previousPagePoint:new P,previousScreenPoint:new P,currentPagePoint:new P,currentScreenPoint:new P,keys:new Set,buttons:new Set,isPen:!1,shiftKey:!1,ctrlKey:!1,altKey:!1,isDragging:!1,isPointing:!1,isPinching:!1,isEditing:!1,isPanning:!1,pointerVelocity:new P});m(this,"_clickManager",new q4(this));m(this,"_prevCursor","default");m(this,"_shiftKeyTimeout",-1);m(this,"_setShiftKeyTimeout",()=>{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"})});m(this,"_altKeyTimeout",-1);m(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"})});m(this,"_ctrlKeyTimeout",-1);m(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"})});m(this,"_restoreToolId","select");m(this,"_pinchStart",1);m(this,"_didPinch",!1);m(this,"_selectedShapeIdsAtPointerDown",[]);m(this,"_longPressTimeout",-1);m(this,"capturedPointerId",null);m(this,"dispatch",n=>(this._pendingEventsForNextTick.push(n),n.type==="pointer"&&n.name==="pointer_move"||n.type==="wheel"||n.type==="pinch"||this._flushEventsForTick(0),this));m(this,"_pendingEventsForNextTick",[]);m(this,"_flushEventForTick",n=>{if(this.getCrashingError())return this;const{inputs:r}=this,{type:o}=n;if(n.type==="misc"){(n.name==="cancel"||n.name==="complete")&&(this.inputs.isDragging=!1,this.inputs.isPanning&&(this.inputs.isPanning=!1,this.updateInstanceState({cursor:{type:this._prevCursor,rotation:0}}))),this.root.handleEvent(n);return}n.shiftKey?(clearInterval(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,r.shiftKey=!0):!n.shiftKey&&r.shiftKey&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=setTimeout(this._setShiftKeyTimeout,150)),n.altKey?(clearInterval(this._altKeyTimeout),this._altKeyTimeout=-1,r.altKey=!0):!n.altKey&&r.altKey&&this._altKeyTimeout===-1&&(this._altKeyTimeout=setTimeout(this._setAltKeyTimeout,150)),n.ctrlKey?(clearInterval(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,r.ctrlKey=!0):!n.ctrlKey&&r.ctrlKey&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=setTimeout(this._setCtrlKeyTimeout,150));const{originPagePoint:s,originScreenPoint:i,currentPagePoint:a,currentScreenPoint:c}=r;switch(r.isPointing||(r.isDragging=!1),o){case"pinch":{if(!this.getInstanceState().canMoveCamera)return;switch(clearTimeout(this._longPressTimeout),this._updateInputsFromEvent(n),n.name){case"pinch_start":{if(r.isPinching)return;r.isEditing||(this._pinchStart=this.getCamera().z,this._selectedShapeIdsAtPointerDown.length||(this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds()),this._didPinch=!0,r.isPinching=!0,this.interrupt());return}case"pinch":{if(!r.isPinching)return;const{point:{z:l=1},delta:{x:u,y:d}}=n,{screenBounds:p}=this.store.unsafeGetWithoutCapture(In),{x:f,y}=P.SubXY(n.point,p.x,p.y),{x:g,y:w,z:S}=this.getCamera(),v=Math.min(xs,Math.max(qc,l));this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this._setCamera({x:g+u/S-f/S+f/v,y:w+d/S-y/S+y/v,z:v},!0);return}case"pinch_end":{if(!r.isPinching)return this;r.isPinching=!1;const{_selectedShapeIdsAtPointerDown:l}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown,{squashing:!0}),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,this.once("tick",()=>{this._didPinch||this.setSelectedShapes(l,{squashing:!0})}));return}}}case"wheel":{if(!this.getInstanceState().canMoveCamera)return;if(this._updateInputsFromEvent(n),!this.getIsMenuOpen()){if(this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),r.ctrlKey){const{x:p,y:f}=this.inputs.currentScreenPoint,{x:y,y:g,z:w}=this.getCamera(),S=Math.min(xs,Math.max(qc,w+(n.delta.z??0)*w));this._setCamera({x:y+(p/S-p)-(p/w-p),y:g+(f/S-f)-(f/w-f),z:S},!0);return}const{x:l,y:u,z:d}=this.getCamera();this._setCamera({x:l+n.delta.x/d,y:u+n.delta.y/d,z:d},!0),!r.isDragging&&r.isPointing&&P.Dist2(s,a)>(this.getInstanceState().isCoarsePointer?BS:iu)/this.getZoomLevel()&&(clearTimeout(this._longPressTimeout),r.isDragging=!0)}break}case"pointer":{if(r.isPinching)return;this._updateInputsFromEvent(n);const{isPen:l}=n;switch(n.name){case"pointer_down":{if(this.clearOpenMenus(),this._longPressTimeout=setTimeout(()=>{this.dispatch({...n,name:"long_press"})},B5),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),n.button===0&&(this.capturedPointerId=n.pointerId),r.buttons.add(n.button),r.isPointing=!0,r.isDragging=!1,this.getInstanceState().isPenMode){if(!l)return}else l&&this.updateInstanceState({isPenMode:!0});if(n.button===5?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):n.button===1&&(this.inputs.isPanning||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.isPanning=!0),this.inputs.isPanning)return this.stopCameraAnimation(),this.setCursor({type:"grabbing",rotation:0}),this;i.setTo(c),s.setTo(a);break}case"pointer_move":{if(!l&&this.getInstanceState().isPenMode)return;if(this.inputs.isPanning&&this.inputs.isPointing){clearTimeout(this._longPressTimeout);const{currentScreenPoint:u,previousScreenPoint:d}=this.inputs;this.pan(P.Sub(u,d));return}!r.isDragging&&r.isPointing&&P.Dist2(s,a)>(this.getInstanceState().isCoarsePointer?BS:iu)/this.getZoomLevel()&&(clearTimeout(this._longPressTimeout),r.isDragging=!0);break}case"pointer_up":{if(r.buttons.delete(n.button),r.isPointing=!1,r.isDragging=!1,this.getIsMenuOpen()||!l&&this.getInstanceState().isPenMode)return;this.capturedPointerId===n.pointerId&&(this.capturedPointerId=null,n.button=0),r.isPanning?n.button===1?this.inputs.keys.has(" ")?(this.slideCamera({speed:Math.min(2,this.inputs.pointerVelocity.len()),direction:this.inputs.pointerVelocity,friction:Sh}),this.setCursor({type:"grab",rotation:0})):(r.isPanning=!1,this.slideCamera({speed:Math.min(2,this.inputs.pointerVelocity.len()),direction:this.inputs.pointerVelocity,friction:Sh}),this.setCursor({type:this._prevCursor,rotation:0})):n.button===0&&(this.slideCamera({speed:Math.min(2,this.inputs.pointerVelocity.len()),direction:this.inputs.pointerVelocity,friction:Sh}),this.setCursor({type:"grab",rotation:0})):n.button===5&&(this.complete(),this.setCurrentTool(this._restoreToolId));break}}break}case"keyboard":{switch(n.key==="ShiftRight"&&(n.key="ShiftLeft"),n.key==="AltRight"&&(n.key="AltLeft"),n.code==="ControlRight"&&(n.code="ControlLeft"),n.name){case"key_down":{r.keys.add(n.code),!n.ctrlKey&&n.code==="Space"&&(this.inputs.isPanning||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.isPanning=!0,this.setCursor({type:this.inputs.isPointing?"grabbing":"grab",rotation:0}));break}case"key_up":{r.keys.delete(n.code),n.code==="Space"&&!this.inputs.buttons.has(1)&&(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0}));break}}break}}if(n.type==="pointer"&&(n.button===1?n.name="middle_click":n.button===2&&(n.name="right_click"),n.isPen===this.getInstanceState().isPenMode))switch(n.name){case"pointer_down":{const l=this._clickManager.transformPointerDownEvent(n);if(n.name!==l.name){this.root.handleEvent(n),this.emit("event",n),this.root.handleEvent(l),this.emit("event",l);return}break}case"pointer_up":{clearTimeout(this._longPressTimeout);const l=this._clickManager.transformPointerUpEvent(n);if(n.name!==l.name){this.root.handleEvent(n),this.emit("event",n),this.root.handleEvent(l),this.emit("event",l);return}break}case"pointer_move":{this._clickManager.handleMove();break}}return this.root.handleEvent(n),this.emit("event",n),this});this.store=n,this.snaps=new Uf(this),this.user=new Hr(r??k2(),c??!1),this.getContainer=i??(()=>document.body),this.textMeasure=new mz(this),this._tickManager=new yz(this);class l extends bh{}m(l,"initial",a??""),this.root=new l(this),this.root.children={};const u=A2(o),d={},p={},f=new Map;for(const b of u){const E=new b(this);d[b.type]=E;const C=uk(b.props??{});p[b.type]=C;for(const I of C.keys())if(!f.has(I.id))f.set(I.id,I);else if(f.get(I.id)!==I)throw Error(`Multiple style props with id "${I.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=d,this.styleProps=p;for(const b of[...s]){if(ro(this.root.children,b.id))throw Error(`Can't override tool with id "${b.id}"`);this.root.children[b.id]=new b(this,this.root)}this.environment=new Z4(this),this.scribbles=new tz(this);const y=new Set,g=b=>{var Q;const E=this.getShape(b);if(!E)return;const{start:C,end:I}=E.props,_=C.type==="binding"?this.getShape(C.boundShapeId):void 0,k=I.type==="binding"?this.getShape(I.boundShapeId):void 0,$=this.getAncestorPageId(E);if(!$)return;let T;if(_&&k)T=this.findCommonAncestor([_,k])??$;else if(_||k){const H=(Q=_||k)==null?void 0:Q.parentId;H&&H===E.parentId?T=E.parentId:T=$}else return;T&&T!==E.parentId&&this.reparentShapes([b],T);const O=this.getShape(b);if(!O)throw Error("no reparented arrow");const N=this.getShapeNearestSibling(O,_),F=this.getShapeNearestSibling(O,k);let L;if(N&&F)L=N.index>F.index?N:F;else if(N&&!F)L=N;else if(F&&!N)L=F;else return;let B;const q=this.getSortedChildIdsForParent(L.parentId).map(H=>this.getShape(H)).filter(H=>H.index>L.index);if(q.length){const H=q.find(U=>U.type!=="arrow");if(O.index>L.index&&(!H||O.index{const{x:C,y:I}=jr(this,b)[E];this.store.put([{...b,props:{...b.props,[E]:{type:"point",x:C,y:I}}}])},S=b=>{for(const E of["start","end"]){const C=b.props[E];if(C.type!=="binding")continue;const I=this.getShape(C.boundShapeId),_=this.getAncestorPageId(b)===this.getAncestorPageId(I);(!I||!_)&&w(b,E)}g(b.id)},v=(b,E)=>{let C=null;const I=b.selectedShapeIds.filter($=>!E.has($));I.length!==b.selectedShapeIds.length&&(C||(C={...b}),C.selectedShapeIds=I);const _=b.erasingShapeIds.filter($=>!E.has($));_.length!==b.erasingShapeIds.length&&(C||(C={...b}),C.erasingShapeIds=_),b.hoveredShapeId&&E.has(b.hoveredShapeId)&&(C||(C={...b}),C.hoveredShapeId=null),b.editingShapeId&&E.has(b.editingShapeId)&&(C||(C={...b}),C.editingShapeId=null);const k=b.hintingShapeIds.filter($=>!E.has($));return k.length!==b.hintingShapeIds.length&&(C||(C={...b}),C.hintingShapeIds=k),b.focusedGroupId&&E.has(b.focusedGroupId)&&(C||(C={...b}),C.focusedGroupId=null),C};if(this.sideEffects=new nz(this),this.sideEffects.registerBatchCompleteHandler(()=>{var b;for(const E of y){y.delete(E);const C=this.getShape(E);if(!C)continue;const I=this.getShapeUtil(C),_=(b=I.onChildrenChange)==null?void 0:b.call(I,C);_!=null&&_.length&&this.updateShapes(_,{squashing:!0})}this.emit("update")}),this.sideEffects.registerBeforeDeleteHandler("shape",b=>{b.parentId&&Kn(b.parentId)&&y.add(b.parentId);const E=this._getArrowBindingsIndex().get()[b.id];if(E!=null&&E.length)for(const{arrowId:_,handleId:k}of E){const $=this.getShape(_);$&&w($,k)}const C=new Set([b.id]),I=fe(this.getPageStates().map(_=>v(_,C)));I.length&&this.store.put(I)}),this.sideEffects.registerBeforeDeleteHandler("page",b=>{var _;if(this.getInstanceState().currentPageId!==b.id)return;const E=(_=this.getPages().find(k=>k.id!==b.id))==null?void 0:_.id;if(!E)return;this.store.put([{...this.getInstanceState(),currentPageId:E}]);const C=hn.createId(b.id),I=Zt.createId(b.id);this.store.remove([C,I])}),this.sideEffects.registerAfterChangeHandler("shape",(b,E)=>{if(this.isShapeOfType(E,"arrow")&&S(E),b.parentId!==E.parentId){const C=I=>{const _=this._getArrowBindingsIndex().get()[I];if(_!=null&&_.length)for(const k of _)g(k.arrowId)};C(E.id),this.visitDescendants(E.id,C)}if(b.parentId!==E.parentId&&bn(E.parentId)){const C=new Set([b.id]);this.visitDescendants(b.id,I=>{C.add(I)});for(const I of this.getPageStates()){if(I.pageId===E.parentId)continue;const _=v(I,C);_&&this.store.put([_])}}b.parentId&&Kn(b.parentId)&&y.add(b.parentId),E.parentId!==b.parentId&&Kn(E.parentId)&&y.add(E.parentId)}),this.sideEffects.registerAfterChangeHandler("instance_page_state",(b,E)=>{if((b==null?void 0:b.selectedShapeIds)!==(E==null?void 0:E.selectedShapeIds)){const C=E.selectedShapeIds.filter(_=>{var $,T;let k=($=this.getShape(_))==null?void 0:$.parentId;for(;Kn(k);){if(E.selectedShapeIds.includes(k))return!1;k=(T=this.getShape(k))==null?void 0:T.parentId}return!0});let I=null;if(C.length>0){const _=this.findCommonAncestor(fe(C.map(k=>this.getShape(k))),k=>this.isShapeOfType(k,"group"));_&&(I=_)}else E!=null&&E.focusedGroupId&&(I=E.focusedGroupId);(C.length!==E.selectedShapeIds.length||I!==E.focusedGroupId)&&this.store.put([{...E,selectedShapeIds:C,focusedGroupId:I??null}])}}),this.sideEffects.registerAfterCreateHandler("shape",b=>{this.isShapeOfType(b,"arrow")&&S(b)}),this.sideEffects.registerAfterCreateHandler("page",b=>{const E=hn.createId(b.id),C=Zt.createId(b.id);this.store.has(E)||this.store.put([hn.create({id:E})]),this.store.has(C)||this.store.put([Zt.create({id:C,pageId:b.id})])}),this._currentPageShapeIds=V4(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=W4(this.store),this.disposables.add(this.store.listen(b=>{this.emit("change",b)})),this.store.ensureStoreIsUsable(),this._setInstancePageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]},{ephemeral:!0}),a&&this.root.children[a]===void 0)throw Error(`No state found for initialState "${a}".`);this.root.enter(void 0,"initial"),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this.updateRenderingBounds(),this.on("tick",this._flushEventsForTick),requestAnimationFrame(()=>{this._tickManager.start()})}dispose(){this.disposables.forEach(n=>n()),this.disposables.clear()}getShapeUtil(n){const r=typeof n=="string"?n:n.type,o=Lr(this.shapeUtils,r);return _t(o,`No shape util found for type "${r}"`),o}undo(){return this._flushEventsForTick(0),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.history.redo(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(n,r,o){return this.history.mark(n,r,o),this}bail(){return this.history.bail(),this}bailToMark(n){return this.history.bailToMark(n),this}batch(n){return this.history.batch(n),this}_getArrowBindingsIndex(){return U4(this)}getArrowsBoundTo(n){return this._getArrowBindingsIndex().get()[n]||Do}getArrowInfoCache(){return this.store.createComputedCache("arrow infoCache",n=>Zc(n)?Al(this,n):xm(this,n))}getArrowInfo(n){const r=typeof n=="string"?n:n.id;return this.getArrowInfoCache().get(r)}annotateError(n,{origin:r,willCrashApp:o,tags:s,extras:i}){const a=this.createErrorAnnotations(r,o);return D0(n,{tags:{...a.tags,...s},extras:{...a.extras,...i}}),o&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(n,r){try{const o=this.getEditingShapeId();return{tags:{origin:n,willCrashApp:r},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:o?this.getShape(o):void 0,inputs:this.inputs}}}catch{return{tags:{origin:n,willCrashApp:r},extras:{}}}}getCrashingError(){return this._crashingError}crash(n){return this._crashingError=n,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:n}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(n){const r=n.split(".").reverse();let o=this.root;for(;r.length>0;){const s=r.pop();if(!s)return!0;const i=o.getCurrent();if((i==null?void 0:i.id)===s){if(r.length===0)return!0;o=i;continue}else return!1}return!1}isInAny(...n){return n.some(r=>this.isIn(r))}setCurrentTool(n,r={}){return this.root.transition(n,r),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const n=this.getCurrentTool();return n?n.getCurrentToolIdMask()??n.id:""}getStateDescendant(n){var s;const r=n.split(".").reverse();let o=this.root;for(;r.length>0;){const i=r.pop();if(!i)return o;const a=(s=o.children)==null?void 0:s[i];if(!a)return;o=a}return o}getDocumentSettings(){return this.store.get(FS)}updateDocumentSettings(n){return this.store.put([{...this.getDocumentSettings(),...n}]),this}getInstanceState(){return this.store.get(In)}updateInstanceState(n,r){return this._updateInstanceState(n,{ephemeral:!0,squashing:!0,...r}),n.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),n.isChangingStyle===!0&&(this._isChangingStyleTimeout=setTimeout(()=>{this.updateInstanceState({isChangingStyle:!1},{ephemeral:!0})},2e3))),this}getOpenMenus(){return this.getInstanceState().openMenus}addOpenMenu(n){const r=new Set(this.getOpenMenus());return r.has(n)||(r.add(n),this.updateInstanceState({openMenus:[...r]})),this}deleteOpenMenu(n){const r=new Set(this.getOpenMenus());return r.has(n)&&(r.delete(n),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 Zt.createId(this.getCurrentPageId())}updateCurrentPageState(n,r){return this._setInstancePageState(n,r),this}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:n}=this.getCurrentPageState();return fe(n.map(r=>this.store.get(r)))}setSelectedShapes(n,r){const o=n.map(s=>typeof s=="string"?s:s.id);return this._setSelectedShapes(o,r),this}select(...n){const r=typeof n[0]=="string"?n:n.map(o=>o.id);return this.setSelectedShapes(r),this}deselect(...n){const r=typeof n[0]=="string"?n:n.map(s=>s.id),o=this.getSelectedShapeIds();return o.length>0&&r.length>0&&this.setSelectedShapes(o.filter(s=>!r.includes(s))),this}selectAll(){const n=this.getSortedChildIdsForParent(this.getCurrentPageId());return n.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(n)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var n;return((n=this.getOnlySelectedShape())==null?void 0:n.id)??null}getOnlySelectedShape(){const n=this.getSelectedShapes();return n.length===1?n[0]:null}getSelectionPageBounds(){const n=this.getCurrentPageState().selectedShapeIds;return n.length===0?null:ne.Common(fe(n.map(r=>this.getShapePageBounds(r))))}getSelectionRotation(){const n=this.getSelectedShapeIds();let r=!1,o=0;for(let s=0,i=n.length;s{const i=this.getShapePageTransform(s);return i?i.applyToPoints(this.getShapeGeometry(s).bounds.corners):[]}).map(s=>s.rot(-r)));return o.point=o.point.rot(r),o}getSelectionRotatedScreenBounds(){const n=this.getSelectionRotatedPageBounds();if(!n)return;const{x:r,y:o}=this.pageToScreen(n.point),s=this.getZoomLevel();return new ne(r,o,n.width*s,n.height*s)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const n=this.getFocusedGroupId();return n?this.getShape(n):void 0}setFocusedGroup(n){const r=typeof n=="string"?n:(n==null?void 0:n.id)??null;if(r!==null){const o=this.getShape(r);if(!o)throw Error(`Editor.setFocusedGroup: Shape with id ${r} does not exist`);if(!this.isShapeOfType(o,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${o.type}`)}return r===this.getFocusedGroupId()?this:(this._setFocusedGroupId(r),this)}popFocusedGroupId(){const n=this.getFocusedGroup();if(n){const r=this.findShapeAncestor(n,o=>this.isShapeOfType(o,"group"));this.setFocusedGroup((r==null?void 0:r.id)??null),this.select(n.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const n=this.getEditingShapeId();return n?this.getShape(n):void 0}setEditingShape(n){const r=typeof n=="string"?n:(n==null?void 0:n.id)??null;if(r!==this.getEditingShapeId()){if(r){const o=this.getShape(r);if(o&&this.getShapeUtil(o).canEdit(o))return this._setInstancePageState({editingShapeId:r}),this}this._setInstancePageState({editingShapeId:null})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const n=this.getHoveredShapeId();return n?this.getShape(n):void 0}setHoveredShape(n){const r=typeof n=="string"?n:(n==null?void 0:n.id)??null;return r===this.getHoveredShapeId()?this:(this.updateCurrentPageState({hoveredShapeId:r},{ephemeral:!0}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const n=this.getHintingShapeIds();return fe(n.map(r=>this.getShape(r)))}setHintingShapes(n){const r=typeof n[0]=="string"?n:n.map(o=>o.id);return this.updateCurrentPageState({hintingShapeIds:Mp(r)},{ephemeral:!0}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const n=this.getErasingShapeIds();return fe(n.map(r=>this.getShape(r)))}setErasingShapes(n){const r=typeof n[0]=="string"?n:n.map(s=>s.id);r.sort();const o=this.getErasingShapeIds();if(r.length===o.length){for(let s=0;s{const s={...o,...n};this.store.put([s]);const{currentScreenPoint:i,currentPagePoint:a}=this.inputs,{screenBounds:c}=this.store.unsafeGetWithoutCapture(In);if(i.x/s.z-s.x!==a.x||i.y/s.z-s.y!==a.y){const l={type:"pointer",target:"canvas",name:"pointer_move",point:P.AddXY(i,c.x,c.y),pointerId:b1.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,button:0,isPen:this.getInstanceState().isPenMode??!1};r?this._flushEventForTick(l):this.dispatch(l)}this._tickCameraState()}),this)}setCamera(n,r){const o=Number.isFinite(n.x)?n.x:0,s=Number.isFinite(n.y)?n.y:0,i=Number.isFinite(n.z)?n.z:this.getZoomLevel();if(this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),r){const{width:a,height:c}=this.getViewportScreenBounds();return this._animateToViewport(new ne(-o,-s,a/i,c/i),r)}else this._setCamera({x:o,y:s,z:i});return this}centerOnPoint(n,r){if(!this.getInstanceState().canMoveCamera)return this;const{width:o,height:s}=this.getViewportPageBounds();return this.setCamera({x:-(n.x-o/2),y:-(n.y-s/2),z:this.getCamera().z},r),this}zoomToContent(n={duration:220}){const r=this.getSelectionPageBounds()??this.getCurrentPageBounds();return r&&this.zoomToBounds(r,{targetZoom:Math.min(1,this.getZoomLevel()),...n}),this}zoomToFit(n){if(!this.getInstanceState().canMoveCamera)return this;const r=[...this.getCurrentPageShapeIds()];if(r.length<=0)return this;const o=ne.Common(fe(r.map(s=>this.getShapePageBounds(s))));return this.zoomToBounds(o,n),this}resetZoom(n=this.getViewportScreenCenter(),r){if(!this.getInstanceState().canMoveCamera)return this;const{x:o,y:s,z:i}=this.getCamera(),{x:a,y:c}=n;return this.setCamera({x:o+(a/1-a)-(a/i-a),y:s+(c/1-c)-(c/i-c),z:1},r),this}zoomIn(n=this.getViewportScreenCenter(),r){if(!this.getInstanceState().canMoveCamera)return this;const{x:o,y:s,z:i}=this.getCamera();let a=xs;for(let u=1;u0;u--){const d=ta[u-1],p=ta[u];if(!(p-i>=(p-d)/2)){a=d;break}}const{x:c,y:l}=n;return this.setCamera({x:o+(c/a-c)-(c/i-c),y:s+(l/a-l)-(l/i-l),z:a},r),this}zoomToSelection(n){if(!this.getInstanceState().canMoveCamera)return this;const r=this.getSelectionPageBounds();return r?(this.zoomToBounds(r,{targetZoom:Math.max(1,this.getZoomLevel()),...n}),this):this}panZoomIntoView(n,r){if(!this.getInstanceState().canMoveCamera)return this;if(n.length<=0)return this;const o=ne.Common(fe(n.map(i=>this.getShapePageBounds(i)))),s=this.getViewportPageBounds();if(s.ho.minY&&(c=i.minY-o.minY),i.maxXo.minX&&(a=i.minX-o.minX);const l=this.getCamera();this.setCamera({x:l.x+a,y:l.y+c,z:l.z},r)}return this}zoomToBounds(n,r){if(!this.getInstanceState().canMoveCamera)return this;const o=this.getViewportScreenBounds(),s=(r==null?void 0:r.inset)??Math.min(256,o.width*.28);let i=Ns(Math.min((o.width-s)/n.width,(o.height-s)/n.height),qc,xs);return(r==null?void 0:r.targetZoom)!==void 0&&(i=Math.min(r.targetZoom,i)),this.setCamera({x:-n.minX+(o.width-n.width*i)/2/i,y:-n.minY+(o.height-n.height*i)/2/i,z:i},r),this}pan(n,r){if(!this.getInstanceState().canMoveCamera)return this;const{x:o,y:s,z:i}=this.getCamera();return this.setCamera({x:o+n.x/i,y:s+n.y/i,z:i},r),this._flushEventsForTick(0),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(n){if(!this._viewportAnimation)return;const r=()=>{this.removeListener("tick",this._animateViewport),this.removeListener("stop-camera-animation",r),this._viewportAnimation=null};this.once("stop-camera-animation",r),this._viewportAnimation.elapsed+=n;const{elapsed:o,easing:s,duration:i,start:a,end:c}=this._viewportAnimation;if(o>i){this._setCamera({x:-c.x,y:-c.y,z:this.getViewportScreenBounds().width/c.width}),r();return}const l=i-o,u=s(1-l/i),d=a.minX+(c.minX-a.minX)*u,p=a.minY+(c.minY-a.minY)*u,f=a.maxX+(c.maxX-a.maxX)*u;this._setCamera({x:-d,y:-p,z:this.getViewportScreenBounds().width/(f-d)})}_animateToViewport(n,r={}){const{duration:o=0,easing:s=nn.easeInOutCubic}=r,i=this.user.getAnimationSpeed(),a=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),o===0||i===0?this._setCamera({x:-n.x,y:-n.y,z:this.getViewportScreenBounds().width/n.width}):(this._viewportAnimation={elapsed:0,duration:o/i,easing:s,start:a.clone(),end:n.clone()},this.addListener("tick",this._animateViewport),this)}slideCamera(n={}){if(!this.getInstanceState().canMoveCamera)return this;if(this.stopCameraAnimation(),this.user.getAnimationSpeed()===0)return this;const{speed:o,friction:s,direction:i,speedThreshold:a=.01}=n;let c=Math.min(o,1);const l=()=>{this.removeListener("tick",u),this.removeListener("stop-camera-animation",l)};this.once("stop-camera-animation",l);const u=d=>{const{x:p,y:f,z:y}=this.getCamera(),g=P.Mul(i,c*d/y);c*=1-s,co.userId===n);return r?(this.batch(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const o=r.currentPageId===this.getCurrentPageId();o||this.setCurrentPage(r.currentPageId);const s=o?{duration:500}:void 0;this.centerOnPoint(r.cursor,s);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,n]}),setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],c=a.indexOf(n);c<0||(a.splice(c,1),this.updateInstanceState({highlightedUserIds:a}))},Vk)}),this):this}animateToShape(n,r=j5){if(!this.getInstanceState().canMoveCamera)return this;const o=this.getViewportScreenBounds().clone().expandBy(-32),s=o.width/o.height,i=this.getShapePageBounds(n);if(!i)return this;const a=i.width/i.height,c=i.clone(),l=i.width/o.width;return c.width+=(o.minX+o.maxX)*l,c.height+=(o.minY+o.maxY)*l,c.x-=o.minX*l,c.y-=o.minY*l,a>s?(c.height=i.width/s,c.y-=(c.height-i.height)/2):(c.width=i.height*s,c.x-=(c.width-i.width)/2),this._animateToViewport(c,r)}updateViewportScreenBounds(n,r=!1){n.width=Math.max(n.width,1),n.height=Math.max(n.height,1);const o=[n.minY!==0,document.body.scrollWidth!==n.maxX,document.body.scrollHeight!==n.maxY,n.minX!==0],s=n.equals(this.getViewportScreenBounds()),{_willSetInitialBounds:i}=this;if(s)this._willSetInitialBounds=!1;else if(i)this._willSetInitialBounds=!1,this.updateInstanceState({screenBounds:n.toJson(),insets:o},{squashing:!0,ephemeral:!0});else if(r&&!this.getInstanceState().followingUserId){const a=this.getViewportPageCenter();this.updateInstanceState({screenBounds:n.toJson(),insets:o},{squashing:!0,ephemeral:!0}),this.centerOnPoint(a)}else this.updateInstanceState({screenBounds:n.toJson(),insets:o},{squashing:!0,ephemeral:!0});return this._tickCameraState(),this.updateRenderingBounds(),this}getViewportScreenBounds(){const{x:n,y:r,w:o,h:s}=this.getInstanceState().screenBounds;return new ne(n,r,o,s)}getViewportScreenCenter(){const n=this.getViewportScreenBounds();return new P(n.midX-n.minX,n.midY-n.minY)}getViewportPageBounds(){const{w:n,h:r}=this.getViewportScreenBounds(),{x:o,y:s,z:i}=this.getCamera();return new ne(-o,-s,n/i,r/i)}getViewportPageCenter(){return this.getViewportPageBounds().center}screenToPage(n){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(In),{x:o,y:s,z:i=1}=this.getCamera();return{x:(n.x-r.x)/i-o,y:(n.y-r.y)/i-s,z:n.z??.5}}pageToScreen(n){const r=this.getViewportScreenBounds(),{x:o,y:s,z:i=1}=this.getCamera();return{x:(n.x+o)*i+r.x,y:(n.y+s)*i+r.y,z:n.z??.5}}pageToViewport(n){const{x:r,y:o,z:s=1}=this.getCamera();return{x:(n.x+r)*s,y:(n.y+o)*s,z:n.z??.5}}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const n=this._getCollaboratorsQuery().get();return n.length?[...new Set(n.map(o=>o.userId))].sort().map(o=>n.filter(i=>i.userId===o).sort((i,a)=>a.lastActivityTimestamp-i.lastActivityTimestamp)[0]):Do}getCollaboratorsOnCurrentPage(){const n=this.getCurrentPageId();return this.getCollaborators().filter(r=>r.currentPageId===n)}startFollowingUser(n){const r=this._getCollaboratorsQuery().get().filter(c=>c.userId===n),o=this.user.getId();if(o||console.warn("You should set the userId for the current instance before following a user"),r.some(c=>c.followingUserId===o))return this;Mr(()=>{this.stopFollowingUser(),this.updateInstanceState({followingUserId:n},{ephemeral:!0})});const s=()=>{this.removeListener("frame",a),this.removeListener("stop-following",s)};let i=!1;const a=()=>{const c=[...r].sort((F,L)=>F.lastActivityTimestamp-L.lastActivityTimestamp).pop();if(!c){this.stopFollowingUser();return}const l=c.currentPageId===this.getCurrentPageId(),u=l?I5:1;if(!l){this.stopFollowingUser(),this.setCurrentPage(c.currentPageId),this.startFollowingUser(n);return}const{center:d,width:p,height:f}=this.getViewportPageBounds(),y=ne.From(c.screenBounds),g=y.width/c.camera.z,w=y.height/c.camera.z,S=new P(g/2-c.camera.x,w/2-c.camera.y),v=c.followingUserId===o,b=p+(g-p)*u,E=f+(w-f)*u,C=v?f/E:Math.min(p/b,f/E),I=Ns(this.getCamera().z*C,qc,xs),_=this.getViewportScreenBounds().w/I,k=this.getViewportScreenBounds().h/I,$=S.sub(d),T=P.Add(d,P.Mul($,u)),O=P.Sub(T,d).len(),N=Math.abs(I-this.getCamera().z);if(O{const p=this.getShape(l);if(!p)return;u*=p.opacity;let f=!1;const y=this.getShapeUtil(p);n&&(f=!d&&i.includes(l),f&&(u*=.32)),r.push({id:l,shape:p,util:y,index:o,backgroundIndex:s,opacity:u}),o+=1,s+=1;const g=this.getSortedChildIdsForParent(l);if(!g.length)return;let w=null;y.providesBackgroundForChildren(p)&&(w=s,s=o,o+=Io);for(const S of g)a(S,u,d||f);w!==null&&(s=w)},c=n?[this.getCurrentPage()]:this.getPages();for(const l of c)for(const u of this.getSortedChildIdsForParent(l.id))a(u,1,!1);return r}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(B3)}getRenderingBounds(){return this._renderingBounds.get()}updateRenderingBounds(){const n=this.getViewportPageBounds();return n.equals(this._renderingBounds.__unsafe__getWithoutCapture())?this:(this._renderingBounds.set(n.clone()),this)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return this._getAllPagesQuery().get().sort(en)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(n){return this.store.get(typeof n=="string"?n:n.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(n){const r=typeof n=="string"?n:n.id,o=this.store.query.exec("shape",{parentId:{eq:r}});return this.getShapeAndDescendantIds(o.map(s=>s.id))}setCurrentPage(n,r){const o=typeof n=="string"?n:n.id;return this._setCurrentPageId(o,r),this}updatePage(n,r){return this._updatePage(n,r),this}createPage(n){return this._createPage(n),this}deletePage(n){const r=typeof n=="string"?n:n.id;return this._deletePage(r),this}duplicatePage(n,r=Ho.createId()){if(this.getPages().length>=Gp)return this;const o=typeof n=="string"?n:n.id,s=this.getPage(o);if(!s)return this;const i={...this.getCamera()},a=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(s.id));return this.batch(()=>{var u;const c=this.getPages(),l=kl(s.index,(u=c[c.indexOf(s)+1])==null?void 0:u.index);if(this.createPage({name:s.name+" Copy",id:r,index:l}),this.setCurrentPage(r),this.setCamera(i),a)return this.putContentOntoCurrentPage(a)}),this}renamePage(n,r,o){const s=typeof n=="string"?n:n.id;return this.getInstanceState().isReadonly?this:(this.updatePage({id:s,name:r},o),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(n){return this._createAssets(n),this}updateAssets(n){return this._updateAssets(n),this}deleteAssets(n){const r=typeof n[0]=="string"?n:n.map(o=>o.id);return this._deleteAssets(r),this}getAsset(n){return this.store.get(typeof n=="string"?n:n.id)}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",n=>this.getShapeUtil(n).getGeometry(n),(n,r)=>n.props===r.props)}getShapeGeometry(n){return this._getShapeGeometryCache().get(typeof n=="string"?n:n.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",n=>{var r,o;return(o=(r=this.getShapeUtil(n)).getHandles)==null?void 0:o.call(r,n)})}getShapeHandles(n){return this._getShapeHandlesCache().get(typeof n=="string"?n:n.id)}getShapeLocalTransform(n){const r=typeof n=="string"?n:n.id,o=this.getShape(r);if(!o)throw Error("Editor.getTransform: shape not found");return oe.Identity().translate(o.x,o.y).rotate(o.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",n=>{if(bn(n.parentId))return this.getShapeLocalTransform(n);const r=this._getShapePageTransformCache().get(n.parentId)??oe.Identity();return oe.Compose(r,this.getShapeLocalTransform(n))})}getShapeParentTransform(n){const r=typeof n=="string"?n:n.id,o=this.getShape(r);return!o||bn(o.parentId)?oe.Identity():this._getShapePageTransformCache().get(o.parentId)??oe.Identity()}getShapePageTransform(n){const r=typeof n=="string"?n:n.id;return this._getShapePageTransformCache().get(r)??oe.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",n=>{const r=this._getShapePageTransformCache().get(n.id);return r?ne.FromPoints(oe.applyToPoints(r,this.getShapeGeometry(n).vertices)):new ne})}getShapePageBounds(n){return this._getShapePageBoundsCache().get(typeof n=="string"?n:n.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",n=>{const r=this._getShapeMaskCache().get(n.id);if(!r)return;if(r.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const o=this._getShapePageTransformCache().get(n.id);return o?`polygon(${oe.applyToPoints(oe.Inverse(o),r).map(i=>`${i.x}px ${i.y}px`).join(",")})`:void 0})}getShapeClipPath(n){return this._getShapeClipPathCache().get(typeof n=="string"?n:n.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",n=>{if(bn(n.parentId))return;const r=this.getShapeAncestors(n.id).filter(s=>this.isShapeOfType(s,"frame"));return r.length===0?void 0:r.map(s=>this._getShapePageTransformCache().get(s.id).applyToPoints(this.getShapeGeometry(s).vertices)).reduce((s,i)=>{if(!(i&&s))return;const a=W1(s,i);return a?a.map(P.Cast):[]})})}getShapeMask(n){return this._getShapeMaskCache().get(typeof n=="string"?n:n.id)}getShapeMaskedPageBounds(n){return typeof n!="string"&&(n=n.id),this._getShapeMaskedPageBoundsCache().get(n)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",n=>{const r=this._getShapePageBoundsCache().get(n.id);if(!r)return;const o=this._getShapeMaskCache().get(n.id);if(o){if(o.length===0)return;const{corners:s}=r;if(s.every((a,c)=>a&&P.Equals(a,o[c])))return r.clone();const i=W1(o,s);return i?ne.FromPoints(i):void 0}return r})}getShapeAncestors(n,r=[]){const o=typeof n=="string"?n:n.id,s=this.getShape(o);if(!s)return r;const i=s.parentId;if(bn(i))return r.reverse(),r;const a=this.store.get(i);return a?(r.push(a),this.getShapeAncestors(a,r)):r}findShapeAncestor(n,r){const o=typeof n=="string"?n:n.id,s=this.getShape(o);if(!s)return;const i=s.parentId;if(bn(i))return;const a=this.getShape(i);if(a)return r(a)?a:this.findShapeAncestor(a,r)}hasAncestor(n,r){const o=typeof n=="string"?n:n==null?void 0:n.id,s=o&&this.getShape(o);return s?s.parentId===r?!0:this.hasAncestor(this.getShapeParent(s),r):!1}findCommonAncestor(n,r){var l;if(n.length===0)return;const o=typeof n[0]=="string"?n:n.map(u=>u.id),s=fe(o.map(u=>this.getShape(u)));if(s.length===1){const u=s[0].parentId;return bn(u)?void 0:r?(l=this.findShapeAncestor(s[0],r))==null?void 0:l.id:u}const[i,...a]=s;let c=this.getShapeParent(i);for(;c;){if(r&&!r(c)){c=this.getShapeParent(c);continue}if(a.every(u=>this.hasAncestor(u,c.id)))return c.id;c=this.getShapeParent(c)}}isShapeOrAncestorLocked(n){const r=typeof n=="string"?this.getShape(n):n;return r===void 0?!1:r.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(r))}_notVisibleShapes(){return K4(this)}getCulledShapes(){const n=this._notVisibleShapes().get(),r=this.getSelectedShapeIds(),o=this.getEditingShapeId(),s=new Set(n);return o&&s.delete(o),r.forEach(i=>{s.delete(i)}),s}getCurrentPageBounds(){let n;return this.getCurrentPageShapeIdsSorted().forEach(r=>{const o=this.getShapeMaskedPageBounds(r);o&&(n?n=n.expand(o):n=o.clone())}),n}getSelectedShapeAtPoint(n){const r=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(o=>o.type!=="group"&&r.includes(o.id)).reverse().find(o=>this.isPointInShape(o,n,{hitInside:!0,margin:0}))}getShapeAtPoint(n,r={}){const o=this.getZoomLevel(),s=this.getViewportPageBounds(),{filter:i,margin:a=0,hitLabels:c=!1,hitInside:l=!1,hitFrameInside:u=!1}=r;let d=1/0,p=null,f=1/0,y=null;const g=(r.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(w=>{if(this.isShapeOfType(w,"group"))return!1;const S=this.getShapeMask(w);return S&&!Zn(n,S)?!1:i?i(w):!0});for(let w=g.length-1;w>=0;w--){const S=g[w],v=this.getShapeGeometry(S),b=v instanceof Br,E=this.getPointInShapeSpace(S,n);if((this.isShapeOfType(S,"arrow")||this.isShapeOfType(S,"geo")&&S.props.fill==="none")&&S.props.text.trim()){for(const I of v.children)if(I.isLabel&&I.isPointInBounds(E))return S}if(this.isShapeOfType(S,"frame")){const I=v.distanceToPoint(E,l);if(Math.abs(I)<=a)return y||S;if(v.hitTestPoint(E,0,!0))return y||p||(u?S:void 0);continue}let C;if(b){let I=1/0;for(const _ of v.children){if(_.isLabel&&!c)continue;const k=_.distanceToPoint(E,l);kthis.isPointInShape(o,n,r))}isPointInShape(n,r,o={}){const{hitInside:s=!1,margin:i=0}=o,a=typeof n=="string"?n:n.id,c=this.getShapeMask(a);return c&&!Zn(r,c)?!1:this.getShapeGeometry(a).hitTestPoint(this.getPointInShapeSpace(n,r),i,s)}getPointInShapeSpace(n,r){const o=typeof n=="string"?n:n.id;return this._getShapePageTransformCache().get(o).clone().invert().applyToPoint(r)}getPointInParentSpace(n,r){const o=typeof n=="string"?n:n.id,s=this.getShape(o);if(!s)return new P(0,0);if(bn(s.parentId))return P.From(r);const i=this.getShapePageTransform(s.parentId);return i?i.clone().invert().applyToPoint(r):P.From(r)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),n=>this.store.get(n))}getCurrentPageShapesSorted(){const n=[],r=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let o=0,s=r.length;o!n.has(r))}isShapeOfType(n,r){const o=typeof n=="string"?this.getShape(n):n;return o?o.type===r:!1}getShape(n){const r=typeof n=="string"?n:n.id;if(Kn(r))return this.store.get(r)}getShapeParent(n){const r=typeof n=="string"?n:n==null?void 0:n.id;if(!r)return;const o=this.getShape(r);if(!(o===void 0||!Kn(o.parentId)))return this.store.get(o.parentId)}getShapeNearestSibling(n,r){return r?r.parentId===n.parentId?r:this.findShapeAncestor(r,s=>s.parentId===n.parentId):void 0}isShapeInPage(n,r=this.getCurrentPageId()){const o=typeof n=="string"?n:n.id,s=this.getShape(o);if(!s)return!1;let i=!1;if(s.parentId===r)i=!0;else{let a=this.getShape(s.parentId);e:for(;a;){if(a.parentId===r){i=!0;break e}a=this.getShape(a.parentId)}}return i}getAncestorPageId(n){const r=typeof n=="string"?n:n==null?void 0:n.id,o=r&&this.getShape(r);if(o)return bn(o.parentId)?o.parentId:this.getAncestorPageId(this.getShape(o.parentId))}reparentShapes(n,r,o){const s=typeof n[0]=="string"?n:n.map(y=>y.id);if(s.length===0)return this;const i=[],a=bn(r)?oe.Identity():this.getShapePageTransform(r),c=a.rotation();let l=[];const u=fe(this.getSortedChildIdsForParent(r).map(y=>this.getShape(y)));if(o){const y=u.find(g=>g.index===o);if(y){const g=u[u.indexOf(y)+1];g?l=oc(o,g.index,s.length):l=rm(o,s.length)}else{const g=u.sort(en).find(w=>w.index>o);g?l=oc(o,g.index,s.length):l=rm(o,s.length)}}else{const y=u.length&&u[u.length-1];l=y?rm(y.index,s.length):eu(s.length)}const d=a.clone().invert(),p=fe(s.map(y=>this.getShape(y))),f=p.filter(y=>y.isLocked);f.length&&this.updateShapes(f.map(({id:y,type:g})=>({id:y,type:g,isLocked:!1})));for(let y=0;yo):Do}visitDescendants(n,r){const o=typeof n=="string"?n:n.id,s=this.getSortedChildIdsForParent(o);for(const i of s)r(i)!==!1&&this.visitDescendants(i,r);return this}getShapeAndDescendantIds(n){const r=new Set,o=[...n];for(;o.length>0;){const s=o.pop();if(!s)break;if(!r.has(s)){r.add(s);for(const i of this.getSortedChildIdsForParent(s))o.push(i)}}return r}getDroppingOverShape(n,r=[]){const o=this.getCurrentPageShapesSorted();for(let s=o.length-1;s>=0;s--){const i=o[s];if(this.getSelectedShapeIds().includes(i.id)||!this.getShapeUtil(i).canDropShapes(i,r)||r.find(c=>c.id===i.id||this.hasAncestor(i,c.id)))continue;const a=this.getShapeMaskedPageBounds(i.id);if(a&&a.containsPoint(n)&&this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(i,n),0,!0))return i}}getOutermostSelectableShape(n,r){const o=typeof n=="string"?n:n.id,s=this.getShape(o);let i=s,a=s;const c=this.getFocusedGroup();for(;a;){if(this.isShapeOfType(a,"group")&&(c==null?void 0:c.id)!==a.id&&!this.hasAncestor(c,a.id)&&((r==null?void 0:r(a))??!0))i=a;else if((c==null?void 0:c.id)===a.id)break;a=this.getShapeParent(a)}return i}rotateShapesBy(n,r){if((typeof n[0]=="string"?n:n.map(i=>i.id)).length<=0)return this;const s=j2({editor:this});return s?(wh({delta:r,snapshot:s,editor:this,stage:"one-off"}),this):this}getChangesToTranslateShape(n,r){var i,a,c;let o=n;const s=this.getShapeUtil(n);return o=Qc(o,((i=s.onTranslateStart)==null?void 0:i.call(s,o))??void 0),o=Qc(o,{id:n.id,type:n.type,x:r.x,y:r.y}),o=Qc(o,((a=s.onTranslate)==null?void 0:a.call(s,n,o))??void 0),o=Qc(o,((c=s.onTranslateEnd)==null?void 0:c.call(s,n,o))??void 0),o}nudgeShapes(n,r,o){const s=typeof n[0]=="string"?n:n.map(a=>a.id);if(s.length<=0)return this;const i=[];for(const a of s){const c=this.getShape(a),l=P.From(r),u=this.getShapeParentTransform(c);u&&l.rot(-u.rotation()),i.push(this.getChangesToTranslateShape(c,l.add(c)))}return this.updateShapes(i,{squashing:!0,...o}),this}duplicateShapes(n,r){const o=typeof n[0]=="string"?n:n.map(u=>u.id);if(o.length<=0)return this;const s=new Set(o),i=[],a=[...o];for(;a.length>0;){const u=a.pop();if(!u)break;i.push(u),this.getSortedChildIdsForParent(u).forEach(d=>a.push(d))}i.reverse();const c=new Map(i.map(u=>[u,Be()])),l=fe(i.map(u=>{const d=this.getShape(u);if(!d)return null;const p=c.get(u);let f=0,y=0;if(r&&s.has(u)){const I=this.getShapeParentTransform(d),_=new P(r.x,r.y).rot(-I.rotation());f=_.x,y=_.y}const g=d.parentId??this.getCurrentPageId(),w=this.getSortedChildIdsForParent(g),S=w.indexOf(d.id),v=w[S+1],b=v?this.getShape(v):null,E=b?kl(d.index,b.index):$o(d.index);let C=Ye(d);if(this.isShapeOfType(d,"arrow")&&this.isShapeOfType(C,"arrow")){const I=this.getArrowInfo(d);let _,k;if(d.props.start.type==="binding"&&(_=c.get(d.props.start.boundShapeId),!_))if(I!=null&&I.isValid){const{x:T,y:O}=I.start.point;C.props.start={type:"point",x:T,y:O}}else{const{start:T}=jr(this,d);C.props.start={type:"point",x:T.x,y:T.y}}if(d.props.end.type==="binding"&&(k=c.get(d.props.end.boundShapeId),!k))if(I!=null&&I.isValid){const{x:T,y:O}=I.end.point;C.props.end={type:"point",x:T,y:O}}else{const{end:T}=jr(this,d);C.props.start={type:"point",x:T.x,y:T.y}}const $=Zc(C)?Al(this,C):xm(this,C);if(I!=null&&I.isValid&&($!=null&&$.isValid)&&!Zc(d)){const T=P.Med(I.start.handle,I.end.handle),O=P.Dist(I.middle,T),N=P.Dist($.middle,T);C.props.bend<0?C.props.bend+=N-O:C.props.bend-=N-O}C.props.start.type==="binding"&&_&&(C.props.start.boundShapeId=_),C.props.end.type==="binding"&&k&&(C.props.end.boundShapeId=k)}return C={...C,id:p,x:d.x+f,y:d.y+y,index:E},C}));return l.forEach(u=>{Kn(u.parentId)&&c.has(u.parentId)&&(u.parentId=c.get(u.parentId))}),this.history.batch(()=>{const u=l.length+this.getCurrentPageShapeIds().size>Io;u&&_d(this);const d=u?l.slice(0,Io-this.getCurrentPageShapeIds().size):l,p=d.map(f=>f.id);if(this.createShapes(d),this.setSelectedShapes(p),r!==void 0){const f=this.getSelectionPageBounds(),y=this.getViewportPageBounds();f&&!y.contains(f)&&this.centerOnPoint(f.center,{duration:Qr})}}),this}moveShapesToPage(n,r){const o=typeof n[0]=="string"?n:n.map(c=>c.id);if(o.length===0)return this;if(this.getInstanceState().isReadonly)return this;const s=this.getCurrentPageId();if(r===s)return this;if(!this.store.has(r))return this;const i=this.getContentFromCurrentPage(o);if(!i)return this;if(this.getPageShapeIds(r).size+i.shapes.length>Io)return _d(this,r),this;const a=this.getCamera().z;return this.history.batch(()=>{this.deleteShapes(o),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(n){const r=typeof n[0]=="string"?n:n.map(a=>a.id);if(this.getInstanceState().isReadonly||r.length===0)return this;let o=!0,s=!0;const i=[];for(const a of r){const c=this.getShape(a);c&&(i.push(c),c.isLocked?s=!1:o=!1)}return this.batch(()=>{s?(this.updateShapes(i.map(a=>({id:a.id,type:a.type,isLocked:!0}))),this.setSelectedShapes([])):o?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(n){const r=typeof n[0]=="string"?n:n.map(s=>s.id),o=Ed(this,"toBack",r);return o&&this.updateShapes(o),this}sendBackward(n){const r=typeof n[0]=="string"?n:n.map(s=>s.id),o=Ed(this,"backward",r);return o&&this.updateShapes(o),this}bringForward(n){const r=typeof n[0]=="string"?n:n.map(s=>s.id),o=Ed(this,"forward",r);return o&&this.updateShapes(o),this}bringToFront(n){const r=typeof n[0]=="string"?n:n.map(s=>s.id),o=Ed(this,"toFront",r);return o&&this.updateShapes(o),this}flipShapes(n,r){const o=typeof n[0]=="string"?n:n.map(a=>a.id);if(this.getInstanceState().isReadonly)return this;let s=fe(o.map(a=>this.getShape(a)));if(!s.length)return this;s=fe(s.map(a=>this.isShapeOfType(a,"group")?this.getSortedChildIdsForParent(a.id).map(c=>this.getShape(c)):a).flat());const i=ne.Common(fe(s.map(a=>this.getShapePageBounds(a)))).center;return this.batch(()=>{for(const a of s){const c=this.getShapeGeometry(a).bounds,l=this.getShapePageTransform(a.id);l&&this.resizeShape(a.id,{x:r==="horizontal"?-1:1,y:r==="vertical"?-1:1},{initialBounds:c,initialPageTransform:l,initialShape:a,mode:"scale_shape",scaleOrigin:i,scaleAxisRotation:0})}}),this}stackShapes(n,r,o){const s=typeof n[0]=="string"?n:n.map(w=>w.id);if(this.getInstanceState().isReadonly)return this;const i=fe(s.map(w=>this.getShape(w)).filter(w=>!(!w||this.isShapeOfType(w,"arrow")&&(w.props.start.type==="binding"||w.props.end.type==="binding")))),a=i.length;if(o===0&&a<3||a<2)return this;const c=Object.fromEntries(i.map(w=>[w.id,this.getShapePageBounds(w)]));let l,u,d,p;r==="horizontal"?(l="x",u="minX",d="maxX",p="width"):(l="y",u="minY",d="maxY",p="height");let f;if(o===0){const w=[];i.sort((v,b)=>c[v.id][u]-c[b.id][u]);for(let v=0;v$.gap===_);k?k.count++:w.push({gap:_,count:1})}let S=0;w.forEach(v=>{v.count>S&&(S=v.count,f=v.gap)}),S===1&&(f=Math.max(0,w.reduce((v,b)=>v+b.gap*b.count,0)/(a-1)))}else f=o;const y=[];let g=c[i[0].id][d];return i.forEach((w,S)=>{var I,_;if(S===0)return;const v={x:0,y:0};v[l]=g+f-c[w.id][l];const b=this.getShapeParent(w),E=b?P.Rot(v,-this.getShapePageTransform(b).decompose().rotation):v,C=(_=(I=this.getShapeUtil(w)).onTranslateStart)==null?void 0:_.call(I,w);y.push(C?{...C,[l]:w[l]+E[l]}:{id:w.id,type:w.type,[l]:w[l]+E[l]}),g+=c[w.id][p]+f}),this.updateShapes(y),this}packShapes(n,r){var _,k;const o=typeof n[0]=="string"?n:n.map($=>$.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=fe(o.map($=>this.getShape($)).filter($=>!(!$||this.isShapeOfType($,"arrow")&&($.props.start.type==="binding"||$.props.end.type==="binding")))),i={},a={};let c,l,u=0;for(let $=0;$i[T.id].height-i[$.id].height);const f=Math.max(Math.ceil(Math.sqrt(u/.95)),p),y=[new ne(d.x,d.y,f,1/0)];let g=0,w=0,S,v;for(let $=0;$=0;T--)if(S=y[T],!(l.width>S.width||l.height>S.height)){l.x=S.x,l.y=S.y,w=Math.max(w,l.maxY),g=Math.max(g,l.maxX),l.width===S.width&&l.height===S.height?(v=y.pop(),Tl.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=fe(o.map(l=>this.getShape(l))),i=Object.fromEntries(s.map(l=>[l.id,this.getShapePageBounds(l)])),a=ne.Common(fe(Object.values(i))),c=[];return s.forEach(l=>{const u=i[l.id];if(!u)return;const d={x:0,y:0};switch(r){case"top":{d.y=a.minY-u.minY;break}case"center-vertical":{d.y=a.midY-u.minY-u.height/2;break}case"bottom":{d.y=a.maxY-u.minY-u.height;break}case"left":{d.x=a.minX-u.minX;break}case"center-horizontal":{d.x=a.midX-u.minX-u.width/2;break}case"right":{d.x=a.maxX-u.minX-u.width;break}}const p=this.getShapeParent(l),f=p?P.Rot(d,-this.getShapePageTransform(p).decompose().rotation):d;c.push(this.getChangesToTranslateShape(l,P.Add(l,f)))}),this.updateShapes(c),this}distributeShapes(n,r){const o=typeof n[0]=="string"?n:n.map(b=>b.id);if(this.getInstanceState().isReadonly)return this;if(o.length<3)return this;const s=o.length,i=fe(o.map(b=>this.getShape(b))),a=Object.fromEntries(i.map(b=>[b.id,this.getShapePageBounds(b)]));let c,l,u,d,p;r==="horizontal"?(c="x",l="minX",u="maxX",d="midX",p="width"):(c="y",l="minY",u="maxY",d="midY",p="height");const f=[],y=i.sort((b,E)=>a[b.id][l]-a[E.id][l])[0],g=i.sort((b,E)=>a[E.id][u]-a[b.id][u])[0],w=a[y.id][d],S=(a[g.id][d]-w)/(s-1),v=w+S;return i.filter(b=>b!==y&&b!==g).sort((b,E)=>a[b.id][d]-a[E.id][d]).forEach((b,E)=>{const C={x:0,y:0};C[c]=v+S*E-a[b.id][p]/2-a[b.id][c];const I=this.getShapeParent(b),_=I?P.Rot(C,-this.getShapePageTransform(I).rotation()):C;f.push(this.getChangesToTranslateShape(b,P.Add(b,_)))}),this.updateShapes(f),this}stretchShapes(n,r){const o=typeof n[0]=="string"?n:n.map(l=>l.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=fe(o.map(l=>this.getShape(l))),i=Object.fromEntries(o.map(l=>[l,this.getShapeGeometry(l).bounds])),a=Object.fromEntries(o.map(l=>[l,this.getShapePageBounds(l)])),c=ne.Common(fe(Object.values(a)));switch(r){case"vertical":{this.batch(()=>{for(const l of s){if(this.getShapePageTransform(l).rotation()%Oe)continue;const d=i[l.id],p=a[l.id],f=new P(0,c.minY-p.minY),y=this.getShapeParentTransform(l);y&&f.rot(-y.rotation());const{x:g,y:w}=P.Add(f,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:w}],{squashing:!0});const S=new P(1,c.height/p.height);this.resizeShape(l.id,S,{initialBounds:d,scaleOrigin:new P(p.center.x,c.minY),scaleAxisRotation:0})}});break}case"horizontal":{this.batch(()=>{for(const l of s){const u=i[l.id],d=a[l.id];if(this.getShapePageTransform(l).rotation()%Oe)continue;const f=new P(c.minX-d.minX,0),y=this.getShapeParentTransform(l);y&&f.rot(-y.rotation());const{x:g,y:w}=P.Add(f,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:w}],{squashing:!0});const S=new P(c.width/d.width,1);this.resizeShape(l.id,S,{initialBounds:u,scaleOrigin:new P(c.minX,d.center.y),scaleAxisRotation:0})}});break}}return this}resizeShape(n,r,o={}){var f;const s=typeof n=="string"?n:n.id;if(this.getInstanceState().isReadonly)return this;Number.isFinite(r.x)||(r=new P(1,r.y)),Number.isFinite(r.y)||(r=new P(r.x,1));const i=o.initialShape??this.getShape(s);if(!i)return this;const a=o.scaleOrigin??((f=this.getShapePageBounds(s))==null?void 0:f.center);if(!a)return this;const c=o.initialPageTransform?oe.Cast(o.initialPageTransform):this.getShapePageTransform(s);if(!c)return this;const l=c.rotation();if(l==null)return this;const u=o.scaleAxisRotation??l,d=o.initialBounds??this.getShapeGeometry(s).bounds;if(!d)return this;if(!Wk(l,u))return this._resizeUnalignedShape(s,r,{...o,initialBounds:d,scaleOrigin:a,scaleAxisRotation:u,initialPageTransform:c,initialShape:i});const p=this.getShapeUtil(i);if(p.isAspectRatioLocked(i)&&(Math.abs(r.x)>Math.abs(r.y)?r=new P(r.x,Math.sign(r.y)*Math.abs(r.x)):r=new P(Math.sign(r.x)*Math.abs(r.y),r.y)),p.onResize&&p.canResize(i)){const y=this._scalePagePoint(oe.applyToPoint(c,new P(0,0)),a,r,u),g=this.getPointInParentSpace(i.id,y),w=new P(r.x,r.y),S=Ml((l-u)%Math.PI,0);w.x=S?r.x:r.y,w.y=S?r.y:r.x;const v=oe.applyToPoint(c,new P),{x:b,y:E}=this.getPointInParentSpace(i.id,v);this.updateShapes([{id:s,type:i.type,x:g.x,y:g.y,...p.onResize({...i,x:b,y:E},{newPoint:g,handle:o.dragHandle??"bottom_right",mode:o.mode??"scale_shape",scaleX:w.x,scaleY:w.y,initialBounds:d,initialShape:i})}],{squashing:!0})}else{const y=oe.applyToPoint(c,d.center),g=this._scalePagePoint(y,a,r,u),w=this.getPointInParentSpace(i.id,y),S=this.getPointInParentSpace(i.id,g),v=P.Sub(S,w);this.updateShapes([{id:s,type:i.type,x:i.x+v.x,y:i.y+v.y}],{squashing:!0})}return this}_scalePagePoint(n,r,o,s){const i=P.RotWith(n,r,-s).sub(r),a=P.MulV(i,o);return P.Add(a,r).rotWith(r,s)}_resizeUnalignedShape(n,r,o){const{type:s}=o.initialShape,i=new P(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(n,i,{initialShape:o.initialShape,initialBounds:o.initialBounds}),Math.sign(r.x)*Math.sign(r.y)<0){let{rotation:S}=oe.Decompose(o.initialPageTransform);S-=2*S,this.updateShapes([{id:n,type:s,rotation:S}],{squashing:!0})}const a=oe.applyToPoint(o.initialPageTransform,o.initialBounds.center),c=this._scalePagePoint(a,o.scaleOrigin,r,o.scaleAxisRotation),l=this.getShapePageBounds(n),u=this.getShapePageTransform(n),d=l.center,p=u.point();if(!d||!p)return this;const f=P.Sub(c,d),y=P.Add(p,f),{x:g,y:w}=this.getPointInParentSpace(n,y);return this.updateShapes([{id:n,type:s,x:g,y:w}],{squashing:!0}),this}getInitialMetaForShape(n){return{}}createShape(n){return this._createShapes([n]),this}createShapes(n){if(!Array.isArray(n))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");return this._createShapes(n),this}animateShape(n,r){return this.animateShapes([n],r)}animateShapes(n,r={}){const{duration:o=500,easing:s=nn.linear}=r,i=et();let a=o,c;const l=[];let u,d;for(let y=0,g=n.length;y{if(a-=y,a<0){const{animatingShapes:v}=this,b=n.filter(E=>E&&v.get(E.id)===i);b.length&&this.updateShapes(b,{squashing:!1}),this.removeListener("tick",f);return}c=s(1-a/o);const{animatingShapes:g}=this,w=[];let S;for(let v=0,b=l.length;v(E[C]=I+(_-I)*c,E),{})});this._updateShapes(w,{squashing:!0})};return this.addListener("tick",f),this}groupShapes(n,r=Be()){var f;if(!Array.isArray(n))throw Error("Editor.groupShapes: must provide an array of shapes or shape ids");if(this.getInstanceState().isReadonly)return this;const o=typeof n[0]=="string"?n:n.map(y=>y.id);if(o.length<=1)return this;const s=fe(this._getUnlockedShapeIds(o).map(y=>this.getShape(y))),i=s.sort(en).map(y=>y.id),a=ne.Common(fe(s.map(y=>this.getShapePageBounds(y)))),{x:c,y:l}=a.point,u=this.findCommonAncestor(s)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const d=s.filter(y=>y.parentId===u).sort(en),p=(f=d[d.length-1])==null?void 0:f.index;return this.batch(()=>{this.createShapes([{id:r,type:"group",parentId:u,index:p,x:c,y:l,opacity:1,props:{}}]),this.reparentShapes(i,r),this.select(r)}),this}ungroupShapes(n){const r=typeof n[0]=="string"?n:n.map(a=>a.id);if(this.getInstanceState().isReadonly)return this;if(r.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const o=new Set,s=fe(r.map(a=>this.getShape(a))),i=[];return s.forEach(a=>{this.isShapeOfType(a,"group")?i.push(a):o.add(a.id)}),i.length===0?this:(this.batch(()=>{let a;for(let c=0,l=i.length;cc.id)),this.select(...o)}),this)}updateShape(n,r){return this.updateShapes([n],r),this}updateShapes(n,r){const o=Array(n.length);for(let s=0,i=n.length;s{var o;return!((o=this.getShape(r))!=null&&o.isLocked)})}deleteShapes(n){if(!Array.isArray(n))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");return this._deleteShapes(this._getUnlockedShapeIds(typeof n[0]=="string"?n:n.map(r=>r.id))),this}deleteShape(n){return this.deleteShapes([typeof n=="string"?n:n.id]),this}_extractSharedStyles(n,r){if(this.isShapeOfType(n,"group")){const o=this._parentIdsToChildIds.get()[n.id];if(!o)return;for(let s=0,i=o.length;s0)return this._getSelectionSharedStyles();const n=this.root.getCurrent(),r=new VS;if(!n)return r;if(n.shapeType)for(const o of this.styleProps[n.shapeType].keys())r.applyValue(o,this.getStyleForNextShape(o));return r}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const n=[],r=s=>{const i=this.getShape(s);if(i)if(this.isShapeOfType(i,"group"))for(const a of this.getSortedChildIdsForParent(i.id))r(a);else n.push(i)};for(const s of this.getSelectedShapeIds())r(s);let o=null;for(const s of n)if(o===null)o=s.opacity;else if(o!==s.opacity)return{type:"mixed"};if(o!==null)return{type:"shared",value:o}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(n,r){return this.updateInstanceState({opacityForNextShape:n},r),this}setOpacityForSelectedShapes(n,r){const o=this.getSelectedShapes();if(o.length>0){const s=[],i=a=>{if(this.isShapeOfType(a,"group")){const c=this.getSortedChildIdsForParent(a);for(const l of c)i(this.getShape(l))}else s.push(a)};for(const a of o)i(a);this.updateShapes(s.map(a=>({id:a.id,type:a.type,opacity:n})),r)}return this}setStyleForNextShapes(n,r,o){const s=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...s,[n.id]:r}},o),this}setStyleForSelectedShapes(n,r,o){const s=this.getSelectedShapes();if(s.length>0){const i=[],a=c=>{if(this.isShapeOfType(c,"group")){const l=this.getSortedChildIdsForParent(c.id);for(const u of l)a(this.getShape(u))}else{const l=this.getShapeUtil(c),u=this.styleProps[c.type].get(n);if(u){const d={id:c.id,type:c.type,props:{[u]:r}};i.push({util:l,originalShape:c,updatePartial:d})}}};for(const c of s)a(c);this.updateShapes(i.map(({updatePartial:c})=>c),o)}return this}registerExternalAssetHandler(n,r){return this.externalAssetContentHandlers[n]=r,this}async getAssetForExternalContent(n){var r,o;return await((o=(r=this.externalAssetContentHandlers)[n.type])==null?void 0:o.call(r,n))}registerExternalContentHandler(n,r){return this.externalContentHandlers[n]=r,this}async putExternalContent(n){var r,o;return(o=(r=this.externalContentHandlers)[n.type])==null?void 0:o.call(r,n)}getContentFromCurrentPage(n){const r=typeof n[0]=="string"?n:n.map(c=>c.id);if(!r||r.length===0)return;const o={};let s=Mp(r.map(c=>this.getShape(c)).sort(en).flatMap(c=>{const l=[c];return this.visitDescendants(c.id,u=>{l.push(this.getShape(u))}),l}));s=s.map(c=>{if(o[c.id]=this.getShapePageTransform(c.id),c=Ye(c),this.isShapeOfType(c,"arrow")){const l=c.props.start.type==="binding"?c.props.start.boundShapeId:void 0,u=c.props.end.type==="binding"?c.props.end.boundShapeId:void 0,d=this.getArrowInfo(c);if(c.props.start.type==="binding"&&!s.some(f=>f.id===l))if(d!=null&&d.isValid){const{x:f,y}=d.start.point;c.props.start={type:"point",x:f,y}}else{const{start:f}=jr(this,c);c.props.start={type:"point",x:f.x,y:f.y}}if(c.props.end.type==="binding"&&!s.some(f=>f.id===u))if(d!=null&&d.isValid){const{x:f,y}=d.end.point;c.props.end={type:"point",x:f,y}}else{const{end:f}=jr(this,c);c.props.end={type:"point",x:f.x,y:f.y}}const p=Zc(c)?Al(this,c):xm(this,c);if(d!=null&&d.isValid&&(p!=null&&p.isValid)&&!Zc(c)){const f=P.Med(d.start.handle,d.end.handle),y=P.Dist(d.middle,f),g=P.Dist(p.middle,f);c.props.bend<0?c.props.bend+=g-y:c.props.bend-=g-y}return c}return c});const i=[];s.forEach(c=>{if(s.find(l=>l.id===c.parentId)===void 0){const l=this.getShapePageTransform(c.id),u=l.point(),d=l.rotation();c.x=u.x,c.y=u.y,c.rotation=d,c.parentId=this.getCurrentPageId(),i.push(c.id)}});const a=new Set;return s.forEach(c=>{"assetId"in c.props&&c.props.assetId!==null&&a.add(c.props.assetId)}),{shapes:s,rootShapeIds:i,schema:this.store.schema.serialize(),assets:fe(Array.from(a).map(c=>this.getAsset(c)))}}putContentOntoCurrentPage(n,r={}){var k;if(this.getInstanceState().isReadonly)return this;if(!n.schema)throw Error(`Could not put content: content is missing a schema.`);const{select:o=!1,preserveIds:s=!1,preservePosition:i=!1}=r;let{point:a=void 0}=r;const c=this.getCurrentPageId(),{rootShapeIds:l}=n,u=[],d=[],p={store:{...Object.fromEntries(n.assets.map($=>[$.id,$])),...Object.fromEntries(n.shapes.map($=>[$.id,$]))},schema:n.schema},f=this.store.schema.migrateStoreSnapshot(p);if(f.type==="error")throw Error("Could not put content: could not migrate content");for(const $ of Object.values(f.value))switch($.typeName){case"asset":{u.push($);break}case"shape":{d.push($);break}}const y=new Map(d.map($=>[$.id,Be()]));let g=this.getCurrentPageId(),w=1/0,S=[];for(const $ of this.getSelectedShapes()){if(w===0)break;const T=this.isShapeOfType($,"frame"),O=this.getShapeAncestors($);T&&O.push($);const N=T?O.length+1:O.length;if(NO.id===l[0]);this.isShapeOfType($,"frame")&&this.isShapeOfType(T,"frame")&&T.props.w===($==null?void 0:$.props.w)&&T.props.h===($==null?void 0:$.props.h)&&(v=!0)}}else g=c}v||(v=y.has(g)),v&&(g=this.getShape(g).parentId);let b=this.getHighestIndexForParent(g);const E=[],C=d.map($=>{let T;if(s)T=Ye($),y.set($.id,$.id);else{const O=y.get($.id);T=Ye({...$,id:O})}if(l.includes($.id)&&(T.parentId=c,E.push(T)),y.has(T.parentId)?T.parentId=y.get($.parentId):(l.push(T.id),T.index=b,b=$o(b)),this.isShapeOfType(T,"arrow")){if(T.props.start.type==="binding"){const O=y.get(T.props.start.boundShapeId);T.props.start=O?{...T.props.start,boundShapeId:O}:{type:"point",x:0,y:0}}if(T.props.end.type==="binding"){const O=y.get(T.props.end.boundShapeId);T.props.end=O?{...T.props.end,boundShapeId:O}:{type:"point",x:0,y:0}}}return T});if(C.length+this.getCurrentPageShapeIds().size>Io)return _d(this),this;const I=[],_=[];for(const $ of u)this.store.has($.id)||(($.type==="image"||$.type==="video")&&((k=$.props.src)!=null&&k.startsWith("data:image"))&&(_.push(Ye($)),$.props.src=null),I.push($));return Promise.allSettled(_.map(async $=>{const T=await R4($.props.src,$.props.name,$.props.mimeType??"image/png"),O=await this.getAssetForExternalContent({type:"file",file:T});if(!O){this.deleteAssets([$.id]);return}this.updateAssets([{...O,id:$.id}])})),this.batch(()=>{I.length>0&&this.createAssets(I),this.createShapes(C),o&&this.select(...E.map(F=>F.id)),g!==c&&this.reparentShapes(E.map(F=>F.id),g);const $=C.map(F=>this.getShape(F.id)),T=ne.Common($.map(F=>this.getShapePageBounds(F)));if(a===void 0)if(bn(g)){const F=this.getViewportPageBounds();i||F.includes(ne.From(T))?a=T.center:a=F.center}else{const F=this.getShape(g);a=oe.applyToPoint(this.getShapePageTransform(F),this.getShapeGeometry(F).bounds.center)}if(E.length===1){const F=E[0];if(this.isShapeOfType(F,"frame"))for(;this.getShapesAtPoint(a).some(L=>this.isShapeOfType(L,"frame")&&L.props.w===F.props.w&&L.props.h===F.props.h);)a.x+=T.w+16}const O=ne.Common(fe(E.map(({id:F})=>this.getShapePageBounds(F)))).center,N=P.Sub(a,O);this.updateShapes(E.map(({id:F})=>{const L=this.getShape(F),B=this.getShapeParentTransform(F).decompose().rotation,q=P.Rot(N,-B);return{id:L.id,type:L.type,x:L.x+q.x,y:L.y+q.y}}))}),this}async getSvgElement(n,r={}){const o=await Y4(this,n,r);if(!o)return;const s=document.createDocumentFragment(),i=A_(s);Ui.flushSync(()=>{i.render(o.jsx)});const a=s.firstElementChild;return _t(a instanceof SVGSVGElement,"Expected an SVG element"),i.unmount(),{svg:a,width:o.width,height:o.height}}async getSvgString(n,r={}){const o=await this.getSvgElement(n,r);return o?{svg:new XMLSerializer().serializeToString(o.svg),width:o.width,height:o.height}:void 0}async getSvg(n,r={}){const o=await this.getSvgElement(n,r);if(o)return o.svg}_updateInputsFromEvent(n){var S;const{pointerVelocity:r,previousScreenPoint:o,previousPagePoint:s,currentScreenPoint:i,currentPagePoint:a}=this.inputs,{screenBounds:c}=this.store.unsafeGetWithoutCapture(In),{x:l,y:u,z:d}=this.store.unsafeGetWithoutCapture(this.getCameraId()),p=n.point.x-c.x,f=n.point.y-c.y,y=n.point.z??.5;o.setTo(i),s.setTo(a),i.set(p,f);const g=p/d-l,w=f/d-u;isFinite(g)&&isFinite(w)&&a.set(g,w,y),this.inputs.isPen=n.type==="pointer"&&n.isPen,(n.name==="pointer_down"||this.inputs.isPinching)&&r.set(0,0),this.store.put([{id:Fp,typeName:"pointer",x:a.x,y:a.y,lastActivityTimestamp:n.type==="pointer"&&n.pointerId===b1.CAMERA_MOVE?((S=this.store.unsafeGetWithoutCapture(Fp))==null?void 0:S.lastActivityTimestamp)??this._tickManager.now:this._tickManager.now,meta:{}}])}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}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_flushEventsForTick(n){this.batch(()=>{if(this._pendingEventsForNextTick.length>0){const r=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const o of r)this._flushEventForTick(o)}n>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:n}),this.scribbles.tick(n)})}}re([V],J.prototype,"getCanUndo");re([V],J.prototype,"getCanRedo");re([V],J.prototype,"_getArrowBindingsIndex");re([V],J.prototype,"getArrowInfoCache");re([V],J.prototype,"getPath");re([V],J.prototype,"getCurrentTool");re([V],J.prototype,"getCurrentToolId");re([V],J.prototype,"getDocumentSettings");re([V],J.prototype,"getInstanceState");re([V],J.prototype,"getOpenMenus");re([V],J.prototype,"getIsMenuOpen");re([V],J.prototype,"getPageStates");re([V],J.prototype,"_getPageStatesQuery");re([V],J.prototype,"getCurrentPageState");re([V],J.prototype,"_getCurrentPageStateId");re([V],J.prototype,"getSelectedShapeIds");re([V],J.prototype,"getSelectedShapes");re([V],J.prototype,"getOnlySelectedShapeId");re([V],J.prototype,"getOnlySelectedShape");re([V],J.prototype,"getSelectionPageBounds");re([V],J.prototype,"getSelectionRotation");re([V],J.prototype,"getSelectionRotatedPageBounds");re([V],J.prototype,"getSelectionRotatedScreenBounds");re([V],J.prototype,"getFocusedGroupId");re([V],J.prototype,"getFocusedGroup");re([V],J.prototype,"getEditingShapeId");re([V],J.prototype,"getEditingShape");re([V],J.prototype,"getHoveredShapeId");re([V],J.prototype,"getHoveredShape");re([V],J.prototype,"getHintingShapeIds");re([V],J.prototype,"getHintingShape");re([V],J.prototype,"getErasingShapeIds");re([V],J.prototype,"getErasingShapes");re([V],J.prototype,"getCameraId");re([V],J.prototype,"getCamera");re([V],J.prototype,"getZoomLevel");re([V],J.prototype,"getViewportScreenBounds");re([V],J.prototype,"getViewportScreenCenter");re([V],J.prototype,"getViewportPageBounds");re([V],J.prototype,"getViewportPageCenter");re([V],J.prototype,"_getCollaboratorsQuery");re([V],J.prototype,"getCollaborators");re([V],J.prototype,"getCollaboratorsOnCurrentPage");re([V],J.prototype,"getRenderingShapes");re([V],J.prototype,"_getAllPagesQuery");re([V],J.prototype,"getPages");re([V],J.prototype,"getCurrentPageId");re([V],J.prototype,"getCurrentPageShapeIdsSorted");re([V],J.prototype,"_getAllAssetsQuery");re([V],J.prototype,"_getShapeGeometryCache");re([V],J.prototype,"_getShapeHandlesCache");re([V],J.prototype,"_getShapePageTransformCache");re([V],J.prototype,"_getShapePageBoundsCache");re([V],J.prototype,"_getShapeClipPathCache");re([V],J.prototype,"_getShapeMaskCache");re([V],J.prototype,"_getShapeMaskedPageBoundsCache");re([V],J.prototype,"_notVisibleShapes");re([V],J.prototype,"getCulledShapes");re([V],J.prototype,"getCurrentPageBounds");re([V],J.prototype,"getCurrentPageShapes");re([V],J.prototype,"getCurrentPageShapesSorted");re([V],J.prototype,"getCurrentPageRenderingShapesSorted");re([V],J.prototype,"_getSelectionSharedStyles");re([V({isEqual:(e,t)=>e.equals(t)})],J.prototype,"getSharedStyles");re([V],J.prototype,"getSharedOpacity");function _d(e,t=e.getCurrentPageId()){const n=e.getPage(t).name;e.emit("max-shapes",{name:n,pageId:t,count:Io})}function Qc(e,t){if(!t)return e;let n=null;const r=Object.entries(t);for(let o=0,s=r.length;o(t==null?void 0:t.isDarkMode)??e.user.getIsDarkMode(),[t,e])}const eP="",tP="",kd='';function ds(e,t,n,r,o,s=16,i=16){const a=(-n-t)*(Pe/180),c=Math.sin(a),l=Math.cos(a),u=1*l-1*c,d=1*c+1*l;return`url("data:image/svg+xml,`+e.replaceAll('"',"'")+`") ${s} ${i}, pointer`}const Iz=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],Ez={none:()=>"none","ew-resize":(e,t,n)=>ds(tP,e,0,t,n),"ns-resize":(e,t,n)=>ds(tP,e,90,t,n),"nesw-resize":(e,t,n)=>ds(eP,e,0,t,n),"nwse-resize":(e,t,n)=>ds(eP,e,90,t,n),"nwse-rotate":(e,t,n)=>ds(kd,e,0,t,n),"nesw-rotate":(e,t,n)=>ds(kd,e,90,t,n),"senw-rotate":(e,t,n)=>ds(kd,e,180,t,n),"swne-rotate":(e,t,n)=>ds(kd,e,270,t,n)};function Bn(e,t=0,n="black"){return Ez[e](P5(t),!1,n)}function _z(){const e=z(),t=cn(),n=Ru();js("useCursor",()=>{const{type:r,rotation:o}=e.getInstanceState().cursor;if(Iz.includes(r)){t.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}t.style.setProperty("--tl-cursor",Bn(r,o,n?"white":"black"))},[e,t,n])}function kz(){const e=z(),t=cn(),n=Ru(),r=K($t.forceSrgb);Se.useEffect(()=>{n?(t.setAttribute("data-color-mode","dark"),t.classList.remove("tl-theme__light"),t.classList.add("tl-theme__dark")):(t.setAttribute("data-color-mode","light"),t.classList.remove("tl-theme__dark"),t.classList.add("tl-theme__light")),r?t.classList.add("tl-theme__force-sRGB"):t.classList.remove("tl-theme__force-sRGB")},[e,t,r,n])}function lx(e){const t=x.useRef();return x.useLayoutEffect(()=>{t.current=e}),x.useDebugValue(e),x.useCallback((...n)=>{const r=t.current;return _t(r,"fn does not exist"),r(...n)},[])}function Tz(e){const t=z(),n=cn();x.useLayoutEffect(()=>{e?(t.getInstanceState().isFocused||t.updateInstanceState({isFocused:!0}),t.getContainer().focus()):t.getInstanceState().isFocused&&t.updateInstanceState({isFocused:!1})},[t,n,e])}function $z(){const[e,t]=x.useState(0);x.useEffect(()=>t(n=>n+1),[])}const Va="TLDRAW_TAB_ID_v2",so=globalThis.window;function Mz(){return so?["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(so.navigator.platform)||so.navigator.userAgent.includes("Mac")&&"ontouchend"in document:!1}const ef=so?so[Va]??X_(Va)??"TLDRAW_INSTANCE_STATE_V1_"+et():"";so&&(so[Va]=ef,Mz()?N0(Va,ef):q_(Va));so==null||so.addEventListener("beforeunload",()=>{N0(Va,ef)});const F2={Initial:0},Hf=Math.max(...Object.values(F2));function Az(e){e.version{const n=e.get(In);if(!n)return null;const r=[...t.get()];return{version:Hf,currentPageId:n.currentPageId,exportBackground:n.exportBackground,isFocusMode:n.isFocusMode,isDebugMode:n.isDebugMode,isToolLocked:n.isToolLocked,isGridMode:n.isGridMode,pageStates:r.map(o=>{const s=e.get(Zt.createId(o)),i=e.get(hn.createId(o));return{pageId:o,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:(s==null?void 0:s.selectedShapeIds)??[],focusedGroupId:(s==null?void 0:s.focusedGroupId)??null}})}})}function Dz(e,t){const n=jz(t);if(!n)return;const r=e.allRecords().filter(i=>i.typeName==="instance_page_state"||i.typeName==="camera"),o={added:{},updated:{},removed:{...R0(r.map(i=>[i.id,i]))}};e.has(In)&&(o.removed[In]=e.get(In));const s={removed:{},updated:{},added:{[In]:e.schema.types.instance.create({id:In,currentPageId:n.currentPageId,isDebugMode:n.isDebugMode,isFocusMode:n.isFocusMode,isToolLocked:n.isToolLocked,isGridMode:n.isGridMode,exportBackground:n.exportBackground})}};for(const i of n.pageStates){const a=hn.createId(i.pageId),c=Zt.createId(i.pageId);s.added[a]=hn.create({id:hn.createId(i.pageId),x:i.camera.x,y:i.camera.y,z:i.camera.z}),s.added[c]=Zt.create({id:Zt.createId(i.pageId),pageId:i.pageId,selectedShapeIds:i.selectedShapeIds,focusedGroupId:i.focusedGroupId})}Mr(()=>{e.applyDiff(Af([o,s])),e.ensureStoreIsUsable()})}function Rz(e){var o;const t=[];for(const s of Object.values(e))(o=s.typeName)!=null&&o.match(/^(instance.*|pointer|camera)$/)&&t.push(s);const n=t.filter(s=>s.typeName==="instance"&&s.id!==In)[0];if(!n)return null;const r={version:Hf,currentPageId:n.currentPageId,exportBackground:!!n.exportBackground,isFocusMode:!!n.isFocusMode,isDebugMode:!!n.isDebugMode,isToolLocked:!!n.isToolLocked,isGridMode:!1,pageStates:t.filter(s=>s.typeName==="instance_page_state"&&s.instanceId===n.id).map(s=>{const i=e[s.cameraId]??{x:0,y:0,z:1};return{pageId:s.pageId,camera:{x:i.x,y:i.y,z:i.z},selectedShapeIds:s.selectedShapeIds,focusedGroupId:s.focusedGroupId}})};try{return N2.validate(r),r}catch{return null}}function Lz(){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. • If your hard disk is full, try clearing up some space and then reload the page.`)}function Fz(){window.alert(`Oops! We could not access your browser's storage—and the app won't work correctly without that. We now need to reload the page and try again. 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.`)}const Nz=(e,t)=>t.some(n=>e instanceof n);let nP,rP;function zz(){return nP||(nP=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Bz(){return rP||(rP=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const z2=new WeakMap,GS=new WeakMap,B2=new WeakMap,wm=new WeakMap,ux=new WeakMap;function Uz(e){const t=new Promise((n,r)=>{const o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{n(Ro(e.result)),o()},i=()=>{r(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return t.then(n=>{n instanceof IDBCursor&&z2.set(n,e)}).catch(()=>{}),ux.set(t,e),t}function Hz(e){if(GS.has(e))return;const t=new Promise((n,r)=>{const o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{n(),o()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});GS.set(e,t)}let YS={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return GS.get(e);if(t==="objectStoreNames")return e.objectStoreNames||B2.get(e);if(t==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ro(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Kz(e){YS=e(YS)}function Wz(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...n){const r=e.call(bm(this),t,...n);return B2.set(r,t.sort?t.sort():[t]),Ro(r)}:Bz().includes(e)?function(...t){return e.apply(bm(this),t),Ro(z2.get(this))}:function(...t){return Ro(e.apply(bm(this),t))}}function Vz(e){return typeof e=="function"?Wz(e):(e instanceof IDBTransaction&&Hz(e),Nz(e,zz())?new Proxy(e,YS):e)}function Ro(e){if(e instanceof IDBRequest)return Uz(e);if(wm.has(e))return wm.get(e);const t=Vz(e);return t!==e&&(wm.set(e,t),ux.set(t,e)),t}const bm=e=>ux.get(e);function Gz(e,t,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(e,t),a=Ro(i);return r&&i.addEventListener("upgradeneeded",c=>{r(Ro(i.result),c.oldVersion,c.newVersion,Ro(i.transaction),c)}),n&&i.addEventListener("blocked",c=>n(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Yz(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",r=>t(r.oldVersion,r)),Ro(n).then(()=>{})}const Xz=["get","getKey","getAll","getAllKeys","count"],qz=["put","add","delete","clear"],Pm=new Map;function oP(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(Pm.get(t))return Pm.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=qz.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||Xz.includes(n)))return;const s=async function(i,...a){const c=this.transaction(i,o?"readwrite":"readonly");let l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),o&&c.done]))[0]};return Pm.set(t,s),s}Kz(e=>({...e,get:(t,n,r)=>oP(t,n)||e.get(t,n,r),has:(t,n)=>!!oP(t,n)||e.has(t,n)}));const Kf="TLDRAW_DOCUMENT_v2",U2="TLDRAW_DB_NAME_INDEX_v2",Le={Records:"records",Schema:"schema",SessionState:"session_state"};async function Wf(e,t){t8(e);const n=await Gz(e,3,{upgrade(r){r.objectStoreNames.contains(Le.Records)||r.createObjectStore(Le.Records),r.objectStoreNames.contains(Le.Schema)||r.createObjectStore(Le.Schema),r.objectStoreNames.contains(Le.SessionState)||r.createObjectStore(Le.SessionState)}});try{return await t(n)}finally{n.close()}}async function Zz({persistenceKey:e,sessionId:t,didCancel:n}){const r=Kf+e;if(dx().includes(r))return await e8({persistenceKey:e,didCancel:n}),await Wf(r,async o=>{var d,p;if(n!=null&&n())return;const s=o.transaction([Le.Records,Le.Schema,Le.SessionState],"readonly"),i=s.objectStore(Le.Records),a=s.objectStore(Le.Schema),c=s.objectStore(Le.SessionState);let l=t?(d=await c.get(t))==null?void 0:d.snapshot:null;l||(l=(p=(await c.getAll()).sort((y,g)=>y.updatedAt-g.updatedAt).pop())==null?void 0:p.snapshot);const u={records:await i.getAll(),schema:await a.get(Le.Schema),sessionStateSnapshot:l};if(n!=null&&n()){s.abort();return}return await s.done,u})}async function Qz({persistenceKey:e,schema:t,changes:n,sessionId:r,sessionStateSnapshot:o,didCancel:s}){const i=Kf+e;await Wf(i,async a=>{const c=a.transaction([Le.Records,Le.Schema,Le.SessionState],"readwrite"),l=c.objectStore(Le.Records),u=c.objectStore(Le.Schema),d=c.objectStore(Le.SessionState);for(const[p,f]of Object.entries(n.added))await l.put(f,p);for(const[p,f]of Object.values(n.updated))await l.put(f,f.id);for(const p of Object.keys(n.removed))await l.delete(p);if(u.put(t.serialize(),Le.Schema),o&&r?d.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together"),s!=null&&s())return c.abort();await c.done})}async function Jz({persistenceKey:e,schema:t,snapshot:n,sessionId:r,sessionStateSnapshot:o,didCancel:s}){const i=Kf+e;await Wf(i,async a=>{const c=a.transaction([Le.Records,Le.Schema,Le.SessionState],"readwrite"),l=c.objectStore(Le.Records),u=c.objectStore(Le.Schema),d=c.objectStore(Le.SessionState);await l.clear();for(const[p,f]of Object.entries(n))await l.put(f,p);if(u.put(t.serialize(),Le.Schema),o&&r?d.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together"),s!=null&&s())return c.abort();await c.done})}async function e8({persistenceKey:e,didCancel:t}){await Wf(Kf+e,async n=>{const r=n.transaction([Le.SessionState],"readwrite"),o=r.objectStore(Le.SessionState),s=(await o.getAll()).sort((a,c)=>a.updatedAt-c.updatedAt);if(s.length<10){await r.done;return}const i=s.slice(0,s.length-10);for(const{id:a}of i)await o.delete(a);if(t!=null&&t())return r.abort();await r.done})}function dx(){const e=JSON.parse(L0(U2)||"[]")??[];return Array.isArray(e)?e:[]}function t8(e){const t=new Set(dx());t.add(e),F0(U2,JSON.stringify([...t]))}const n8=350,r8=1e4,sP=Symbol("UPDATE_INSTANCE_STATE"),o8=e=>e;class s8{constructor(t){m(this,"onmessage")}postMessage(t){}close(){}}const i8=typeof BroadcastChannel>"u"?s8:BroadcastChannel;class a8{constructor(t,{persistenceKey:n,sessionId:r=ef,onLoad:o,onLoadError:s},i=new i8(`tldraw-tab-sync-${n}`)){m(this,"disposables",new Set);m(this,"diffQueue",[]);m(this,"didDispose",!1);m(this,"shouldDoFullDBWrite",!0);m(this,"isReloading",!1);m(this,"persistenceKey");m(this,"sessionId");m(this,"serializedSchema");m(this,"isDebugging",!1);m(this,"documentTypes");m(this,"$sessionStateSnapshot");m(this,"initTime",Date.now());m(this,"isPersisting",!1);m(this,"didLastWriteError",!1);m(this,"scheduledPersistTimeout",null);this.store=t,this.channel=i,typeof window<"u"&&(window.tlsync=this),this.persistenceKey=n,this.sessionId=r,this.serializedSchema=this.store.schema.serialize(),this.$sessionStateSnapshot=Oz(this.store),this.disposables.add(t.listen(({changes:a})=>{this.diffQueue.push(a),this.channel.postMessage(o8({type:"diff",storeId:this.store.id,changes:a,schema:this.serializedSchema})),this.schedulePersist()},{source:"user",scope:"document"})),this.disposables.add(t.listen(()=>{this.diffQueue.push(sP),this.schedulePersist()},{scope:"session"})),this.connect(o,s),this.documentTypes=new Set(Object.values(this.store.schema.types).filter(a=>a.scope==="document").map(a=>a.typeName))}debug(...t){this.isDebugging&&console.debug(...t)}async connect(t,n){this.debug("connecting");let r;try{r=await Zz({persistenceKey:this.persistenceKey,sessionId:this.sessionId,didCancel:()=>this.didDispose})}catch(o){n(o),Fz(),typeof window<"u"&&window.location.reload();return}if(this.debug("loaded data from store",r,"didDispose",this.didDispose),!this.didDispose)try{if(r){const o=Object.fromEntries(r.records.map(a=>[a.id,a])),s=r.sessionStateSnapshot??Rz(o),i=this.store.schema.migrateStoreSnapshot({store:o,schema:r.schema??this.store.schema.serializeEarliestVersion()});if(i.type==="error"){console.error("failed to migrate store",i),n(new Error(`Failed to migrate store: ${i.reason}`));return}this.store.mergeRemoteChanges(()=>{this.store.put(Object.values(i.value).filter(a=>this.documentTypes.has(a.typeName)),"initialize")}),s&&Dz(this.store,s)}this.channel.onmessage=({data:o})=>{var a,c;this.debug("got message",o);const s=o,i=this.store.schema.getMigrationsSince(s.schema);if(i.ok){if(i.value.length>0){this.debug("telling them to reload"),this.channel.postMessage({type:"announce",schema:this.serializedSchema}),this.shouldDoFullDBWrite=!0,this.persistIfNeeded();return}}else{if(Date.now()-this.initTime<5e3){n(new Error("Schema mismatch, please close other tabs and reload the page"));return}this.debug("reloading"),this.isReloading=!0,(c=(a=window==null?void 0:window.location)==null?void 0:a.reload)==null||c.call(a);return}s.type==="diff"&&(this.debug("applying diff"),Mr(()=>{this.store.mergeRemoteChanges(()=>{this.store.applyDiff(s.changes),this.store.ensureStoreIsUsable()})}))},this.channel.postMessage({type:"announce",schema:this.serializedSchema}),this.disposables.add(()=>{this.channel.close()}),t(this)}catch(o){if(this.debug("error loading data from store",o),this.didDispose)return;n(o);return}}close(){this.debug("closing"),this.didDispose=!0,this.disposables.forEach(t=>t())}schedulePersist(){this.debug("schedulePersist",this.scheduledPersistTimeout),!this.scheduledPersistTimeout&&(this.scheduledPersistTimeout=setTimeout(()=>{this.scheduledPersistTimeout=null,this.persistIfNeeded()},this.didLastWriteError?r8:n8))}persistIfNeeded(){this.debug("persistIfNeeded",{isPersisting:this.isPersisting,isReloading:this.isReloading,shouldDoFullDBWrite:this.shouldDoFullDBWrite,diffQueueLength:this.diffQueue.length,storeIsPossiblyCorrupt:this.store.isPossiblyCorrupted()}),this.scheduledPersistTimeout&&(clearTimeout(this.scheduledPersistTimeout),this.scheduledPersistTimeout=null),!this.isPersisting&&(this.isReloading||this.store.isPossiblyCorrupted()||(this.shouldDoFullDBWrite||this.diffQueue.length>0)&&this.doPersist())}async doPersist(){_t(!this.isPersisting,"persist already in progress"),this.isPersisting=!0,this.debug("doPersist start");const t=this.diffQueue;this.diffQueue=[];try{if(this.shouldDoFullDBWrite)this.shouldDoFullDBWrite=!1,await Jz({persistenceKey:this.persistenceKey,schema:this.store.schema,snapshot:this.store.serialize(),didCancel:()=>this.didDispose,sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()});else{const n=Af(t.filter(r=>r!==sP));await Qz({persistenceKey:this.persistenceKey,changes:n,schema:this.store.schema,didCancel:()=>this.didDispose,sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()})}this.didLastWriteError=!1}catch(n){this.shouldDoFullDBWrite=!0,this.didLastWriteError=!0,console.error("failed to store changes in indexed db",n),Lz(),typeof window<"u"&&window.location.reload()}this.isPersisting=!1,this.debug("doPersist end"),this.schedulePersist()}}function H2({initialData:e,defaultName:t="",...n}){const r="schema"in n&&n.schema?n.schema:p5({shapes:c8(A2("shapeUtils"in n&&n.shapeUtils?n.shapeUtils:[])),migrations:"migrations"in n?n.migrations:[]});return new tk({schema:r,initialData:e,props:{defaultName:t}})}function c8(e){return Object.fromEntries(e.map(t=>[t.type,{props:t.props,migrations:t.migrations}]))}function iP(e){const t=H2(e);return e.snapshot&&t.loadSnapshot(e.snapshot),{store:t,opts:e}}function K2(e){const[t,n]=x.useState(()=>iP(e));if(!K_(t.opts,e)){const r=iP(e);return n(r),r.store}return t.store}function l8({persistenceKey:e,sessionId:t,...n}){const[r,o]=x.useState(null),s=K2(n);return x.useEffect(()=>{const i=et();if(!e){o({id:i,storeWithStatus:{status:"not-synced",store:s}});return}o({id:i,storeWithStatus:{status:"loading"}});const a=l=>{o(u=>(u==null?void 0:u.id)===i?{id:i,storeWithStatus:l}:u)},c=new a8(s,{sessionId:t,persistenceKey:e,onLoad(){a({store:s,status:"synced-local"})},onLoadError(l){a({status:"error",error:l})}});return()=>{o(l=>(l==null?void 0:l.id)===i?null:l),c.close()}},[e,s,t]),(r==null?void 0:r.storeWithStatus)??{status:"loading"}}let W2=!1;if(typeof window<"u"){const e=window.navigator.userAgent,t=!!e.match(/iPad/i)||!!e.match(/iPhone/i),n=!!e.match(/WebKit/i);W2=t&&n&&!e.match(/CriOS/i)}function u8(){const e=z();x.useEffect(()=>{if(!W2)return;function t(n){(n.target instanceof HTMLInputElement&&n.target.type==="text"||n.target instanceof HTMLTextAreaElement)&&e.complete()}return document.addEventListener("focusout",t),()=>document.removeEventListener("focusout",t)},[e])}function d8(){const e=z(),t=cn();x.useEffect(()=>{const n=s=>t.style.setProperty("--tl-zoom",s.toString()),r=H_(n,100),o=new yc("useZoomCss",()=>{e.getCurrentPageShapeIds().size<300?n(e.getZoomLevel()):r(e.getZoomLevel())});return o.attach(),o.execute(),()=>{o.detach()}},[e,t])}const h8=[],p8=[],f8=x.memo(function({store:t,components:n,className:r,user:o,...s}){const[i,a]=Se.useState(null),c=x.useMemo(()=>o??k2(),[o]),l=(n==null?void 0:n.ErrorFallback)===void 0?w2:n==null?void 0:n.ErrorFallback,u={...s,shapeUtils:s.shapeUtils??h8,tools:s.tools??p8,components:n};return h.jsx("div",{ref:a,draggable:!1,className:ue("tl-container tl-theme__light",r),onPointerDown:Ut,tabIndex:-1,children:h.jsx(su,{fallback:l,onError:d=>D0(d,{tags:{origin:"react.tldraw-before-app"}}),children:i&&h.jsx(Y5,{container:i,children:h.jsx(f4,{overrides:n,children:t?t instanceof tk?h.jsx(G2,{...u,store:t,user:c}):h.jsx(V2,{...u,store:t,user:c}):h.jsx(g8,{...u,store:t,user:c})})})})})});function g8(e){const{defaultName:t,snapshot:n,initialData:r,shapeUtils:o,persistenceKey:s,sessionId:i,user:a}=e,c=l8({shapeUtils:o,initialData:r,persistenceKey:s,sessionId:i,defaultName:t,snapshot:n});return h.jsx(V2,{...e,store:c,user:a})}const V2=x.memo(function({store:t,user:n,...r}){const o=cn();x.useLayoutEffect(()=>{n.userPreferences.get().isDarkMode&&(o.classList.remove("tl-theme__light"),o.classList.add("tl-theme__dark"))},[o,n]);const{LoadingScreen:s}=dt();switch(t.status){case"error":throw t.error;case"loading":return s?h.jsx(s,{}):null}return h.jsx(G2,{...r,store:t.store,user:n})});function G2({onMount:e,children:t,store:n,tools:r,shapeUtils:o,user:s,initialState:i,autoFocus:a=!0,inferDarkMode:c}){const{ErrorFallback:l}=dt(),u=cn(),[d,p]=x.useState(null);x.useLayoutEffect(()=>{const g=new J({store:n,shapeUtils:o,tools:r,getContainer:()=>u,user:s,initialState:i,inferDarkMode:c});return p(g),()=>{g.dispose()}},[u,o,r,n,s,i,c]);const f=x.useSyncExternalStore(x.useCallback(g=>d?(d.on("crash",g),()=>d.off("crash",g)):()=>{},[d]),()=>(d==null?void 0:d.getCrashingError())??null),{Canvas:y}=dt();return d?h.jsx(su,{fallback:l,onError:g=>d.annotateError(g,{origin:"react.tldraw",willCrashApp:!0}),children:f?h.jsx(y8,{crashingError:f}):h.jsx(Rf.Provider,{value:d,children:h.jsx(m8,{autoFocus:a,onMount:e,children:t??(y?h.jsx(y,{}):null)})})}):null}function m8({children:e,onMount:t,autoFocus:n}){return d8(),_z(),kz(),u8(),$z(),Tz(n),S8(t),h.jsx(h.Fragment,{children:e})}function y8({crashingError:e}){throw e}function Y2({children:e}){return h.jsx("div",{className:"tl-loading",children:e})}function X2({children:e}){return h.jsx("div",{className:"tl-loading",children:e})}function S8(e){const t=z(),n=lx(r=>{const o=e==null?void 0:e(r);return r.emit("mount"),window.tldrawReady=!0,o});Se.useLayoutEffect(()=>{if(t)return n==null?void 0:n(t)},[t,n])}function Ai({children:e,className:t="",...n}){return h.jsx("div",{...n,className:ue("tl-html-container",t),children:e})}function q2(e,t,n={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=t,{minWidth:a=1,maxWidth:c=1/0,minHeight:l=1,maxHeight:u=1/0}=n;let d=e.props.w*s,p=e.props.h*i;const f=new P(0,0);if(d>0){if(d0){if(pq2(n,r))}getGeometry(n){return new Wo({width:n.props.w,height:n.props.h,isFilled:!0})}getHandleSnapGeometry(n){return{points:this.getGeometry(n).bounds.cornersAndCenter}}}var Sy;let v8=(Sy=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",n=>{this.parent.transition("pointing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Sy,"id","idle"),Sy);var vy;let x8=(vy=class extends se{constructor(){super(...arguments);m(this,"markId","");m(this,"wasFocusedOnEnter",!1);m(this,"onEnter",()=>{this.wasFocusedOnEnter=!this.editor.getIsMenuOpen()});m(this,"onPointerMove",n=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,o=this.parent.shapeType,s=Be();this.markId=`creating:${s}`,this.editor.mark(this.markId),this.editor.createShapes([{id:s,type:o,x:r.x,y:r.y,props:{w:1,h:1}}]).select(s),this.editor.setCurrentTool("select.resizing",{...n,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:this.parent.onCreate})}});m(this,"onPointerUp",()=>{this.complete()});m(this,"onCancel",()=>{this.cancel()});m(this,"onComplete",()=>{this.complete()});m(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:n}=this.editor.inputs;if(!this.wasFocusedOnEnter)return;this.editor.mark(this.markId);const r=this.parent.shapeType,o=Be();this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:r,x:n.x,y:n.y}]);const s=this.editor.getShape(o),{w:i,h:a}=this.editor.getShapeUtil(s).getDefaultProps(),c=new P(i/2,a/2),l=this.editor.getShapeParentTransform(s);l&&c.rot(-l.rotation()),this.editor.updateShapes([{id:o,type:r,x:s.x-c.x,y:s.y-c.y}]),this.editor.setSelectedShapes([o]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},m(vy,"id","pointing"),vy);class Ph extends se{constructor(){super(...arguments);m(this,"onCreate")}}m(Ph,"id","box"),m(Ph,"initial","idle"),m(Ph,"children",()=>[v8,x8]);function Vf(e){const t=z();return K("isEditing",()=>t.getEditingShapeId()===e,[t,e])}function w8(){return x.useId().replace(/:/g,"_")}function Xr(e){const t=z();return x.useMemo(function(){const o=l=>{if(l.isKilled)return;if(l.button===2){t.dispatch({type:"pointer",target:"selection",handle:e,name:"right_click",..._n(l)});return}if(l.button!==0)return;const u=Yp(l.currentTarget);function d(){u.removeEventListener("pointerup",d),Au(u,l)}Mu(u,l),u.addEventListener("pointerup",d),t.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:e,..._n(l)}),Ut(l)};let s,i;function a(l){l.isKilled||l.button===0&&(l.clientX===s&&l.clientY===i||(s=l.clientX,i=l.clientY,t.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:e,..._n(l)})))}return{onPointerDown:o,onPointerMove:a,onPointerUp:l=>{l.isKilled||l.button===0&&t.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:e,..._n(l)})}}},[t,e])}const b8=20,P8=8;function hx(e,t=b8){return Math.max(P8,Math.ceil(e/t))}class Z2 extends Hi{constructor(n){super({...n,isFilled:!1,isClosed:!1});m(this,"_center");m(this,"radius");m(this,"start");m(this,"end");m(this,"measure");m(this,"length");m(this,"angleStart");m(this,"angleEnd");const{center:r,radius:o,sweepFlag:s,largeArcFlag:i,start:a,end:c}=n;if(a.equals(c))throw Error("Arc must have different start and end points.");this.angleStart=P.Angle(r,a),this.angleEnd=P.Angle(r,c),this.measure=C5(this.angleStart,this.angleEnd,s,i),this.length=this.measure*o,this.start=a,this.end=c,this._center=r,this.radius=o}nearestPoint(n){const{_center:r,measure:o,radius:s,angleEnd:i,angleStart:a,start:c,end:l}=this,u=zS(o,a,i,r.angle(n));if(u<=0)return c;if(u>=1)return l;const d=r.clone().add(n.clone().sub(r).uni().mul(s));let p,f=1/0,y;for(const g of[c,l,d])y=P.Dist2(n,g),y{const d=zS(i,a,c,o.angle(u));return d>=0&&d<=1})}getVertices(){const{_center:n,measure:r,length:o,radius:s,angleStart:i}=this,a=[];for(let c=0,l=hx(Math.abs(o));cn+r.length,0)),this._length}getVertices(){const n=this.segments.reduce((r,o)=>r.concat(o.vertices),[]);return n.push(this.points[this.points.length-1]),n}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(n),s=P.Dist2(i,n),so.hitTestLineSegment(n,r))}}class Q2 extends Hi{constructor(n){super({...n,isClosed:!0});m(this,"w");m(this,"h");m(this,"_edges");this.config=n;const{width:r,height:o}=n;this.w=r,this.h=o}get edges(){if(!this._edges){const{vertices:n}=this;this._edges=[];for(let r=0,o=n.length;ro.hitTestLineSegment(n,r))}getBounds(){return new ne(0,0,this.w,this.h)}}const Co=18;class _8 extends Q2{constructor(t){super({...t}),this.config=t}getVertices(){const t=Math.max(1,this.w),n=Math.max(1,this.h),r=t/2,o=n/2,s=Array(Co);let i,a;if(n>t)for(let c=0;cu?-Math.min(1,(c-u)/s):0}function fx(e){if(!e.inputs.isDragging||e.inputs.isPanning||!e.getInstanceState().canMoveCamera)return;const{inputs:{currentScreenPoint:{x:t,y:n}}}=e,r=e.getZoomLevel(),o=e.getViewportScreenBounds(),s=o.w<1e3?.612:1,i=o.h<1e3?.612:1,{isCoarsePointer:a,insets:[c,l,u,d]}=e.getInstanceState(),p=aP(t,o.w,a,d,l),f=aP(n,o.h,a,c,u);if(p===0&&f===0)return;const y=e.user.getEdgeScrollSpeed()*L5,g=y*p*s/r,w=y*f*i/r,S=e.getCamera();e.setCamera({x:S.x+g,y:S.y+w})}async function k8({shouldReload:e=!0}={}){H3(),await Promise.all(dx().map(t=>Yz(t))),U3(),e&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=k8);function T8(e,t="_blank"){tx.openWindow(e,t)}var Jc=function(e){return e&&e.Math===Math&&e},Dn=Jc(typeof globalThis=="object"&&globalThis)||Jc(typeof window=="object"&&window)||Jc(typeof self=="object"&&self)||Jc(typeof tn=="object"&&tn)||Jc(typeof tn=="object"&&tn)||function(){return this}()||Function("return this")(),gx={},vn=function(e){try{return!!e()}catch{return!0}},$8=vn,Xs=!$8(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),M8=vn,Gf=!M8(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),A8=Gf,Td=Function.prototype.call,es=A8?Td.bind(Td):function(){return Td.apply(Td,arguments)},J2={},eT={}.propertyIsEnumerable,tT=Object.getOwnPropertyDescriptor,j8=tT&&!eT.call({1:2},1);J2.f=j8?function(t){var n=tT(this,t);return!!n&&n.enumerable}:eT;var nT=function(e,t){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:t}},rT=Gf,oT=Function.prototype,XS=oT.call,O8=rT&&oT.bind.bind(XS,XS),jt=rT?O8:function(e){return function(){return XS.apply(e,arguments)}},sT=jt,D8=sT({}.toString),R8=sT("".slice),Cc=function(e){return R8(D8(e),8,-1)},L8=jt,F8=vn,N8=Cc,Cm=Object,z8=L8("".split),B8=F8(function(){return!Cm("z").propertyIsEnumerable(0)})?function(e){return N8(e)==="String"?z8(e,""):Cm(e)}:Cm,Yf=function(e){return e==null},U8=Yf,H8=TypeError,Ic=function(e){if(U8(e))throw new H8("Can't call method on "+e);return e},K8=B8,W8=Ic,Xf=function(e){return K8(W8(e))},Im=typeof document=="object"&&document.all,xn=typeof Im>"u"&&Im!==void 0?function(e){return typeof e=="function"||e===Im}:function(e){return typeof e=="function"},V8=xn,Wi=function(e){return typeof e=="object"?e!==null:V8(e)},Em=Dn,G8=xn,Y8=function(e){return G8(e)?e:void 0},qf=function(e,t){return arguments.length<2?Y8(Em[e]):Em[e]&&Em[e][t]},X8=jt,iT=X8({}.isPrototypeOf),q8=typeof navigator<"u"&&String(navigator.userAgent)||"",aT=Dn,_m=q8,cP=aT.process,lP=aT.Deno,uP=cP&&cP.versions||lP&&lP.version,dP=uP&&uP.v8,Ar,tf;dP&&(Ar=dP.split("."),tf=Ar[0]>0&&Ar[0]<4?1:+(Ar[0]+Ar[1]));!tf&&_m&&(Ar=_m.match(/Edge\/(\d+)/),(!Ar||Ar[1]>=74)&&(Ar=_m.match(/Chrome\/(\d+)/),Ar&&(tf=+Ar[1])));var Z8=tf,hP=Z8,Q8=vn,J8=Dn,e7=J8.String,cT=!!Object.getOwnPropertySymbols&&!Q8(function(){var e=Symbol("symbol detection");return!e7(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&hP&&hP<41}),t7=cT,lT=t7&&!Symbol.sham&&typeof Symbol.iterator=="symbol",n7=qf,r7=xn,o7=iT,s7=lT,i7=Object,uT=s7?function(e){return typeof e=="symbol"}:function(e){var t=n7("Symbol");return r7(t)&&o7(t.prototype,i7(e))},a7=String,c7=function(e){try{return a7(e)}catch{return"Object"}},l7=xn,u7=c7,d7=TypeError,mx=function(e){if(l7(e))return e;throw new d7(u7(e)+" is not a function")},h7=mx,p7=Yf,yx=function(e,t){var n=e[t];return p7(n)?void 0:h7(n)},km=es,Tm=xn,$m=Wi,f7=TypeError,g7=function(e,t){var n,r;if(t==="string"&&Tm(n=e.toString)&&!$m(r=km(n,e))||Tm(n=e.valueOf)&&!$m(r=km(n,e))||t!=="string"&&Tm(n=e.toString)&&!$m(r=km(n,e)))return r;throw new f7("Can't convert object to primitive value")},dT={exports:{}},pP=Dn,m7=Object.defineProperty,Sx=function(e,t){try{m7(pP,e,{value:t,configurable:!0,writable:!0})}catch{pP[e]=t}return t},y7=Dn,S7=Sx,fP="__core-js_shared__",gP=dT.exports=y7[fP]||S7(fP,{});(gP.versions||(gP.versions=[])).push({version:"3.37.1",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.37.1/LICENSE",source:"https://github.com/zloirock/core-js"});var vx=dT.exports,mP=vx,xx=function(e,t){return mP[e]||(mP[e]=t||{})},v7=Ic,x7=Object,Lu=function(e){return x7(v7(e))},w7=jt,b7=Lu,P7=w7({}.hasOwnProperty),qs=Object.hasOwn||function(t,n){return P7(b7(t),n)},C7=jt,I7=0,E7=Math.random(),_7=C7(1 .toString),hT=function(e){return"Symbol("+(e===void 0?"":e)+")_"+_7(++I7+E7,36)},k7=Dn,T7=xx,yP=qs,$7=hT,M7=cT,A7=lT,Aa=k7.Symbol,Mm=T7("wks"),j7=A7?Aa.for||Aa:Aa&&Aa.withoutSetter||$7,ts=function(e){return yP(Mm,e)||(Mm[e]=M7&&yP(Aa,e)?Aa[e]:j7("Symbol."+e)),Mm[e]},O7=es,SP=Wi,vP=uT,D7=yx,R7=g7,L7=ts,F7=TypeError,N7=L7("toPrimitive"),z7=function(e,t){if(!SP(e)||vP(e))return e;var n=D7(e,N7),r;if(n){if(t===void 0&&(t="default"),r=O7(n,e,t),!SP(r)||vP(r))return r;throw new F7("Can't convert object to primitive value")}return t===void 0&&(t="number"),R7(e,t)},B7=z7,U7=uT,pT=function(e){var t=B7(e,"string");return U7(t)?t:t+""},H7=Dn,xP=Wi,qS=H7.document,K7=xP(qS)&&xP(qS.createElement),fT=function(e){return K7?qS.createElement(e):{}},W7=Xs,V7=vn,G7=fT,gT=!W7&&!V7(function(){return Object.defineProperty(G7("div"),"a",{get:function(){return 7}}).a!==7}),Y7=Xs,X7=es,q7=J2,Z7=nT,Q7=Xf,J7=pT,eB=qs,tB=gT,wP=Object.getOwnPropertyDescriptor;gx.f=Y7?wP:function(t,n){if(t=Q7(t),n=J7(n),tB)try{return wP(t,n)}catch{}if(eB(t,n))return Z7(!X7(q7.f,t,n),t[n])};var Ec={},nB=Xs,rB=vn,mT=nB&&rB(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),oB=Wi,sB=String,iB=TypeError,Vi=function(e){if(oB(e))return e;throw new iB(sB(e)+" is not an object")},aB=Xs,cB=gT,lB=mT,$d=Vi,bP=pT,uB=TypeError,Am=Object.defineProperty,dB=Object.getOwnPropertyDescriptor,jm="enumerable",Om="configurable",Dm="writable";Ec.f=aB?lB?function(t,n,r){if($d(t),n=bP(n),$d(r),typeof t=="function"&&n==="prototype"&&"value"in r&&Dm in r&&!r[Dm]){var o=dB(t,n);o&&o[Dm]&&(t[n]=r.value,r={configurable:Om in r?r[Om]:o[Om],enumerable:jm in r?r[jm]:o[jm],writable:!1})}return Am(t,n,r)}:Am:function(t,n,r){if($d(t),n=bP(n),$d(r),cB)try{return Am(t,n,r)}catch{}if("get"in r||"set"in r)throw new uB("Accessors not supported");return"value"in r&&(t[n]=r.value),t};var hB=Xs,pB=Ec,fB=nT,wx=hB?function(e,t,n){return pB.f(e,t,fB(1,n))}:function(e,t,n){return e[t]=n,e},yT={exports:{}},ZS=Xs,gB=qs,ST=Function.prototype,mB=ZS&&Object.getOwnPropertyDescriptor,bx=gB(ST,"name"),yB=bx&&(function(){}).name==="something",SB=bx&&(!ZS||ZS&&mB(ST,"name").configurable),vB={EXISTS:bx,PROPER:yB,CONFIGURABLE:SB},xB=jt,wB=xn,QS=vx,bB=xB(Function.toString);wB(QS.inspectSource)||(QS.inspectSource=function(e){return bB(e)});var vT=QS.inspectSource,PB=Dn,CB=xn,PP=PB.WeakMap,IB=CB(PP)&&/native code/.test(String(PP)),EB=xx,_B=hT,CP=EB("keys"),xT=function(e){return CP[e]||(CP[e]=_B(e))},Px={},kB=IB,wT=Dn,TB=Wi,$B=wx,Rm=qs,Lm=vx,MB=xT,AB=Px,IP="Object already initialized",JS=wT.TypeError,jB=wT.WeakMap,nf,uu,rf,OB=function(e){return rf(e)?uu(e):nf(e,{})},DB=function(e){return function(t){var n;if(!TB(t)||(n=uu(t)).type!==e)throw new JS("Incompatible receiver, "+e+" required");return n}};if(kB||Lm.state){var Gr=Lm.state||(Lm.state=new jB);Gr.get=Gr.get,Gr.has=Gr.has,Gr.set=Gr.set,nf=function(e,t){if(Gr.has(e))throw new JS(IP);return t.facade=e,Gr.set(e,t),t},uu=function(e){return Gr.get(e)||{}},rf=function(e){return Gr.has(e)}}else{var sa=MB("state");AB[sa]=!0,nf=function(e,t){if(Rm(e,sa))throw new JS(IP);return t.facade=e,$B(e,sa,t),t},uu=function(e){return Rm(e,sa)?e[sa]:{}},rf=function(e){return Rm(e,sa)}}var bT={set:nf,get:uu,has:rf,enforce:OB,getterFor:DB},Cx=jt,RB=vn,LB=xn,Md=qs,ev=Xs,FB=vB.CONFIGURABLE,NB=vT,PT=bT,zB=PT.enforce,BB=PT.get,EP=String,Ch=Object.defineProperty,UB=Cx("".slice),HB=Cx("".replace),KB=Cx([].join),WB=ev&&!RB(function(){return Ch(function(){},"length",{value:8}).length!==8}),VB=String(String).split("String"),GB=yT.exports=function(e,t,n){UB(EP(t),0,7)==="Symbol("&&(t="["+HB(EP(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(t="get "+t),n&&n.setter&&(t="set "+t),(!Md(e,"name")||FB&&e.name!==t)&&(ev?Ch(e,"name",{value:t,configurable:!0}):e.name=t),WB&&n&&Md(n,"arity")&&e.length!==n.arity&&Ch(e,"length",{value:n.arity});try{n&&Md(n,"constructor")&&n.constructor?ev&&Ch(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=zB(e);return Md(r,"source")||(r.source=KB(VB,typeof t=="string"?t:"")),e};Function.prototype.toString=GB(function(){return LB(this)&&BB(this).source||NB(this)},"toString");var YB=yT.exports,XB=xn,qB=Ec,ZB=YB,QB=Sx,CT=function(e,t,n,r){r||(r={});var o=r.enumerable,s=r.name!==void 0?r.name:t;if(XB(n)&&ZB(n,s,r),r.global)o?e[t]=n:QB(t,n);else{try{r.unsafe?e[t]&&(o=!0):delete e[t]}catch{}o?e[t]=n:qB.f(e,t,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},IT={},JB=Math.ceil,e9=Math.floor,t9=Math.trunc||function(t){var n=+t;return(n>0?e9:JB)(n)},n9=t9,Gi=function(e){var t=+e;return t!==t||t===0?0:n9(t)},r9=Gi,o9=Math.max,s9=Math.min,i9=function(e,t){var n=r9(e);return n<0?o9(n+t,0):s9(n,t)},a9=Gi,c9=Math.min,ET=function(e){var t=a9(e);return t>0?c9(t,9007199254740991):0},l9=ET,Fu=function(e){return l9(e.length)},u9=Xf,d9=i9,h9=Fu,_P=function(e){return function(t,n,r){var o=u9(t),s=h9(o);if(s===0)return!e&&-1;var i=d9(r,s),a;if(e&&n!==n){for(;s>i;)if(a=o[i++],a!==a)return!0}else for(;s>i;i++)if((e||i in o)&&o[i]===n)return e||i||0;return!e&&-1}},p9={includes:_P(!0),indexOf:_P(!1)},f9=jt,Fm=qs,g9=Xf,m9=p9.indexOf,y9=Px,kP=f9([].push),_T=function(e,t){var n=g9(e),r=0,o=[],s;for(s in n)!Fm(y9,s)&&Fm(n,s)&&kP(o,s);for(;t.length>r;)Fm(n,s=t[r++])&&(~m9(o,s)||kP(o,s));return o},Ix=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],S9=_T,v9=Ix,x9=v9.concat("length","prototype");IT.f=Object.getOwnPropertyNames||function(t){return S9(t,x9)};var kT={};kT.f=Object.getOwnPropertySymbols;var w9=qf,b9=jt,P9=IT,C9=kT,I9=Vi,E9=b9([].concat),_9=w9("Reflect","ownKeys")||function(t){var n=P9.f(I9(t)),r=C9.f;return r?E9(n,r(t)):n},TP=qs,k9=_9,T9=gx,$9=Ec,M9=function(e,t,n){for(var r=k9(t),o=$9.f,s=T9.f,i=0;ii;)Z9.f(t,a=o[i++],r[a]);return t};var tU=qf,nU=tU("document","documentElement"),rU=Vi,oU=TT,$P=Ix,sU=Px,iU=nU,aU=fT,cU=xT,MP=">",AP="<",tv="prototype",nv="script",$T=cU("IE_PROTO"),Nm=function(){},MT=function(e){return AP+nv+MP+e+AP+"/"+nv+MP},jP=function(e){e.write(MT("")),e.close();var t=e.parentWindow.Object;return e=null,t},lU=function(){var e=aU("iframe"),t="java"+nv+":",n;return e.style.display="none",iU.appendChild(e),e.src=String(t),n=e.contentWindow.document,n.open(),n.write(MT("document.F=Object")),n.close(),n.F},jd,Ih=function(){try{jd=new ActiveXObject("htmlfile")}catch{}Ih=typeof document<"u"?document.domain&&jd?jP(jd):lU():jP(jd);for(var e=$P.length;e--;)delete Ih[tv][$P[e]];return Ih()};sU[$T]=!0;var AT=Object.create||function(t,n){var r;return t!==null?(Nm[tv]=rU(t),r=new Nm,Nm[tv]=null,r[$T]=t):r=Ih(),n===void 0?r:oU.f(r,n)},uU=ts,dU=AT,hU=Ec.f,rv=uU("unscopables"),ov=Array.prototype;ov[rv]===void 0&&hU(ov,rv,{configurable:!0,value:dU(null)});var Ex=function(e){ov[rv][e]=!0},pU=_c,fU=Lu,gU=Fu,mU=Gi,yU=Ex;pU({target:"Array",proto:!0},{at:function(t){var n=fU(this),r=gU(n),o=mU(t),s=o>=0?o:r+o;return s<0||s>=r?void 0:n[s]}});yU("at");var SU=Dn,vU=jt,zu=function(e,t){return vU(SU[e].prototype[t])},xU=zu;xU("Array","at");var wU=Cc,jT=Array.isArray||function(t){return wU(t)==="Array"},bU=TypeError,PU=9007199254740991,CU=function(e){if(e>PU)throw bU("Maximum allowed index exceeded");return e},IU=Cc,EU=jt,_U=function(e){if(IU(e)==="Function")return EU(e)},OP=_U,kU=mx,TU=Gf,$U=OP(OP.bind),MU=function(e,t){return kU(e),t===void 0?e:TU?$U(e,t):function(){return e.apply(t,arguments)}},AU=jT,jU=Fu,OU=CU,DU=MU,OT=function(e,t,n,r,o,s,i,a){for(var c=o,l=0,u=i?DU(i,a):!1,d,p;l0&&AU(d)?(p=jU(d),c=OT(e,t,d,p,c,s-1)-1):(OU(c+1),e[c]=d),c++),l++;return c},DT=OT,RU=ts,LU=RU("toStringTag"),RT={};RT[LU]="z";var FU=String(RT)==="[object z]",NU=FU,zU=xn,Eh=Cc,BU=ts,UU=BU("toStringTag"),HU=Object,KU=Eh(function(){return arguments}())==="Arguments",WU=function(e,t){try{return e[t]}catch{}},LT=NU?Eh:function(e){var t,n,r;return e===void 0?"Undefined":e===null?"Null":typeof(n=WU(t=HU(e),UU))=="string"?n:KU?Eh(t):(r=Eh(t))==="Object"&&zU(t.callee)?"Arguments":r},VU=jt,GU=vn,FT=xn,YU=LT,XU=qf,qU=vT,NT=function(){},zT=XU("Reflect","construct"),_x=/^\s*(?:class|function)\b/,ZU=VU(_x.exec),QU=!_x.test(NT),el=function(t){if(!FT(t))return!1;try{return zT(NT,[],t),!0}catch{return!1}},BT=function(t){if(!FT(t))return!1;switch(YU(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return QU||!!ZU(_x,qU(t))}catch{return!0}};BT.sham=!0;var JU=!zT||GU(function(){var e;return el(el.call)||!el(Object)||!el(function(){e=!0})||e})?BT:el,DP=jT,eH=JU,tH=Wi,nH=ts,rH=nH("species"),RP=Array,oH=function(e){var t;return DP(e)&&(t=e.constructor,eH(t)&&(t===RP||DP(t.prototype))?t=void 0:tH(t)&&(t=t[rH],t===null&&(t=void 0))),t===void 0?RP:t},sH=oH,UT=function(e,t){return new(sH(e))(t===0?0:t)},iH=_c,aH=DT,cH=mx,lH=Lu,uH=Fu,dH=UT;iH({target:"Array",proto:!0},{flatMap:function(t){var n=lH(this),r=uH(n),o;return cH(t),o=dH(n,0),o.length=aH(o,n,n,r,0,1,t,arguments.length>1?arguments[1]:void 0),o}});var hH=Ex;hH("flatMap");var pH=zu;pH("Array","flatMap");var fH=_c,gH=DT,mH=Lu,yH=Fu,SH=Gi,vH=UT;fH({target:"Array",proto:!0},{flat:function(){var t=arguments.length?arguments[0]:void 0,n=mH(this),r=yH(n),o=vH(n,0);return o.length=gH(o,n,n,r,0,t===void 0?1:SH(t)),o}});var xH=Ex;xH("flat");var wH=zu;wH("Array","flat");var bH=LT,PH=String,Bu=function(e){if(bH(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return PH(e)},CH=_c,IH=jt,EH=Ic,_H=Gi,kH=Bu,TH=vn,$H=IH("".charAt),MH=TH(function(){return"𠮷".at(-2)!=="\uD842"});CH({target:"String",proto:!0,forced:MH},{at:function(t){var n=kH(EH(this)),r=n.length,o=_H(t),s=o>=0?o:r+o;return s<0||s>=r?void 0:$H(n,s)}});var AH=zu;AH("String","at");var jH=Vi,HT=function(){var e=jH(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},kx=vn,OH=Dn,Tx=OH.RegExp,$x=kx(function(){var e=Tx("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),DH=$x||kx(function(){return!Tx("a","y").sticky}),RH=$x||kx(function(){var e=Tx("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),LH={BROKEN_CARET:RH,MISSED_STICKY:DH,UNSUPPORTED_Y:$x},FH=vn,NH=Dn,zH=NH.RegExp,BH=FH(function(){var e=zH(".","s");return!(e.dotAll&&e.test(` `)&&e.flags==="s")}),UH=vn,HH=Dn,KH=HH.RegExp,WH=UH(function(){var e=KH("(?b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$c")!=="bc"}),ja=es,Zf=jt,VH=Bu,GH=HT,YH=LH,XH=xx,qH=AT,ZH=bT.get,QH=BH,JH=WH,eK=XH("native-string-replace",String.prototype.replace),of=RegExp.prototype.exec,sv=of,tK=Zf("".charAt),nK=Zf("".indexOf),rK=Zf("".replace),zm=Zf("".slice),iv=function(){var e=/a/,t=/b*/g;return ja(of,e,"a"),ja(of,t,"a"),e.lastIndex!==0||t.lastIndex!==0}(),KT=YH.BROKEN_CARET,av=/()??/.exec("")[1]!==void 0,oK=iv||av||KT||QH||JH;oK&&(sv=function(t){var n=this,r=ZH(n),o=VH(t),s=r.raw,i,a,c,l,u,d,p;if(s)return s.lastIndex=n.lastIndex,i=ja(sv,s,o),n.lastIndex=s.lastIndex,i;var f=r.groups,y=KT&&n.sticky,g=ja(GH,n),w=n.source,S=0,v=o;if(y&&(g=rK(g,"y",""),nK(g,"g")===-1&&(g+="g"),v=zm(o,n.lastIndex),n.lastIndex>0&&(!n.multiline||n.multiline&&tK(o,n.lastIndex-1)!==` `)&&(w="(?: "+w+")",v=" "+v,S++),a=new RegExp("^(?:"+w+")",g)),av&&(a=new RegExp("^"+w+"$(?!\\s)",g)),iv&&(c=n.lastIndex),l=ja(of,y?a:n,v),y?l?(l.input=zm(l.input,S),l[0]=zm(l[0],S),l.index=n.lastIndex,n.lastIndex+=l[0].length):n.lastIndex=0:iv&&l&&(n.lastIndex=n.global?l.index+l[0].length:c),av&&l&&l.length>1&&ja(eK,l[0],a,function(){for(u=1;u=s?e?"":void 0:(i=HP(r,o),i<55296||i>56319||o+1===s||(a=HP(r,o+1))<56320||a>57343?e?gK(r,o):i:e?mK(r,o,o+2):(i-55296<<10)+(a-56320)+65536)}},yK={codeAt:KP(!1),charAt:KP(!0)},SK=yK.charAt,vK=function(e,t,n){return t+(n?SK(e,t).length:1)},jx=jt,xK=Lu,wK=Math.floor,Um=jx("".charAt),bK=jx("".replace),Hm=jx("".slice),PK=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,CK=/\$([$&'`]|\d{1,2})/g,GT=function(e,t,n,r,o,s){var i=n+e.length,a=r.length,c=CK;return o!==void 0&&(o=xK(o),c=PK),bK(s,c,function(l,u){var d;switch(Um(u,0)){case"$":return"$";case"&":return e;case"`":return Hm(t,0,n);case"'":return Hm(t,i);case"<":d=o[Hm(u,1,-1)];break;default:var p=+u;if(p===0)return l;if(p>a){var f=wK(p/10);return f===0?l:f<=a?r[f-1]===void 0?Um(u,1):r[f-1]+Um(u,1):l}d=r[p-1]}return d===void 0?"":d})},WP=es,IK=Vi,EK=xn,_K=Cc,kK=Mx,TK=TypeError,$K=function(e,t){var n=e.exec;if(EK(n)){var r=WP(n,e,t);return r!==null&&IK(r),r}if(_K(e)==="RegExp")return WP(kK,e,t);throw new TK("RegExp#exec called on incompatible receiver")},MK=aK,VP=es,Qf=jt,AK=dK,jK=vn,OK=Vi,DK=xn,RK=Yf,LK=Gi,FK=ET,ia=Bu,NK=Ic,zK=vK,BK=yx,UK=GT,HK=$K,KK=ts,cv=KK("replace"),WK=Math.max,VK=Math.min,GK=Qf([].concat),Km=Qf([].push),GP=Qf("".indexOf),YP=Qf("".slice),YK=function(e){return e===void 0?e:String(e)},XK=function(){return"a".replace(/./,"$0")==="$0"}(),XP=function(){return/./[cv]?/./[cv]("a","$0")==="":!1}(),qK=!jK(function(){var e=/./;return e.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(e,"$")!=="7"});AK("replace",function(e,t,n){var r=XP?"$":"$0";return[function(s,i){var a=NK(this),c=RK(s)?void 0:BK(s,cv);return c?VP(c,s,a,i):VP(t,ia(a),s,i)},function(o,s){var i=OK(this),a=ia(o);if(typeof s=="string"&&GP(s,r)===-1&&GP(s,"$<")===-1){var c=n(t,i,a,s);if(c.done)return c.value}var l=DK(s);l||(s=ia(s));var u=i.global,d;u&&(d=i.unicode,i.lastIndex=0);for(var p=[],f;f=HK(i,a),!(f===null||(Km(p,f),!u));){var y=ia(f[0]);y===""&&(i.lastIndex=zK(a,FK(i.lastIndex),d))}for(var g="",w=0,S=0;S=w&&(g+=YP(a,w,b)+C,w=b+v.length)}return g+YP(a,w)}]},!qK||!XK||XP);var ZK=Wi,QK=Cc,JK=ts,eW=JK("match"),tW=function(e){var t;return ZK(e)&&((t=e[eW])!==void 0?!!t:QK(e)==="RegExp")},nW=es,rW=qs,oW=iT,sW=HT,qP=RegExp.prototype,iW=function(e){var t=e.flags;return t===void 0&&!("flags"in qP)&&!rW(e,"flags")&&oW(qP,e)?nW(sW,e):t},aW=_c,cW=es,Ox=jt,ZP=Ic,lW=xn,uW=Yf,dW=tW,tl=Bu,hW=yx,pW=iW,fW=GT,gW=ts,mW=gW("replace"),yW=TypeError,Wm=Ox("".indexOf);Ox("".replace);var QP=Ox("".slice),SW=Math.max;aW({target:"String",proto:!0},{replaceAll:function(t,n){var r=ZP(this),o,s,i,a,c,l,u,d,p,f=0,y=0,g="";if(!uW(t)){if(o=dW(t),o&&(s=tl(ZP(pW(t))),!~Wm(s,"g")))throw new yW("`.replaceAll` does not allow non-global regexes");if(i=hW(t,mW),i)return cW(i,t,r,n)}for(a=tl(r),c=tl(t),l=lW(n),l||(n=tl(n)),u=c.length,d=SW(1,u),f=Wm(a,c);f!==-1;)p=l?tl(n(c,f,a)):fW(c,a,f,[],void 0,n),g+=QP(a,y,f)+p,y=f+u,f=f+d>a.length?-1:Wm(a,c,f+d);return ye.getShape(r)).filter(r=>!(!r||e.isShapeOfType(r,"arrow")&&r.props.start.type==="binding"||e.isShapeOfType(r,"arrow")&&r.props.end.type==="binding"))}const YT=()=>{const e=z();return K("threeStackableItems",()=>xW(e).length>2,[e])},XT=()=>{const e=z();return K("allow group",()=>{const t=e.getSelectedShapes();if(t.length<2)return!1;for(const n of t)if(e.isShapeOfType(n,"arrow")){const{start:r,end:o}=n.props;if(r.type==="binding"&&!t.some(s=>s.id===r.boundShapeId)||o.type==="binding"&&!t.some(s=>s.id===o.boundShapeId))return!1}return!0},[e])},qT=()=>{const e=z();return K("allowUngroup",()=>e.getSelectedShapeIds().some(t=>{var n;return((n=e.getShape(t))==null?void 0:n.type)==="group"}),[e])},wW=typeof window<"u"&&"navigator"in window&&!!navigator.clipboard&&!!navigator.clipboard.read;function bW(e,t){const n=z();return K("selectedShapes",()=>n.getSelectedShapes().length>=e,[n,e,t])}function wn(e,t){const n=z();return K("selectedShapes",()=>{const r=n.getSelectedShapes().filter(o=>!n.isShapeOrAncestorLocked(o)).length;return e===void 0?r:r>=e},[n])}function PW(){const e=z();return K("showAutoSizeToggle",()=>{const t=e.getSelectedShapes();return t.length===1&&e.isShapeOfType(t[0],"text")&&t[0].props.autoSize===!1},[e])}function ZT(){const e=z();return K("hasLinkShapeSelected",()=>{const t=e.getOnlySelectedShape();return!!(t&&t.type!=="embed"&&"url"in t.props&&!t.isLocked)},[e])}function CW(){const e=z();return K("onlyFlippableShape",()=>{const t=e.getOnlySelectedShape();return t&&(e.isShapeOfType(t,"group")||e.isShapeOfType(t,"arrow")||e.isShapeOfType(t,"line")||e.isShapeOfType(t,"draw"))},[e])}function QT(){const e=z();return K("useCanRedo",()=>e.getCanRedo(),[e])}function JT(){const e=z();return K("useCanUndo",()=>e.getCanUndo(),[e])}function IW({children:e}){const t=z();return K("shouldDisplayHandles",()=>{if(t.isInAny("select.idle","select.pointing_handle","select.pointing_shape"))return!0;if(t.isInAny("select.editing_shape")){const r=t.getOnlySelectedShape();return r&&t.isShapeOfType(r,"note")}return!1},[t])?h.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}):null}const{PI:EW}=Math,Ga=EW+1e-4;function e$(e,t={}){const{size:n=16,smoothing:r=.5}=t;if(e.length===0||n<=0)return{left:[],right:[]};const o=e[0],s=e[e.length-1],i=s.runningLength,a=Math.pow(n*r,2),c=[],l=[];let u=e[0].vector,d=e[0].point,p=d,f=d,y=p,g=!1,w;for(let S=0;S-.62&&i-w.runningLength>w.radius){const T=u.clone().mul(w.radius);u.clone().cpr(C)<0?(f=P.Add(v,T),y=P.Sub(v,T)):(f=P.Sub(v,T),y=P.Add(v,T)),c.push(f),l.push(y)}else{const T=u.clone().mul(w.radius).per(),O=P.Sub(w.input,T);for(let N=1/13,F=0;F<1;F+=N)f=P.RotWith(O,w.input,Ga*F),c.push(f),y=P.RotWith(O,w.input,Ga+Ga*-F),l.push(y)}d=f,p=y,k&&(g=!0);continue}if(g=!1,w===o||w===s){const T=P.Per(b).mul(w.radius);c.push(P.Sub(v,T)),l.push(P.Add(v,T));continue}const $=P.Lrp(C,b,I).per().mul(w.radius);f=P.Sub(v,$),(S<=1||P.Dist2(d,f)>a)&&(c.push(f),d=f),y=P.Add(v,$),(S<=1||P.Dist2(p,y)>a)&&(l.push(y),p=y),u=b}return{left:c,right:l}}function Dx(e,t={}){const{size:n=16,start:r={},end:o={},last:s=!1}=t,{cap:i=!0}=r,{cap:a=!0}=o;if(e.length===0||n<=0)return[];const c=e[0],l=e[e.length-1],u=l.runningLength,d=r.taper===!1?0:r.taper===!0?Math.max(n,u):r.taper,p=o.taper===!1?0:o.taper===!0?Math.max(n,u):o.taper,{left:f,right:y}=e$(e,t),g=c.point,w=e.length>1?e[e.length-1].point:P.AddXY(c.point,1,1);if(e.length===1&&(!(d||p)||s)){const E=P.Add(g,P.Sub(g,w).uni().per().mul(-c.radius)),C=[];for(let I=1/13,_=I;_<=1;_+=I)C.push(P.RotWith(E,g,Ga*2*_));return C}const S=[];if(!(d||p&&e.length===1))if(i)for(let E=1/8,C=E;C<=1;C+=E){const I=P.RotWith(y[0],g,Ga*C);S.push(I)}else{const E=P.Sub(f[0],y[0]),C=P.Mul(E,.5),I=P.Mul(E,.51);S.push(P.Sub(g,C),P.Sub(g,I),P.Add(g,I),P.Add(g,C))}const v=[],b=l.vector.clone().per().neg();if(p||d&&e.length===1)v.push(w);else if(a){const E=P.Add(w,P.Mul(b,l.radius));for(let C=1/29,I=C;I<1;I+=C)v.push(P.RotWith(E,w,Ga*3*I))}else v.push(P.Add(w,P.Mul(b,l.radius)),P.Add(w,P.Mul(b,l.radius*.99)),P.Sub(w,P.Mul(b,l.radius*.99)),P.Sub(w,P.Mul(b,l.radius)));return f.concat(v,y.reverse(),S)}const _W=.025,kW=.01;function lo(e,t={}){var w;const{streamline:n=.5,size:r=16,simulatePressure:o=!1}=t;if(e.length===0)return[];const s=.15+(1-n)*.85;let i=e.map(P.From),a=0;if(!o){let S=i[0];for(;S&&!(S.z>=_W);)i.shift(),S=i[0]}if(!o){let S=i[i.length-1];for(;S&&!(S.z>=kW);)i.pop(),S=i[i.length-1]}if(i.length===0)return[{point:P.From(e[0]),input:P.From(e[0]),pressure:o?.5:.15,vector:new P(1,1),distance:0,runningLength:0,radius:1}];let c=i[1];for(;c&&!(P.Dist2(c,i[0])>(r/3)**2);)i[0].z=Math.max(i[0].z,c.z),i.splice(1,1),c=i[1];const l=i.pop();for(c=i[i.length-1];c&&!(P.Dist2(c,l)>(r/3)**2);)i.pop(),c=i[i.length-1],a++;i.push(l);const u=t.last||!t.simulatePressure||i.length>1&&P.Dist2(i[i.length-1],i[i.length-2])0;if(i.length===2&&t.simulatePressure){const S=i[1];i=i.slice(0,-1);for(let v=1;v<5;v++){const b=P.Lrp(i[0],S,v/4);b.z=(i[0].z+(S.z-i[0].z))*v/4,i.push(b)}}const d=[{point:i[0],input:i[0],pressure:o?.5:i[0].z,vector:new P(1,1),distance:0,runningLength:0,radius:1}];let p=0,f=d[0],y,g;u&&n>0&&i.push(i[i.length-1].clone());for(let S=1,v=i.length;Sv.pressure));d.forEach(v=>v.pressure=S)}return d}const{min:hs}=Math,Vm=.275;function Jf(e,t){const{size:n=16,thinning:r=.5,simulatePressure:o=!0,easing:s=w=>w,start:i={},end:a={}}=t,{easing:c=nn.easeOutQuad}=i,{easing:l=nn.easeOutCubic}=a,u=e[e.length-1].runningLength;let d,p=e[0].pressure,f;if(!o&&uMath.max(S,v.pressure),.5);return e.forEach(S=>{S.pressure=w,S.radius=n*s(.5-r*(.5-S.pressure))}),e}else{let w;for(let S=0,v=e.length;Sn*5));S++){const b=hs(1,f.distance/n);if(o){const E=hs(1,1-b);w=hs(1,p+(E-p)*(b*Vm))}else w=hs(1,p+(f.pressure-p)*.5);p=p+(w-p)*.5}for(let S=0;S{const n=z();return K("should display",()=>n.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","text.resizing"),[n])?h.jsx(y2,{bounds:e,rotation:t}):null};function ns(){const e=z();return K("isReadonlyMode",()=>e.getInstanceState().isReadonly,[e])}function MW({size:e,width:t,height:n,hideAlternateHandles:r}){const o=j(e/3),s=o/2;return h.jsxs("svg",{className:"tl-overlays__item",children:[h.jsx("polyline",{className:"tl-corner-crop-handle",points:` ${j(0-s)},${j(e)} ${j(0-s)},${j(0-s)} ${j(e)},${j(0-s)}`,strokeWidth:o,"data-testid":"selection.crop.top_left","aria-label":"top_left handle"}),h.jsx("line",{className:ue("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:j(t/2-e),y1:j(0-s),x2:j(t/2+e),y2:j(0-s),strokeWidth:o,"data-testid":"selection.crop.top","aria-label":"top handle"}),h.jsx("polyline",{className:ue("tl-corner-crop-handle",{"tl-hidden":r}),points:` ${j(t-e)},${j(0-s)} ${j(t+s)},${j(0-s)} ${j(t+s)},${j(e)}`,strokeWidth:o,"data-testid":"selection.crop.top_right","aria-label":"top_right handle"}),h.jsx("line",{className:ue("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:j(t+s),y1:j(n/2-e),x2:j(t+s),y2:j(n/2+e),strokeWidth:o,"data-testid":"selection.crop.right","aria-label":"right handle"}),h.jsx("polyline",{className:"tl-corner-crop-handle",points:` ${j(t+s)},${j(n-e)} ${j(t+s)},${j(n+s)} ${j(t-e)},${j(n+s)}`,strokeWidth:o,"data-testid":"selection.crop.bottom_right","aria-label":"bottom_right handle"}),h.jsx("line",{className:ue("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:j(t/2-e),y1:j(n+s),x2:j(t/2+e),y2:j(n+s),strokeWidth:o,"data-testid":"selection.crop.bottom","aria-label":"bottom handle"}),h.jsx("polyline",{className:ue("tl-corner-crop-handle",{"tl-hidden":r}),points:` ${j(0+e)},${j(n+s)} ${j(0-s)},${j(n+s)} ${j(0-s)},${j(n-e)}`,strokeWidth:o,"data-testid":"selection.crop.bottom_left","aria-label":"bottom_left handle"}),h.jsx("line",{className:ue("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:j(0-s),y1:j(n/2-e),x2:j(0-s),y2:j(n/2+e),strokeWidth:o,"data-testid":"selection.crop.left","aria-label":"left handle"})]})}const AW=or(function({bounds:t,rotation:n}){const r=z(),o=x.useRef(null),s=ns(),i=Xr("top"),a=Xr("right"),c=Xr("bottom"),l=Xr("left"),u=Xr("top_left"),d=Xr("top_right"),p=Xr("bottom_right"),f=Xr("bottom_left"),y=!r.getIsMenuOpen()&&r.getInstanceState().cursor.type==="default",g=r.getInstanceState().isCoarsePointer,w=r.getOnlySelectedShape(),S=w&&r.isShapeOrAncestorLocked(w),v=w?r.getShapeUtil(w).expandSelectionOutlinePx(w):0;if(xc(o,t==null?void 0:t.x,t==null?void 0:t.y,1,r.getSelectionRotation(),{x:-v,y:-v}),!t)return null;t=t.clone().expandBy(v).zeroFix();const b=r.getZoomLevel(),E=r.getInstanceState().isChangingStyle,C=t.width,I=t.height,_=8/b,k=C<_*2,$=I<_*2,T=C<_*4,O=I<_*4,N=C<_*5,F=I<_*5,L=g?1.75:1,B=6/b*L,q=(T?B/2:B)*(L*.75),Q=(O?B/2:B)*(L*.75),H=(w?!r.getShapeUtil(w).hideSelectionBoundsFg(w):!0)&&!E;let U=H&&r.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_canvas","select.pointing_selection","select.pointing_shape","select.crop.idle","select.crop.pointing_crop","select.pointing_resize_handle","select.pointing_crop_handle")||H&&r.isIn("select.resizing")&&w&&r.isShapeOfType(w,"text");w&&U&&r.environment.isFirefox&&r.isShapeOfType(w,"embed")&&(U=!1);const W=r.isInAny("select.pointing_crop_handle","select.crop.idle","select.crop.pointing_crop")&&!E&&!s,Z=r.isInAny("select.idle","select.pointing_selection","select.pointing_shape","select.crop.idle")&&!E&&!s,le=!g&&!(k||$)&&(Z||W)&&(w?!r.getShapeUtil(w).hideRotateHandle(w):!0)&&!S,be=g&&(!T||!O)&&(Z||W)&&(w?!r.getShapeUtil(w).hideRotateHandle(w):!0)&&!S,Me=Z&&(w?r.getShapeUtil(w).canResize(w)&&!r.getShapeUtil(w).hideResizeHandles(w):!0)&&!W&&!S,ae=k||$,Ae=k&&$,Re=N||F,ot=Me||W,Ie=!le,ht=!Z||!be,He=!Z||!ot,ir=!Z||!ot||ae,Ln=!Z||!ot||ae,Fn=!Z||!ot||Ae&&!W;let qe=!0,Ot=!0;if(W)qe=Re,Ot=Re;else if(Me){qe=ae||Ae||g;const jc=g&&w&&w.type==="text";Ot=qe&&!jc}const wo=Math.min(24/b,I-Q*3),Ac=Z&&g&&w&&r.isShapeOfType(w,"text")&&wo*b>=4;return h.jsx("svg",{className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:h.jsxs("g",{ref:o,children:[U&&h.jsx("rect",{className:"tl-selection__fg__outline",width:j(C),height:j(I)}),h.jsx(Od,{"data-testid":"selection.rotate.top-left",cx:0,cy:0,targetSize:B,corner:"top_left_rotate",cursor:y?Bn("nwse-rotate",n):void 0,isHidden:Ie}),h.jsx(Od,{"data-testid":"selection.rotate.top-right",cx:C+B*3,cy:0,targetSize:B,corner:"top_right_rotate",cursor:y?Bn("nesw-rotate",n):void 0,isHidden:Ie}),h.jsx(Od,{"data-testid":"selection.rotate.bottom-left",cx:0,cy:I+B*3,targetSize:B,corner:"bottom_left_rotate",cursor:y?Bn("swne-rotate",n):void 0,isHidden:Ie}),h.jsx(Od,{"data-testid":"selection.rotate.bottom-right",cx:C+B*3,cy:I+B*3,targetSize:B,corner:"bottom_right_rotate",cursor:y?Bn("senw-rotate",n):void 0,isHidden:Ie}),h.jsx(OW,{"data-testid":"selection.rotate.mobile",cx:T?-B*1.5:C/2,cy:T?I/2:-B*1.5,size:_,isHidden:ht}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":qe}),"data-testid":"selection.resize.top","aria-label":"top target",pointerEvents:"all",x:0,y:j(0-(O?Q*2:Q)),width:j(C),height:j(Math.max(1,Q*2)),style:y?{cursor:Bn("ns-resize",n)}:void 0,...i}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":Ot}),"data-testid":"selection.resize.right","aria-label":"right target",pointerEvents:"all",x:j(C-(T?0:q)),y:0,height:j(I),width:j(Math.max(1,q*2)),style:y?{cursor:Bn("ew-resize",n)}:void 0,...a}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":qe}),"data-testid":"selection.resize.bottom","aria-label":"bottom target",pointerEvents:"all",x:0,y:j(I-(O?0:Q)),width:j(C),height:j(Math.max(1,Q*2)),style:y?{cursor:Bn("ns-resize",n)}:void 0,...c}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":Ot}),"data-testid":"selection.resize.left","aria-label":"left target",pointerEvents:"all",x:j(0-(T?q*2:q)),y:0,height:j(I),width:j(Math.max(1,q*2)),style:y?{cursor:Bn("ew-resize",n)}:void 0,...l}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":He}),"data-testid":"selection.target.top-left","aria-label":"top-left target",pointerEvents:"all",x:j(0-(T?q*2:q*1.5)),y:j(0-(O?Q*2:Q*1.5)),width:j(q*3),height:j(Q*3),style:y?{cursor:Bn("nwse-resize",n)}:void 0,...u}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":ir}),"data-testid":"selection.target.top-right","aria-label":"top-right target",pointerEvents:"all",x:j(C-(T?0:q*1.5)),y:j(0-(O?Q*2:Q*1.5)),width:j(q*3),height:j(Q*3),style:y?{cursor:Bn("nesw-resize",n)}:void 0,...d}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":Fn}),"data-testid":"selection.target.bottom-right","aria-label":"bottom-right target",pointerEvents:"all",x:j(C-(T?q:q*1.5)),y:j(I-(O?Q:Q*1.5)),width:j(q*3),height:j(Q*3),style:y?{cursor:Bn("nwse-resize",n)}:void 0,...p}),h.jsx("rect",{className:ue("tl-transparent",{"tl-hidden":Ln}),"data-testid":"selection.target.bottom-left","aria-label":"bottom-left target",pointerEvents:"all",x:j(0-(T?q*3:q*1.5)),y:j(I-(O?0:Q*1.5)),width:j(q*3),height:j(Q*3),style:y?{cursor:Bn("nesw-resize",n)}:void 0,...f}),Me&&h.jsxs(h.Fragment,{children:[h.jsx("rect",{"data-testid":"selection.resize.top-left",className:ue("tl-corner-handle",{"tl-hidden":He}),"aria-label":"top_left handle",x:j(0-_/2),y:j(0-_/2),width:j(_),height:j(_)}),h.jsx("rect",{"data-testid":"selection.resize.top-right",className:ue("tl-corner-handle",{"tl-hidden":ir}),"aria-label":"top_right handle",x:j(C-_/2),y:j(0-_/2),width:j(_),height:j(_)}),h.jsx("rect",{"data-testid":"selection.resize.bottom-right",className:ue("tl-corner-handle",{"tl-hidden":Fn}),"aria-label":"bottom_right handle",x:j(C-_/2),y:j(I-_/2),width:j(_),height:j(_)}),h.jsx("rect",{"data-testid":"selection.resize.bottom-left",className:ue("tl-corner-handle",{"tl-hidden":Ln}),"aria-label":"bottom_left handle",x:j(0-_/2),y:j(I-_/2),width:j(_),height:j(_)})]}),Ac&&h.jsxs(h.Fragment,{children:[h.jsx("rect",{"data-testid":"selection.text-resize.left.handle",className:"tl-text-handle","aria-label":"bottom_left handle",x:j(0-_/4),y:j(I/2-wo/2),rx:_/4,width:j(_/2),height:j(wo)}),h.jsx("rect",{"data-testid":"selection.text-resize.right.handle",className:"tl-text-handle","aria-label":"bottom_left handle",rx:_/4,x:j(C-_/4),y:j(I/2-wo/2),width:j(_/2),height:j(wo)})]}),W&&h.jsx(MW,{size:_,width:C,height:I,hideAlternateHandles:Re})]})})}),Od=function({cx:t,cy:n,targetSize:r,corner:o,cursor:s,isHidden:i,"data-testid":a}){const c=Xr(o);return h.jsx("rect",{className:ue("tl-transparent","tl-rotate-corner",{"tl-hidden":i}),"data-testid":a,"aria-label":`${o} target`,pointerEvents:"all",x:j(t-r*3),y:j(n-r*3),width:j(Math.max(1,r*3)),height:j(Math.max(1,r*3)),cursor:s,...c})},jW=Math.sqrt(Math.PI),OW=function({cx:t,cy:n,size:r,isHidden:o,"data-testid":s}){const i=Xr("mobile_rotate"),a=z(),c=K("zoom level",()=>a.getZoomLevel(),[a]),l=Math.max(14*(1/c),20/Math.max(1,c));return h.jsxs("g",{children:[h.jsx("circle",{"data-testid":s,pointerEvents:"all",className:ue("tl-transparent","tl-mobile-rotate__bg",{"tl-hidden":o}),cx:t,cy:n,r:l,...i}),h.jsx("circle",{className:ue("tl-mobile-rotate__fg",{"tl-hidden":o}),cx:t,cy:n,r:r/jW})]})},Ht={lineHeight:1.35,fontWeight:"normal",fontVariant:"normal",fontStyle:"normal",padding:"0px"},Mt={s:2,m:3.5,l:5,xl:10},ac={s:18,m:24,l:36,xl:44},Lo={s:18,m:22,l:26,xl:32},hi={s:18,m:20,l:24,xl:28},io={draw:"var(--tl-font-draw)",sans:"var(--tl-font-sans)",serif:"var(--tl-font-serif)",mono:"var(--tl-font-mono)"},DW=20,RW=4.25,Tr=16;/*! * canvas-size * v1.2.6 * https://github.com/jhildenbiddle/canvas-size * (c) 2015-2023 John Hildenbiddle * MIT license */function LW(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,o,s,i,a=[],c=!0,l=!1;try{if(s=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);c=!0);}catch(u){l=!0,o=u}finally{try{if(!c&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(l)throw o}}return a}}function eC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,r)}return n}function Un(e){for(var t=1;t=0)&&(n[o]=e[o]);return n}function zW(e,t){if(e==null)return{};var n=NW(e,t),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function tC(e,t){return UW(e)||LW(e,t)||t$(e,t)||WW()}function Dd(e){return BW(e)||HW(e)||t$(e)||KW()}function BW(e){if(Array.isArray(e))return lv(e)}function UW(e){if(Array.isArray(e))return e}function HW(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function t$(e,t){if(e){if(typeof e=="string")return lv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return lv(e,t)}}function lv(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n=s;){var c=t||n?a:1,l=t||r?a:1;o.push([c,l]),a-=i}return o}function Rd(e){var t=window&&"HTMLCanvasElement"in window,n=window&&"OffscreenCanvas"in window,r=Date.now(),o=e.onError,s=e.onSuccess,i=zW(e,YW),a=null;if(!t)return!1;if(e.useWorker&&n){var c=` var canvasTest = `.concat(jl.toString(),`; onmessage = function(e) { canvasTest(e.data); }; `),l=new Blob([c],{type:"application/javascript"}),u=URL.createObjectURL(l);a=new Worker(u),URL.revokeObjectURL(u),a.onmessage=function(d){var p=d.data,f=p.width,y=p.height,g=p.benchmark,w=p.isTestPass;w?(nl[r].onSuccess(f,y,g),delete nl[r]):nl[r].onError(f,y,g)}}if(e.usePromise)return new Promise(function(d,p){var f=Un(Un({},e),{},{onError:function(S,v,b){var E;if(e.sizes.length===0)E=!0;else{var C=e.sizes.slice(-1),I=tC(C,1),_=tC(I[0],2),k=_[0],$=_[1];E=S===k&&v===$}o(S,v,b),E&&p({width:S,height:v,benchmark:b})},onSuccess:function(S,v,b){s(S,v,b),d({width:S,height:v,benchmark:b})}});if(a){var y=f.onError,g=f.onSuccess;nl[r]={onError:y,onSuccess:g},a.postMessage(i)}else jl(f)});if(a)nl[r]={onError:o,onSuccess:s},a.postMessage(i);else return jl(e)}var Xm={maxArea:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Ym({width:t.max,height:t.max,min:t.min,step:t.step,sizes:Dd(Gm.area)}),r=Un(Un(Un({},Oa),t),{},{sizes:n});return Rd(r)},maxHeight:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Ym({width:1,height:t.max,min:t.min,step:t.step,sizes:Dd(Gm.height)}),r=Un(Un(Un({},Oa),t),{},{sizes:n});return Rd(r)},maxWidth:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Ym({width:t.max,height:1,min:t.min,step:t.step,sizes:Dd(Gm.width)}),r=Un(Un(Un({},Oa),t),{},{sizes:n});return Rd(r)},test:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=Un(Un({},Oa),t);return n.sizes=Dd(n.sizes),n.width&&n.height&&(n.sizes=[[n.width,n.height]]),Rd(n)}};let qm=null;function XW(){return qm||(qm=qW()),qm}async function qW(){const e=await Xm.maxWidth({usePromise:!0}),t=await Xm.maxHeight({usePromise:!0}),n=await Xm.maxArea({usePromise:!0});return{maxWidth:e.width,maxHeight:t.height,maxArea:n.width*n.height}}const nC=8192,ZW=4096*4096;async function n$(e,t){if(e<=nC&&t<=nC&&e*t<=ZW)return[e,t];const{maxWidth:n,maxHeight:r,maxArea:o}=await XW(),s=e/t;if(e>n&&(e=n,t=e/s),t>r&&(t=r,e=t*s),e*t>o){const i=Math.sqrt(o/(e*t));e*=i,t*=i}return[e,t]}/*! * MIT License * Modified code originally from * Copyright (c) 2016 Józef Sokołowski */function rC(e,t){let n=0;for(;e[t+n];)n+=e[t+n]+1;return n+1}function QW(e){return new TextDecoder("ascii").decode(e.slice(0,3))==="GIF"}function JW(e){const t=new Uint8Array(e);let n,r,o=0,s=0;if(!QW(e))return!1;for(n=t[10]&128,r=t[10]&7,o+=6,o+=7,o+=n?3*Math.pow(2,r+1):0;s<2&&o1}function eV(e,t){const n=e.w/t.w,r=e.h/t.h;return n<=1&&r<=1?e:n>r?{w:e.w/n,h:e.h/n}:{w:e.w/r,h:e.h/r}}async function tV(e,t,n,r={}){const o=await jo.usingObjectURL(e,jo.loadImage),{type:s=e.type,quality:i=.92}=r,[a,c]=await n$(Math.min(t*2,o.naturalWidth),Math.min(n*2,o.naturalHeight)),l=document.createElement("canvas");l.width=a,l.height=c;const u=yi(l.getContext("2d",{willReadFrequently:!0}),"Could not get canvas context");return u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high",u.drawImage(o,0,0,a,c),new Promise((d,p)=>{l.toBlob(f=>{f?d(f):p(new Error("Could not resize image"))},s,i)})}async function nV(e){return JW(await e.arrayBuffer())}function rV(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function oV(e){const t=new URL(e).host.replace("www.","");for(const n of Tu)if(r$(n.hostnames,t)){const r=n.fromEmbedUrl(e);if(r)return{definition:n,url:r,embedUrl:e}}}const sV=e=>e.split("*").map(t=>rV(t)).join(".+"),r$=(e,t)=>!!e.find(n=>{const r=new RegExp(sV(n));return t.match(r)});function iV(e){const t=new URL(e).host.replace("www.","");for(const n of Tu)if(r$(n.hostnames,t)){const r=n.toEmbedUrl(e);if(r)return{definition:n,embedUrl:r,url:e}}}function o$(e){return iV(e)??oV(e)}function Cs(e){try{return o$(e)}catch(t){console.error(t)}}/*! * MIT License * Adapted (mostly copied) the work of https://github.com/fregante/text-field-edit * Copyright (c) Federico Brigante (bfred.it) */const Da=" ",ln=class ln{static insertTextFirefox(t,n){t.setRangeText(n,t.selectionStart||0,t.selectionEnd||0,"end"),t.dispatchEvent(new InputEvent("input",{data:n,inputType:"insertText",isComposing:!1}))}static insert(t,n){const r=t.ownerDocument,o=r.activeElement;o!==t&&t.focus(),r.execCommand("insertText",!1,n)||ln.insertTextFirefox(t,n),o===r.body?t.blur():o instanceof HTMLElement&&o!==t&&o.focus()}static set(t,n){t.select(),ln.insert(t,n)}static getSelection(t){const{selectionStart:n,selectionEnd:r}=t;return t.value.slice(n||void 0,r||void 0)}static wrapSelection(t,n,r){const{selectionStart:o,selectionEnd:s}=t,i=ln.getSelection(t);ln.insert(t,n+i+(r??n)),t.selectionStart=(o||0)+n.length,t.selectionEnd=(s||0)+n.length}static replace(t,n,r){let o=0;t.value.replace(n,(...s)=>{const i=o+s[s.length-2],a=s[0].length;t.selectionStart=i,t.selectionEnd=i+a;const c=typeof r=="string"?r:r(...s);return ln.insert(t,c),t.selectionStart=i,o+=c.length-a,c})}static findLineEnd(t,n){const r=t.lastIndexOf(` `,n-1)+1;return t.charAt(r)!==" "?n:r+1}static indent(t){var a;const{selectionStart:n,selectionEnd:r,value:o}=t,s=o.slice(n,r),i=(a=/\n/g.exec(s))==null?void 0:a.length;if(i&&i>0){const c=o.lastIndexOf(` `,n-1)+1,l=t.value.slice(c,r-1),u=l.replace(/^|\n/g,`$&${Da}`),d=u.length-l.length;t.setSelectionRange(c,r-1),ln.insert(t,u),t.setSelectionRange(n+1,r+d)}else ln.insert(t,Da)}static unindent(t){const{selectionStart:n,selectionEnd:r,value:o}=t,s=o.lastIndexOf(` `,n-1)+1,i=ln.findLineEnd(o,r),a=t.value.slice(s,i),c=a.replace(/(^|\n)(\t| {1,2})/g,"$1"),l=a.length-c.length;t.setSelectionRange(s,i),ln.insert(t,c);const u=/\t| {1,2}/.exec(o.slice(s,n)),d=u?u[0].length:0,p=n-d;t.setSelectionRange(n-d,Math.max(p,r-l))}static indentCE(t){var c;const n=window.getSelection(),r=t.innerText,o=Ld(t)??0,s=Ld(t)??0,i=r.slice(o,s),a=(c=/\n/g.exec(i))==null?void 0:c.length;if(a&&a>0){const l=r.lastIndexOf(` `,o-1)+1,u=r.slice(l,s-1),p=u.replace(/^|\n/g,`$&${Da}`).length-u.length;n&&n.setBaseAndExtent(t,o+1,t,s+p)}else{const l=window.getSelection();t.innerText=r.slice(0,o)+Da+r.slice(o),l==null||l.setBaseAndExtent(t,o+1,t,o+2)}}static unindentCE(t){const n=window.getSelection(),r=t.innerText,o=Ld(t)??0,s=Ld(t)??0,i=r.lastIndexOf(` `,o-1)+1,a=ln.findLineEnd(r,s),c=r.slice(i,a),l=c.replace(/(^|\n)(\t| {1,2})/g,"$1"),u=c.length-l.length;if(n){n.setBaseAndExtent(t,i,t,a);const d=/\t| {1,2}/.exec(r.slice(i,o)),p=d?d[0].length:0,f=o-p;n.setBaseAndExtent(t,o-p,t,Math.max(f,s-u))}}static normalizeText(t){return t.replace(ln.fixNewLines,` `)}static normalizeTextForDom(t){return t.replace(ln.fixNewLines,` `).split(` `).map(n=>n||" ").join(` `)}};m(ln,"fixNewLines",/\r?\n|\r/g);let cc=ln;function Ld(e){if(typeof window.getSelection>"u")return;const t=window.getSelection();if(!t)return;let n=0;if(t.rangeCount!==0){const r=t.getRangeAt(0),o=r.cloneRange();o.selectNodeContents(e),o.setEnd(r.endContainer,r.endOffset),n=o.toString().length}return n}const aV=/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;function s$(e){return aV.test(e)}function cV(e){return e.replace(/\t/g,Da)}function lV(e){const t=e.split(` `);for(;t[0]&&t[0].trim().length===0;)t.shift();let n=1/0;for(const r of t)if(r.trim().length>0){const o=r.length-r.trimStart().length;n=Math.min(n,o)}return t.map(r=>r.slice(n)).join(` `)}function uV(e){return e.replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function dV(e){return uV(lV(cV(e)))}const Ol=(e,t)=>e.length<=t?e:e.substring(0,t-3)+"...";function hV(e,{maxImageDimension:t,maxAssetSize:n,acceptedImageMimeTypes:r,acceptedVideoMimeTypes:o},{toasts:s,msg:i}){e.registerExternalAssetHandler("file",async({file:a})=>{const c=a.name;let l=a;const u=r.includes(l.type),d=o.includes(l.type);_t(u||d,`File type not allowed: ${l.type}`),_t(l.size<=n,`File size too big: ${(l.size/1024).toFixed()}kb > ${(n/1024).toFixed()}kb`),l.type==="video/quicktime"&&(l=new Blob([l],{type:"video/mp4"}));let p=u?await jo.getImageSize(l):await jo.getVideoSize(l);const f=l.type==="image/gif"?await nV(l):d,y=await D3(await l.arrayBuffer());if(isFinite(t)){const S=eV(p,{w:t,h:t});p!==S&&(l.type==="image/jpeg"||l.type==="image/png")&&(p=S)}(l.type==="image/jpeg"||l.type==="image/png")&&(l=await tV(l,p.w,p.h,{type:l.type,quality:.92}));const g=Si.createId(y);return Si.create({id:g,type:u?"image":"video",typeName:"asset",props:{name:c,src:await Ka.blobToDataUrl(l),w:p.w,h:p.h,mimeType:l.type,isAnimated:f}})}),e.registerExternalAssetHandler("url",async({url:a})=>{var l,u,d;let c;try{const f=await(await fetch(a,{method:"GET",mode:"no-cors"})).text(),y=new DOMParser().parseFromString(f,"text/html");c={image:((l=y.head.querySelector('meta[property="og:image"]'))==null?void 0:l.getAttribute("content"))??"",title:((u=y.head.querySelector('meta[property="og:title"]'))==null?void 0:u.getAttribute("content"))??Ol(a,32),description:((d=y.head.querySelector('meta[property="og:description"]'))==null?void 0:d.getAttribute("content"))??""}}catch(p){console.error(p),s.addToast({title:i("assets.url.failed"),severity:"error"}),c={image:"",title:Ol(a,32),description:""}}return{id:Si.createId(AS(a)),typeName:"asset",type:"bookmark",props:{src:a,description:c.description,image:c.image,title:c.title},meta:{}}}),e.registerExternalContentHandler("svg-text",async({point:a,text:c})=>{const l=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageCenter()),u=new DOMParser().parseFromString(c,"image/svg+xml").querySelector("svg");if(!u)throw new Error("No element present");let d=parseFloat(u.getAttribute("width")||"0"),p=parseFloat(u.getAttribute("height")||"0");if(!(d&&p)){document.body.appendChild(u);const y=u.getBoundingClientRect();document.body.removeChild(u),d=y.width,p=y.height}const f=await e.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});if(!f)throw Error("Could not create an asset");oC(e,[f],l)}),e.registerExternalContentHandler("embed",({point:a,url:c,embed:l})=>{const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageCenter()),{width:d,height:p}=l,f=Be(),y={id:f,type:"embed",x:u.x-(d||450)/2,y:u.y-(p||450)/2,props:{w:d,h:p,url:c}};e.createShapes([y]).select(f)}),e.registerExternalContentHandler("files",async({point:a,files:c})=>{const l=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageCenter()),u=new P(l.x,l.y),d=[];await Promise.all(c.map(async(p,f)=>{if(p.size>n)return console.warn(`File size too big: ${(p.size/1024).toFixed()}kb > ${(n/1024).toFixed()}kb`),null;if(!p.type)throw new Error("No mime type");if(!r.concat(o).includes(p.type))return console.warn(`${p.name} not loaded - Extension not allowed.`),null;try{const y=await e.getAssetForExternalContent({type:"file",file:p});if(!y)throw Error("Could not create an asset");d[f]=y}catch(y){return s.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error(y),null}})),oC(e,fe(d),u)}),e.registerExternalContentHandler("text",async({point:a,text:c})=>{const l=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageCenter()),u=e.getShapeUtil("text").getDefaultProps(),d=dV(c),p=e.getOnlySelectedShape();if(p&&"text"in p.props){e.updateShapes([{id:p.id,type:p.type,props:{text:d}}]);return}let f,y,g,w="middle";const S=d.split(` `).length>1,v=s$(d);S&&(w=S?v?"end":"start":"middle");const b=e.textMeasure.measureText(d,{...Ht,fontFamily:io[u.font],fontSize:ac[u.size],maxWidth:null}),E=Math.min(S?e.getViewportPageBounds().width*.9:920,Math.max(200,e.getViewportPageBounds().width*.9));if(b.w>E){const C=e.textMeasure.measureText(d,{...Ht,fontFamily:io[u.font],fontSize:ac[u.size],maxWidth:E});f=C.w,y=C.h,g=!1,w=v?"end":"start"}else f=b.w,y=b.h,g=!0;l.y-y/2{const l=Cs(c);if(l)return e.putExternalContent({type:"embed",url:l.url,point:a,embed:l.definition});const u=a??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageCenter()),d=Si.createId(AS(c)),p=pV(e,c,u);let f=e.getAsset(d),y=!1;if(!f){y=!0;try{const g=await e.getAssetForExternalContent({type:"url",url:c});if(!g)throw Error("Could not create an asset");f=g}catch{s.addToast({title:i("assets.url.failed"),severity:"error"});return}}e.batch(()=>{y&&e.createAssets([f]),e.updateShapes([{id:p.id,type:p.type,props:{assetId:f.id}}])})})}async function oC(e,t,n){if(!t.length)return[];const r=P.From(n),o=[];for(const s of t)switch(s.type){case"bookmark":{o.push({id:Be(),type:"bookmark",x:r.x-150,y:r.y-160,opacity:1,props:{assetId:s.id,url:s.props.src}}),r.x+=300;break}case"image":{o.push({id:Be(),type:"image",x:r.x-s.props.w/2,y:r.y-s.props.h/2,opacity:1,props:{assetId:s.id,w:s.props.w,h:s.props.h}}),r.x+=s.props.w;break}case"video":o.push({id:Be(),type:"video",x:r.x-s.props.w/2,y:r.y-s.props.h/2,opacity:1,props:{assetId:s.id,w:s.props.w,h:s.props.h}}),r.x+=s.props.w}return e.batch(()=>{const s=t.filter(i=>!e.getAsset(i.id));s.length&&e.createAssets(s),e.createShapes(o).select(...o.map(i=>i.id)),i$(e,n)}),o.map(s=>s.id)}function i$(e,t){const n=e.getViewportPageBounds();let r=e.getSelectionPageBounds();if(r){const o=r.center.sub(t);e.updateShapes(e.getSelectedShapes().map(s=>{const i=e.getShapeParentTransform(s).decompose().rotation,a=P.Rot(o,-i);return{id:s.id,type:s.type,x:s.x-a.x,y:s.y-a.y}}))}r=e.getSelectionPageBounds(),r&&!n.contains(r)&&e.zoomToSelection()}function pV(e,t,n){const r={id:Be(),type:"bookmark",x:n.x-150,y:n.y-160,opacity:1,props:{assetId:null,url:t}};return e.batch(()=>{e.createShapes([r]).select(r.id),i$(e,n)}),e.getShape(r.id)}var xy;let fV=(xy=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",n=>{this.parent.transition("pointing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")});m(this,"onKeyUp",n=>{var r;if(n.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const o=this.editor.getOnlySelectedShape();o&&this.editor.getShapeUtil(o).canEdit(o)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(o.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...n,target:"shape",shape:o}))}})}},m(xy,"id","idle"),xy);var wy;let gV=(wy=class extends se{constructor(){super(...arguments);m(this,"shape");m(this,"markId","");m(this,"onEnter",()=>{this.didTimeout=!1;const n=this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{filter:r=>!r.isLocked&&this.editor.getShapeUtil(r).canBind(r),margin:0,hitInside:!0,renderingOnly:!0});n?this.editor.setHintingShapes([n.id]):this.createArrowShape(),this.startPreciseTimeout()});m(this,"onExit",()=>{this.shape=void 0,this.editor.setHintingShapes([]),this.clearPreciseTimeout()});m(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:this.editor.getShapeHandles(this.shape).find(n=>n.id==="end"),isCreating:!0,onInteractionEnd:"arrow"})}});m(this,"onPointerUp",()=>{this.cancel()});m(this,"onCancel",()=>{this.cancel()});m(this,"onComplete",()=>{this.cancel()});m(this,"onInterrupt",()=>{this.cancel()});m(this,"preciseTimeout",-1);m(this,"didTimeout",!1)}cancel(){this.shape&&this.editor.bailToMark(this.markId),this.editor.setHintingShapes([]),this.parent.transition("idle")}createArrowShape(){var u,d;const{originPagePoint:n}=this.editor.inputs,r=Be();this.markId=`creating:${r}`,this.editor.mark(this.markId),this.editor.createShapes([{id:r,type:"arrow",x:n.x,y:n.y}]);const o=this.editor.getShape(r);if(!o)throw Error("expected shape");const s=this.editor.getShapeHandles(o);if(!s)throw Error("expected handles for arrow");const i=this.editor.getShapeUtil("arrow"),a=this.shape,c=s.find(p=>p.id==="start"),l=(u=i.onHandleDrag)==null?void 0:u.call(i,o,{handle:{...c,x:0,y:0},isPrecise:!0,initial:a});if(l){const p=(d=l.props)==null?void 0:d.start;(p==null?void 0:p.type)==="binding"&&this.editor.setHintingShapes([p.boundShapeId]),this.editor.updateShapes([l],{squashing:!0})}this.shape=this.editor.getShape(r),this.editor.select(r)}updateArrowShapeEndHandle(){var s,i,a;const n=this.shape;if(!n)throw Error("expected shape");const r=this.editor.getShapeHandles(n);if(!r)throw Error("expected handles for arrow");const o={...n,props:{...n.props,end:{...n.props.end,x:0,y:0}}};{const c=this.editor.getShapeUtil("arrow"),l=this.shape,u=this.editor.getPointInShapeSpace(n,this.editor.inputs.currentPagePoint),d=r.find(f=>f.id==="end"),p=(s=c.onHandleDrag)==null?void 0:s.call(c,o,{handle:{...d,x:u.x,y:u.y},isPrecise:!1,initial:l});if(p){const f=(i=p.props)==null?void 0:i.end;(f==null?void 0:f.type)==="binding"&&this.editor.setHintingShapes([f.boundShapeId]),this.editor.updateShapes([p],{squashing:!0})}}{const c=this.editor.getShapeUtil("arrow"),l=this.shape,u=r.find(p=>p.id==="start"),d=(a=c.onHandleDrag)==null?void 0:a.call(c,o,{handle:{...u,x:0,y:0},isPrecise:this.didTimeout,initial:l});d&&this.editor.updateShapes([d],{squashing:!0})}this.shape=this.editor.getShape(n.id)}startPreciseTimeout(){this.preciseTimeout=window.setTimeout(()=>{this.getIsActive()&&(this.didTimeout=!0)},320)}clearPreciseTimeout(){clearTimeout(this.preciseTimeout)}},m(wy,"id","pointing"),wy);class _h extends se{constructor(){super(...arguments);m(this,"shapeType","arrow")}}m(_h,"id","arrow"),m(_h,"initial","idle"),m(_h,"children",()=>[fV,gV]);class Rx extends se{constructor(){super(...arguments);m(this,"info",{});m(this,"initialShape");m(this,"shapeType",this.parent.id==="highlight"?"highlight":"draw");m(this,"util",this.editor.getShapeUtil(this.shapeType));m(this,"isPen",!1);m(this,"segmentMode","free");m(this,"didJustShiftClickToExtendPreviousShapeLine",!1);m(this,"pagePointWhereCurrentSegmentChanged",{});m(this,"pagePointWhereNextSegmentChanged",null);m(this,"lastRecordedPoint",{});m(this,"mergeNextPoint",!1);m(this,"currentLineLength",0);m(this,"canDraw",!1);m(this,"markId",null);m(this,"onEnter",n=>{this.markId=null,this.info=n,this.canDraw=!this.editor.getIsMenuOpen(),this.lastRecordedPoint=this.editor.inputs.currentPagePoint.clone(),this.canDraw&&this.startShape()});m(this,"onPointerMove",()=>{const{inputs:n}=this.editor;if(this.isPen!==n.isPen){if(this.markId){this.editor.bailToMark(this.markId),this.startShape();return}}else!this.canDraw&&n.isDragging&&(this.startShape(),this.canDraw=!0);this.canDraw&&(n.isPen?P.Dist(n.currentPagePoint,this.lastRecordedPoint)>=1/this.editor.getZoomLevel()?(this.lastRecordedPoint=n.currentPagePoint.clone(),this.mergeNextPoint=!1):this.mergeNextPoint=!0:this.mergeNextPoint=!1,this.updateDrawingShape())});m(this,"onKeyDown",n=>{if(n.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()});m(this,"onKeyUp",n=>{if(n.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()});m(this,"onExit",()=>{this.editor.snaps.clearIndicators(),this.pagePointWhereCurrentSegmentChanged=this.editor.inputs.currentPagePoint.clone()});m(this,"onPointerUp",()=>{this.complete()});m(this,"onCancel",()=>{this.cancel()});m(this,"onComplete",()=>{this.complete()});m(this,"onInterrupt",()=>{this.editor.inputs.isDragging||(this.markId&&this.editor.bailToMark(this.markId),this.cancel())})}canClose(){return this.shapeType!=="highlight"}getIsClosed(n,r){if(!this.canClose())return!1;const o=Mt[r],s=n[0].points[0],i=n[n.length-1],a=i.points[i.points.length-1];return s!==a&&this.currentLineLength>o*4&&P.DistMin(s,a,o*2)}startShape(){const{inputs:{originPagePoint:n,isPen:r}}=this.editor;this.markId="draw start "+et(),this.editor.mark(this.markId),this.isPen=r;const o=this.isPen?this.info.point.z*1.25:.5;if(this.segmentMode=this.editor.inputs.shiftKey?"straight":"free",this.didJustShiftClickToExtendPreviousShapeLine=!1,this.lastRecordedPoint=n.clone(),this.initialShape){const i=this.editor.getShape(this.initialShape.id);if(i&&this.segmentMode==="straight"){this.didJustShiftClickToExtendPreviousShapeLine=!0;const a=Wn(i.props.segments);if(!a)throw Error("Expected a previous segment!");const c=Wn(a.points);if(!c)throw Error("Expected a previous point!");const{x:l,y:u}=this.editor.getPointInShapeSpace(i,n).toFixed(),d=this.isPen?this.info.point.z*1.25:.5,p={type:this.segmentMode,points:[{x:c.x,y:c.y,z:+d.toFixed(2)},{x:l,y:u,z:+d.toFixed(2)}]},f=oe.applyToPoint(this.editor.getShapePageTransform(i.id),c);this.pagePointWhereCurrentSegmentChanged=f,this.pagePointWhereNextSegmentChanged=null;const y=[...i.props.segments,p];this.currentLineLengthiu){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="straight";const y=Wn(a);if(!y)throw Error("Expected a previous segment!");const g=Wn(y.points);if(!g)throw Error("Expected a previous last point!");let w;const S=this.editor.getPointInShapeSpace(i,this.pagePointWhereCurrentSegmentChanged).toFixed().toJson();if(y.type==="straight"){this.currentLineLength+=P.Dist(g,S),w={type:"straight",points:[{...g},S]};const b=this.editor.getShapePageTransform(i);this.pagePointWhereCurrentSegmentChanged=oe.applyToPoint(b,g)}else w={type:"straight",points:[S,d]};const v={id:o,type:this.shapeType,props:{segments:[...a,w]}};this.canClose()&&(v.props.isClosed=this.getIsClosed(a,s)),this.editor.updateShapes([v],{squashing:!0})}break}case"starting_free":{const{pagePointWhereNextSegmentChanged:p}=this;if(p===null)throw Error("We should have a point where the segment changed");if(P.Dist2(p,r.currentPagePoint)>iu){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";const y=a.slice(),g=y[y.length-1],w=Wn(g.points);if(!w)throw Error("No previous point!");const S={type:"free",points:[...P.PointsBetween(w,d,6).map(E=>E.toFixed().toJson())]},v=[...y,S];this.currentLineLength2){let k,$=8/this.editor.getZoomLevel();for(let T=0,O=a.length-2;T500){this.editor.updateShapes([{id:o,type:this.shapeType,props:{isComplete:!0}}]);const w=Be();this.editor.createShapes([{id:w,type:this.shapeType,x:Vp(r.currentPagePoint.x),y:Vp(r.currentPagePoint.y),props:{isPen:this.isPen,segments:[{type:"free",points:[{x:0,y:0,z:this.isPen?+(u*1.25).toFixed():.5}]}]}}]),this.initialShape=Ye(this.editor.getShape(w)),this.mergeNextPoint=!1,this.lastRecordedPoint=r.currentPagePoint.clone(),this.currentLineLength=0}break}}}getLineLength(n){let r=0;for(const o of n)for(let s=0;s{this.parent.transition("drawing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(by,"id","idle"),by);class kh extends se{constructor(){super(...arguments);m(this,"shapeType","draw");m(this,"onExit",()=>{const n=this.children.drawing;n.initialShape=void 0})}}m(kh,"id","draw"),m(kh,"initial","idle"),m(kh,"children",()=>[a$,Rx]);class uv extends Ph{constructor(){super(...arguments);m(this,"shapeType","frame");m(this,"onCreate",n=>{if(!n)return;const r=this.editor.getShapePageBounds(n),o=[],s=this.editor.getShapeAncestors(n).map(i=>i.id);this.editor.getSortedChildIdsForParent(n.parentId).map(i=>{const a=this.editor.getShape(i);if(!a||a.id===n.id||a.isLocked)return;const c=this.editor.getShapePageBounds(a);c&&r.contains(c)&&mV(a,s,n)&&o.push(a.id)}),this.editor.reparentShapes(o,n.id),this.editor.getInstanceState().isToolLocked?this.editor.setCurrentTool("frame"):this.editor.setCurrentTool("select.idle")})}}m(uv,"id","frame"),m(uv,"initial","idle");function mV(e,t,n){return t.includes(e.id)?!1:e.parentId===n.parentId}var Py;let yV=(Py=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",n=>{this.parent.transition("pointing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onKeyUp",n=>{var r;if(n.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const o=this.editor.getOnlySelectedShape();o&&this.editor.getShapeUtil(o).canEdit(o)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(o.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...n,target:"shape",shape:o}))}});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Py,"id","idle"),Py);var Cy;let SV=(Cy=class extends se{constructor(){super(...arguments);m(this,"markId","");m(this,"onPointerUp",()=>{this.complete()});m(this,"onPointerMove",n=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,o=Be();this.markId=`creating:${o}`,this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:"geo",x:r.x,y:r.y,props:{w:1,h:1,geo:this.editor.getStyleForNextShape(oo)}}]).select(o).setCurrentTool("select.resizing",{...n,target:"selection",handle:"bottom_right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:"geo"})}});m(this,"onCancel",()=>{this.cancel()});m(this,"onComplete",()=>{this.complete()});m(this,"onInterrupt",()=>{this.cancel()})}complete(){const{originPagePoint:n}=this.editor.inputs,r=Be();this.markId=`creating:${r}`,this.editor.mark(this.markId),this.editor.createShapes([{id:r,type:"geo",x:n.x,y:n.y,props:{geo:this.editor.getStyleForNextShape(oo),w:1,h:1}}]);const o=this.editor.getShape(r);if(!o)return;const s=o.props.geo==="star"?new ne(0,0,200,190):o.props.geo==="cloud"?new ne(0,0,300,180):new ne(0,0,200,200),i=s.center,a=this.editor.getShapeParentTransform(o);a&&i.rot(-a.rotation()),this.editor.select(r),this.editor.updateShapes([{id:o.id,type:"geo",x:o.x-i.x,y:o.y-i.y,props:{geo:this.editor.getStyleForNextShape(oo),w:s.width,h:s.height}}]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select",{})}cancel(){this.parent.transition("idle")}},m(Cy,"id","pointing"),Cy);class Th extends se{constructor(){super(...arguments);m(this,"shapeType","geo")}}m(Th,"id","geo"),m(Th,"initial","idle"),m(Th,"children",()=>[yV,SV]);class $h extends se{constructor(){super(...arguments);m(this,"shapeType","highlight");m(this,"onExit",()=>{const n=this.children.drawing;n.initialShape=void 0})}}m($h,"id","highlight"),m($h,"initial","idle"),m($h,"children",()=>[a$,Rx]);var Iy;let vV=(Iy=class extends se{constructor(){super(...arguments);m(this,"shapeId","");m(this,"onEnter",n=>{this.shapeId=n.shapeId,this.editor.setCursor({type:"cross",rotation:0})});m(this,"onPointerDown",()=>{this.parent.transition("pointing",{shapeId:this.shapeId})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Iy,"id","idle"),Iy);const sC=2;var Ey;let xV=(Ey=class extends se{constructor(){super(...arguments);m(this,"shape",{});m(this,"markId");m(this,"onEnter",n=>{const{inputs:r}=this.editor,{currentPagePoint:o}=r;this.markId=void 0;const s=n.shapeId&&this.editor.getShape(n.shapeId);if(s&&r.shiftKey){this.markId=`creating:${s.id}`,this.editor.mark(this.markId),this.shape=s;const i=this.editor.getShapeHandles(this.shape);if(!i)return;const a=i.filter(f=>f.type==="vertex").sort(en),c=a[a.length-1],l=a[a.length-2],u=oe.applyToPoint(this.editor.getShapeParentTransform(this.shape),new P(this.shape.x,this.shape.y)),d=P.Sub(o,u).addXY(.1,.1),p=Ye(this.shape.props.points);if(P.DistMin(c,l,sC)||P.DistMin(d,c,sC))p[c.id]={id:c.id,index:c.index,x:d.x,y:d.y};else{const f=$o(c.index);p[f]={id:f,index:f,x:d.x,y:d.y}}this.editor.updateShapes([{id:this.shape.id,type:this.shape.type,props:{points:p}}])}else{const i=Be();this.markId=`creating:${i}`,this.editor.mark(this.markId),this.editor.createShapes([{id:i,type:"line",x:o.x,y:o.y}]),this.editor.select(i),this.shape=this.editor.getShape(i)}});m(this,"onPointerMove",()=>{if(this.shape&&this.editor.inputs.isDragging){const n=this.editor.getShapeHandles(this.shape);if(!n)throw this.markId&&this.editor.bailToMark(this.markId),Error("No handles found");const r=Wn(n);this.editor.setCurrentTool("select.dragging_handle",{shape:this.shape,isCreating:!0,handle:{...r,x:r.x-.1,y:r.y-.1},onInteractionEnd:"line"})}});m(this,"onPointerUp",()=>{this.complete()});m(this,"onCancel",()=>{this.cancel()});m(this,"onComplete",()=>{this.complete()});m(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()}},m(Ey,"id","pointing"),Ey);class Mh extends se{constructor(){super(...arguments);m(this,"shapeType","line")}}m(Mh,"id","line"),m(Mh,"initial","idle"),m(Mh,"children",()=>[vV,xV]);var _y;let wV=(_y=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",n=>{this.parent.transition("pointing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(_y,"id","idle"),_y);function We(e,t){var o;const n=new Set;for(const s of t){const i=e.getShape(s);if(!i)continue;e.getShapeUtil(i).onDragShapesOut&&n.add(i);const a=e.getShape(i.parentId);a&&e.getShapeUtil(a).onDragShapesOut&&n.add(a)}const r=new Map;for(const s of n){const i=c$(e,s);i.length&&r.set(s,i)}for(const[s,i]of r){const a=e.getShapeUtil(s),c=fe(i.map(l=>e.getShape(l)));(o=a.onDragShapesOut)==null||o.call(a,s,c)}}function c$(e,t){const n=e.getSortedChildIdsForParent(t.id);if(n.length===0)return[];const r=e.getShapePageBounds(t);if(!r)return[];let o,s,i;const a=[];for(const c of n){const l=e.getShapePageBounds(c);if(!l)continue;if(!r.includes(l)){a.push(c);continue}o??(o=e.getShapeGeometry(t)),s??(s=e.getShapePageTransform(t)),i??(i=s.applyToPoints(o.vertices));const u=e.getShapePageTransform(c).clone().invert().applyToPoints(i),{vertices:d,isClosed:p}=e.getShapeGeometry(c);if(!d.some(f=>Zn(f,u))){if(p){if($2(u,d))continue}else if(A4(u,d))continue;a.push(c)}}return a}function sf(e,t,n=!1){e.select(t),e.setEditingShape(t),e.setCurrentTool("select.editing_shape",{target:"shape",shape:t}),n&&e.emit("select-all-text",{shapeId:t.id}),l$(e)}const bV=16;function l$(e){const t=e.getSelectionPageBounds(),n=e.getViewportPageBounds();if(t&&!n.contains(t)){const r=t.clone().expandBy(bV/e.getZoomLevel()).expand(n),o=n.clone().translate({x:(r.center.x-n.center.x)*2,y:(r.center.y-n.center.y)*2});e.zoomToBounds(o,{duration:Qr,inset:0})}}const vi=20,PV=0,Te=200,Lx={x:Te/2,y:Te/2},u$=10,CV={a1:new P(Te*.5,Te*-.5-vi),a2:new P(Te*1.5+vi,Te*.5),a3:new P(Te*.5,Te*1.5+vi),a4:new P(Te*-.5-vi,Te*.5)};function d$(e,t,n,r){return Object.fromEntries(Object.entries(CV).map(([o,s],i)=>{const a=s.clone();return i===0&&r?a.y-=r:i===2&&n&&(a.y+=n),[o,a.rot(t).add(e)]}))}function h$(e,t,n){const r=new Set(e.getSelectedShapeIds()),o=(Te+vi+n)**2,s=new Map,i=[];for(const l of e.getCurrentPageShapes()){if(!e.isShapeOfType(l,"note")||r.has(l.id))continue;const u=e.getShapePageTransform(l.id);t===u.rotation()&&(s.set(l,e.getShapePageBounds(l).center),i.push(...Object.values(d$(u.point(),t,l.props.growY,n))))}const a=i.length;let c;for(const[l,u]of s)for(let d=0;do||e.isPointInShape(l,c)&&(i[d]=void 0));return fe(i)}function p$(e,t,n,r,o=!1){let s;const i=e.getCurrentPageShapesSorted(),a=Te+vi**2;for(let c=i.length-1;c>=0;c--){const l=i[c];if(l.type==="note"&&l.id!==t.id){const u=e.getShapePageBounds(l);if(u&&P.Dist2(u.center,n){const{editor:n}=this;if(this.wasFocusedOnEnter=!n.getIsMenuOpen(),this.wasFocusedOnEnter){const r=Be();this.markId=`creating:${r}`,n.mark(this.markId);const o=this.editor.inputs.originPagePoint.clone(),s=iC(this.editor,o);s&&o.sub(s),this.shape=aC(this.editor,r,o)}});m(this,"onPointerMove",n=>{if(this.editor.inputs.isDragging){if(!this.wasFocusedOnEnter){const r=Be(),o=this.editor.inputs.originPagePoint.clone(),s=iC(this.editor,o);s&&o.sub(s),this.shape=aC(this.editor,r,o)}this.editor.setCurrentTool("select.translating",{...n,target:"shape",shape:this.shape,onInteractionEnd:"note",isCreating:!0,onCreate:()=>{this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape")}})}});m(this,"onPointerUp",()=>{this.complete()});m(this,"onInterrupt",()=>{this.cancel()});m(this,"onComplete",()=>{this.complete()});m(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)}},m(ky,"id","pointing"),ky);function iC(e,t){let n=u$/e.getZoomLevel(),r;for(const o of h$(e,0,0)){const s=P.Sub(t,o),i=s.len();i[wV,IV]);function EV(e){const t=e.getShapeAtPoint(e.inputs.currentPagePoint,{hitInside:!1,hitLabels:!1,margin:Ko/e.getZoomLevel(),renderingOnly:!0});if(!t)return e.setHoveredShape(null);let n;const r=e.getOutermostSelectableShape(t);return r===t||r.id===e.getFocusedGroupId()||e.getSelectedShapeIds().includes(r.id)?n=t:n=r,e.setHoveredShape(n.id)}const Ya=B_(EV,32);var Ty;let _V=(Ty=class extends se{constructor(){super(...arguments);m(this,"onPointerMove",n=>{switch(n.target){case"shape":case"canvas":Ya(this.editor)}});m(this,"onPointerDown",n=>{this.parent.transition("pointing",n)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onKeyDown",n=>{var r;if(n.key==="Enter"){if(this.editor.getInstanceState().isReadonly)return null;const o=this.editor.getOnlySelectedShape();o&&this.editor.getShapeUtil(o).canEdit(o)&&(this.editor.setCurrentTool("select"),this.editor.setEditingShape(o.id),(r=this.editor.root.getCurrent())==null||r.transition("editing_shape",{...n,target:"shape",shape:o}))}});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Ty,"id","idle"),Ty);var $y;let kV=($y=class extends se{constructor(){super(...arguments);m(this,"shape");m(this,"markId","");m(this,"onExit",()=>{this.editor.setHintingShapes([])});m(this,"onPointerMove",n=>{if(this.editor.inputs.isDragging){const{inputs:{originPagePoint:r}}=this.editor,o=Be();if(this.markId=`creating:${o}`,this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:"text",x:r.x,y:r.y,props:{text:"",autoSize:!1,w:20}}]),this.editor.select(o),this.shape=this.editor.getShape(o),!this.shape)return;const{shape:s}=this;this.editor.setCurrentTool("select.resizing",{...n,target:"selection",handle:"right",isCreating:!0,creationCursorOffset:{x:1,y:1},onInteractionEnd:"text",onCreate:()=>{this.editor.setEditingShape(s.id),this.editor.setCurrentTool("select.editing_shape")}})}});m(this,"onPointerUp",()=>{this.complete()});m(this,"onComplete",()=>{this.cancel()});m(this,"onCancel",()=>{this.cancel()});m(this,"onInterrupt",()=>{this.cancel()})}complete(){var s;this.editor.mark("creating text shape");const n=Be(),{x:r,y:o}=this.editor.inputs.currentPagePoint;this.editor.createShapes([{id:n,type:"text",x:r,y:o,props:{text:"",autoSize:!0}}]).select(n),this.editor.setEditingShape(n),this.editor.setCurrentTool("select"),(s=this.editor.root.getCurrent())==null||s.transition("editing_shape")}cancel(){this.parent.transition("idle"),this.editor.bailToMark(this.markId)}},m($y,"id","pointing"),$y);class jh extends se{constructor(){super(...arguments);m(this,"shapeType","text")}}m(jh,"id","text"),m(jh,"initial","idle"),m(jh,"children",()=>[_V,kV]);const TV=[jh,kh,Th,Ah,Mh,uv,_h,$h];function xt(){return Jo({isDarkMode:Ru()})}const Pt=Se.memo(function({theme:t,d:n,color:r,fill:o}){switch(o){case"none":return null;case"solid":return h.jsx("path",{fill:t[r].semi,d:n});case"semi":return h.jsx("path",{fill:t.solid,d:n});case"pattern":return h.jsx($V,{theme:t,color:r,fill:o,d:n})}}),$V=function({d:t,color:n,theme:r}){const o=z(),s=D2(),i=K("zoomLevel",()=>o.getZoomLevel(),[o]),a=Math.ceil(i),c=o.getZoomLevel()<=.18;return h.jsxs(h.Fragment,{children:[h.jsx("path",{fill:r[n].pattern,d:t}),h.jsx("path",{fill:s?`url(#${ic[`1_${r.id}`]})`:c?r[n].semi:`url(#${ic[`${a}_${r.id}`]})`,d:t})]})};function MV(e){return e.replace(/\s/g," ")}function dv(e,t,n){const{padding:r=0}=n;if(t.length===0)return null;const o=ne.From(t[0].box);for(const{box:l}of t)o.union(l);const s=r+(n.offsetX??0),i=(n.offsetY??0)+n.fontSize/2+(n.verticalTextAlign==="start"?r:n.verticalTextAlign==="end"?n.height-r-o.height:(Math.ceil(n.height)-o.height)/2);let a=null;const c=[];for(const{text:l,box:u}of t)a!==null&&u.y>a&&c.push(h.jsx("tspan",{alignmentBaseline:"mathematical",x:s,y:u.y+i,children:` `},c.length)),c.push(h.jsx("tspan",{alignmentBaseline:"mathematical",x:u.x+s,y:u.y+i,children:MV(l)},c.length)),a=u.y;return h.jsx("text",{fontSize:n.fontSize,fontFamily:n.fontFamily,fontStyle:n.fontFamily,fontWeight:n.fontWeight,dominantBaseline:"mathematical",alignmentBaseline:"mathematical",stroke:n.stroke,strokeWidth:n.strokeWidth,fill:n.fill,children:c})}function AV(e,t,n,r){if((e==="start-legacy"||e==="end-legacy")&&n.length!==0){const o=ne.From(n[0].box);for(const{box:s}of n)o.union(s);if(e==="start-legacy")return(r-2*t-o.width)/2;if(e==="end-legacy")return-(r-2*t-o.width)/2}}function jV(e){return e==="start-legacy"||e==="middle-legacy"||e==="end-legacy"}function eg({fontSize:e,font:t,align:n,verticalAlign:r,text:o,labelColor:s,bounds:i,padding:a=16,stroke:c=!0}){const l=z(),u=xt(),d={fontSize:e,fontFamily:pk[t],textAlign:n,verticalTextAlign:r,width:Math.ceil(i.width),height:Math.ceil(i.height),padding:a,lineHeight:Ht.lineHeight,fontStyle:"normal",fontWeight:"normal",overflow:"wrap",offsetX:0,offsetY:0,fill:s,stroke:void 0,strokeWidth:void 0},p=l.textMeasure.measureTextSpans(o,d),f=AV(n,a,p,i.width);f&&(d.offsetX=f),d.offsetX+=i.x,d.offsetY+=i.y;const y=dv(l,p,d);let g=null;return c&&(d.fill=u.background,d.stroke=u.background,d.strokeWidth=2,g=dv(l,p,d)),h.jsxs(h.Fragment,{children:[g,y]})}function lc(e){return{key:`${ao.id}:${e}`,getElement:async()=>{const t=OV(e);if(!t)return null;const n=t.$$_url,r=t.$$_fontface;if(!n||!r)return null;const o=await(await fetch(n)).blob(),s=await Ka.blobToDataUrl(o),i=r.replace(n,s);return h.jsx("style",{children:i})}}}function OV(e){const t=pk[e];for(const n of document.fonts)if(t.includes(n.family))return n;return null}function Fx(e){return{key:`${ao.id}:${e}`,getElement:async()=>e!=="pattern"?null:h.jsx(DV,{})}}function DV(){const e=xt(),t=8/12;return h.jsxs(h.Fragment,{children:[h.jsxs("mask",{id:"hash_pattern_mask",children:[h.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:"white"}),h.jsxs("g",{strokeLinecap:"round",stroke:"black",children:[h.jsx("line",{x1:t*1,y1:t*3,x2:t*3,y2:t*1}),h.jsx("line",{x1:t*5,y1:t*7,x2:t*7,y2:t*5}),h.jsx("line",{x1:t*9,y1:t*11,x2:t*11,y2:t*9})]})]}),h.jsx("pattern",{id:ic[`1_${e.id}`],width:"8",height:"8",patternUnits:"userSpaceOnUse",children:h.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:e.solid,mask:"url(#hash_pattern_mask)"})})]})}function Nx(){return{key:`${ao.id}:pattern`,component:FV}}const ml=8,cC=(e,t,n)=>new Promise((r,o)=>{const s=ml*t*e,i=document.createElement("canvas");i.width=s,i.height=s;const a=i.getContext("2d");if(!a)return;a.fillStyle=n?"#212529":"#f8f9fa",a.fillRect(0,0,s,s),a.globalCompositeOperation="destination-out",a.lineCap="round",a.lineWidth=1.25*t*e;const c=8/12,l=u=>u*t*e;a.beginPath(),a.moveTo(l(c*1),l(c*3)),a.lineTo(l(c*3),l(c*1)),a.moveTo(l(c*5),l(c*7)),a.lineTo(l(c*7),l(c*5)),a.moveTo(l(c*9),l(c*11)),a.lineTo(l(c*11),l(c*9)),a.stroke(),i.toBlob(u=>{!u||$t.throwToBlob.get()?o():r(u)})}),lC=(e,t)=>{const n=document.createElement("canvas");n.width=e[0],n.height=e[1];const r=n.getContext("2d");return r?(t(r),n.toDataURL()):""},RV=()=>{const e=[];for(let t=1;t<=Math.ceil(xs);t++){const n=lC([1,1],o=>{o.fillStyle=Np.lightMode.black.semi,o.fillRect(0,0,1,1)}),r=lC([1,1],o=>{o.fillStyle=Np.darkMode.black.semi,o.fillRect(0,0,1,1)});e.push({zoom:t,url:n,darkMode:!1}),e.push({zoom:t,url:r,darkMode:!0})}return e};function LV(){const t=z().getInstanceState().devicePixelRatio,[n,r]=x.useState(!1),o=x.useMemo(()=>RV(),[]),[s,i]=x.useState(o);return x.useEffect(()=>{const c=[];for(let u=1;u<=Math.ceil(xs);u++)c.push(cC(t,u,!1).then(d=>({zoom:u,url:URL.createObjectURL(d),darkMode:!1}))),c.push(cC(t,u,!0).then(d=>({zoom:u,url:URL.createObjectURL(d),darkMode:!0})));let l=!1;return Promise.all(c).then(u=>{l||(i(u),r(!0))}),()=>{l=!0,r(!1)}},[t]),{defs:h.jsx(h.Fragment,{children:s.map(c=>{const l=c.zoom+(c.darkMode?"_dark":"_light");return h.jsx("pattern",{id:ic[l],width:ml,height:ml,patternUnits:"userSpaceOnUse",children:h.jsx("image",{href:c.url,width:ml,height:ml})},l)})}),isReady:n}}function FV(){const e=z(),t=x.useRef(null),{defs:n,isReady:r}=LV();return x.useEffect(()=>{if(r&&e.environment.isSafari){const o=f$(t.current);o&&requestAnimationFrame(()=>{o.style.display="none",requestAnimationFrame(()=>{o.style.display=""})})}},[e,r]),h.jsx("g",{ref:t,"data-testid":r?"ready-pattern-fill-defs":void 0,children:n})}function f$(e){return e.classList.contains("tl-html-layer")?e:e.parentElement?f$(e.parentElement):null}function Vo(e,t,n={}){const{closed:r=!1,snap:o=1,start:s="outset",end:i="outset",lengthRatio:a=2,style:c="dashed"}=n;let l=0,u=0,d=1,p=0,f=0;switch(c){case"dashed":{d=1,l=Math.min(t*a,e/4);break}case"dotted":{d=100,l=t/d;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(s==="outset"?(e+=l/2,f+=l/2):s==="skip"&&(e-=l,f-=l),i==="outset"?e+=l/2:i==="skip"&&(e-=l)),u=Math.floor(e/l/(2*d)),u-=u%o,u<3&&c==="dashed"?e/t<5?(l=e,u=1,p=0):(l=e*.333,p=e*.333):(u=Math.max(u,3),l=e/u/(2*d),r?(f=l/2,p=(e-u*l)/u):p=(e-u*l)/Math.max(1,u-1)),{strokeDasharray:[l,p].join(" "),strokeDashoffset:f.toString()}}const uC=new WeakMap;function zx(e,t){const n=uC.get(t);if(n)return n;const r=e.getArrowInfo(t);let o=0,s=0;const i=r.isStraight?new lu({start:P.From(r.start.point),end:P.From(r.end.point)}):new Z2({center:P.Cast(r.handleArc.center),radius:r.handleArc.radius,start:P.Cast(r.start.point),end:P.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});if(t.props.text.trim()){const c=i.bounds,{w:l,h:u}=e.textMeasure.measureText(t.props.text,{...Ht,fontFamily:io[t.props.font],fontSize:hi[t.props.size],maxWidth:null});if(o=l,s=u,c.width>c.height){o=Math.max(Math.min(l,64),Math.min(c.width-64,l));const{w:d,h:p}=e.textMeasure.measureText(t.props.text,{...Ht,fontFamily:io[t.props.font],fontSize:hi[t.props.size],maxWidth:o});o=d,s=p}if(o>16*hi[t.props.size]){o=16*hi[t.props.size];const{w:d,h:p}=e.textMeasure.measureText(t.props.text,{...Ht,fontFamily:io[t.props.font],fontSize:hi[t.props.size],maxWidth:o});o=d,s=p}}const a=new P(o,s).addScalar(RW*2);return uC.set(t,a),a}function g$(e,t){const n=Mt[t.props.size];return DW+(n-Mt.s)*2+(n===Mt.xl?20:0)}function NV(e,t,n){const r=zx(e,t),o=g$(e,t),s=P.Nudge(n.start.point,n.end.point,o),i=P.Nudge(n.end.point,n.start.point,o),a=ox(s,i,ne.FromCenter(n.middle,r).corners);if(!a||a.length!==2)return{start:.5,end:.5};let[c,l]=a;P.Dist2(c,s)>P.Dist2(l,s)&&([l,c]=a);const u=s.add(P.Sub(n.middle,c)),d=i.add(P.Sub(n.middle,l)),p=P.Dist(n.start.point,u)/n.length,f=P.Dist(n.start.point,d)/n.length;return{start:p,end:f}}function zV(e,t,n){const r=zx(e,t),o=g$(e,t),s=Math.sign(t.props.bend),i=o/n.handleArc.radius*s,a=P.Angle(n.bodyArc.center,n.start.point)-i,c=P.Angle(n.bodyArc.center,n.end.point)+i,l=$i(n.bodyArc.center,n.bodyArc.radius,a),u=$i(n.bodyArc.center,n.bodyArc.radius,c),d=[],p=dC(n.bodyArc.center,n.bodyArc.radius,a,c,s,ne.FromCenter(l,r).corners);d.push(new wt({points:ne.FromCenter(l,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));const f=dC(n.bodyArc.center,n.bodyArc.radius,a,c,s,ne.FromCenter(u,r).corners);d.push(new wt({points:ne.FromCenter(u,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));for(const _ of[...p??[],...f??[],l,u])d.push(new px({x:_.x-3,y:_.y-3,radius:3,isFilled:!1,debugColor:"magenta",ignore:!0}));const y=(p&&hC(n.start.point,p))??n.middle,g=(f&&hC(n.end.point,f))??n.middle,w=P.Angle(n.bodyArc.center,n.start.point),S=P.Angle(n.bodyArc.center,n.end.point),v=P.Angle(n.bodyArc.center,y),b=P.Angle(n.bodyArc.center,g);if(vs(w,v,s)>vs(w,b,s))return{start:.5,end:.5,dbg:d};const E=vs(w,S,s),C=vs(w,v,s)/E,I=vs(w,b,s)/E;return{start:C,end:I,dbg:d}}function Oh(e,t){let n;const r=[],o=e.getArrowInfo(t),s=t.props.start.type==="binding",i=t.props.end.type==="binding",a=o.start.arrowhead!=="none",c=o.end.arrowhead!=="none";if(o.isStraight){const u=NV(e,t,o);let d=Ns(t.props.labelPosition,a||s?u.start:0,c||i?u.end:1);d=d>=.48&&d<=.52?.5:d,n=P.Lrp(o.start.point,o.end.point,d)}else{const u=zV(e,t,o);u.dbg&&r.push(...u.dbg);let d=Ns(t.props.labelPosition,a||s?u.start:0,c||i?u.end:1);d=d>=.48&&d<=.52?.5:d;const p=BV(P.Angle(o.bodyArc.center,o.start.point),P.Angle(o.bodyArc.center,o.end.point),Math.sign(t.props.bend),d);n=$i(o.bodyArc.center,o.bodyArc.radius,p)}const l=zx(e,t);return{box:ne.FromCenter(n,l),debugGeom:r}}function dC(e,t,n,r,o,s){const i=WS(e,t,s),a=vs(n,r,o);return i==null?void 0:i.filter(c=>{const l=vs(n,P.Angle(e,c),o);return l>=0&&l<=a})}function hC(e,t){let n=null,r=-1/0;for(const o of t){const s=P.Dist2(e,o);s>r&&(n=o,r=s)}return n}function BV(e,t,n,r){const o=vs(e,t,n);return e+o*r*n*-1}function UV(e,t,n){const r=t==="end"?e.end.point:e.start.point,o=t==="end"?e.start.point:e.end.point,s=e.isStraight?P.Dist(o,r):Math.abs(e.bodyArc.length),i=Math.max(Math.min(s/5,n*3),n);let a;if(e.isStraight)a=P.Nudge(r,o,i);else{const c=$4(r,i,e.handleArc.center,e.handleArc.radius);a=t==="end"?e.handleArc.sweepFlag?c[0]:c[1]:e.handleArc.sweepFlag?c[1]:c[0]}return P.IsNaN(a)&&(a=e.start.point),{point:r,int:a}}function HV({point:e,int:t}){const n=P.RotWith(t,e,Pe/6),r=P.RotWith(t,e,-Pe/6);return`M ${n.x} ${n.y} L ${e.x} ${e.y} L ${r.x} ${r.y}`}function KV({point:e,int:t}){const n=P.RotWith(t,e,Pe/6),r=P.RotWith(t,e,-Pe/6);return`M ${n.x} ${n.y} L ${e.x} ${e.y} L ${r.x} ${r.y} Z`}function WV({point:e,int:t}){const n=P.Sub(t,e).div(2),r=P.Add(e,P.Rot(n,ze)),o=P.Sub(e,P.Rot(n,ze));return`M ${r.x} ${r.y} L ${t.x} ${t.y} L ${o.x} ${o.y} Z`}function VV({point:e,int:t}){const n=P.Lrp(e,t,.45),r=P.Dist(n,e);return`M ${n.x-r},${n.y} a ${r},${r} 0 1,0 ${r*2},0 a ${r},${r} 0 1,0 -${r*2},0 `}function GV({point:e,int:t}){const n=P.Lrp(e,t,.75),r=P.RotWith(n,e,Pe/4),o=P.RotWith(n,e,-Pe/4),s=P.Lrp(r,o,.5);return s.add(P.Sub(s,e)),`M ${s.x} ${s.y} L ${r.x} ${r.y} ${e.x} ${e.y} L ${o.x} ${o.y} Z`}function YV({int:e,point:t}){const n=P.Lrp(t,e,.85),r=P.Sub(n,t).div(2),o=P.Add(t,P.Rot(r,ze)),s=P.Sub(t,P.Rot(r,ze)),i=P.Add(n,P.Rot(r,ze)),a=P.Sub(n,P.Rot(r,ze));return`M ${o.x} ${o.y} L ${i.x} ${i.y} L ${a.x} ${a.y} L ${s.x} ${s.y} Z`}function XV({int:e,point:t}){const n=P.Sub(e,t).div(2),r=P.Add(t,P.Rot(n,ze)),o=P.Sub(t,P.Rot(n,ze));return`M ${r.x} ${r.y} L ${o.x} ${o.y}`}function af(e,t,n){const r=t==="end"?e.end.arrowhead:e.start.arrowhead;if(r==="none")return;const o=UV(e,t,n);if(o){switch(r){case"bar":return XV(o);case"square":return YV(o);case"diamond":return GV(o);case"dot":return VV(o);case"inverted":return WV(o);case"arrow":return HV(o);case"triangle":return KV(o)}return""}}function qV(e){const{start:t,end:n,handleArc:{radius:r,largeArcFlag:o,sweepFlag:s}}=e;return`M${t.handle.x},${t.handle.y} A${r} ${r} 0 ${o} ${s} ${n.handle.x},${n.handle.y}`}function m$(e){const{start:t,end:n,bodyArc:{radius:r,largeArcFlag:o,sweepFlag:s}}=e;return`M${t.point.x},${t.point.y} A${r} ${r} 0 ${o} ${s} ${n.point.x},${n.point.y}`}function y$(e,t){return`M${e.x},${e.y}L${t.x},${t.y}`}function ZV(e){return y$(e.start.handle,e.end.handle)}function S$(e){return y$(e.start.point,e.end.point)}const QV=x.forwardRef(function({isEditing:t,text:n,handleFocus:r,handleChange:o,handleKeyDown:s,handleBlur:i,handleInputPointerDown:a,handleDoubleClick:c},l){return h.jsx("textarea",{ref:l,className:"tl-text tl-text-input",name:"text",tabIndex:-1,readOnly:!t,autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",autoSave:"off",placeholder:"",spellCheck:"true",wrap:"off",dir:"auto",datatype:"wysiwyg",defaultValue:n,onFocus:r,onChange:o,onKeyDown:s,onBlur:i,onTouchEnd:Ut,onContextMenu:t?Ut:void 0,onPointerDown:a,onDoubleClick:c,onDragStart:Ee})});function JV(e,t,n){const r=z(),o=x.useRef(null),s=x.useRef(),i=K("isEditing",()=>r.getEditingShapeId()===e,[r]),a=K("isEditingAnything",()=>!!r.getEditingShapeId(),[r]);x.useEffect(()=>{function p({shapeId:f}){requestAnimationFrame(()=>{if(f===e){const y=o.current;y&&(document.activeElement!==y&&y.focus(),y.select())}})}return r.on("select-all-text",p),()=>{r.off("select-all-text",p)}},[r,e]),x.useEffect(()=>{if(!i)return;const p=o.current;if(!p)return;document.activeElement!==p?(p.focus(),r.getInstanceState().isCoarsePointer&&p.select()):r.environment.isSafari&&(p.blur(),p.focus());function f(){var g,w;const y=(g=window.getSelection)==null?void 0:g.call(window);if(y&&y.type!=="None"){const S=[];for(let v=0;v{document.removeEventListener("selectionchange",f)}},[r,i]);const c=x.useCallback(()=>{const p=s.current;requestAnimationFrame(()=>{var g;const f=o.current,y=r.getEditingShapeId();if(y){if(f&&y===e&&(f.focus(),p&&p.length)){const w=window.getSelection();w&&p.forEach(S=>w.addRange(S))}}else(g=window.getSelection())==null||g.removeAllRanges()})},[r,e]),l=x.useCallback(p=>{if(r.getEditingShapeId()===e)switch(p.key){case"Enter":{(p.ctrlKey||p.metaKey)&&r.complete();break}}},[r,e]),u=x.useCallback(p=>{if(r.getEditingShapeId()!==e)return;let f=cc.normalizeText(p.currentTarget.value);const y=f.replace(/\t/g,Da);if(y!==f){const g=p.currentTarget.selectionStart;p.currentTarget.value=y,p.currentTarget.selectionStart=g+(y.length-f.length),p.currentTarget.selectionEnd=g+(y.length-f.length),f=y}r.updateShape({id:e,type:t,props:{text:f}})},[r,e,t]),d=x.useCallback(p=>{r.dispatch({..._n(p),type:"pointer",name:"pointer_down",target:"shape",shape:r.getShape(e)}),Ut(p)},[r,e]);return{rInput:o,handleFocus:eG,handleBlur:c,handleKeyDown:l,handleChange:u,handleInputPointerDown:d,handleDoubleClick:Ut,isEmpty:n.trim().length===0,isEditing:i,isEditingAnything:a}}function eG(){}const tg=Se.memo(function({id:t,type:n,text:r,labelColor:o,font:s,fontSize:i,lineHeight:a,align:c,verticalAlign:l,wrap:u,isSelected:d,onKeyDown:p,classNamePrefix:f,style:y,textWidth:g,textHeight:w}){const{rInput:S,isEmpty:v,isEditing:b,isEditingAnything:E,...C}=JV(t,n,r),[I,_]=x.useState(r);x.useEffect(()=>{b||_(r)},[b,r]);const k=cc.normalizeTextForDom(r),$=k.length>0,T=jV(c);if(!b&&!$)return null;const O=f||"tl-text";return h.jsx("div",{className:`${O}-label tl-text-wrapper`,"data-font":s,"data-align":c,"data-hastext":!v,"data-isediting":b,"data-iseditinganything":E,"data-textwrap":!!u,"data-isselected":d,style:{justifyContent:c==="middle"||T?"center":c,alignItems:l==="middle"?"center":l,...y},children:h.jsxs("div",{className:`${O}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:i*a+"px",minHeight:a+32,minWidth:g||0,color:o,width:g,height:w},children:[h.jsx("div",{className:`${O} tl-text tl-text-content`,dir:"ltr",children:k}),(E||d)&&h.jsx(QV,{ref:S,text:r,isEditing:b,...C,handleKeyDown:p??C.handleKeyDown},I)]})})}),tG=x.memo(function({id:t,text:n,size:r,font:o,position:s,width:i,isSelected:a,labelColor:c}){const l=xt();return h.jsx(tg,{id:t,classNamePrefix:"tl-arrow",type:"arrow",font:o,fontSize:hi[r],lineHeight:Ht.lineHeight,align:"middle",verticalAlign:"middle",text:n,labelColor:l[c].solid,textWidth:i,isSelected:a,style:{transform:`translate(${s.x}px, ${s.y}px)`}})});let nG=0;class Dh extends Fr{constructor(){super(...arguments);m(this,"canEdit",()=>!0);m(this,"canBind",()=>!1);m(this,"canSnap",()=>!1);m(this,"hideResizeHandles",()=>!0);m(this,"hideRotateHandle",()=>!0);m(this,"hideSelectionBoundsBg",()=>!0);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"onHandleDrag",(n,{handle:r,isPrecise:o})=>{const s=r.id;if(s==="middle"){const{start:w,end:S}=jr(this.editor,n),v=P.Sub(S,w),b=P.Per(v),E=P.Med(S,w),C=P.Sub(E,b),I=P.Add(E,b),_=P.NearestPointOnLineSegment(C,I,r,!1);let k=P.Dist(_,E);return P.Clockwise(_,S,E)&&(k*=-1),{id:n.id,type:n.type,props:{bend:k}}}const i=Ye(n);if(this.editor.inputs.ctrlKey)return i.props[s]={type:"point",x:r.x,y:r.y},i;const a=this.editor.getShapePageTransform(n.id).applyToPoint(r),c=this.editor.getShapeAtPoint(a,{hitInside:!0,hitFrameInside:!0,margin:0,filter:w=>!w.isLocked&&this.editor.getShapeUtil(w).canBind(w)});if(!c)return i.props[s]={type:"point",x:r.x,y:r.y},i;const l=this.editor.getShapeGeometry(c),u=ne.ZeroFix(l.bounds),p=this.editor.getShapePageTransform(i.id).applyToPoint(r),f=this.editor.getPointInShapeSpace(c,p);let y=o;if(!y){const w=i.props[s];(w.type==="point"||w.type==="binding"&&c.id!==w.boundShapeId)&&(y=this.editor.inputs.pointerVelocity.len()<.5)}if(!o){l.isClosed||(y=!0);const w=i.props[s==="start"?"end":"start"];w.type==="binding"&&c.id===w.boundShapeId&&w.isPrecise&&(y=!0)}const g={x:(f.x-u.minX)/u.width,y:(f.y-u.minY)/u.height};return y&&P.Dist(f,u.center){const r=n.props.start.type==="binding"?n.props.start.boundShapeId:null,o=n.props.end.type==="binding"?n.props.end.boundShapeId:null,s=jr(this.editor,n),i=this.editor.getShapePageTransform(n.id),a=this.editor.getSelectedShapeIds(),c=new Set;r&&(c.add(r),this.editor.getShapeAncestors(r).forEach(u=>c.add(u.id))),o&&(c.add(o),this.editor.getShapeAncestors(o).forEach(u=>c.add(u.id)));for(const u of a)if(c.has(u))return;let l=n;fC.set(n,{pagePosition:i.applyToPoint(n),terminalBindings:Mf(s,(u,d)=>{const p=n.props[u];return p.type!=="binding"?null:{binding:p,shapePosition:d,pagePosition:i.applyToPoint(d)}})});for(const u of["start","end"]){const d=n.props[u];d.type==="binding"&&(l={...n,props:{...n.props,[u]:{...d,isPrecise:!0}}})}return l});m(this,"onTranslate",(n,r)=>{const o=fC.get(n);if(!o)return;const s=this.editor.getShapePageTransform(r.id),i=P.Sub(s.applyToPoint(r),o.pagePosition);let a=r;for(const[c,l]of An(o.terminalBindings)){if(!l)continue;const u=P.Add(l.pagePosition,P.Mul(i,.5)),d=this.editor.getShapeAtPoint(u,{hitInside:!0,hitFrameInside:!0,margin:0,filter:p=>!p.isLocked&&this.editor.getShapeUtil(p).canBind(p)});if((d==null?void 0:d.id)===l.binding.boundShapeId){const p=ne.ZeroFix(this.editor.getShapeGeometry(d).bounds),f=this.editor.getPointInShapeSpace(d,u),y={x:(f.x-p.minX)/p.width,y:(f.y-p.minY)/p.height};a={...a,props:{...a.props,[c]:{...l.binding,isPrecise:!0,normalizedAnchor:y}}}}else a={...a,props:{...a.props,[c]:{type:"point",x:l.shapePosition.x,y:l.shapePosition.y}}}}return a});m(this,"onResize",(n,r)=>{const{scaleX:o,scaleY:s}=r,i=jr(this.editor,n),{start:a,end:c}=Ye(n.props);let{bend:l}=n.props;a.type==="point"&&(a.x=i.start.x*o,a.y=i.start.y*s),c.type==="point"&&(c.x=i.end.x*o,c.y=i.end.y*s);const u=Math.abs(o),d=Math.abs(s);return o<0&&s>=0?(l!==0&&(l*=-1,l*=Math.max(u,d)),a.type==="binding"&&(a.normalizedAnchor.x=1-a.normalizedAnchor.x),c.type==="binding"&&(c.normalizedAnchor.x=1-c.normalizedAnchor.x)):o>=0&&s<0?(l!==0&&(l*=-1,l*=Math.max(u,d)),a.type==="binding"&&(a.normalizedAnchor.y=1-a.normalizedAnchor.y),c.type==="binding"&&(c.normalizedAnchor.y=1-c.normalizedAnchor.y)):o>=0&&s>=0?l!==0&&(l*=Math.max(u,d)):o<0&&s<0&&(l!==0&&(l*=Math.max(u,d)),a.type==="binding"&&(a.normalizedAnchor.x=1-a.normalizedAnchor.x,a.normalizedAnchor.y=1-a.normalizedAnchor.y),c.type==="binding"&&(c.normalizedAnchor.x=1-c.normalizedAnchor.x,c.normalizedAnchor.y=1-c.normalizedAnchor.y)),{props:{start:a,end:c,bend:l}}});m(this,"onDoubleClickHandle",(n,r)=>{switch(r.id){case"start":return{id:n.id,type:n.type,props:{...n.props,arrowheadStart:n.props.arrowheadStart==="none"?"arrow":"none"}};case"end":return{id:n.id,type:n.type,props:{...n.props,arrowheadEnd:n.props.arrowheadEnd==="none"?"arrow":"none"}}}});m(this,"onEditEnd",n=>{const{id:r,type:o,props:{text:s}}=n;s.trimEnd()!==n.props.text&&this.editor.updateShapes([{id:r,type:o,props:{text:s.trimEnd()}}])})}getDefaultProps(){return{dash:"draw",size:"m",fill:"none",color:"black",labelColor:"black",bend:0,start:{type:"point",x:0,y:0},end:{type:"point",x:2,y:0},arrowheadStart:"none",arrowheadEnd:"arrow",text:"",labelPosition:.5,font:"draw"}}getGeometry(n){const r=this.editor.getArrowInfo(n),o=[],s=r.isStraight?new lu({start:P.From(r.start.point),end:P.From(r.end.point)}):new Z2({center:P.Cast(r.handleArc.center),radius:r.handleArc.radius,start:P.Cast(r.start.point),end:P.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});let i;if(n.props.text.trim()){const a=Oh(this.editor,n);o.push(...a.debugGeom),i=new Wo({x:a.box.x,y:a.box.y,width:a.box.w,height:a.box.h,isFilled:!0,isLabel:!0})}return new Br({children:[...i?[s,i]:[s],...o]})}getHandles(n){const r=this.editor.getArrowInfo(n);return[{id:"start",type:"vertex",index:"a0",x:r.start.handle.x,y:r.start.handle.y,canBind:!0},{id:"middle",type:"virtual",index:"a2",x:r.middle.x,y:r.middle.y,canBind:!1},{id:"end",type:"vertex",index:"a3",x:r.end.handle.x,y:r.end.handle.y,canBind:!0}].filter(Boolean)}component(n){const r=this.editor.getOnlySelectedShape(),o=this.editor.isInAny("select.idle","select.pointing_handle","select.dragging_handle","select.translating","arrow.dragging")&&!this.editor.getInstanceState().isReadonly,s=this.editor.getArrowInfo(n);if(!(s!=null&&s.isValid))return null;const i=Oh(this.editor,n),a=n.id===this.editor.getOnlySelectedShapeId(),l=this.editor.getEditingShapeId()===n.id||n.props.text;return h.jsxs(h.Fragment,{children:[h.jsx(zs,{id:n.id,style:{minWidth:50,minHeight:50},children:h.jsx(pC,{shape:n,shouldDisplayHandles:o&&r===n})}),l&&h.jsx(tG,{id:n.id,text:n.props.text,font:n.props.font,size:n.props.size,position:i.box.center,width:i.box.w,isSelected:a,labelColor:n.props.labelColor})]})}indicator(n){const{start:r,end:o}=jr(this.editor,n),s=this.editor.getArrowInfo(n),i=this.editor.getShapeGeometry(n),a=i.bounds,c=n.props.text.trim()?i.children[1]:null,l=Vf(n.id);if(!s||P.Equals(r,o))return null;const u=Mt[n.props.size],d=s.start.arrowhead&&af(s,"start",u),p=s.end.arrowhead&&af(s,"end",u),f=s.isStraight?S$(s):m$(s),y=d&&s.start.arrowhead!=="arrow"||p&&s.end.arrowhead!=="arrow"||!!c,g=(n.id+"_clip").replace(":","_");return l&&c?h.jsx("rect",{x:j(c.x),y:j(c.y),width:c.w,height:c.h,rx:3.5,ry:3.5}):h.jsxs("g",{children:[y&&h.jsx("defs",{children:h.jsxs("mask",{id:g,children:[h.jsx("rect",{x:a.minX-100,y:a.minY-100,width:a.w+200,height:a.h+200,fill:"white"}),c&&h.jsx("rect",{x:j(c.x),y:j(c.y),width:c.w,height:c.h,fill:"black",rx:3.5,ry:3.5}),d&&h.jsx("path",{d,fill:s.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),p&&h.jsx("path",{d:p,fill:s.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),h.jsxs("g",{...y?{mask:`url(#${g})`}:void 0,children:[y&&h.jsx("rect",{x:a.minX-100,y:a.minY-100,width:a.width+200,height:a.height+200,opacity:0}),h.jsx("path",{d:f})]}),d&&h.jsx("path",{d}),p&&h.jsx("path",{d:p}),c&&h.jsx("rect",{x:j(c.x),y:j(c.y),width:c.w,height:c.h,rx:3.5,ry:3.5})]})}toSvg(n,r){r.addExportDef(Fx(n.props.fill)),n.props.text&&r.addExportDef(lc(n.props.font));const o=Jo(r);return h.jsxs(h.Fragment,{children:[h.jsx(pC,{shape:n,shouldDisplayHandles:!1}),h.jsx(eg,{fontSize:hi[n.props.size],font:n.props.font,align:"middle",verticalAlign:"middle",text:n.props.text,labelColor:o[n.props.labelColor].solid,bounds:Oh(this.editor,n).box,padding:4})]})}getCanvasSvgDefs(){return[Nx(),{key:"arrow:dot",component:oG},{key:"arrow:cross",component:sG}]}}m(Dh,"type","arrow"),m(Dh,"props",gk),m(Dh,"migrations",mk);function rG(e,t){const n=e.getArrowInfo(t);return n.isStraight?P.Dist(n.start.handle,n.end.handle):Math.abs(n.handleArc.length)}const pC=or(function({shape:t,shouldDisplayHandles:n}){const r=z(),o=xt(),s=r.getArrowInfo(t),i=ne.ZeroFix(r.getShapeGeometry(t).bounds),a=Se.useMemo(()=>r.environment.isSafari?nG+=1:0,[t]);if(!(s!=null&&s.isValid))return null;const c=Mt[t.props.size],l=s.start.arrowhead&&af(s,"start",c),u=s.end.arrowhead&&af(s,"end",c),d=s.isStraight?S$(s):m$(s);let p=null;if(n){const{strokeDasharray:E,strokeDashoffset:C}=Vo(rG(r,t),2,{end:"skip",start:"skip",lengthRatio:2.5});p=t.props.start.type==="binding"||t.props.end.type==="binding"?h.jsx("path",{className:"tl-arrow-hint",d:s.isStraight?ZV(s):qV(s),strokeDasharray:E,strokeDashoffset:C,strokeWidth:2,markerStart:t.props.start.type==="binding"?t.props.start.isExact?"":t.props.start.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",markerEnd:t.props.end.type==="binding"?t.props.end.isExact?"":t.props.end.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",opacity:.16}):null}const{strokeDasharray:f,strokeDashoffset:y}=Vo(s.isStraight?s.length:Math.abs(s.bodyArc.length),c,{style:t.props.dash}),g=Oh(r,t),w=!(s.start.arrowhead==="none"||s.start.arrowhead==="arrow"),S=!(s.end.arrowhead==="none"||s.end.arrowhead==="arrow"),v=(t.id+"_clip_"+a).replace(":","_");return h.jsxs(h.Fragment,{children:[h.jsx("defs",{children:h.jsxs("mask",{id:v,children:[h.jsx("rect",{x:j(-100+i.minX),y:j(-100+i.minY),width:j(i.width+200),height:j(i.height+200),fill:"white"}),t.props.text.trim()&&h.jsx("rect",{x:g.box.x,y:g.box.y,width:g.box.w,height:g.box.h,fill:"black",rx:4,ry:4}),l&&w&&h.jsx("path",{d:l,fill:s.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),u&&S&&h.jsx("path",{d:u,fill:s.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),h.jsxs("g",{fill:"none",stroke:o[t.props.color].solid,strokeWidth:c,strokeLinejoin:"round",strokeLinecap:"round",pointerEvents:"none",children:[p,h.jsxs("g",{mask:`url(#${v})`,children:[h.jsx("rect",{x:j(i.minX-100),y:j(i.minY-100),width:j(i.width+200),height:j(i.height+200),opacity:0}),h.jsx("path",{d,strokeDasharray:f,strokeDashoffset:y})]}),l&&w&&t.props.fill!=="none"&&h.jsx(Pt,{theme:o,d:l,color:t.props.color,fill:t.props.fill}),u&&S&&t.props.fill!=="none"&&h.jsx(Pt,{theme:o,d:u,color:t.props.color,fill:t.props.fill}),l&&h.jsx("path",{d:l}),u&&h.jsx("path",{d:u})]})]})}),fC=new WeakMap;function oG(){return h.jsx("marker",{id:"arrowhead-dot",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"0",children:h.jsx("circle",{cx:"3",cy:"3",r:"2",strokeDasharray:"100%"})})}function sG(){return h.jsxs("marker",{id:"arrowhead-cross",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"auto",children:[h.jsx("line",{x1:"1.5",y1:"1.5",x2:"4.5",y2:"4.5",strokeDasharray:"100%"}),h.jsx("line",{x1:"1.5",y1:"4.5",x2:"4.5",y2:"1.5",strokeDasharray:"100%"})]})}const gC="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 uc({url:e,zoomLevel:t}){return h.jsx("a",{className:ue("tl-hyperlink-button",{"tl-hyperlink-button__hidden":t<.32}),href:e,target:"_blank",rel:"noopener noreferrer",onPointerDown:Ut,onPointerUp:Ut,title:e,draggable:!1,children:h.jsx("div",{className:"tl-hyperlink-button__icon",style:{mask:`url("${gC}") center 100% / 100% no-repeat`,WebkitMask:`url("${gC}") center 100% / 100% no-repeat`}})})}const iG=[{offsetX:0,offsetY:2,blur:4,spread:0,color:"#00000029"},{offsetX:0,offsetY:3,blur:6,spread:0,color:"#0000001f"}];function Bx(e){return iG.map(n=>{const{offsetX:r,offsetY:o,blur:s,spread:i,color:a}=n,c=new P(r,o),{x:l,y:u}=c.rot(-e);return`${l}px ${u}px ${s}px ${i}px ${a}`}).join(", ")}class Rh extends Pc{constructor(){super(...arguments);m(this,"canResize",()=>!1);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"onBeforeCreate",n=>{mC(this.editor,n)});m(this,"onBeforeUpdate",(n,r)=>{if(n.props.url!==r.props.url)if(er.isValid(r.props.url))mC(this.editor,r);else return{...r,props:{...r.props,url:n.props.url}}})}getDefaultProps(){return{url:"",w:300,h:320,assetId:null}}component(n){const r=n.props.assetId?this.editor.getAsset(n.props.assetId):null,o=this.editor.getShapePageTransform(n).rotation(),s=aG(n);return h.jsx(Ai,{children:h.jsxs("div",{className:"tl-bookmark__container",style:{boxShadow:Bx(o)},children:[h.jsxs("div",{className:"tl-bookmark__image_container",children:[r!=null&&r.props.image?h.jsx("img",{className:"tl-bookmark__image",draggable:!1,src:r==null?void 0:r.props.image,alt:(r==null?void 0:r.props.title)||""}):h.jsx("div",{className:"tl-bookmark__placeholder"}),h.jsx(uc,{url:n.props.url,zoomLevel:this.editor.getZoomLevel()})]}),h.jsxs("div",{className:"tl-bookmark__copy_container",children:[(r==null?void 0:r.props.title)&&h.jsx("h2",{className:"tl-bookmark__heading",children:Ol((r==null?void 0:r.props.title)||"",54)}),(r==null?void 0:r.props.description)&&h.jsx("p",{className:"tl-bookmark__description",children:Ol((r==null?void 0:r.props.description)||"",128)}),h.jsx("a",{className:"tl-bookmark__link",href:n.props.url||"",target:"_blank",rel:"noopener noreferrer",onPointerDown:Ut,onPointerUp:Ut,onClick:Ut,children:Ol(s,45)})]})]})})}indicator(n){return h.jsx("rect",{width:j(n.props.w),height:j(n.props.h),rx:"6",ry:"6"})}}m(Rh,"type","bookmark"),m(Rh,"props",yk),m(Rh,"migrations",Sk);const aG=e=>{try{const t=new URL(e.props.url),n=t.pathname.replace(/\/*$/,"");return`${t.hostname}${n}`}catch{return e.props.url}};function mC(e,t){const{url:n}=t.props,r=Si.createId(AS(n));e.getAsset(r)?t.props.assetId!==r&&e.updateShapes([{id:t.id,type:t.type,props:{assetId:r}}]):(e.updateShapes([{id:t.id,type:t.type,props:{assetId:null}}]),cG(e,t))}const cG=H_(async(e,t)=>{const{url:n}=t.props,r=await e.getAssetForExternalContent({type:"url",url:n});r&&e.batch(()=>{e.createAssets([r]),e.updateShapes([{id:t.id,type:t.type,props:{assetId:r.id}}])})},500);function ji(e,t=!1){const n=e.length;if(n<2)return"";let r=e[0].point,o=e[1].point;if(n===2)return`M${Ft(r)}L${Ft(o)}`;let s="";for(let i=2,a=n-1;i3?"T":""}${s}L${Ft(e[n-1].point)}`}function lG(e,t={}){const{start:n={},end:r={}}=t,{cap:o=!0}=n,{cap:s=!0}=r;_t(!n.taper&&!r.taper,"cap taper not supported here"),_t(!n.easing&&!r.easing,"cap easing not supported here"),_t(o&&s,"cap must be true");const i=lo(e,t);Jf(i,t);const a=uG(i);let c="";for(const l of a)c+=hG(l,t);return c}function uG(e){if(e.length<=2)return[e];const t=[];let n=[e[0]],r=P.Sub(e[1].point,e[0].point).uni(),o,s,i,a,c;for(let l=1,u=e.length;l.7)&&(P.Dist2(i.point,a.point)+P.Dist2(a.point,c.point))/((i.radius+a.radius+c.radius)/3)**2<1.5){n.push(a),t.push(Zm(n)),n=[a];continue}}return n.push(e[e.length-1]),t.push(Zm(n)),t}function Zm(e){const t=e[0];let n;for(;e.length>2&&(n=e[1],P.Dist2(t.point,n.point)<((t.radius+n.radius)/2*.5)**2);)e.splice(1,1);const r=e[e.length-1];let o;for(;e.length>2&&(o=e[e.length-2],P.Dist2(r.point,o.point)<((r.radius+o.radius)/2*.5)**2);)e.splice(e.length-2,1);return e.length>1&&(e[0]={...e[0],vector:P.Sub(e[0].point,e[1].point).uni()},e[e.length-1]={...e[e.length-1],vector:P.Sub(e[e.length-2].point,e[e.length-1].point).uni()}),e}function dG(e,t,n){return"M "+e+" "+t+" m -"+n+", 0 a "+n+","+n+" 0 1,1 "+n*2+",0 a "+n+","+n+" 0 1,1 -"+n*2+",0"}function hG(e,t={}){if(e.length===0)return"";if(e.length===1)return dG(e[0].point.x,e[0].point.y,e[0].radius);const{left:n,right:r}=e$(e,t);r.reverse();let o=`M${Ft(n[0])}T`;for(let s=1;se.getZoomLevel()<.35,[e])}const pG=e=>e*.65+w5(e*Pe/2)*.35,fG=e=>({size:1+e,thinning:.5,streamline:.62+(1+e)/8*.06,smoothing:.62,easing:nn.easeOutSine,simulatePressure:!0}),gG=e=>({size:1+e*1.2,thinning:.62,streamline:.62,smoothing:.62,simulatePressure:!1,easing:pG}),yC=e=>({size:1+e,thinning:0,streamline:.62+(1+e)/8*.06,smoothing:.62,simulatePressure:!1,easing:nn.linear});function hv({strokeWidth:e,showAsComplete:t}){return{size:1+e,thinning:0,streamline:.5,smoothing:.5,simulatePressure:!1,easing:nn.easeOutSine,last:t}}function pv(e,t,n,r){return{...r?yC(t):e.dash==="draw"?e.isPen?gG(t):fG(t):yC(t),last:e.isComplete||n}}function hu(e){const t=[];for(const n of e)if(n.type==="free"||n.points.length<2)t.push(...n.points.map(P.Cast));else{const r=Math.max(4,Math.floor(P.Dist(n.points[0],n.points[1])/16));t.push(...P.PointsBetween(n.points[0],n.points[1],r))}return t}function mG(e,t){return{draw:"none",solid:"none",dotted:`0.1 ${t*2}`,dashed:`${t*2} ${t*2}`}[e.props.dash]}class Lh extends Fr{constructor(){super(...arguments);m(this,"hideResizeHandles",n=>Qm(n));m(this,"hideRotateHandle",n=>Qm(n));m(this,"hideSelectionBoundsFg",n=>Qm(n));m(this,"onResize",(n,r)=>{const{scaleX:o,scaleY:s}=r,i=[];for(const a of n.props.segments)i.push({...a,points:a.points.map(({x:c,y:l,z:u})=>({x:Vp(o*c),y:Vp(s*l),z:u}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",fill:"none",dash:"draw",size:"m",isComplete:!1,isClosed:!1,isPen:!1}}getGeometry(n){const r=hu(n.props.segments),o=Mt[n.props.size];if(n.props.segments.length===1){const i=ne.FromPoints(r);if(i.widthi.point);return n.props.isClosed?new wt({points:s,isFilled:n.props.fill!=="none"}):new Ki({points:s})}component(n){return h.jsx(zs,{id:n.id,children:h.jsx(SC,{shape:n,forceSolid:du()})})}indicator(n){var d;const r=du(),o=Mt[n.props.size],s=hu(n.props.segments);let i=o;!r&&!n.props.isPen&&n.props.dash==="draw"&&s.length===1&&(i+=Ys(n.id)()*(o/6));const a=n.props.isComplete||((d=Wn(n.props.segments))==null?void 0:d.type)==="straight",c=pv(n.props,i,a,!0),l=lo(s,c),u=l.length>1?ji(l,n.props.isClosed):v$(s[0],i);return h.jsx("path",{d:u})}toSvg(n,r){return r.addExportDef(Fx(n.props.fill)),h.jsx(SC,{shape:n,forceSolid:!1})}getCanvasSvgDefs(){return[Nx()]}expandSelectionOutlinePx(n){const r=n.props.dash==="draw"?1.6:1;return Mt[n.props.size]*r/2}}m(Lh,"type","draw"),m(Lh,"props",xk),m(Lh,"migrations",wk);function v$(e,t){const n=(t+1)*.5;return`M ${e.x} ${e.y} m -${n}, 0 a ${n},${n} 0 1,0 ${n*2},0 a ${n},${n} 0 1,0 -${n*2},0`}function Qm(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function SC({shape:e,forceSolid:t}){var d;const n=xt(),r=Mt[e.props.size],o=hu(e.props.segments),s=e.props.isComplete||((d=Wn(e.props.segments))==null?void 0:d.type)==="straight";let i=r;!t&&!e.props.isPen&&e.props.dash==="draw"&&o.length===1&&(i+=Ys(e.id)()*(r/6));const a=pv(e.props,i,s,t);if(!t&&e.props.dash==="draw")return h.jsxs(h.Fragment,{children:[e.props.isClosed&&e.props.fill&&o.length>1?h.jsx(Pt,{theme:n,fill:e.props.isClosed?e.props.fill:"none",color:e.props.color,d:ji(lo(o,a),e.props.isClosed)}):null,h.jsx("path",{d:lG(o,a),strokeLinecap:"round",fill:n[e.props.color].solid})]});const c=lo(o,a),l=c.length<2,u=l?v$(o[0],0):ji(c,e.props.isClosed);return h.jsxs(h.Fragment,{children:[h.jsx(Pt,{theme:n,color:e.props.color,fill:l||e.props.isClosed?e.props.fill:"none",d:u}),h.jsx("path",{d:u,strokeLinecap:"round",fill:l?n[e.props.color].solid:"none",stroke:n[e.props.color].solid,strokeWidth:r,strokeDasharray:l?"none":mG(e,r),strokeDashoffset:"0"})]})}function yG(e,t,n={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=t,{minWidth:a=1,maxWidth:c=1/0,minHeight:l=1,maxHeight:u=1/0}=n;let d=e.props.w*s,p=e.props.h*i;const f=new P(0,0);if(d>0){if(d0){if(pObject.entries(e).filter(([t,n])=>n).map(([t])=>t).join(" ");class Fh extends Pc{constructor(){super(...arguments);m(this,"hideSelectionBoundsFg",n=>!this.canResize(n));m(this,"canEdit",()=>!0);m(this,"canResize",n=>{var r,o;return!!((o=(r=Cs(n.props.url))==null?void 0:r.definition)!=null&&o.doesResize)});m(this,"canEditInReadOnly",()=>!0);m(this,"isAspectRatioLocked",n=>{const r=Cs(n.props.url);return(r==null?void 0:r.definition.isAspectRatioLocked)??!1});m(this,"onResize",(n,r)=>{const o=this.isAspectRatioLocked(n),s=Cs(n.props.url);let i=(s==null?void 0:s.definition.minWidth)??200,a=(s==null?void 0:s.definition.minHeight)??200;if(o){const c=n.props.w/n.props.h;c>1?i*=c:a/=c}return yG(n,r,{minWidth:i,minHeight:a})})}getDefaultProps(){return{w:300,h:300,url:""}}component(n){const{w:r,h:o,url:s}=n.props,i=Vf(n.id),a=x.useMemo(()=>o$(s),[s]),c=K("is hovering",()=>{const{editingShapeId:p,hoveredShapeId:f}=this.editor.getCurrentPageState();if(p&&f!==p){const y=this.editor.getShape(p);if(y&&this.editor.isShapeOfType(y,"embed"))return!0}return!1},[]),l=this.editor.getShapePageTransform(n).rotation(),u=i||c;if((a==null?void 0:a.definition.type)==="github_gist"){const p=a.url.split("/").pop();if(!p)throw Error("No gist id!");return h.jsx(Ai,{className:"tl-embed-container",id:n.id,children:h.jsx(vG,{id:p,width:j(r),height:j(o),isInteractive:u,pageRotation:l})})}const d=SG({...a5,...(a==null?void 0:a.definition.overridePermissions)??{}});return h.jsx(Ai,{className:"tl-embed-container",id:n.id,children:a!=null&&a.definition?h.jsx("iframe",{className:"tl-embed",sandbox:d,src:a.embedUrl,width:j(r),height:j(o),draggable:!1,frameBorder:"0",referrerPolicy:"no-referrer-when-downgrade",style:{border:0,pointerEvents:u?"auto":"none",zIndex:u?"":"-1",boxShadow:Bx(l),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:a==null?void 0:a.definition.backgroundColor}}):null})}indicator(n){const r=x.useMemo(()=>Cs(n.props.url),[n.props.url]);return h.jsx("rect",{width:j(n.props.w),height:j(n.props.h),rx:(r==null?void 0:r.definition.overrideOutlineRadius)??8,ry:(r==null?void 0:r.definition.overrideOutlineRadius)??8})}}m(Fh,"type","embed"),m(Fh,"props",bk),m(Fh,"migrations",Pk);function vG({id:e,file:t,isInteractive:n,width:r,height:o,style:s,pageRotation:i}){return h.jsx("iframe",{className:"tl-embed",draggable:!1,width:j(r),height:j(o),frameBorder:"0",scrolling:"no",seamless:!0,referrerPolicy:"no-referrer-when-downgrade",style:{...s,pointerEvents:n?"all":"none",zIndex:n?"":"-1",boxShadow:Bx(i)},srcDoc:`