var XL=Object.defineProperty;var qL=(e,n,t)=>n in e?XL(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var m=(e,n,t)=>qL(e,typeof n!="symbol"?n+"":n,t);function ZL(e,n){for(var t=0;tr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.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 t(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=t(o);fetch(o.href,s)}})();var sn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ei(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var cE={exports:{}},_f={},uE={exports:{}},ve={};/** * @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 Iu=Symbol.for("react.element"),QL=Symbol.for("react.portal"),JL=Symbol.for("react.fragment"),e$=Symbol.for("react.strict_mode"),t$=Symbol.for("react.profiler"),n$=Symbol.for("react.provider"),r$=Symbol.for("react.context"),o$=Symbol.for("react.forward_ref"),s$=Symbol.for("react.suspense"),i$=Symbol.for("react.memo"),a$=Symbol.for("react.lazy"),_b=Symbol.iterator;function l$(e){return e===null||typeof e!="object"?null:(e=_b&&e[_b]||e["@@iterator"],typeof e=="function"?e:null)}var dE={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},hE=Object.assign,pE={};function Il(e,n,t){this.props=e,this.context=n,this.refs=pE,this.updater=t||dE}Il.prototype.isReactComponent={};Il.prototype.setState=function(e,n){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,n,"setState")};Il.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function fE(){}fE.prototype=Il.prototype;function ex(e,n,t){this.props=e,this.context=n,this.refs=pE,this.updater=t||dE}var tx=ex.prototype=new fE;tx.constructor=ex;hE(tx,Il.prototype);tx.isPureReactComponent=!0;var Tb=Array.isArray,gE=Object.prototype.hasOwnProperty,nx={current:null},mE={key:!0,ref:!0,__self:!0,__source:!0};function yE(e,n,t){var r,o={},s=null,i=null;if(n!=null)for(r in n.ref!==void 0&&(i=n.ref),n.key!==void 0&&(s=""+n.key),n)gE.call(n,r)&&!mE.hasOwnProperty(r)&&(o[r]=n[r]);var a=arguments.length-2;if(a===1)o.children=t;else if(1>>1,le=z[J];if(0>>1;Jo(ae,X))Ueo(Ae,ae)?(z[J]=Ae,z[Ue]=X,J=Ue):(z[J]=ae,z[Me]=X,J=Me);else if(Ueo(Ae,X))z[J]=Ae,z[Ue]=X,J=Ue;else break e}}return U}function o(z,U){var X=z.sortIndex-U.sortIndex;return X!==0?X:z.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 l=[],c=[],d=1,h=null,p=3,f=!1,S=!1,g=!1,x=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function b(z){for(var U=t(c);U!==null;){if(U.callback===null)r(c);else if(U.startTime<=z)r(c),U.sortIndex=U.expirationTime,n(l,U);else break;U=t(c)}}function E(z){if(g=!1,b(z),!S)if(t(l)!==null)S=!0,W(I);else{var U=t(c);U!==null&&K(E,U.startTime-z)}}function I(z,U){S=!1,g&&(g=!1,y(T),T=-1),f=!0;var X=p;try{for(b(U),h=t(l);h!==null&&(!(h.expirationTime>U)||z&&!j());){var J=h.callback;if(typeof J=="function"){h.callback=null,p=h.priorityLevel;var le=J(h.expirationTime<=U);U=e.unstable_now(),typeof le=="function"?h.callback=le:h===t(l)&&r(l),b(U)}else r(l);h=t(l)}if(h!==null)var ye=!0;else{var Me=t(c);Me!==null&&K(E,Me.startTime-U),ye=!1}return ye}finally{h=null,p=X,f=!1}}var C=!1,k=null,T=-1,O=5,_=-1;function j(){return!(e.unstable_now()-_z||125J?(z.sortIndex=X,n(c,z),t(l)===null&&z===t(c)&&(g?(y(T),T=-1):g=!0,K(E,X-J))):(z.sortIndex=le,n(l,z),S||f||(S=!0,W(I))),z},e.unstable_shouldYield=j,e.unstable_wrapCallback=function(z){var U=p;return function(){var X=p;p=U;try{return z.apply(this,arguments)}finally{p=X}}}})(bE);wE.exports=bE;var x$=wE.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 w$=P,rr=x$;function q(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Qy=Object.prototype.hasOwnProperty,b$=/^[: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]*$/,jb={},Ab={};function P$(e){return Qy.call(Ab,e)?!0:Qy.call(jb,e)?!1:b$.test(e)?Ab[e]=!0:(jb[e]=!0,!1)}function C$(e,n,t,r){if(t!==null&&t.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function I$(e,n,t,r){if(n===null||typeof n>"u"||C$(e,n,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function Sn(e,n,t,r,o,s,i){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=s,this.removeEmptyString=i}var Gt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Gt[e]=new Sn(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];Gt[n]=new Sn(n,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Gt[e]=new Sn(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Gt[e]=new Sn(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){Gt[e]=new Sn(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Gt[e]=new Sn(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Gt[e]=new Sn(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Gt[e]=new Sn(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Gt[e]=new Sn(e,5,!1,e.toLowerCase(),null,!1,!1)});var ox=/[\-:]([a-z])/g;function sx(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 n=e.replace(ox,sx);Gt[n]=new Sn(n,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(ox,sx);Gt[n]=new Sn(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(ox,sx);Gt[n]=new Sn(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Gt[e]=new Sn(e,1,!1,e.toLowerCase(),null,!1,!1)});Gt.xlinkHref=new Sn("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Gt[e]=new Sn(e,1,!1,e.toLowerCase(),null,!0,!0)});function ix(e,n,t,r){var o=Gt.hasOwnProperty(n)?Gt[n]:null;(o!==null?o.type!==0:r||!(2a||o[i]!==s[a]){var l=` `+o[i].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=i&&0<=a);break}}}finally{Wg=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?yc(e):""}function E$(e){switch(e.tag){case 5:return yc(e.type);case 16:return yc("Lazy");case 13:return yc("Suspense");case 19:return yc("SuspenseList");case 0:case 2:case 15:return e=Gg(e.type,!1),e;case 11:return e=Gg(e.type.render,!1),e;case 1:return e=Gg(e.type,!0),e;default:return""}}function nS(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 ka:return"Fragment";case Ea:return"Portal";case Jy:return"Profiler";case ax:return"StrictMode";case eS:return"Suspense";case tS:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case IE:return(e.displayName||"Context")+".Consumer";case CE:return(e._context.displayName||"Context")+".Provider";case lx:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cx:return n=e.displayName||null,n!==null?n:nS(e.type)||"Memo";case ws:n=e._payload,e=e._init;try{return nS(e(n))}catch{}}return null}function k$(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return nS(n);case 8:return n===ax?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function Ks(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function kE(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function _$(e){var n=kE(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var o=t.get,s=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return o.call(this)},set:function(i){r=""+i,s.call(this,i)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function dd(e){e._valueTracker||(e._valueTracker=_$(e))}function _E(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=kE(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function gp(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 rS(e,n){var t=n.checked;return pt({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function Db(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=Ks(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function TE(e,n){n=n.checked,n!=null&&ix(e,"checked",n,!1)}function oS(e,n){TE(e,n);var t=Ks(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?sS(e,n.type,t):n.hasOwnProperty("defaultValue")&&sS(e,n.type,Ks(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function Rb(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function sS(e,n,t){(n!=="number"||gp(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var Sc=Array.isArray;function Ya(e,n,t,r){if(e=e.options,n){n={};for(var o=0;o"+n.valueOf().toString()+"",n=hd.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function Gc(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var Tc={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},T$=["Webkit","ms","Moz","O"];Object.keys(Tc).forEach(function(e){T$.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Tc[n]=Tc[e]})});function OE(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||Tc.hasOwnProperty(e)&&Tc[e]?(""+n).trim():n+"px"}function DE(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,o=OE(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,o):e[t]=o}}var M$=pt({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function lS(e,n){if(n){if(M$[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(q(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(q(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(q(61))}if(n.style!=null&&typeof n.style!="object")throw Error(q(62))}}function cS(e,n){if(e.indexOf("-")===-1)return typeof n.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var uS=null;function ux(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var dS=null,Xa=null,qa=null;function Fb(e){if(e=_u(e)){if(typeof dS!="function")throw Error(q(280));var n=e.stateNode;n&&(n=Of(n),dS(e.stateNode,e.type,n))}}function RE(e){Xa?qa?qa.push(e):qa=[e]:Xa=e}function LE(){if(Xa){var e=Xa,n=qa;if(qa=Xa=null,Fb(e),n)for(e=0;e>>=0,e===0?32:31-(B$(e)/U$|0)|0}var pd=64,fd=4194304;function vc(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 vp(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,o=e.suspendedLanes,s=e.pingedLanes,i=t&268435455;if(i!==0){var a=i&~o;a!==0?r=vc(a):(s&=i,s!==0&&(r=vc(s)))}else i=t&~o,i!==0?r=vc(i):s!==0&&(r=vc(s));if(r===0)return 0;if(n!==0&&n!==r&&!(n&o)&&(o=r&-r,s=n&-n,o>=s||o===16&&(s&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function Eu(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Nr(n),e[n]=t}function G$(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=jc),Vb=" ",Yb=!1;function nk(e,n){switch(e){case"keyup":return xF.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function rk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _a=!1;function bF(e,n){switch(e){case"compositionend":return rk(n);case"keypress":return n.which!==32?null:(Yb=!0,Vb);case"textInput":return e=n.data,e===Vb&&Yb?null:e;default:return null}}function PF(e,n){if(_a)return e==="compositionend"||!Sx&&nk(e,n)?(e=ek(),gh=gx=Es=null,_a=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=Qb(t)}}function ak(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?ak(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function lk(){for(var e=window,n=gp();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=gp(e.document)}return n}function vx(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function AF(e){var n=lk(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&ak(t.ownerDocument.documentElement,t)){if(r!==null&&vx(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var o=t.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=Jb(t,s);var i=Jb(t,r);o&&i&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(n=n.createRange(),n.setStart(o.node,o.offset),e.removeAllRanges(),s>r?(e.addRange(n),e.extend(i.node,i.offset)):(n.setEnd(i.node,i.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,Ta=null,yS=null,Oc=null,SS=!1;function e1(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;SS||Ta==null||Ta!==gp(r)||(r=Ta,"selectionStart"in r&&vx(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}),Oc&&Qc(Oc,r)||(Oc=r,r=bp(yS,"onSelect"),0Aa||(e.current=CS[Aa],CS[Aa]=null,Aa--)}function Ge(e,n){Aa++,CS[Aa]=e.current,e.current=n}var Ws={},ln=ni(Ws),Rn=ni(!1),Li=Ws;function al(e,n){var t=e.type.contextTypes;if(!t)return Ws;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var o={},s;for(s in t)o[s]=n[s];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=o),o}function Ln(e){return e=e.childContextTypes,e!=null}function Cp(){Je(Rn),Je(ln)}function a1(e,n,t){if(ln.current!==Ws)throw Error(q(168));Ge(ln,n),Ge(Rn,t)}function yk(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var o in r)if(!(o in n))throw Error(q(108,k$(e)||"Unknown",o));return pt({},t,r)}function Ip(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ws,Li=ln.current,Ge(ln,e),Ge(Rn,Rn.current),!0}function l1(e,n,t){var r=e.stateNode;if(!r)throw Error(q(169));t?(e=yk(e,n,Li),r.__reactInternalMemoizedMergedChildContext=e,Je(Rn),Je(ln),Ge(ln,e)):Je(Rn),Ge(Rn,t)}var Ro=null,Df=!1,im=!1;function Sk(e){Ro===null?Ro=[e]:Ro.push(e)}function KF(e){Df=!0,Sk(e)}function ri(){if(!im&&Ro!==null){im=!0;var e=0,n=Fe;try{var t=Ro;for(Fe=1;e>=i,o-=i,Fo=1<<32-Nr(n)+o|t<T?(O=k,k=null):O=k.sibling;var _=p(y,k,b[T],E);if(_===null){k===null&&(k=O);break}e&&k&&_.alternate===null&&n(y,k),v=s(_,v,T),C===null?I=_:C.sibling=_,C=_,k=O}if(T===b.length)return t(y,k),nt&&wi(y,T),I;if(k===null){for(;TT?(O=k,k=null):O=k.sibling;var j=p(y,k,_.value,E);if(j===null){k===null&&(k=O);break}e&&k&&j.alternate===null&&n(y,k),v=s(j,v,T),C===null?I=j:C.sibling=j,C=j,k=O}if(_.done)return t(y,k),nt&&wi(y,T),I;if(k===null){for(;!_.done;T++,_=b.next())_=h(y,_.value,E),_!==null&&(v=s(_,v,T),C===null?I=_:C.sibling=_,C=_);return nt&&wi(y,T),I}for(k=r(y,k);!_.done;T++,_=b.next())_=f(k,y,T,_.value,E),_!==null&&(e&&_.alternate!==null&&k.delete(_.key===null?T:_.key),v=s(_,v,T),C===null?I=_:C.sibling=_,C=_);return e&&k.forEach(function(L){return n(y,L)}),nt&&wi(y,T),I}function x(y,v,b,E){if(typeof b=="object"&&b!==null&&b.type===ka&&b.key===null&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case ud:e:{for(var I=b.key,C=v;C!==null;){if(C.key===I){if(I=b.type,I===ka){if(C.tag===7){t(y,C.sibling),v=o(C,b.props.children),v.return=y,y=v;break e}}else if(C.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===ws&&d1(I)===C.type){t(y,C.sibling),v=o(C,b.props),v.ref=Zl(y,C,b),v.return=y,y=v;break e}t(y,C);break}else n(y,C);C=C.sibling}b.type===ka?(v=Ai(b.props.children,y.mode,E,b.key),v.return=y,y=v):(E=Ph(b.type,b.key,b.props,null,y.mode,E),E.ref=Zl(y,v,b),E.return=y,y=E)}return i(y);case Ea:e:{for(C=b.key;v!==null;){if(v.key===C)if(v.tag===4&&v.stateNode.containerInfo===b.containerInfo&&v.stateNode.implementation===b.implementation){t(y,v.sibling),v=o(v,b.children||[]),v.return=y,y=v;break e}else{t(y,v);break}else n(y,v);v=v.sibling}v=fm(b,y.mode,E),v.return=y,y=v}return i(y);case ws:return C=b._init,x(y,v,C(b._payload),E)}if(Sc(b))return S(y,v,b,E);if(Gl(b))return g(y,v,b,E);wd(y,b)}return typeof b=="string"&&b!==""||typeof b=="number"?(b=""+b,v!==null&&v.tag===6?(t(y,v.sibling),v=o(v,b),v.return=y,y=v):(t(y,v),v=pm(b,y.mode,E),v.return=y,y=v),i(y)):t(y,v)}return x}var cl=bk(!0),Pk=bk(!1),_p=ni(null),Tp=null,Ra=null,Px=null;function Cx(){Px=Ra=Tp=null}function Ix(e){var n=_p.current;Je(_p),e._currentValue=n}function kS(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function Qa(e,n){Tp=e,Px=Ra=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(jn=!0),e.firstContext=null)}function Cr(e){var n=e._currentValue;if(Px!==e)if(e={context:e,memoizedValue:n,next:null},Ra===null){if(Tp===null)throw Error(q(308));Ra=e,Tp.dependencies={lanes:0,firstContext:e}}else Ra=Ra.next=e;return n}var Ii=null;function Ex(e){Ii===null?Ii=[e]:Ii.push(e)}function Ck(e,n,t,r){var o=n.interleaved;return o===null?(t.next=t,Ex(n)):(t.next=o.next,o.next=t),n.interleaved=t,Xo(e,r)}function Xo(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var bs=!1;function kx(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ik(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Uo(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Rs(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,ke&2){var o=r.pending;return o===null?n.next=n:(n.next=o.next,o.next=n),r.pending=n,Xo(e,t)}return o=r.interleaved,o===null?(n.next=n,Ex(r)):(n.next=o.next,o.next=n),r.interleaved=n,Xo(e,t)}function yh(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,hx(e,t)}}function h1(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var o=null,s=null;if(t=t.firstBaseUpdate,t!==null){do{var i={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};s===null?o=s=i:s=s.next=i,t=t.next}while(t!==null);s===null?o=s=n:s=s.next=n}else o=s=n;t={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:s,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function Mp(e,n,t,r){var o=e.updateQueue;bs=!1;var s=o.firstBaseUpdate,i=o.lastBaseUpdate,a=o.shared.pending;if(a!==null){o.shared.pending=null;var l=a,c=l.next;l.next=null,i===null?s=c:i.next=c,i=l;var d=e.alternate;d!==null&&(d=d.updateQueue,a=d.lastBaseUpdate,a!==i&&(a===null?d.firstBaseUpdate=c:a.next=c,d.lastBaseUpdate=l))}if(s!==null){var h=o.baseState;i=0,d=c=l=null,a=s;do{var p=a.lane,f=a.eventTime;if((r&p)===p){d!==null&&(d=d.next={eventTime:f,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var S=e,g=a;switch(p=n,f=t,g.tag){case 1:if(S=g.payload,typeof S=="function"){h=S.call(f,h,p);break e}h=S;break e;case 3:S.flags=S.flags&-65537|128;case 0:if(S=g.payload,p=typeof S=="function"?S.call(f,h,p):S,p==null)break e;h=pt({},h,p);break e;case 2:bs=!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},d===null?(c=d=f,l=h):d=d.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(d===null&&(l=h),o.baseState=l,o.firstBaseUpdate=c,o.lastBaseUpdate=d,n=o.shared.interleaved,n!==null){o=n;do i|=o.lane,o=o.next;while(o!==n)}else s===null&&(o.shared.lanes=0);Ni|=i,e.lanes=i,e.memoizedState=h}}function p1(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=lm.transition;lm.transition={};try{e(!1),n()}finally{Fe=t,lm.transition=r}}function Uk(){return Ir().memoizedState}function YF(e,n,t){var r=$s(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},Hk(e))Kk(n,t);else if(t=Ck(e,n,t,r),t!==null){var o=mn();zr(t,e,r,o),Wk(t,n,r)}}function XF(e,n,t){var r=$s(e),o={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(Hk(e))Kk(n,o);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=n.lastRenderedReducer,s!==null))try{var i=n.lastRenderedState,a=s(i,t);if(o.hasEagerState=!0,o.eagerState=a,Ur(a,i)){var l=n.interleaved;l===null?(o.next=o,Ex(n)):(o.next=l.next,l.next=o),n.interleaved=o;return}}catch{}finally{}t=Ck(e,n,o,r),t!==null&&(o=mn(),zr(t,e,r,o),Wk(t,n,r))}}function Hk(e){var n=e.alternate;return e===ht||n!==null&&n===ht}function Kk(e,n){Dc=Ap=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Wk(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,hx(e,t)}}var Op={readContext:Cr,useCallback:Zt,useContext:Zt,useEffect:Zt,useImperativeHandle:Zt,useInsertionEffect:Zt,useLayoutEffect:Zt,useMemo:Zt,useReducer:Zt,useRef:Zt,useState:Zt,useDebugValue:Zt,useDeferredValue:Zt,useTransition:Zt,useMutableSource:Zt,useSyncExternalStore:Zt,useId:Zt,unstable_isNewReconciler:!1},qF={readContext:Cr,useCallback:function(e,n){return to().memoizedState=[e,n===void 0?null:n],e},useContext:Cr,useEffect:g1,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,vh(4194308,4,$k.bind(null,n,e),t)},useLayoutEffect:function(e,n){return vh(4194308,4,e,n)},useInsertionEffect:function(e,n){return vh(4,2,e,n)},useMemo:function(e,n){var t=to();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=to();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=YF.bind(null,ht,e),[r.memoizedState,e]},useRef:function(e){var n=to();return e={current:e},n.memoizedState=e},useState:f1,useDebugValue:Rx,useDeferredValue:function(e){return to().memoizedState=e},useTransition:function(){var e=f1(!1),n=e[0];return e=VF.bind(null,e[1]),to().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=ht,o=to();if(nt){if(t===void 0)throw Error(q(407));t=t()}else{if(t=n(),Ot===null)throw Error(q(349));Fi&30||Tk(r,n,t)}o.memoizedState=t;var s={value:t,getSnapshot:n};return o.queue=s,g1(jk.bind(null,r,s,e),[e]),r.flags|=2048,iu(9,Mk.bind(null,r,s,t,n),void 0,null),t},useId:function(){var e=to(),n=Ot.identifierPrefix;if(nt){var t=No,r=Fo;t=(r&~(1<<32-Nr(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=ou++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(t,{is:r.is}):(e=i.createElement(t),t==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,t),e[oo]=n,e[tu]=r,t_(e,n,!1,!1),n.stateNode=e;e:{switch(i=cS(t,r),t){case"dialog":Ze("cancel",e),Ze("close",e),o=r;break;case"iframe":case"object":case"embed":Ze("load",e),o=r;break;case"video":case"audio":for(o=0;ohl&&(n.flags|=128,r=!0,Ql(s,!1),n.lanes=4194304)}else{if(!r)if(e=jp(i),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),Ql(s,!0),s.tail===null&&s.tailMode==="hidden"&&!i.alternate&&!nt)return Qt(n),null}else 2*xt()-s.renderingStartTime>hl&&t!==1073741824&&(n.flags|=128,r=!0,Ql(s,!1),n.lanes=4194304);s.isBackwards?(i.sibling=n.child,n.child=i):(t=s.last,t!==null?t.sibling=i:n.child=i,s.last=i)}return s.tail!==null?(n=s.tail,s.rendering=n,s.tail=n.sibling,s.renderingStartTime=xt(),n.sibling=null,t=ct.current,Ge(ct,r?t&1|2:t&1),n):(Qt(n),null);case 22:case 23:return Bx(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?Yn&1073741824&&(Qt(n),n.subtreeFlags&6&&(n.flags|=8192)):Qt(n),null;case 24:return null;case 25:return null}throw Error(q(156,n.tag))}function oN(e,n){switch(wx(n),n.tag){case 1:return Ln(n.type)&&Cp(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return ul(),Je(Rn),Je(ln),Mx(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return Tx(n),null;case 13:if(Je(ct),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(q(340));ll()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return Je(ct),null;case 4:return ul(),null;case 10:return Ix(n.type._context),null;case 22:case 23:return Bx(),null;case 24:return null;default:return null}}var Pd=!1,rn=!1,sN=typeof WeakSet=="function"?WeakSet:Set,te=null;function La(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){mt(e,n,r)}else t.current=null}function LS(e,n,t){try{t()}catch(r){mt(e,n,r)}}var E1=!1;function iN(e,n){if(vS=xp,e=lk(),vx(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var o=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{t.nodeType,s.nodeType}catch{t=null;break e}var i=0,a=-1,l=-1,c=0,d=0,h=e,p=null;t:for(;;){for(var f;h!==t||o!==0&&h.nodeType!==3||(a=i+o),h!==s||r!==0&&h.nodeType!==3||(l=i+r),h.nodeType===3&&(i+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===e)break t;if(p===t&&++c===o&&(a=i),p===s&&++d===r&&(l=i),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}t=a===-1||l===-1?null:{start:a,end:l}}else t=null}t=t||{start:0,end:0}}else t=null;for(xS={focusedElem:e,selectionRange:t},xp=!1,te=n;te!==null;)if(n=te,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,te=e;else for(;te!==null;){n=te;try{var S=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(S!==null){var g=S.memoizedProps,x=S.memoizedState,y=n.stateNode,v=y.getSnapshotBeforeUpdate(n.elementType===n.type?g:jr(n.type,g),x);y.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var b=n.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(q(163))}}catch(E){mt(n,n.return,E)}if(e=n.sibling,e!==null){e.return=n.return,te=e;break}te=n.return}return S=E1,E1=!1,S}function Rc(e,n,t){var r=n.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&&LS(n,t,s)}o=o.next}while(o!==r)}}function $f(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function $S(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function o_(e){var n=e.alternate;n!==null&&(e.alternate=null,o_(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[oo],delete n[tu],delete n[PS],delete n[UF],delete n[HF])),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 s_(e){return e.tag===5||e.tag===3||e.tag===4}function k1(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||s_(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 FS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Pp));else if(r!==4&&(e=e.child,e!==null))for(FS(e,n,t),e=e.sibling;e!==null;)FS(e,n,t),e=e.sibling}function NS(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(NS(e,n,t),e=e.sibling;e!==null;)NS(e,n,t),e=e.sibling}var $t=null,Ar=!1;function fs(e,n,t){for(t=t.child;t!==null;)i_(e,n,t),t=t.sibling}function i_(e,n,t){if(ho&&typeof ho.onCommitFiberUnmount=="function")try{ho.onCommitFiberUnmount(Tf,t)}catch{}switch(t.tag){case 5:rn||La(t,n);case 6:var r=$t,o=Ar;$t=null,fs(e,n,t),$t=r,Ar=o,$t!==null&&(Ar?(e=$t,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):$t.removeChild(t.stateNode));break;case 18:$t!==null&&(Ar?(e=$t,t=t.stateNode,e.nodeType===8?sm(e.parentNode,t):e.nodeType===1&&sm(e,t),qc(e)):sm($t,t.stateNode));break;case 4:r=$t,o=Ar,$t=t.stateNode.containerInfo,Ar=!0,fs(e,n,t),$t=r,Ar=o;break;case 0:case 11:case 14:case 15:if(!rn&&(r=t.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)&&LS(t,n,i),o=o.next}while(o!==r)}fs(e,n,t);break;case 1:if(!rn&&(La(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(a){mt(t,n,a)}fs(e,n,t);break;case 21:fs(e,n,t);break;case 22:t.mode&1?(rn=(r=rn)||t.memoizedState!==null,fs(e,n,t),rn=r):fs(e,n,t);break;default:fs(e,n,t)}}function _1(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new sN),n.forEach(function(r){var o=gN.bind(null,e,r);t.has(r)||(t.add(r),r.then(o,o))})}}function Mr(e,n){var t=n.deletions;if(t!==null)for(var r=0;ro&&(o=i),r&=~s}if(r=o,r=xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*lN(r/1960))-r,10e?16:e,ks===null)var r=!1;else{if(e=ks,ks=null,Lp=0,ke&6)throw Error(q(331));var o=ke;for(ke|=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 l=0;lxt()-Nx?ji(e,0):Fx|=t),$n(e,n)}function f_(e,n){n===0&&(e.mode&1?(n=fd,fd<<=1,!(fd&130023424)&&(fd=4194304)):n=1);var t=mn();e=Xo(e,n),e!==null&&(Eu(e,n,t),$n(e,t))}function fN(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),f_(e,t)}function gN(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(t=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(q(314))}r!==null&&r.delete(n),f_(e,t)}var g_;g_=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Rn.current)jn=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return jn=!1,nN(e,n,t);jn=!!(e.flags&131072)}else jn=!1,nt&&n.flags&1048576&&vk(n,kp,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;xh(e,n),e=n.pendingProps;var o=al(n,ln.current);Qa(n,t),o=Ax(null,n,r,e,o,t);var s=Ox();return n.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Ln(r)?(s=!0,Ip(n)):s=!1,n.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kx(n),o.updater=Lf,n.stateNode=o,o._reactInternals=n,TS(n,r,e,t),n=AS(null,n,r,!0,s,t)):(n.tag=0,nt&&s&&xx(n),fn(null,n,o,t),n=n.child),n;case 16:r=n.elementType;e:{switch(xh(e,n),e=n.pendingProps,o=r._init,r=o(r._payload),n.type=r,o=n.tag=yN(r),e=jr(r,e),o){case 0:n=jS(null,n,r,e,t);break e;case 1:n=P1(null,n,r,e,t);break e;case 11:n=w1(null,n,r,e,t);break e;case 14:n=b1(null,n,r,jr(r.type,e),t);break e}throw Error(q(306,r,""))}return n;case 0:return r=n.type,o=n.pendingProps,o=n.elementType===r?o:jr(r,o),jS(e,n,r,o,t);case 1:return r=n.type,o=n.pendingProps,o=n.elementType===r?o:jr(r,o),P1(e,n,r,o,t);case 3:e:{if(Qk(n),e===null)throw Error(q(387));r=n.pendingProps,s=n.memoizedState,o=s.element,Ik(e,n),Mp(n,r,null,t);var i=n.memoizedState;if(r=i.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},n.updateQueue.baseState=s,n.memoizedState=s,n.flags&256){o=dl(Error(q(423)),n),n=C1(e,n,r,t,o);break e}else if(r!==o){o=dl(Error(q(424)),n),n=C1(e,n,r,t,o);break e}else for(Zn=Ds(n.stateNode.containerInfo.firstChild),Qn=n,nt=!0,Rr=null,t=Pk(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(ll(),r===o){n=qo(e,n,t);break e}fn(e,n,r,t)}n=n.child}return n;case 5:return Ek(n),e===null&&ES(n),r=n.type,o=n.pendingProps,s=e!==null?e.memoizedProps:null,i=o.children,wS(r,o)?i=null:s!==null&&wS(r,s)&&(n.flags|=32),Zk(e,n),fn(e,n,i,t),n.child;case 6:return e===null&&ES(n),null;case 13:return Jk(e,n,t);case 4:return _x(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=cl(n,null,r,t):fn(e,n,r,t),n.child;case 11:return r=n.type,o=n.pendingProps,o=n.elementType===r?o:jr(r,o),w1(e,n,r,o,t);case 7:return fn(e,n,n.pendingProps,t),n.child;case 8:return fn(e,n,n.pendingProps.children,t),n.child;case 12:return fn(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,o=n.pendingProps,s=n.memoizedProps,i=o.value,Ge(_p,r._currentValue),r._currentValue=i,s!==null)if(Ur(s.value,i)){if(s.children===o.children&&!Rn.current){n=qo(e,n,t);break e}}else for(s=n.child,s!==null&&(s.return=n);s!==null;){var a=s.dependencies;if(a!==null){i=s.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(s.tag===1){l=Uo(-1,t&-t),l.tag=2;var c=s.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}s.lanes|=t,l=s.alternate,l!==null&&(l.lanes|=t),kS(s.return,t,n),a.lanes|=t;break}l=l.next}}else if(s.tag===10)i=s.type===n.type?null:s.child;else if(s.tag===18){if(i=s.return,i===null)throw Error(q(341));i.lanes|=t,a=i.alternate,a!==null&&(a.lanes|=t),kS(i,t,n),i=s.sibling}else i=s.child;if(i!==null)i.return=s;else for(i=s;i!==null;){if(i===n){i=null;break}if(s=i.sibling,s!==null){s.return=i.return,i=s;break}i=i.return}s=i}fn(e,n,o.children,t),n=n.child}return n;case 9:return o=n.type,r=n.pendingProps.children,Qa(n,t),o=Cr(o),r=r(o),n.flags|=1,fn(e,n,r,t),n.child;case 14:return r=n.type,o=jr(r,n.pendingProps),o=jr(r.type,o),b1(e,n,r,o,t);case 15:return Xk(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,o=n.pendingProps,o=n.elementType===r?o:jr(r,o),xh(e,n),n.tag=1,Ln(r)?(e=!0,Ip(n)):e=!1,Qa(n,t),Gk(n,r,o),TS(n,r,o,t),AS(null,n,r,!0,e,t);case 19:return e_(e,n,t);case 22:return qk(e,n,t)}throw Error(q(156,n.tag))};function m_(e,n){return HE(e,n)}function mN(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function xr(e,n,t,r){return new mN(e,n,t,r)}function Hx(e){return e=e.prototype,!(!e||!e.isReactComponent)}function yN(e){if(typeof e=="function")return Hx(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lx)return 11;if(e===cx)return 14}return 2}function Fs(e,n){var t=e.alternate;return t===null?(t=xr(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function Ph(e,n,t,r,o,s){var i=2;if(r=e,typeof e=="function")Hx(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case ka:return Ai(t.children,o,s,n);case ax:i=8,o|=8;break;case Jy:return e=xr(12,t,n,o|2),e.elementType=Jy,e.lanes=s,e;case eS:return e=xr(13,t,n,o),e.elementType=eS,e.lanes=s,e;case tS:return e=xr(19,t,n,o),e.elementType=tS,e.lanes=s,e;case EE:return Nf(t,o,s,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case CE:i=10;break e;case IE:i=9;break e;case lx:i=11;break e;case cx:i=14;break e;case ws:i=16,r=null;break e}throw Error(q(130,e==null?e:typeof e,""))}return n=xr(i,t,n,o),n.elementType=e,n.type=r,n.lanes=s,n}function Ai(e,n,t,r){return e=xr(7,e,r,n),e.lanes=t,e}function Nf(e,n,t,r){return e=xr(22,e,r,n),e.elementType=EE,e.lanes=t,e.stateNode={isHidden:!1},e}function pm(e,n,t){return e=xr(6,e,null,n),e.lanes=t,e}function fm(e,n,t){return n=xr(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function SN(e,n,t,r,o){this.tag=n,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Yg(0),this.expirationTimes=Yg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Yg(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kx(e,n,t,r,o,s,i,a,l){return e=new SN(e,n,t,a,l),n===1?(n=1,s===!0&&(n|=8)):n=0,s=xr(3,null,null,n),e.current=s,s.stateNode=e,s.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},kx(s),e}function vN(e,n,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(x_)}catch(e){console.error(e)}}x_(),xE.exports=ir;var ra=xE.exports;const CN=ei(ra);var w_,L1=ra;w_=Zy.createRoot=L1.createRoot,Zy.hydrateRoot=L1.hydrateRoot;var ec=function(e){return e&&e.Math===Math&&e},zn=ec(typeof globalThis=="object"&&globalThis)||ec(typeof window=="object"&&window)||ec(typeof self=="object"&&self)||ec(typeof sn=="object"&&sn)||ec(typeof sn=="object"&&sn)||function(){return this}()||Function("return this")(),Yx={},vn=function(e){try{return!!e()}catch{return!0}},IN=vn,oi=!IN(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),EN=vn,Kf=!EN(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),kN=Kf,Ed=Function.prototype.call,rs=kN?Ed.bind(Ed):function(){return Ed.apply(Ed,arguments)},b_={},P_={}.propertyIsEnumerable,C_=Object.getOwnPropertyDescriptor,_N=C_&&!P_.call({1:2},1);b_.f=_N?function(n){var t=C_(this,n);return!!t&&t.enumerable}:P_;var I_=function(e,n){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:n}},E_=Kf,k_=Function.prototype,KS=k_.call,TN=E_&&k_.bind.bind(KS,KS),Dt=E_?TN:function(e){return function(){return KS.apply(e,arguments)}},__=Dt,MN=__({}.toString),jN=__("".slice),_l=function(e){return jN(MN(e),8,-1)},AN=Dt,ON=vn,DN=_l,gm=Object,RN=AN("".split),LN=ON(function(){return!gm("z").propertyIsEnumerable(0)})?function(e){return DN(e)==="String"?RN(e,""):gm(e)}:gm,Wf=function(e){return e==null},$N=Wf,FN=TypeError,Tl=function(e){if($N(e))throw new FN("Can't call method on "+e);return e},NN=LN,zN=Tl,Gf=function(e){return NN(zN(e))},mm=typeof document=="object"&&document.all,xn=typeof mm>"u"&&mm!==void 0?function(e){return typeof e=="function"||e===mm}:function(e){return typeof e=="function"},BN=xn,oa=function(e){return typeof e=="object"?e!==null:BN(e)},ym=zn,UN=xn,HN=function(e){return UN(e)?e:void 0},Vf=function(e,n){return arguments.length<2?HN(ym[e]):ym[e]&&ym[e][n]},KN=Dt,T_=KN({}.isPrototypeOf),WN=typeof navigator<"u"&&String(navigator.userAgent)||"",M_=zn,Sm=WN,$1=M_.process,F1=M_.Deno,N1=$1&&$1.versions||F1&&F1.version,z1=N1&&N1.v8,Lr,Np;z1&&(Lr=z1.split("."),Np=Lr[0]>0&&Lr[0]<4?1:+(Lr[0]+Lr[1]));!Np&&Sm&&(Lr=Sm.match(/Edge\/(\d+)/),(!Lr||Lr[1]>=74)&&(Lr=Sm.match(/Chrome\/(\d+)/),Lr&&(Np=+Lr[1])));var GN=Np,B1=GN,VN=vn,YN=zn,XN=YN.String,j_=!!Object.getOwnPropertySymbols&&!VN(function(){var e=Symbol("symbol detection");return!XN(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&B1&&B1<41}),qN=j_,A_=qN&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ZN=Vf,QN=xn,JN=T_,ez=A_,tz=Object,O_=ez?function(e){return typeof e=="symbol"}:function(e){var n=ZN("Symbol");return QN(n)&&JN(n.prototype,tz(e))},nz=String,rz=function(e){try{return nz(e)}catch{return"Object"}},oz=xn,sz=rz,iz=TypeError,Xx=function(e){if(oz(e))return e;throw new iz(sz(e)+" is not a function")},az=Xx,lz=Wf,qx=function(e,n){var t=e[n];return lz(t)?void 0:az(t)},vm=rs,xm=xn,wm=oa,cz=TypeError,uz=function(e,n){var t,r;if(n==="string"&&xm(t=e.toString)&&!wm(r=vm(t,e))||xm(t=e.valueOf)&&!wm(r=vm(t,e))||n!=="string"&&xm(t=e.toString)&&!wm(r=vm(t,e)))return r;throw new cz("Can't convert object to primitive value")},D_={exports:{}},U1=zn,dz=Object.defineProperty,Zx=function(e,n){try{dz(U1,e,{value:n,configurable:!0,writable:!0})}catch{U1[e]=n}return n},hz=zn,pz=Zx,H1="__core-js_shared__",K1=D_.exports=hz[H1]||pz(H1,{});(K1.versions||(K1.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 Qx=D_.exports,W1=Qx,Jx=function(e,n){return W1[e]||(W1[e]=n||{})},fz=Tl,gz=Object,Mu=function(e){return gz(fz(e))},mz=Dt,yz=Mu,Sz=mz({}.hasOwnProperty),si=Object.hasOwn||function(n,t){return Sz(yz(n),t)},vz=Dt,xz=0,wz=Math.random(),bz=vz(1 .toString),R_=function(e){return"Symbol("+(e===void 0?"":e)+")_"+bz(++xz+wz,36)},Pz=zn,Cz=Jx,G1=si,Iz=R_,Ez=j_,kz=A_,Fa=Pz.Symbol,bm=Cz("wks"),_z=kz?Fa.for||Fa:Fa&&Fa.withoutSetter||Iz,os=function(e){return G1(bm,e)||(bm[e]=Ez&&G1(Fa,e)?Fa[e]:_z("Symbol."+e)),bm[e]},Tz=rs,V1=oa,Y1=O_,Mz=qx,jz=uz,Az=os,Oz=TypeError,Dz=Az("toPrimitive"),Rz=function(e,n){if(!V1(e)||Y1(e))return e;var t=Mz(e,Dz),r;if(t){if(n===void 0&&(n="default"),r=Tz(t,e,n),!V1(r)||Y1(r))return r;throw new Oz("Can't convert object to primitive value")}return n===void 0&&(n="number"),jz(e,n)},Lz=Rz,$z=O_,L_=function(e){var n=Lz(e,"string");return $z(n)?n:n+""},Fz=zn,X1=oa,WS=Fz.document,Nz=X1(WS)&&X1(WS.createElement),$_=function(e){return Nz?WS.createElement(e):{}},zz=oi,Bz=vn,Uz=$_,F_=!zz&&!Bz(function(){return Object.defineProperty(Uz("div"),"a",{get:function(){return 7}}).a!==7}),Hz=oi,Kz=rs,Wz=b_,Gz=I_,Vz=Gf,Yz=L_,Xz=si,qz=F_,q1=Object.getOwnPropertyDescriptor;Yx.f=Hz?q1:function(n,t){if(n=Vz(n),t=Yz(t),qz)try{return q1(n,t)}catch{}if(Xz(n,t))return Gz(!Kz(Wz.f,n,t),n[t])};var Ml={},Zz=oi,Qz=vn,N_=Zz&&Qz(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Jz=oa,e3=String,t3=TypeError,sa=function(e){if(Jz(e))return e;throw new t3(e3(e)+" is not an object")},n3=oi,r3=F_,o3=N_,kd=sa,Z1=L_,s3=TypeError,Pm=Object.defineProperty,i3=Object.getOwnPropertyDescriptor,Cm="enumerable",Im="configurable",Em="writable";Ml.f=n3?o3?function(n,t,r){if(kd(n),t=Z1(t),kd(r),typeof n=="function"&&t==="prototype"&&"value"in r&&Em in r&&!r[Em]){var o=i3(n,t);o&&o[Em]&&(n[t]=r.value,r={configurable:Im in r?r[Im]:o[Im],enumerable:Cm in r?r[Cm]:o[Cm],writable:!1})}return Pm(n,t,r)}:Pm:function(n,t,r){if(kd(n),t=Z1(t),kd(r),r3)try{return Pm(n,t,r)}catch{}if("get"in r||"set"in r)throw new s3("Accessors not supported");return"value"in r&&(n[t]=r.value),n};var a3=oi,l3=Ml,c3=I_,ew=a3?function(e,n,t){return l3.f(e,n,c3(1,t))}:function(e,n,t){return e[n]=t,e},z_={exports:{}},GS=oi,u3=si,B_=Function.prototype,d3=GS&&Object.getOwnPropertyDescriptor,tw=u3(B_,"name"),h3=tw&&(function(){}).name==="something",p3=tw&&(!GS||GS&&d3(B_,"name").configurable),f3={EXISTS:tw,PROPER:h3,CONFIGURABLE:p3},g3=Dt,m3=xn,VS=Qx,y3=g3(Function.toString);m3(VS.inspectSource)||(VS.inspectSource=function(e){return y3(e)});var U_=VS.inspectSource,S3=zn,v3=xn,Q1=S3.WeakMap,x3=v3(Q1)&&/native code/.test(String(Q1)),w3=Jx,b3=R_,J1=w3("keys"),H_=function(e){return J1[e]||(J1[e]=b3(e))},nw={},P3=x3,K_=zn,C3=oa,I3=ew,km=si,_m=Qx,E3=H_,k3=nw,eP="Object already initialized",YS=K_.TypeError,_3=K_.WeakMap,zp,lu,Bp,T3=function(e){return Bp(e)?lu(e):zp(e,{})},M3=function(e){return function(n){var t;if(!C3(n)||(t=lu(n)).type!==e)throw new YS("Incompatible receiver, "+e+" required");return t}};if(P3||_m.state){var eo=_m.state||(_m.state=new _3);eo.get=eo.get,eo.has=eo.has,eo.set=eo.set,zp=function(e,n){if(eo.has(e))throw new YS(eP);return n.facade=e,eo.set(e,n),n},lu=function(e){return eo.get(e)||{}},Bp=function(e){return eo.has(e)}}else{var ha=E3("state");k3[ha]=!0,zp=function(e,n){if(km(e,ha))throw new YS(eP);return n.facade=e,I3(e,ha,n),n},lu=function(e){return km(e,ha)?e[ha]:{}},Bp=function(e){return km(e,ha)}}var W_={set:zp,get:lu,has:Bp,enforce:T3,getterFor:M3},rw=Dt,j3=vn,A3=xn,_d=si,XS=oi,O3=f3.CONFIGURABLE,D3=U_,G_=W_,R3=G_.enforce,L3=G_.get,tP=String,Ch=Object.defineProperty,$3=rw("".slice),F3=rw("".replace),N3=rw([].join),z3=XS&&!j3(function(){return Ch(function(){},"length",{value:8}).length!==8}),B3=String(String).split("String"),U3=z_.exports=function(e,n,t){$3(tP(n),0,7)==="Symbol("&&(n="["+F3(tP(n),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),t&&t.getter&&(n="get "+n),t&&t.setter&&(n="set "+n),(!_d(e,"name")||O3&&e.name!==n)&&(XS?Ch(e,"name",{value:n,configurable:!0}):e.name=n),z3&&t&&_d(t,"arity")&&e.length!==t.arity&&Ch(e,"length",{value:t.arity});try{t&&_d(t,"constructor")&&t.constructor?XS&&Ch(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch{}var r=R3(e);return _d(r,"source")||(r.source=N3(B3,typeof n=="string"?n:"")),e};Function.prototype.toString=U3(function(){return A3(this)&&L3(this).source||D3(this)},"toString");var H3=z_.exports,K3=xn,W3=Ml,G3=H3,V3=Zx,V_=function(e,n,t,r){r||(r={});var o=r.enumerable,s=r.name!==void 0?r.name:n;if(K3(t)&&G3(t,s,r),r.global)o?e[n]=t:V3(n,t);else{try{r.unsafe?e[n]&&(o=!0):delete e[n]}catch{}o?e[n]=t:W3.f(e,n,{value:t,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return e},Y_={},Y3=Math.ceil,X3=Math.floor,q3=Math.trunc||function(n){var t=+n;return(t>0?X3:Y3)(t)},Z3=q3,ia=function(e){var n=+e;return n!==n||n===0?0:Z3(n)},Q3=ia,J3=Math.max,eB=Math.min,tB=function(e,n){var t=Q3(e);return t<0?J3(t+n,0):eB(t,n)},nB=ia,rB=Math.min,X_=function(e){var n=nB(e);return n>0?rB(n,9007199254740991):0},oB=X_,ju=function(e){return oB(e.length)},sB=Gf,iB=tB,aB=ju,nP=function(e){return function(n,t,r){var o=sB(n),s=aB(o);if(s===0)return!e&&-1;var i=iB(r,s),a;if(e&&t!==t){for(;s>i;)if(a=o[i++],a!==a)return!0}else for(;s>i;i++)if((e||i in o)&&o[i]===t)return e||i||0;return!e&&-1}},lB={includes:nP(!0),indexOf:nP(!1)},cB=Dt,Tm=si,uB=Gf,dB=lB.indexOf,hB=nw,rP=cB([].push),q_=function(e,n){var t=uB(e),r=0,o=[],s;for(s in t)!Tm(hB,s)&&Tm(t,s)&&rP(o,s);for(;n.length>r;)Tm(t,s=n[r++])&&(~dB(o,s)||rP(o,s));return o},ow=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],pB=q_,fB=ow,gB=fB.concat("length","prototype");Y_.f=Object.getOwnPropertyNames||function(n){return pB(n,gB)};var Z_={};Z_.f=Object.getOwnPropertySymbols;var mB=Vf,yB=Dt,SB=Y_,vB=Z_,xB=sa,wB=yB([].concat),bB=mB("Reflect","ownKeys")||function(n){var t=SB.f(xB(n)),r=vB.f;return r?wB(t,r(n)):t},oP=si,PB=bB,CB=Yx,IB=Ml,EB=function(e,n,t){for(var r=PB(n),o=IB.f,s=CB.f,i=0;ii;)GB.f(n,a=o[i++],r[a]);return n};var qB=Vf,ZB=qB("document","documentElement"),QB=sa,JB=Q_,sP=ow,e5=nw,t5=ZB,n5=$_,r5=H_,iP=">",aP="<",qS="prototype",ZS="script",J_=r5("IE_PROTO"),Mm=function(){},eT=function(e){return aP+ZS+iP+e+aP+"/"+ZS+iP},lP=function(e){e.write(eT("")),e.close();var n=e.parentWindow.Object;return e=null,n},o5=function(){var e=n5("iframe"),n="java"+ZS+":",t;return e.style.display="none",t5.appendChild(e),e.src=String(n),t=e.contentWindow.document,t.open(),t.write(eT("document.F=Object")),t.close(),t.F},Md,Ih=function(){try{Md=new ActiveXObject("htmlfile")}catch{}Ih=typeof document<"u"?document.domain&&Md?lP(Md):o5():lP(Md);for(var e=sP.length;e--;)delete Ih[qS][sP[e]];return Ih()};e5[J_]=!0;var tT=Object.create||function(n,t){var r;return n!==null?(Mm[qS]=QB(n),r=new Mm,Mm[qS]=null,r[J_]=n):r=Ih(),t===void 0?r:JB.f(r,t)},s5=os,i5=tT,a5=Ml.f,QS=s5("unscopables"),JS=Array.prototype;JS[QS]===void 0&&a5(JS,QS,{configurable:!0,value:i5(null)});var sw=function(e){JS[QS][e]=!0},l5=jl,c5=Mu,u5=ju,d5=ia,h5=sw;l5({target:"Array",proto:!0},{at:function(n){var t=c5(this),r=u5(t),o=d5(n),s=o>=0?o:r+o;return s<0||s>=r?void 0:t[s]}});h5("at");var p5=zn,f5=Dt,Ou=function(e,n){return f5(p5[e].prototype[n])},g5=Ou;g5("Array","at");var m5=_l,nT=Array.isArray||function(n){return m5(n)==="Array"},y5=TypeError,S5=9007199254740991,v5=function(e){if(e>S5)throw y5("Maximum allowed index exceeded");return e},x5=_l,w5=Dt,b5=function(e){if(x5(e)==="Function")return w5(e)},cP=b5,P5=Xx,C5=Kf,I5=cP(cP.bind),E5=function(e,n){return P5(e),n===void 0?e:C5?I5(e,n):function(){return e.apply(n,arguments)}},k5=nT,_5=ju,T5=v5,M5=E5,rT=function(e,n,t,r,o,s,i,a){for(var l=o,c=0,d=i?M5(i,a):!1,h,p;c0&&k5(h)?(p=_5(h),l=rT(e,n,h,p,l,s-1)-1):(T5(l+1),e[l]=h),l++),c++;return l},oT=rT,j5=os,A5=j5("toStringTag"),sT={};sT[A5]="z";var O5=String(sT)==="[object z]",D5=O5,R5=xn,Eh=_l,L5=os,$5=L5("toStringTag"),F5=Object,N5=Eh(function(){return arguments}())==="Arguments",z5=function(e,n){try{return e[n]}catch{}},iT=D5?Eh:function(e){var n,t,r;return e===void 0?"Undefined":e===null?"Null":typeof(t=z5(n=F5(e),$5))=="string"?t:N5?Eh(n):(r=Eh(n))==="Object"&&R5(n.callee)?"Arguments":r},B5=Dt,U5=vn,aT=xn,H5=iT,K5=Vf,W5=U_,lT=function(){},cT=K5("Reflect","construct"),iw=/^\s*(?:class|function)\b/,G5=B5(iw.exec),V5=!iw.test(lT),tc=function(n){if(!aT(n))return!1;try{return cT(lT,[],n),!0}catch{return!1}},uT=function(n){if(!aT(n))return!1;switch(H5(n)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return V5||!!G5(iw,W5(n))}catch{return!0}};uT.sham=!0;var Y5=!cT||U5(function(){var e;return tc(tc.call)||!tc(Object)||!tc(function(){e=!0})||e})?uT:tc,uP=nT,X5=Y5,q5=oa,Z5=os,Q5=Z5("species"),dP=Array,J5=function(e){var n;return uP(e)&&(n=e.constructor,X5(n)&&(n===dP||uP(n.prototype))?n=void 0:q5(n)&&(n=n[Q5],n===null&&(n=void 0))),n===void 0?dP:n},eU=J5,dT=function(e,n){return new(eU(e))(n===0?0:n)},tU=jl,nU=oT,rU=Xx,oU=Mu,sU=ju,iU=dT;tU({target:"Array",proto:!0},{flatMap:function(n){var t=oU(this),r=sU(t),o;return rU(n),o=iU(t,0),o.length=nU(o,t,t,r,0,1,n,arguments.length>1?arguments[1]:void 0),o}});var aU=sw;aU("flatMap");var lU=Ou;lU("Array","flatMap");var cU=jl,uU=oT,dU=Mu,hU=ju,pU=ia,fU=dT;cU({target:"Array",proto:!0},{flat:function(){var n=arguments.length?arguments[0]:void 0,t=dU(this),r=hU(t),o=fU(t,0);return o.length=uU(o,t,t,r,0,n===void 0?1:pU(n)),o}});var gU=sw;gU("flat");var mU=Ou;mU("Array","flat");var yU=iT,SU=String,Du=function(e){if(yU(e)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return SU(e)},vU=jl,xU=Dt,wU=Tl,bU=ia,PU=Du,CU=vn,IU=xU("".charAt),EU=CU(function(){return"𠮷".at(-2)!=="\uD842"});vU({target:"String",proto:!0,forced:EU},{at:function(n){var t=PU(wU(this)),r=t.length,o=bU(n),s=o>=0?o:r+o;return s<0||s>=r?void 0:IU(t,s)}});var kU=Ou;kU("String","at");var _U=sa,hT=function(){var e=_U(this),n="";return e.hasIndices&&(n+="d"),e.global&&(n+="g"),e.ignoreCase&&(n+="i"),e.multiline&&(n+="m"),e.dotAll&&(n+="s"),e.unicode&&(n+="u"),e.unicodeSets&&(n+="v"),e.sticky&&(n+="y"),n},aw=vn,TU=zn,lw=TU.RegExp,cw=aw(function(){var e=lw("a","y");return e.lastIndex=2,e.exec("abcd")!==null}),MU=cw||aw(function(){return!lw("a","y").sticky}),jU=cw||aw(function(){var e=lw("^r","gy");return e.lastIndex=2,e.exec("str")!==null}),AU={BROKEN_CARET:jU,MISSED_STICKY:MU,UNSUPPORTED_Y:cw},OU=vn,DU=zn,RU=DU.RegExp,LU=OU(function(){var e=RU(".","s");return!(e.dotAll&&e.test(` `)&&e.flags==="s")}),$U=vn,FU=zn,NU=FU.RegExp,zU=$U(function(){var e=NU("(?b)","g");return e.exec("b").groups.a!=="b"||"b".replace(e,"$c")!=="bc"}),Na=rs,Yf=Dt,BU=Du,UU=hT,HU=AU,KU=Jx,WU=tT,GU=W_.get,VU=LU,YU=zU,XU=KU("native-string-replace",String.prototype.replace),Up=RegExp.prototype.exec,ev=Up,qU=Yf("".charAt),ZU=Yf("".indexOf),QU=Yf("".replace),jm=Yf("".slice),tv=function(){var e=/a/,n=/b*/g;return Na(Up,e,"a"),Na(Up,n,"a"),e.lastIndex!==0||n.lastIndex!==0}(),pT=HU.BROKEN_CARET,nv=/()??/.exec("")[1]!==void 0,JU=tv||nv||pT||VU||YU;JU&&(ev=function(n){var t=this,r=GU(t),o=BU(n),s=r.raw,i,a,l,c,d,h,p;if(s)return s.lastIndex=t.lastIndex,i=Na(ev,s,o),t.lastIndex=s.lastIndex,i;var f=r.groups,S=pT&&t.sticky,g=Na(UU,t),x=t.source,y=0,v=o;if(S&&(g=QU(g,"y",""),ZU(g,"g")===-1&&(g+="g"),v=jm(o,t.lastIndex),t.lastIndex>0&&(!t.multiline||t.multiline&&qU(o,t.lastIndex-1)!==` `)&&(x="(?: "+x+")",v=" "+v,y++),a=new RegExp("^(?:"+x+")",g)),nv&&(a=new RegExp("^"+x+"$(?!\\s)",g)),tv&&(l=t.lastIndex),c=Na(Up,S?a:t,v),S?c?(c.input=jm(c.input,y),c[0]=jm(c[0],y),c.index=t.lastIndex,t.lastIndex+=c[0].length):t.lastIndex=0:tv&&c&&(t.lastIndex=t.global?c.index+c[0].length:l),nv&&c&&c.length>1&&Na(XU,c[0],a,function(){for(d=1;d=s?e?"":void 0:(i=SP(r,o),i<55296||i>56319||o+1===s||(a=SP(r,o+1))<56320||a>57343?e?u4(r,o):i:e?d4(r,o,o+2):(i-55296<<10)+(a-56320)+65536)}},h4={codeAt:vP(!1),charAt:vP(!0)},p4=h4.charAt,f4=function(e,n,t){return n+(t?p4(e,n).length:1)},hw=Dt,g4=Mu,m4=Math.floor,Om=hw("".charAt),y4=hw("".replace),Dm=hw("".slice),S4=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,v4=/\$([$&'`]|\d{1,2})/g,mT=function(e,n,t,r,o,s){var i=t+e.length,a=r.length,l=v4;return o!==void 0&&(o=g4(o),l=S4),y4(s,l,function(c,d){var h;switch(Om(d,0)){case"$":return"$";case"&":return e;case"`":return Dm(n,0,t);case"'":return Dm(n,i);case"<":h=o[Dm(d,1,-1)];break;default:var p=+d;if(p===0)return c;if(p>a){var f=m4(p/10);return f===0?c:f<=a?r[f-1]===void 0?Om(d,1):r[f-1]+Om(d,1):c}h=r[p-1]}return h===void 0?"":h})},xP=rs,x4=sa,w4=xn,b4=_l,P4=uw,C4=TypeError,I4=function(e,n){var t=e.exec;if(w4(t)){var r=xP(t,e,n);return r!==null&&x4(r),r}if(b4(e)==="RegExp")return xP(P4,e,n);throw new C4("RegExp#exec called on incompatible receiver")},E4=n4,wP=rs,Xf=Dt,k4=i4,_4=vn,T4=sa,M4=xn,j4=Wf,A4=ia,O4=X_,pa=Du,D4=Tl,R4=f4,L4=qx,$4=mT,F4=I4,N4=os,rv=N4("replace"),z4=Math.max,B4=Math.min,U4=Xf([].concat),Rm=Xf([].push),bP=Xf("".indexOf),PP=Xf("".slice),H4=function(e){return e===void 0?e:String(e)},K4=function(){return"a".replace(/./,"$0")==="$0"}(),CP=function(){return/./[rv]?/./[rv]("a","$0")==="":!1}(),W4=!_4(function(){var e=/./;return e.exec=function(){var n=[];return n.groups={a:"7"},n},"".replace(e,"$")!=="7"});k4("replace",function(e,n,t){var r=CP?"$":"$0";return[function(s,i){var a=D4(this),l=j4(s)?void 0:L4(s,rv);return l?wP(l,s,a,i):wP(n,pa(a),s,i)},function(o,s){var i=T4(this),a=pa(o);if(typeof s=="string"&&bP(s,r)===-1&&bP(s,"$<")===-1){var l=t(n,i,a,s);if(l.done)return l.value}var c=M4(s);c||(s=pa(s));var d=i.global,h;d&&(h=i.unicode,i.lastIndex=0);for(var p=[],f;f=F4(i,a),!(f===null||(Rm(p,f),!d));){var S=pa(f[0]);S===""&&(i.lastIndex=R4(a,O4(i.lastIndex),h))}for(var g="",x=0,y=0;y=x&&(g+=PP(a,x,b)+I,x=b+v.length)}return g+PP(a,x)}]},!W4||!K4||CP);var G4=oa,V4=_l,Y4=os,X4=Y4("match"),q4=function(e){var n;return G4(e)&&((n=e[X4])!==void 0?!!n:V4(e)==="RegExp")},Z4=rs,Q4=si,J4=T_,e8=hT,IP=RegExp.prototype,t8=function(e){var n=e.flags;return n===void 0&&!("flags"in IP)&&!Q4(e,"flags")&&J4(IP,e)?Z4(e8,e):n},n8=jl,r8=rs,pw=Dt,EP=Tl,o8=xn,s8=Wf,i8=q4,nc=Du,a8=qx,l8=t8,c8=mT,u8=os,d8=u8("replace"),h8=TypeError,Lm=pw("".indexOf);pw("".replace);var kP=pw("".slice),p8=Math.max;n8({target:"String",proto:!0},{replaceAll:function(n,t){var r=EP(this),o,s,i,a,l,c,d,h,p,f=0,S=0,g="";if(!s8(n)){if(o=i8(n),o&&(s=nc(EP(l8(n))),!~Lm(s,"g")))throw new h8("`.replaceAll` does not allow non-global regexes");if(i=a8(n,d8),i)return r8(i,n,r,t)}for(a=nc(r),l=nc(n),c=o8(t),c||(t=nc(t)),d=l.length,h=p8(1,d),f=Lm(a,l);f!==-1;)p=c?nc(t(l,f,a)):c8(l,a,f,[],void 0,t),g+=kP(a,S,f)+p,S=f+d,f=f+h>a.length?-1:Lm(a,l,f+h);return S=n||k<0||h&&T>=s}function y(){var C=$m();if(x(C))return v(C);a=setTimeout(y,g(C))}function v(C){return a=void 0,p&&r?f(C):(r=o=void 0,i)}function b(){a!==void 0&&clearTimeout(a),c=0,r=l=o=a=void 0}function E(){return a===void 0?i:v($m())}function I(){var C=$m(),k=x(C);if(r=arguments,o=this,l=C,k){if(a===void 0)return S(l);if(h)return a=setTimeout(y,n),f(l)}return a===void 0&&(a=setTimeout(y,n)),i}return I.cancel=b,I.flush=E,I}function T8(e,n,t){var r=!0,o=!0;if(typeof e!="function")throw new TypeError(yT);return Hp(t)&&(r="leading"in t?!!t.leading:r,o="trailing"in t?!!t.trailing:o),_8(e,n,{leading:r,maxWait:n,trailing:o})}function Hp(e){var n=typeof e;return!!e&&(n=="object"||n=="function")}function M8(e){return!!e&&typeof e=="object"}function j8(e){return typeof e=="symbol"||M8(e)&&I8.call(e)==g8}function TP(e){if(typeof e=="number")return e;if(j8(e))return _P;if(Hp(e)){var n=typeof e.valueOf=="function"?e.valueOf():e;e=Hp(n)?n+"":n}if(typeof e!="string")return e===0?e:+e;e=e.replace(m8,"");var t=S8.test(e);return t||v8.test(e)?x8(e.slice(2),t?2:8):y8.test(e)?_P:+e}var A8=T8;const fw=ei(A8);var O8=200,gw="__lodash_hash_undefined__",D8=1/0,R8="[object Function]",L8="[object GeneratorFunction]",$8=/[\\^$.*+?()[\]{}|]/g,F8=/^\[object .+?Constructor\]$/,N8=typeof sn=="object"&&sn&&sn.Object===Object&&sn,z8=typeof self=="object"&&self&&self.Object===Object&&self,mw=N8||z8||Function("return this")();function B8(e,n){var t=e?e.length:0;return!!t&&H8(e,n,0)>-1}function U8(e,n,t,r){for(var o=e.length,s=t+-1;++s-1}function c6(e,n){var t=this.__data__,r=qf(t,e);return r<0?t.push([e,n]):t[r][1]=n,this}Al.prototype.clear=s6;Al.prototype.delete=i6;Al.prototype.get=a6;Al.prototype.has=l6;Al.prototype.set=c6;function Ol(e){var n=-1,t=e?e.length:0;for(this.clear();++n=O8){var c=v6(e);if(c)return ST(c);i=!1,o=W8,l=new Kp}else l=a;e:for(;++r{this.frames++,this.started&&(this.frame=requestAnimationFrame(this.recordFrame))})}start(n){this.name=n,this.frames=0,this.started=!0,this.frame!==null&&cancelAnimationFrame(this.frame),this.frame=requestAnimationFrame(this.recordFrame),this.startTime=performance.now()}stop(){this.started=!1,this.frame!==null&&cancelAnimationFrame(this.frame);const n=(performance.now()-this.startTime)/1e3,t=n===0?0:Math.floor(this.frames/n),r=t>55?wc.Good:t>30?wc.Mid:wc.Poor,o=r===wc.Mid?"black":"white",s=this.name[0].toUpperCase()+this.name.slice(1);console.debug(`%cPerf%c ${s} %c${t}%c fps`,`color: white; background: ${T6};padding: 2px;border-radius: 3px;`,"font-weight: normal",`font-weight: bold; padding: 2px; background: ${r};color: ${o};`,"font-weight: normal")}isStarted(){return this.started}}function vw(e,n){const t=[];e:for(const r of e){for(const o of t)if(n?n(r,o):r===o)continue e;t.push(r)}return t}function me(e){return e.filter(n=>n!=null)}function Nt(e){return e[e.length-1]}function M6(e,n){let t,r=1/0;for(const o of e){const s=n(o);s{try{return e(...t)}catch(r){throw r instanceof Error&&Error.captureStackTrace&&Error.captureStackTrace(r,n),r}};return n}const Wp=()=>{},Ns={ok(e){return{ok:!0,value:e}},err(e){return{ok:!1,error:e}}};function an(e,n){const t=n&&e&&typeof e=="object"&&n in e?e[n]:e;throw new Error(`Unknown switch case ${t}`)}const st=PT((e,n)=>{if(!e)throw new Error(n||"Assertion Error")}),Sr=PT((e,n)=>{if(e==null)throw new Error(n??"value must be defined");return e});function CT(e,n){let t;const r=(...o)=>(t||(t={},t.promise=new Promise((s,i)=>{t.resolve=s,t.reject=i})),clearTimeout(t.timeout),t.latestArgs=o,t.timeout=setTimeout(()=>{const s=t;t=void 0;try{s.resolve(e(...s.latestArgs))}catch(i){s.reject(i)}},n),t.promise);return r.cancel=()=>{t&&clearTimeout(t.timeout)},r}const jP=new WeakMap;function xw(e,n){if(typeof e!="object"||e===null)return;let t=jP.get(e);t||(t={tags:{},extras:{}},jP.set(e,t)),n.tags&&(t.tags={...t.tags,...n.tags}),n.extras&&(t.extras={...t.extras,...n.extras})}async function yo(e,n){return window.fetch(e,{referrerPolicy:"strict-origin-when-cross-origin",...n})}const pl=(e,n)=>{const t=new window.Image(e,n);return t.referrerPolicy="strict-origin-when-cross-origin",t};class Oi{static async dataUrlToArrayBuffer(n){return yo(n).then(function(t){return t.arrayBuffer()})}static async blobToDataUrl(n){return await new Promise((t,r)=>{if(n){const o=new FileReader;o.onload=()=>t(o.result),o.onerror=s=>r(s),o.onabort=s=>r(s),o.readAsDataURL(n)}})}static async blobToText(n){return await new Promise((t,r)=>{if(n){const o=new FileReader;o.onload=()=>t(o.result),o.onerror=s=>r(s),o.onabort=s=>r(s),o.readAsText(n)}})}}function ov(e){let n=0;for(let t=0;t"u"&&(l=p),a>=p||l<=0||a>=l)return-1;s=s.subarray(a,l);let f=-1,S=0,g=0,x="";e:for(;S-1?C+d:b.length-d;x=b.slice(k)}return f>=0&&(f+=a>=0?a:p+a),f}const o=r(n,"IDAT",12);return o>=12?r(n,"acTL",8,o)>=8:!1}const D6=e=>new Uint8Array(e)[3]===44;/*! * MIT License * Modified code originally from * Copyright (c) 2016 Józef Sokołowski */function AP(e,n){let t=0;for(;e[n+t];)t+=e[n+t]+1;return t+1}function R6(e){return new TextDecoder("ascii").decode(e.slice(0,3))==="GIF"}function L6(e){const n=new Uint8Array(e);let t,r,o=0,s=0;if(!R6(e))return!1;for(t=n[10]&128,r=n[10]&7,o+=6,o+=7,o+=t?3*Math.pow(2,r+1):0;s<2&&o1}let sv=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];typeof Int32Array<"u"&&(sv=new Int32Array(sv));/*! * MIT License: https://github.com/alexgorbatchev/crc/blob/master/LICENSE * Copyright: 2014 Alex Gorbatchev * Code: crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts */const $6=(e,n)=>{let t=~~n^-1;for(let r=0;r>>8;return t^-1},OP=4,DP=4;class so{static isPng(n,t){return n.getUint8(t+0)===137&&n.getUint8(t+1)===80&&n.getUint8(t+2)===78&&n.getUint8(t+3)===71&&n.getUint8(t+4)===13&&n.getUint8(t+5)===10&&n.getUint8(t+6)===26&&n.getUint8(t+7)===10}static getChunkType(n,t){return[String.fromCharCode(n.getUint8(t)),String.fromCharCode(n.getUint8(t+1)),String.fromCharCode(n.getUint8(t+2)),String.fromCharCode(n.getUint8(t+3))].join("")}static readChunks(n,t=0){const r={};if(!so.isPng(n,t))throw new Error("Not a PNG");for(t+=8;t<=n.buffer.byteLength;){const o=t,s=n.getInt32(t);t+=4;const i=so.getChunkType(n,t);if(i==="IDAT"&&r[i]){t+=s+OP+DP;continue}if(i==="IEND")break;r[i]={start:o,dataOffset:t+4,size:s},t+=s+OP+DP}return r}static parsePhys(n,t){return{ppux:n.getUint32(t),ppuy:n.getUint32(t+4),unit:n.getUint8(t+4)}}static findChunk(n,t){return so.readChunks(n)[t]}static setPhysChunk(n,t=1,r){let o=46,s=0;const i=so.findChunk(n,"pHYs");i&&(o=i.start,s=i.size);const a=so.findChunk(n,"IDAT");a&&(o=a.start,s=0);const l=new ArrayBuffer(21),c=new DataView(l);c.setUint32(0,9),c.setUint8(4,112),c.setUint8(5,72),c.setUint8(6,89),c.setUint8(7,115);const d=2835.5;c.setInt32(8,d*t),c.setInt32(12,d*t),c.setInt8(16,1);const h=new Uint8Array(l.slice(4,17));c.setInt32(17,$6(h));const p=n.buffer.slice(0,o),f=n.buffer.slice(o+s);return new Blob([p,l,f],r)}}/*! * MIT License: https://github.com/sindresorhus/is-webp/blob/main/license * Copyright (c) Sindre Sorhus (https://sindresorhus.com) */function F6(e){return!e||e.length<12?!1:e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function N6(e){const n=new Uint8Array(e);return!F6(n)||!n||n.length<21?!1:(n[20]>>1&1)===1}const IT=Object.freeze(["image/svg+xml"]),ET=Object.freeze(["image/jpeg","image/png","image/webp"]),kT=Object.freeze(["image/gif","image/apng","image/avif"]),ww=Object.freeze([...ET,...IT,...kT]),_T=Object.freeze(["video/mp4","video/webm","video/quicktime"]),z6=[...ww,..._T].join(",");class ao{static loadVideo(n){return new Promise((t,r)=>{const o=document.createElement("video");o.onloadeddata=()=>t(o),o.onerror=s=>{console.error(s),r(new Error("Could not load video"))},o.crossOrigin="anonymous",o.src=n})}static loadImage(n){return new Promise((t,r)=>{const o=pl();o.onload=()=>t(o),o.onerror=s=>{console.error(s),r(new Error("Could not load image"))},o.crossOrigin="anonymous",o.referrerPolicy="strict-origin-when-cross-origin",o.src=n})}static async getVideoSize(n){return ao.usingObjectURL(n,async t=>{const r=await ao.loadVideo(t);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(n){const t=await ao.usingObjectURL(n,ao.loadImage);try{if(n.type==="image/png"){const r=new DataView(await n.arrayBuffer());if(so.isPng(r,0)){const o=so.findChunk(r,"pHYs");if(o){const s=so.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(t.naturalWidth/i),h:Math.round(t.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:t.naturalWidth,h:t.naturalHeight}}return{w:t.naturalWidth,h:t.naturalHeight}}static async isAnimated(n){return n.type==="image/gif"?L6(await n.arrayBuffer()):n.type==="image/avif"?D6(await n.arrayBuffer()):n.type==="image/webp"?N6(await n.arrayBuffer()):n.type==="image/apng"?O6(await n.arrayBuffer()):!1}static isAnimatedImageType(n){return kT.includes(n||"")}static isStaticImageType(n){return ET.includes(n||"")}static isVectorImageType(n){return IT.includes(n||"")}static isImageType(n){return ww.includes(n)}static async usingObjectURL(n,t){const r=URL.createObjectURL(n);try{return await t(r)}finally{URL.revokeObjectURL(r)}}}function jd(e,n,t){return e+(n-e)*t}function Wr(e=""){let n=0,t=0,r=0,o=0;function s(){const i=n^n<<11;return n=t,t=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 DT(e){if(e.length!==OT(e.charAt(0)))throw new Error("invalid integer part of index key: "+e)}function LP(e){if(e===void 0)throw Error("n is undefined")}function $P(e){DT(e);const[n,...t]=e.split("");let r=!0;for(let o=t.length-1;r&&o>=0;o--){const s=qn.indexOf(t[o])+1;s===qn.length?t[o]="0":(t[o]=qn.charAt(s),r=!1)}if(r){if(n==="Z")return"a0";if(n==="z")return;const o=String.fromCharCode(n.charCodeAt(0)+1);return o>"a"?t.push("0"):t.pop(),o+t.join("")}else return n+t.join("")}function B6(e){DT(e);const[n,...t]=e.split("");let r=!0;for(let o=t.length-1;r&&o>=0;o--){const s=qn.indexOf(t[o])-1;s===-1?t[o]=qn.slice(-1):(t[o]=qn.charAt(s),r=!1)}if(r){if(n==="a")return"Z"+qn.slice(-1);if(n==="A")return;const o=String.fromCharCode(n.charCodeAt(0)-1);return o<"Z"?t.push(qn.slice(-1)):t.pop(),o+t.join("")}else return n+t.join("")}function za(e,n){if(n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e.slice(-1)==="0"||n&&n.slice(-1)==="0")throw new Error("trailing zero");if(n){let o=0;for(;(e.charAt(o)||"0")===n.charAt(o);)o++;if(o>0)return n.slice(0,o)+za(e.slice(o),n.slice(o))}const t=e?qn.indexOf(e.charAt(0)):0,r=n!==void 0?qn.indexOf(n.charAt(0)):qn.length;if(r-t>1){const o=Math.round(.5*(t+r));return qn.charAt(o)}else return n&&n.length>1?n.slice(0,1):qn.charAt(t)+za(e.slice(1),void 0)}function bc(e){const n=OT(e.charAt(0));if(n>e.length)throw new Error("invalid index: "+e);return e.slice(0,n)}function iv(e){if(e===AT)throw new Error("invalid index: "+e);const n=bc(e);if(e.slice(n.length).slice(-1)==="0")throw new Error("invalid index: "+e)}function fa(e,n){if(e!==void 0&&iv(e),n!==void 0&&iv(n),e!==void 0&&n!==void 0&&e>=n)throw new Error(e+" >= "+n);if(e===void 0&&n===void 0)return jT;if(e===void 0){if(n===void 0)throw Error("b is undefined");const a=bc(n),l=n.slice(a.length);if(a===AT)return a+za("",l);if(an.index?1:0}function W6(e,n){return e.id>n.id?1:-1}function bw(e){try{return localStorage.getItem(e)}catch{return null}}function Pw(e,n){try{localStorage.setItem(e,n)}catch{}}function G6(){try{localStorage.clear()}catch{}}function RT(e){try{return sessionStorage.getItem(e)}catch{return null}}function Cw(e,n){try{sessionStorage.setItem(e,n)}catch{}}function LT(e){try{sessionStorage.removeItem(e)}catch{}}function V6(){try{sessionStorage.clear()}catch{}}const Y6=()=>typeof process<"u"&&!1,Ba=[],X6=60,_h=Math.ceil(1e3/X6);let rc,Bm=0,av=0;const q6=()=>{const e=Ba.splice(0,Ba.length);for(const n of e)n()};function $T(){if(rc)return;const e=Date.now(),n=e-av;if(Bm+n<_h){rc=requestAnimationFrame(()=>{rc=void 0,$T()});return}rc=requestAnimationFrame(()=>{rc=void 0,av=e,Bm=Math.min(Bm+n-_h,_h*10),q6()})}let FP=!1;function FT(e){return Y6()?(e(),()=>{}):(Ba.includes(e)||(Ba.push(e),FP||(FP=!0,av=Date.now()-_h-1),$T()),()=>{const n=Ba.indexOf(e);n>-1&&Ba.splice(n,1)})}class Z6{constructor(){m(this,"timeouts",[]);m(this,"intervals",[]);m(this,"rafs",[])}setTimeout(n,t,...r){const o=window.setTimeout(n,t,r);return this.timeouts.push(o),o}setInterval(n,t,...r){const o=window.setInterval(n,t,r);return this.intervals.push(o),o}requestAnimationFrame(n){const t=window.requestAnimationFrame(n);return this.rafs.push(t),t}dispose(){this.timeouts.forEach(n=>clearTimeout(n)),this.intervals.forEach(n=>clearInterval(n)),this.rafs.forEach(n=>cancelAnimationFrame(n)),this.timeouts.length=0,this.intervals.length=0,this.rafs.length=0}}function Q6(e){return e!==null}function J6(){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 NT=J6(),rt=NT[0];NT[1];const eH=Object.getPrototypeOf(rt({}));let Lu=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((n,t)=>(t&=63,t<36?n+=t.toString(36):t<62?n+=(t-26).toString(36).toUpperCase():t>62?n+="-":n+="_",n),"");class Qf{constructor(n,t){m(this,"createDefaultProperties");m(this,"validator");m(this,"ephemeralKeys");m(this,"ephemeralKeySet");m(this,"scope");m(this,"isInstance",n=>(n==null?void 0:n.typeName)===this.typeName);this.typeName=n,this.createDefaultProperties=t.createDefaultProperties,this.validator=t.validator??{validate:o=>o},this.scope=t.scope??"document",this.ephemeralKeys=t.ephemeralKeys;const r=new Set;if(t.ephemeralKeys)for(const[o,s]of Fn(t.ephemeralKeys))s&&r.add(o);this.ephemeralKeySet=r}create(n){const t={...this.createDefaultProperties(),id:this.createId()};for(const[r,o]of Object.entries(n))o!==void 0&&(t[r]=o);return t.typeName=this.typeName,t}clone(n){return{...rt(n),id:this.createId()}}createId(n){return this.typeName+":"+(n??Lu())}createCustomId(n){return this.typeName+":"+n}parseId(n){if(!this.isId(n))throw new Error(`ID "${n}" is not a valid ID for type "${this.typeName}"`);return n.slice(this.typeName.length+1)}isId(n){if(!n)return!1;for(let t=0;t({}),validator:n.validator,scope:n.scope,ephemeralKeys:n.ephemeralKeys})}function Gp(){return{added:{},updated:{},removed:{}}}function lv(e){const n={added:e.removed,removed:e.added,updated:{}};for(const[t,r]of Object.values(e.updated))n.updated[t.id]=[r,t];return n}function zT(e){return Object.keys(e.added).length===0&&Object.keys(e.updated).length===0&&Object.keys(e.removed).length===0}function Iw(e){const n={added:{},removed:{},updated:{}};return Nc(n,e),n}function Nc(e,n){for(const t of n){for(const[r,o]of Fn(t.added))if(e.removed[r]){const s=e.removed[r];delete e.removed[r],s!==o&&(e.updated[r]=[s,o])}else e.added[r]=o;for(const[r,[o,s]]of Fn(t.updated)){if(e.added[r]){e.added[r]=s,delete e.updated[r],delete e.removed[r];continue}if(e.updated[r]){e.updated[r]=[e.updated[r][0],s],delete e.removed[r];continue}e.updated[r]=t.updated[r],delete e.removed[r]}for(const[r,o]of Fn(t.removed))e.added[r]?delete e.added[r]:e.updated[r]?(e.removed[r]=e.updated[r][0],delete e.updated[r]):e.removed[r]=o}}function BT(e){return e&&typeof e=="object"&&"parents"in e}function UT(e){for(let n=0,t=e.parents.length;n{if(e.children.remove(n)&&e.children.isEmpty&&BT(e))for(let t=0,r=e.parents.length;t{if(e.children.add(n)&&BT(e))for(let t=0,r=e.parents.length;tObject.freeze([])),NP=8;class Yp{constructor(){m(this,"arraySize",0);m(this,"array",Array(NP));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(n){if(this.array)return this.array.indexOf(n)!==-1?!1:this.arraySize=c)return[];if(l<=n&&n({stack:null}));function Um(e){const n=tt.stack;tt.stack=null;try{return e()}finally{tt.stack=n}}function WT(e){tt.stack=new tH(tt.stack,e),e.parentSet.clear()}function GT(){const e=tt.stack;if(tt.stack=e.below,e.offset{this._isActivelyListening&&this.execute()});this.name=n,this.runEffect=t,this._scheduleEffect=r==null?void 0:r.scheduleEffect}get isActivelyListening(){return this._isActivelyListening}get scheduleCount(){return this._scheduleCount}maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==En()){if(this.parents.length&&!UT(this)){this.lastReactedEpoch=En();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let n=0,t=this.parents.length;nnH);function aa(e,n,t){const r=new Dl(e,n,t);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function rH(e,n,t){const r=new Dl(e,n,t);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 oH{constructor(n){m(this,"initialAtomValues",new Map);this.parent=n}get isRoot(){return this.parent===null}commit(){this.isRoot?VT(this.initialAtomValues.keys()):this.initialAtomValues.forEach((n,t)=>{this.parent.initialAtomValues.has(t)||this.parent.initialAtomValues.set(t,n)})}abort(){ze.globalEpoch++,this.initialAtomValues.forEach((n,t)=>{var r;t.set(n),(r=t.historyBuffer)==null||r.clear()}),this.commit()}}const ze=ii("transactions",()=>({globalEpoch:_s+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null,reactionEpoch:_s+1}));function sH(){return ze.reactionEpoch}function En(){return ze.globalEpoch}function iH(){return ze.globalIsReacting}function kw(e,n){n.lastTraversedEpoch!==ze.globalEpoch&&(n.lastTraversedEpoch=ze.globalEpoch,n instanceof Dl?e.add(n):n.children.visit(t=>kw(e,t)))}function VT(e){var n;if(ze.globalIsReacting)throw new Error("cannot change atoms during reaction cycle");try{ze.globalIsReacting=!0,ze.reactionEpoch=ze.globalEpoch;const t=new Set;for(const o of e)o.children.visit(s=>kw(t,s));for(const o of t)o.maybeScheduleEffect();let r=0;for(;(n=ze.cleanupReactors)!=null&&n.size;){if(r++>1e3)throw new Error("Reaction update depth limit exceeded");const o=ze.cleanupReactors;ze.cleanupReactors=null;for(const s of o)s.maybeScheduleEffect()}}finally{ze.cleanupReactors=null,ze.globalIsReacting=!1}}function aH(e,n){if(ze.globalIsReacting){const t=ze.cleanupReactors??(ze.cleanupReactors=new Set);e.children.visit(r=>kw(t,r))}else ze.currentTransaction?ze.currentTransaction.initialAtomValues.has(e)||ze.currentTransaction.initialAtomValues.set(e,n):VT([e])}function lH(){ze.globalEpoch++}function cH(e){const n=new oH(ze.currentTransaction);ze.currentTransaction=n;try{let t,r=!1;try{t=e(()=>r=!0)}catch(o){throw n.abort(),o}return r?n.abort():n.commit(),t}finally{ze.currentTransaction=ze.currentTransaction.parent}}function zs(e){return ze.currentTransaction?e():cH(e)}class uH{constructor(n,t,r){m(this,"isEqual");m(this,"computeDiff");m(this,"lastChangedEpoch",En());m(this,"children",new Yp);m(this,"historyBuffer");this.name=n,this.current=t,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new KT(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(n){return this.current}get(){return Xp(this),this.current}set(n,t){var o,s;if(((o=this.isEqual)==null?void 0:o.call(this,this.current,n))??HT(this.current,n))return this.current;lH(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,En(),t??((s=this.computeDiff)==null?void 0:s.call(this,this.current,n,this.lastChangedEpoch,En()))??Jn),this.lastChangedEpoch=En();const r=this.current;return this.current=n,aH(this,r),n}update(n){return this.set(n(this.current))}getDiffSince(n){var t;return Xp(this),n>=this.lastChangedEpoch?Ho:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??Jn}}const dH=ii("Atom",()=>uH);function Mt(e,n,t){return new dH(e,n,t)}let zP=!1;function hH(){zP||(zP=!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 Pc=Symbol.for("com.tldraw.state/UNINITIALIZED"),Di=e=>e===Pc,cv=ii("WithDiff",()=>class{constructor(n,t){this.value=n,this.diff=t}});function Cc(e,n){return new cv(e,n)}class pH{constructor(n,t,r){m(this,"lastChangedEpoch",_s);m(this,"lastTraversedEpoch",_s);m(this,"lastCheckedEpoch",_s);m(this,"parentSet",new Yp);m(this,"parents",[]);m(this,"parentEpochs",[]);m(this,"children",new Yp);m(this,"historyBuffer");m(this,"state",Pc);m(this,"error",null);m(this,"computeDiff");m(this,"isEqual");this.name=n,this.derive=t,r!=null&&r.historyLength&&(this.historyBuffer=new KT(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??HT}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(n){var o;const t=this.lastChangedEpoch===_s,r=En();if(!t&&(this.lastCheckedEpoch===r||this.isActivelyListening&&iH()&&this.lastTraversedEpoch=this.lastChangedEpoch?Ho:((t=this.historyBuffer)==null?void 0:t.getChangesSince(n))??Jn}}const _w=ii("Computed",()=>pH);function fH(e={},n,t,r){const o=r.value,s=Symbol.for("__@tldraw/state__computed__"+t);return r.value=function(){let i=this[s];return i||(i=new _w(t,o.bind(this),e),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[mH]=!0,r}function BP(e={},n,t,r){return r.get?(hH(),gH(e,n,t,r)):fH(e,n,t,r)}function gH(e={},n,t,r){const o=r.get,s=Symbol.for("__@tldraw/state__computed__"+t);return r.get=function(){let i=this[s];return i||(i=new _w(t,o.bind(this),e),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}const mH="@@__isComputedMethod__@@";function V(){if(arguments.length===1){const e=arguments[0];return(n,t,r)=>BP(e,n,t,r)}else return typeof arguments[0]=="string"?new _w(arguments[0],arguments[1],arguments[2]):BP(void 0,arguments[0],arguments[1],arguments[2])}const YT=1,yH=ii("apiVersion",()=>YT);if(yH!==YT)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");function Jf(e,n){const t=xe.useRef(n);t.current=n;const[r,o,s]=xe.useMemo(()=>{let i=null;const a=d=>(i=d,()=>{i=null}),l=new Dl(`useStateTracking(${e})`,()=>{var d;return(d=t.current)==null?void 0:d.call(t)},{scheduleEffect(){i==null||i()}});return[l,a,()=>l.scheduleCount]},[e]);return xe.useSyncExternalStore(o,s,s),xe.useEffect(()=>(r.attach(),r.maybeScheduleEffect(),()=>{r.detach()}),[r]),r.execute()}const UP={apply(e,n,t){return Jf(e.displayName??e.name??"tracked(???)",()=>e.apply(n,t))}},SH=Symbol.for("react.memo"),vH=Symbol.for("react.forward_ref");function lr(e){let n=null;const t=e.$$typeof;return t===SH&&(e=e.type,n=e.compare),t===vH?P.memo(P.forwardRef(new Proxy(e.render,UP))):P.memo(new Proxy(e,UP),n)}function xH(){const e=arguments[0],n=arguments[1],t=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return P.useMemo(()=>V(`useComputed(${e})`,n,t),r)}function Bs(e,n,t=Ho){P.useEffect(()=>{const r=new Dl(e,n);return r.attach(),r.execute(),()=>{r.detach()}},t)}function G(){const e=arguments,n=e.length===3?e[2]:[e[0]],t=e.length===3?e[0]:`useValue(${e[0].name})`,r=P.useRef(!0);r.current=!0;const o=P.useMemo(()=>e.length===1?e[0]:V(t,()=>{if(r.current)return e[1]();try{return e[1]()}catch{return{}}}),n);try{const{subscribe:s,getSnapshot:i}=P.useMemo(()=>({subscribe:a=>aa(`useValue(${t})`,()=>{o.get(),a()}),getSnapshot:()=>o.get()}),[o]);return P.useSyncExternalStore(s,i,i)}finally{r.current=!1}}var qp={exports:{}};qp.exports;(function(e,n){var t=200,r="__lodash_hash_undefined__",o=1,s=2,i=9007199254740991,a="[object Arguments]",l="[object Array]",c="[object AsyncFunction]",d="[object Boolean]",h="[object Date]",p="[object Error]",f="[object Function]",S="[object GeneratorFunction]",g="[object Map]",x="[object Number]",y="[object Null]",v="[object Object]",b="[object Promise]",E="[object Proxy]",I="[object RegExp]",C="[object Set]",k="[object String]",T="[object Symbol]",O="[object Undefined]",_="[object WeakMap]",j="[object ArrayBuffer]",L="[object DataView]",A="[object Float32Array]",R="[object Float64Array]",F="[object Int8Array]",W="[object Int16Array]",K="[object Int32Array]",z="[object Uint8Array]",U="[object Uint8ClampedArray]",X="[object Uint16Array]",J="[object Uint32Array]",le=/[\\^$.*+?()[\]{}|]/g,ye=/^\[object .+?Constructor\]$/,Me=/^(?:0|[1-9]\d*)$/,ae={};ae[A]=ae[R]=ae[F]=ae[W]=ae[K]=ae[z]=ae[U]=ae[X]=ae[J]=!0,ae[a]=ae[l]=ae[j]=ae[d]=ae[L]=ae[h]=ae[p]=ae[f]=ae[g]=ae[x]=ae[v]=ae[I]=ae[C]=ae[k]=ae[_]=!1;var Ue=typeof sn=="object"&&sn&&sn.Object===Object&&sn,Ae=typeof self=="object"&&self&&self.Object===Object&&self,et=Ue||Ae||Function("return this")(),je=n&&!n.nodeType&&n,at=je&&!0&&e&&!e.nodeType&&e,Ne=at&&at.exports===je,Kn=Ne&&Ue.process,Rt=function(){try{return Kn&&Kn.binding&&Kn.binding("util")}catch{}}(),Pn=Rt&&Rt.isTypedArray;function St(M,$){for(var Y=-1,ee=M==null?0:M.length,Xe=0,fe=[];++Y-1}function gL(M,$){var Y=this.__data__,ee=od(Y,M);return ee<0?(++this.size,Y.push([M,$])):Y[ee][1]=$,this}_o.prototype.clear=dL,_o.prototype.delete=hL,_o.prototype.get=pL,_o.prototype.has=fL,_o.prototype.set=gL;function mi(M){var $=-1,Y=M==null?0:M.length;for(this.clear();++$kt))return!1;var lt=fe.get(M);if(lt&&fe.get($))return lt==$;var Wn=-1,Tr=!0,qt=Y&s?new rd:void 0;for(fe.set(M,$),fe.set($,M);++Wn-1&&M%1==0&&M<$}function NL(M){var $=typeof M;return $=="string"||$=="number"||$=="symbol"||$=="boolean"?M!=="__proto__":M===null}function zL(M){return!!db&&db in M}function BL(M){var $=M&&M.constructor,Y=typeof $=="function"&&$.prototype||td;return M===Y}function UL(M){return hb.call(M)}function yi(M){if(M!=null){try{return ub.call(M)}catch{}try{return M+""}catch{}}return""}function bb(M,$){return M===$||M!==M&&$!==$}var HL=Sb(function(){return arguments}())?Sb:function(M){return Wl(M)&&Qr.call(M,"callee")&&!gb.call(M,"callee")},id=Array.isArray;function KL(M){return M!=null&&Cb(M.length)&&!Pb(M)}var Ug=JR||YL;function WL(M,$){return vb(M,$)}function Pb(M){if(!Ib(M))return!1;var $=Kl(M);return $==f||$==S||$==c||$==E}function Cb(M){return typeof M=="number"&&M>-1&&M%1==0&&M<=i}function Ib(M){var $=typeof M;return M!=null&&($=="object"||$=="function")}function Wl(M){return M!=null&&typeof M=="object"}var Eb=Pn?us(Pn):AL;function GL(M){return KL(M)?_L(M):OL(M)}function VL(){return[]}function YL(){return!1}e.exports=WL})(qp,qp.exports);var wH=qp.exports;const bH=ei(wH);function PH(e){if(e.length===0)return new Set;const n=e[0],t=e.slice(1),r=new Set;for(const o of n)t.every(s=>s.has(o))&&r.add(o);return r}function CH(e,n){const t={};for(const r of n)e.has(r)||(t.added??(t.added=new Set),t.added.add(r));for(const r of e)n.has(r)||(t.removed??(t.removed=new Set),t.removed.add(r));return t.added||t.removed?t:void 0}function HP(e,n){for(const[t,r]of Object.entries(e)){const o=r,s=n[t];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 KP(e,n,t){const r=Object.fromEntries(Object.keys(t).map(o=>[o,new Set]));for(const[o,s]of Object.entries(t))if("eq"in s){const a=e.index(n,o).get().get(s.eq);if(a)for(const l of a)r[o].add(l)}else if("neq"in s){const i=e.index(n,o);for(const[a,l]of i.get())if(a!==s.neq)for(const c of l)r[o].add(c)}else if("gt"in s){const i=e.index(n,o);for(const[a,l]of i.get())if(a>s.gt)for(const c of l)r[o].add(c)}return PH(Object.values(r))}class IH{constructor(n,t){m(this,"indexCache",new Map);m(this,"historyCache",new Map);this.atoms=n,this.history=t}filterHistory(n){if(this.historyCache.has(n))return this.historyCache.get(n);const t=V("filterHistory:"+n,(r,o)=>{if(Di(r))return this.history.get();const s=this.history.getDiffSince(o);if(s===Jn)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const d of s){for(const h of gt(d.added))if(h.typeName===n)if(i.removed[h.id]){const p=i.removed[h.id];delete i.removed[h.id],l--,p!==h&&(i.updated[h.id]=[p,h],c++)}else i.added[h.id]=h,a++;for(const[h,p]of gt(d.updated))p.typeName===n&&(i.added[p.id]?i.added[p.id]=p:i.updated[p.id]?i.updated[p.id]=[i.updated[p.id][0],p]:(i.updated[p.id]=[h,p],c++));for(const h of gt(d.removed))h.typeName===n&&(i.added[h.id]?(delete i.added[h.id],a--):i.updated[h.id]?(i.removed[h.id]=i.updated[h.id][0],delete i.updated[h.id],c--,l++):(i.removed[h.id]=h,l++))}return a||l||c?Cc(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(n,t),t}index(n,t){const r=n+":"+t;if(this.indexCache.has(r))return this.indexCache.get(r);const o=this.__uncached_createIndex(n,t);return this.indexCache.set(r,o),o}__uncached_createIndex(n,t){const r=this.filterHistory(n),o=()=>{r.get();const s=new Map;for(const i of gt(this.atoms.get())){const a=i.get();if(a.typeName===n){const l=a[t];s.has(l)||s.set(l,new Set),s.get(l).add(a.id)}}return s};return V("index:"+n+":"+t,(s,i)=>{if(Di(s))return o();const a=r.getDiffSince(i);if(a===Jn)return o();const l=new Map,c=(f,S)=>{let g=l.get(f);g||(g=new kh(s.get(f)??new Set)),g.add(S),l.set(f,g)},d=(f,S)=>{let g=l.get(f);g||(g=new kh(s.get(f)??new Set)),g.remove(S),l.set(f,g)};for(const f of a){for(const S of gt(f.added))if(S.typeName===n){const g=S[t];c(g,S.id)}for(const[S,g]of gt(f.updated))if(g.typeName===n){const x=S[t],y=g[t];x!==y&&(d(x,g.id),c(y,g.id))}for(const S of gt(f.removed))if(S.typeName===n){const g=S[t];d(g,S.id)}}let h,p;for(const[f,S]of l){const g=S.get();g&&(h||(h=new Map(s)),p||(p=new Map),g.value.size===0?h.delete(f):h.set(f,g.value),p.set(f,g.diff))}return h&&p?Cc(h,p):s},{historyLength:100})}record(n,t=()=>({}),r="record:"+n+(t?":"+t.toString():"")){const o=this.ids(n,t,r);return V(r,()=>{var s;for(const i of o.get())return(s=this.atoms.get()[i])==null?void 0:s.get()})}records(n,t=()=>({}),r="records:"+n+(t?":"+t.toString():"")){const o=this.ids(n,t,"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(n,t=()=>({}),r="ids:"+n+(t?":"+t.toString():"")){const o=this.filterHistory(n),s=()=>{o.get();const l=t();return Object.keys(l).length===0?new Set(gt(this.atoms.get()).flatMap(c=>{const d=c.get();return d.typeName===n?d.id:[]})):KP(this,n,l)},i=l=>{const c=s(),d=CH(l,c);return d?Cc(c,d):l},a=V("ids_query:"+r,t,{isEqual:bH});return V("query:"+r,(l,c)=>{const d=a.get();if(Di(l))return s();if(co[s].get())}}class EH{constructor(n){m(this,"_beforeCreateHandlers",{});m(this,"_afterCreateHandlers",{});m(this,"_beforeChangeHandlers",{});m(this,"_afterChangeHandlers",{});m(this,"_beforeDeleteHandlers",{});m(this,"_afterDeleteHandlers",{});m(this,"_operationCompleteHandlers",[]);m(this,"_isEnabled",!0);this.store=n}isEnabled(){return this._isEnabled}setIsEnabled(n){this._isEnabled=n}handleBeforeCreate(n,t){if(!this._isEnabled)return n;const r=this._beforeCreateHandlers[n.typeName];if(r){let o=n;for(const s of r)o=s(o,t);return o}return n}handleAfterCreate(n,t){if(!this._isEnabled)return;const r=this._afterCreateHandlers[n.typeName];if(r)for(const o of r)o(n,t)}handleBeforeChange(n,t,r){if(!this._isEnabled)return t;const o=this._beforeChangeHandlers[t.typeName];if(o){let s=t;for(const i of o)s=i(n,s,r);return s}return t}handleAfterChange(n,t,r){if(!this._isEnabled)return;const o=this._afterChangeHandlers[t.typeName];if(o)for(const s of o)s(n,t,r)}handleBeforeDelete(n,t){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[n.typeName];if(r){for(const o of r)if(o(n,t)===!1)return!1}return!0}handleAfterDelete(n,t){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[n.typeName];if(r)for(const o of r)o(n,t)}handleOperationComplete(n){if(this._isEnabled)for(const t of this._operationCompleteHandlers)t(n)}register(n){const t=[];for(const[r,o]of Object.entries(n))o!=null&&o.beforeCreate&&t.push(this.registerBeforeCreateHandler(r,o.beforeCreate)),o!=null&&o.afterCreate&&t.push(this.registerAfterCreateHandler(r,o.afterCreate)),o!=null&&o.beforeChange&&t.push(this.registerBeforeChangeHandler(r,o.beforeChange)),o!=null&&o.afterChange&&t.push(this.registerAfterChangeHandler(r,o.afterChange)),o!=null&&o.beforeDelete&&t.push(this.registerBeforeDeleteHandler(r,o.beforeDelete)),o!=null&&o.afterDelete&&t.push(this.registerAfterDeleteHandler(r,o.afterDelete));return()=>{for(const r of t)r()}}registerBeforeCreateHandler(n,t){return this._beforeCreateHandlers[n]||(this._beforeCreateHandlers[n]=[]),this._beforeCreateHandlers[n].push(t),()=>vi(this._beforeCreateHandlers[n],t)}registerAfterCreateHandler(n,t){return this._afterCreateHandlers[n]||(this._afterCreateHandlers[n]=[]),this._afterCreateHandlers[n].push(t),()=>vi(this._afterCreateHandlers[n],t)}registerBeforeChangeHandler(n,t){return this._beforeChangeHandlers[n]||(this._beforeChangeHandlers[n]=[]),this._beforeChangeHandlers[n].push(t),()=>vi(this._beforeChangeHandlers[n],t)}registerAfterChangeHandler(n,t){return this._afterChangeHandlers[n]||(this._afterChangeHandlers[n]=[]),this._afterChangeHandlers[n].push(t),()=>vi(this._afterChangeHandlers[n],t)}registerBeforeDeleteHandler(n,t){return this._beforeDeleteHandlers[n]||(this._beforeDeleteHandlers[n]=[]),this._beforeDeleteHandlers[n].push(t),()=>vi(this._beforeDeleteHandlers[n],t)}registerAfterDeleteHandler(n,t){return this._afterDeleteHandlers[n]||(this._afterDeleteHandlers[n]=[]),this._afterDeleteHandlers[n].push(t),()=>vi(this._afterDeleteHandlers[n],t)}registerOperationCompleteHandler(n){return this._operationCompleteHandlers.push(n),()=>vi(this._operationCompleteHandlers,n)}}function vi(e,n){const t=e.indexOf(n);t>=0&&e.splice(t,1)}class Tw{constructor(n){m(this,"id");m(this,"atoms",Mt("store_atoms",{}));m(this,"history",Mt("history",0,{historyLength:1e3}));m(this,"query",new IH(this.atoms,this.history));m(this,"listeners",new Set);m(this,"historyAccumulator",new _H);m(this,"historyReactor");m(this,"cancelHistoryReactor",()=>{});m(this,"schema");m(this,"props");m(this,"scopedTypes");m(this,"sideEffects",new EH(this));m(this,"put",(n,t)=>{this.atomic(()=>{const r={},o={},s=this.atoms.__unsafe__getWithoutCapture();let i=null,a,l=!1;const c=this.isMergingRemoteChanges?"remote":"user";for(let d=0,h=n.length;d{this.atomic(()=>{const t=new Set,r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const s of n){const i=this.atoms.__unsafe__getWithoutCapture()[s];i&&this.sideEffects.handleBeforeDelete(i.get(),r)===!1&&t.add(s)}let o;this.atoms.update(s=>{let i;for(const a of n){if(t.has(a)||!(a in s))continue;i||(i={...s}),o||(o={}),delete i[a];const l=s[a].get();o[a]=l,this.addDiffForAfterEvent(l,null)}return i??s}),o&&this.updateHistory({added:{},updated:{},removed:o})})});m(this,"get",n=>{var t;return(t=this.atoms.get()[n])==null?void 0:t.get()});m(this,"unsafeGetWithoutCapture",n=>{var t;return(t=this.atoms.get()[n])==null?void 0:t.__unsafe__getWithoutCapture()});m(this,"serialize",(n="document")=>{const t={};for(const[r,o]of Fn(this.atoms.get())){const s=o.get();(n==="all"||this.scopedTypes[n].has(s.typeName))&&(t[r]=s)}return t});m(this,"allRecords",()=>gt(this.atoms.get()).map(n=>n.get()));m(this,"clear",()=>{this.remove(RP(this.atoms.get()))});m(this,"update",(n,t)=>{const r=this.atoms.get()[n];if(!r){console.error(`Record ${n} not found. This is probably an error`);return}this.put([t(r.__unsafe__getWithoutCapture())])});m(this,"has",n=>!!this.atoms.get()[n]);m(this,"listen",(n,t)=>{this._flushHistory();const r={onHistory:n,filters:{source:(t==null?void 0:t.source)??"all",scope:(t==null?void 0:t.scope)??"all"}};return this.listeners.add(r),this.historyReactor.scheduler.isActivelyListening||this.historyReactor.start(),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}});m(this,"isMergingRemoteChanges",!1);m(this,"mergeRemoteChanges",n=>{if(this.isMergingRemoteChanges)return n();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.isMergingRemoteChanges=!0,zs(n)}finally{this.isMergingRemoteChanges=!1}});m(this,"createComputedCache",(n,t,r)=>{const o=new Zo;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(n+":"+s,()=>t(a.get()))}).get()}}});m(this,"createSelectedComputedCache",(n,t,r)=>{const o=new Zo;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=V(n+":"+s+":selector",()=>t(i.get()));return V(n+":"+s,()=>r(a.get()))}).get()}}});m(this,"_integrityChecker");m(this,"_isPossiblyCorrupted",!1);m(this,"pendingAfterEvents",null);m(this,"_isInAtomicOp",!1);const{initialData:t,schema:r,id:o}=n;this.id=o??Lu(),this.schema=r,this.props=n.props,t&&this.atoms.set(TT(Fn(t).map(([s,i])=>[s,Mt("atom:"+s,this.schema.validateRecord(this,i,"initialize",null))]))),this.historyReactor=rH("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:s=>this.cancelHistoryReactor=FT(s)}),this.scopedTypes={document:new Set(gt(this.schema.types).filter(s=>s.scope==="document").map(s=>s.typeName)),session:new Set(gt(this.schema.types).filter(s=>s.scope==="session").map(s=>s.typeName)),presence:new Set(gt(this.schema.types).filter(s=>s.scope==="presence").map(s=>s.typeName))}}_flushHistory(){if(this.historyAccumulator.hasChanges()){const n=this.historyAccumulator.flush();for(const{changes:t,source:r}of n){let o=null,s=null,i=null;for(const{onHistory:a,filters:l}of this.listeners)if(!(l.source!=="all"&&l.source!==r))if(l.scope!=="all")if(l.scope==="document"){if(s??(s=this.filterChangesByScope(t,"document")),!s)continue;a({changes:s,source:r})}else if(l.scope==="session"){if(o??(o=this.filterChangesByScope(t,"session")),!o)continue;a({changes:o,source:r})}else{if(i??(i=this.filterChangesByScope(t,"presence")),!i)continue;a({changes:i,source:r})}else a({changes:t,source:r})}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(n,t){const r={added:Fc(n.added,(o,s)=>this.scopedTypes[t].has(s.typeName)),updated:Fc(n.updated,(o,s)=>this.scopedTypes[t].has(s[1].typeName)),removed:Fc(n.removed,(o,s)=>this.scopedTypes[t].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(n){this.historyAccumulator.add({changes:n,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,n)}validate(n){this.allRecords().forEach(t=>this.schema.validateRecord(this,t,n,null))}getStoreSnapshot(n="document"){return{store:this.serialize(n),schema:this.schema.serialize()}}getSnapshot(n="document"){return console.warn("[tldraw] `Store.getSnapshot` is deprecated and will be removed in a future release. Use `getSnapshot` from the `tldraw` package instead."),this.getStoreSnapshot(n)}migrateSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);return{store:t.value,schema:this.schema.serialize()}}loadStoreSnapshot(n){const t=this.schema.migrateStoreSnapshot(n);if(t.type==="error")throw new Error(`Failed to migrate snapshot: ${t.reason}`);const r=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(t.value)),this.ensureStoreIsUsable()})}finally{this.sideEffects.setIsEnabled(r)}}loadSnapshot(n){console.warn("[tldraw] `Store.loadSnapshot` is deprecated and will be removed in a future release. Use `loadSnapshot` from the 'tldraw' package instead."),this.loadStoreSnapshot(n)}extractingChanges(n){const t=[],r=this.historyAccumulator.addInterceptor(o=>t.push(o.changes));try{return zs(n),Iw(t)}finally{r()}}applyDiff(n,{runCallbacks:t=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const o=gt(n.added);for(const[i,a]of gt(n.updated)){const l=this.schema.getType(a.typeName);if(r&&l.ephemeralKeySet.size){const c=this.get(a.id);if(!c){o.push(a);continue}let d=null;for(const[h,p]of Object.entries(a))l.ephemeralKeySet.has(h)||Object.is(p,An(c,h))||(d||(d={...c}),d[h]=p);d&&o.push(d)}else o.push(a)}const s=RP(n.removed);o.length&&this.put(o),s.length&&this.remove(s)},t)}ensureStoreIsUsable(){this.atomic(()=>{var n;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(n=this._integrityChecker)==null||n.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(n,t){if(st(this.pendingAfterEvents,"must be in event operation"),n===t||(n&&t&&st(n.id===t.id),!n&&!t))return;const r=(n||t).id,o=this.pendingAfterEvents.get(r);o?o.after=t:this.pendingAfterEvents.set(r,{before:n,after:t})}flushAtomicCallbacks(){let n=0;const t=this.isMergingRemoteChanges?"remote":"user";for(;this.pendingAfterEvents;){const r=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(n++,n>100)throw new Error("Maximum store update depth exceeded, bailing out");for(const{before:o,after:s}of r.values())o&&s?this.sideEffects.handleAfterChange(o,s,t):o&&!s?this.sideEffects.handleAfterDelete(o,t):!o&&s&&this.sideEffects.handleAfterCreate(s,t);this.pendingAfterEvents||this.sideEffects.handleOperationComplete(t)}}}atomic(n,t=!0){return zs(()=>{if(this._isInAtomicOp)return this.pendingAfterEvents||(this.pendingAfterEvents=new Map),n();this.pendingAfterEvents=new Map;const r=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(t??r),this._isInAtomicOp=!0;try{const o=n();return this.flushAtomicCallbacks(),o}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(r),this._isInAtomicOp=!1}})}addHistoryInterceptor(n){return this.historyAccumulator.addInterceptor(t=>n(t,this.isMergingRemoteChanges?"remote":"user"))}}function kH(e){if(e.length===0)return[];const n=[];let t=[e[0]],r;for(let o=1,s=e.length;o({source:o[0].source,changes:Iw(o.map(s=>s.changes))}))}class _H{constructor(){m(this,"_history",[]);m(this,"_interceptors",new Set)}addInterceptor(n){return this._interceptors.add(n),()=>{this._interceptors.delete(n)}}add(n){this._history.push(n);for(const t of this._interceptors)t(n)}flush(){const n=kH(this._history);return this._history=[],n}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function TH(e,n,t){const r=new Zo;return{get(o,s){return r.get(o,()=>(o instanceof Tw?o:o.store).createComputedCache(e,l=>n(o,l),t)).get(s)}}}function MH(e){const n=[];for(let t=e.length-1;t>=0;t--){const r=e[t];if("id"in r)n.unshift(r);else{const o=r.dependsOn,s=n[0];s&&(n[0]={...s,dependsOn:o.concat(s.dependsOn??[])})}}return n}function el({sequence:e,sequenceId:n,retroactive:t=!0}){const r={sequenceId:n,retroactive:t,sequence:MH(e)};return XT(r),r}function Bn(e,n){return Object.fromEntries(Fn(n).map(([t,r])=>[t,`${e}/${r}`]))}function cr(e){const n=e.sequenceId;return el({sequenceId:n,retroactive:e.retroactive??!0,sequence:e.sequence.map(t=>"id"in t?{...t,scope:"record",filter:r=>{var o,s;return r.typeName===e.recordType&&(((o=t.filter)==null?void 0:o.call(t,r))??!0)&&(((s=e.filter)==null?void 0:s.call(e,r))??!0)}}:t)})}function jH(e){const n=new Map(e.map(s=>[s.id,s])),t=new Set,r=[];function o(s){st(!t.has(s.id),`Circular dependency in migrations: ${s.id}`),t.add(s.id);const{version:i,sequenceId:a}=Zp(s.id),l=n.get(`${a}/${i-1}`);if(l&&o(l),s.dependsOn)for(const c of s.dependsOn){const d=n.get(c);d&&o(d)}n.delete(s.id),r.push(s)}for(const s of n.values())o(s);return r}function Zp(e){const[n,t]=e.split("/");return{sequenceId:n,version:parseInt(t)}}function WP(e,n){n&&st(e.startsWith(n+"/"),`Every migration in sequence '${n}' must have an id starting with '${n}/'. Got invalid id: '${e}'`),st(e.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${e}'`)}function XT(e){if(st(!e.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${e.sequenceId}`),st(e.sequenceId.length,"sequenceId must be a non-empty string"),e.sequence.length===0)return;WP(e.sequence[0].id,e.sequenceId);let n=Zp(e.sequence[0].id).version;st(n===1,`Expected the first migrationId to be '${e.sequenceId}/1' but got '${e.sequence[0].id}'`);for(let t=1;t(e.IncompatibleSubtype="incompatible-subtype",e.UnknownType="unknown-type",e.TargetVersionTooNew="target-version-too-new",e.TargetVersionTooOld="target-version-too-old",e.MigrationError="migration-error",e.UnrecognizedSubtype="unrecognized-subtype",e))(Ss||{});function AH(e){if(e.schemaVersion>2||e.schemaVersion<1)return Ns.err("Bad schema version");if(e.schemaVersion===2)return Ns.ok(e);const n={schemaVersion:2,sequences:{}};for(const[t,r]of Object.entries(e.recordVersions))if(n.sequences[`com.tldraw.${t}`]=r.version,"subTypeKey"in r)for(const[o,s]of Object.entries(r.subTypeVersions))n.sequences[`com.tldraw.${t}.${o}`]=s;return Ns.ok(n)}class Mw{constructor(n,t){m(this,"migrations",{});m(this,"sortedMigrations");var o;this.types=n,this.options=t;for(const s of t.migrations??[])st(!this.migrations[s.sequenceId],`Duplicate migration sequenceId ${s.sequenceId}`),XT(s),this.migrations[s.sequenceId]=s;const r=Object.values(this.migrations).flatMap(s=>s.sequence);this.sortedMigrations=jH(r);for(const s of this.sortedMigrations)if((o=s.dependsOn)!=null&&o.length)for(const i of s.dependsOn){const a=r.find(l=>l.id===i);st(a,`Migration '${s.id}' depends on missing migration '${i}'`)}}static create(n,t){return new Mw(n,t??{})}validateRecord(n,t,r,o){try{const s=An(this.types,t.typeName);if(!s)throw new Error(`Missing definition for record type ${t.typeName}`);return s.validate(t,o??void 0)}catch(s){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:n,record:t,phase:r,recordBefore:o,error:s});throw s}}getMigrationsSince(n){const t=AH(n);if(!t.ok)return t;const r=t.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 Ns.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 d of this.migrations[i].sequence)s.add(d.id);continue}const l=`${i}/${a}`,c=this.migrations[i].sequence.findIndex(d=>d.id===l);if(c===-1)return Ns.err("Incompatible schema?");for(const d of this.migrations[i].sequence.slice(c+1))s.add(d.id)}return Ns.ok(this.sortedMigrations.filter(({id:i})=>s.has(i)))}migratePersistedRecord(n,t,r="up"){const o=this.getMigrationsSince(t);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:Ss.MigrationError};let s=o.value;if(s.length===0)return{type:"success",value:n};if(s.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?Ss.TargetVersionTooOld:Ss.TargetVersionTooNew};if(r==="down"){if(!s.every(i=>i.down))return{type:"error",reason:Ss.TargetVersionTooOld};s=s.slice().reverse()}n=rt(n);try{for(const i of s){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(n):!0))continue;const l=i[r](n);l&&(n=rt(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:Ss.MigrationError}}return{type:"success",value:n}}migrateStoreSnapshot(n){let{store:t}=n;const r=this.getMigrationsSince(n.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:Ss.MigrationError};const o=r.value;if(o.length===0)return{type:"success",value:t};t=rt(t);try{for(const s of o)if(s.scope==="record")for(const[i,a]of Object.entries(t)){if(!(s.filter?s.filter(a):!0))continue;const c=s.up(a);c&&(t[i]=rt(c))}else if(s.scope==="store"){const i=s.up(t);i&&(t=rt(i))}else an(s)}catch(s){return console.error("Error migrating store",s),{type:"error",reason:Ss.MigrationError}}return{type:"success",value:t}}createIntegrityChecker(n){var t,r;return((r=(t=this.options).createIntegrityChecker)==null?void 0:r.call(t,n))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n,sequence:t})=>[n,t.length?Zp(t.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:n})=>[n,0]))}}getType(n){const t=An(this.types,n);return st(t,"record type does not exists"),t}}function OH(e){if(!e.length)return null;let n="";for(const t of e)typeof t=="number"?n+=`.${t}`:t.startsWith("(")?n.endsWith(")")?n=`${n.slice(0,-1)}, ${t.slice(1)}`:n+=t:n+=`.${t}`;return n=n.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),n.startsWith(".")?n.slice(1):n}class Pe extends Error{constructor(t,r=[]){const o=OH(r),s=t.split(` `).map((i,a)=>a===0?i:` ${i}`).join(` `);super(r?`At ${o}: ${s}`:s);m(this,"name","ValidationError");this.rawMessage=t,this.path=r}}function Nn(e,n){try{return n()}catch(t){throw t instanceof Pe?new Pe(t.rawMessage,[e,...t.path]):new Pe(t.toString(),[e])}}function Vs(e){if(e===null)return"null";if(Array.isArray(e))return"an array";const n=typeof e;switch(n){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${n}`;case"object":return`an ${n}`;case"undefined":return"undefined";default:an(n)}}class wn{constructor(n,t){this.validationFn=n,this.validateUsingKnownGoodVersionFn=t}validate(n){return this.validationFn(n)}validateUsingKnownGoodVersion(n,t){return Object.is(n,t)?n:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(n,t):this.validate(t)}isValid(n){try{return this.validate(n),!0}catch{return!1}}nullable(){return NH(this)}optional(){return ZT(this)}refine(n){return new wn(t=>n(this.validate(t)),(t,r)=>{const o=this.validateUsingKnownGoodVersion(t,r);return Object.is(t,o)?t:n(o)})}check(n,t){return typeof n=="string"?this.refine(r=>(Nn(`(check ${n})`,()=>t(r)),r)):this.refine(r=>(n(r),r))}}class DH extends wn{constructor(n){super(t=>{const r=GP.validate(t);for(let o=0;on.validate(r[o]));return r},(t,r)=>{if(!n.validateUsingKnownGoodVersion)return this.validate(r);const o=GP.validate(r);let s=t.length!==o.length;for(let i=0;i=t.length){s=!0,Nn(i,()=>n.validate(a));continue}if(Object.is(t[i],a))continue;const l=Nn(i,()=>n.validateUsingKnownGoodVersion(t[i],a));Object.is(l,t[i])||(s=!0)}return s?r:t}),this.itemValidator=n}nonEmpty(){return this.check(n=>{if(n.length===0)throw new Pe("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(n=>{if(n.length<=1)throw new Pe("Expected an array with length greater than 1")})}}class Qp extends wn{constructor(n,t=!1){super(r=>{if(typeof r!="object"||r===null)throw new Pe(`Expected object, got ${Vs(r)}`);for(const[o,s]of Object.entries(n))Nn(o,()=>{s.validate(An(r,o))});if(!t){for(const o of Object.keys(r))if(!fo(n,o))throw new Pe("Unexpected property",[o])}return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Pe(`Expected object, got ${Vs(o)}`);let s=!1;for(const[i,a]of Object.entries(n)){const l=An(r,i),c=An(o,i);if(Object.is(l,c))continue;const d=Nn(i,()=>{const h=a;return h.validateUsingKnownGoodVersion?h.validateUsingKnownGoodVersion(l,c):h.validate(c)});Object.is(d,l)||(s=!0)}if(!t){for(const i of Object.keys(o))if(!fo(n,i))throw new Pe("Unexpected property",[i])}for(const i of Object.keys(r))if(!fo(o,i)){s=!0;break}return s?o:r}),this.config=n,this.shouldAllowUnknownProperties=t}allowUnknownProperties(){return new Qp(this.config,!0)}extend(n){return new Qp({...this.config,...n})}}class eg extends wn{constructor(n,t,r,o){super(s=>{this.expectObject(s);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(s);return i===void 0?this.unknownValueValidation(s,a):Nn(`(${n} = ${a})`,()=>i.validate(s))},(s,i)=>{this.expectObject(i),this.expectObject(s);const{matchingSchema:a,variant:l}=this.getMatchingSchemaAndVariant(i);return a===void 0?this.unknownValueValidation(i,l):An(s,n)!==An(i,n)?Nn(`(${n} = ${l})`,()=>a.validate(i)):Nn(`(${n} = ${l})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(s,i):a.validate(i))}),this.key=n,this.config=t,this.unknownValueValidation=r,this.useNumberKeys=o}expectObject(n){if(typeof n!="object"||n===null)throw new Pe(`Expected an object, got ${Vs(n)}`,[])}getMatchingSchemaAndVariant(n){const t=An(n,this.key);if(!this.useNumberKeys&&typeof t!="string")throw new Pe(`Expected a string for key "${this.key}", got ${Vs(t)}`);if(this.useNumberKeys&&!Number.isFinite(Number(t)))throw new Pe(`Expected a number for key "${this.key}", got "${t}"`);return{matchingSchema:fo(this.config,t)?this.config[t]:void 0,variant:t}}validateUnknownVariants(n){return new eg(this.key,this.config,n,this.useNumberKeys)}}class RH extends wn{constructor(n,t){super(r=>{if(typeof r!="object"||r===null)throw new Pe(`Expected object, got ${Vs(r)}`);for(const[o,s]of Object.entries(r))Nn(o,()=>{n.validate(o),t.validate(s)});return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Pe(`Expected object, got ${Vs(o)}`);let s=!1;for(const[i,a]of Object.entries(o)){if(!fo(r,i)){s=!0,Nn(i,()=>{n.validate(i),t.validate(a)});continue}const l=An(r,i),c=a;if(Object.is(l,c))continue;const d=Nn(i,()=>t.validateUsingKnownGoodVersion?t.validateUsingKnownGoodVersion(l,c):t.validate(c));Object.is(d,l)||(s=!0)}for(const i of Object.keys(r))if(!fo(o,i)){s=!0;break}return s?o:r}),this.keyValidator=n,this.valueValidator=t}}function jw(e){return new wn(n=>{if(typeof n!==e)throw new Pe(`Expected ${e}, got ${Vs(n)}`);return n})}const LH=new wn(e=>e),pe=jw("string"),de=jw("number").check(e=>{if(Number.isNaN(e))throw new Pe("Expected a number, got NaN");if(!Number.isFinite(e))throw new Pe(`Expected a finite number, got ${e}`)}),Jp=de.check(e=>{if(e<0)throw new Pe(`Expected a positive number, got ${e}`)}),Ct=de.check(e=>{if(e<=0)throw new Pe(`Expected a non-zero positive number, got ${e}`)}),qT=de.check(e=>{if(!Number.isInteger(e))throw new Pe(`Expected an integer, got ${e}`)}),Th=qT.check(e=>{if(e<0)throw new Pe(`Expected a positive integer, got ${e}`)}),$H=qT.check(e=>{if(e<=0)throw new Pe(`Expected a non-zero positive integer, got ${e}`)}),we=jw("boolean");function cn(e){return new wn(n=>{if(n!==e)throw new Pe(`Expected ${e}, got ${JSON.stringify(n)}`);return e})}const GP=new wn(e=>{if(!Array.isArray(e))throw new Pe(`Expected an array, got ${Vs(e)}`);return e});function zt(e){return new DH(e)}function Se(e){return new Qp(e)}function uv(e){return typeof e=="object"&&e!==null&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===eH)}function dv(e){return e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(dv):uv(e)?Object.values(e).every(dv):!1}const Bt=new wn(e=>{if(dv(e))return e;throw new Pe(`Expected json serializable value, got ${typeof e}`)},(e,n)=>{if(Array.isArray(e)&&Array.isArray(n)){let t=e.length!==n.length;for(let r=0;r=e.length){t=!0,Bt.validate(n[r]);continue}const o=e[r],s=n[r];if(Object.is(o,s))continue;const i=Bt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(t=!0)}return t?n:e}else if(uv(e)&&uv(n)){let t=!1;for(const r of Object.keys(n)){if(!fo(e,r)){t=!0,Bt.validate(n[r]);continue}const o=e[r],s=n[r];if(Object.is(o,s))continue;const i=Bt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(t=!0)}for(const r of Object.keys(e))if(!fo(n,r)){t=!0;break}return t?n:e}else return Bt.validate(n)});function ef(e,n){return new RH(e,n)}function Aw(e,n){return new eg(e,n,(t,r)=>{throw new Pe(`Expected one of ${Object.keys(n).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!1)}function FH(e,n){return new eg(e,n,(t,r)=>{throw new Pe(`Expected one of ${Object.keys(n).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[e])},!0)}function Io(e,n){return new wn(t=>Nn(e,()=>n.validate(t)),(t,r)=>Nn(e,()=>n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(t,r):n.validate(r)))}function tg(e){return new wn(n=>{if(!e.has(n)){const t=Array.from(e,r=>JSON.stringify(r)).join(" or ");throw new Pe(`Expected ${t}, got ${n}`)}return n})}function ZT(e){return new wn(n=>{if(n!==void 0)return e.validate(n)},(n,t)=>{if(!(n===void 0&&t===void 0)&&t!==void 0)return e.validateUsingKnownGoodVersion&&n!==void 0?e.validateUsingKnownGoodVersion(n,t):e.validate(t)})}function NH(e){return new wn(n=>n===null?null:e.validate(n),(n,t)=>t===null?null:e.validateUsingKnownGoodVersion&&n!==null?e.validateUsingKnownGoodVersion(n,t):e.validate(t))}function ng(...e){return tg(new Set(e))}function QT(e){try{return new URL(e)}catch{if(e.startsWith("/")||e.startsWith("./"))try{return new URL(e,"http://example.com")}catch{throw new Pe(`Expected a valid url, got ${JSON.stringify(e)}`)}throw new Pe(`Expected a valid url, got ${JSON.stringify(e)}`)}}const zH=new Set(["http:","https:","mailto:"]),or=pe.check(e=>{if(e==="")return;const n=QT(e);if(!zH.has(n.protocol.toLowerCase()))throw new Pe(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)}),BH=new Set(["http:","https:","data:","asset:"]),Ui=pe.check(e=>{if(e==="")return;const n=QT(e);if(!BH.has(n.protocol.toLowerCase()))throw new Pe(`Expected a valid url, got ${JSON.stringify(e)} (invalid protocol)`)}),Ow=pe.refine(e=>{try{return H6(e),e}catch{throw new Pe(`Expected an index key, got ${JSON.stringify(e)}`)}});function er(e){return pe.refine(n=>{if(!n.startsWith(`${e}:`))throw new Error(`${e} ID must start with "${e}:"`);return n})}const rg=er("asset");function Dw(e,n){return Se({id:rg,typeName:cn("asset"),type:cn(e),props:n,meta:Bt})}const Hi=Se({x:de,y:de,z:de.optional()}),zc=Se({x:de,y:de,w:de,h:de}),JT=de.check(e=>{if(e<0||e>1)throw new Pe("Opacity must be between 0 and 1")}),UH=pe.refine(e=>{if(!e.startsWith("page:")&&!e.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return e}),gr=er("shape");function HH(e,n,t){return Se({id:gr,typeName:cn("shape"),x:de,y:de,rotation:de,index:Ow,parentId:UH,type:cn(e),isLocked:we,opacity:JT,props:n?Se(n):Bt,meta:t?Se(t):Bt})}const KH=er("binding");function WH(e,n,t){return Se({id:KH,typeName:cn("binding"),type:cn(e),fromId:gr,toId:gr,props:n?Se(n):Bt,meta:t?Se(t):Bt})}Bn("com.tldraw.binding",{});cr({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function Ri(e){return`binding:${Lu()}`}function GH(e){return Co("binding",{scope:"document",validator:Io("binding",Aw("type",Ru(e,(n,{props:t,meta:r})=>WH(n,t,r))))}).withDefaultProperties(()=>({meta:{}}))}class Yt{constructor(n,t,r){this.id=n,this.defaultValue=t,this.type=r}static define(n,t){const{defaultValue:r,type:o=LH}=t;return new Yt(n,r,o)}static defineEnum(n,t){const{defaultValue:r,values:o}=t;return new VH(n,r,o)}validate(n){return this.type.validate(n)}validateUsingKnownGoodVersion(n,t){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(n,t):this.validate(t)}}class VH extends Yt{constructor(n,t,r){super(n,t,ng(...r)),this.values=r}}const Ad=Bn("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),YH=cr({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:Ad.AddIsLocked,up:e=>{e.isLocked=!1},down:e=>{delete e.isLocked}},{id:Ad.HoistOpacity,up:e=>{e.opacity=Number(e.props.opacity??"1"),delete e.props.opacity},down:e=>{const n=e.opacity;delete e.opacity,e.props.opacity=n<.175?"0.1":n<.375?"0.25":n<.625?"0.5":n<.875?"0.75":"1"}},{id:Ad.AddMeta,up:e=>{e.meta={}}},{id:Ad.AddWhite,up:e=>{},down:e=>{e.props.color==="white"&&(e.props.color="black")}}]});function Ua(e){return e?e.typeName==="shape":!1}function kn(e){return e?e.startsWith("shape:"):!1}function $e(e){return`shape:${e??Lu()}`}function eM(e){const n=new Map;for(const[t,r]of Object.entries(e))if(r instanceof Yt){if(n.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);n.set(r,t)}return n}function Gr(e,n){return Ru(n,(t,r)=>`com.tldraw.shape.${e}/${r}`)}function XH(e){return Co("shape",{scope:"document",validator:Io("shape",Aw("type",Ru(e,(n,{props:t,meta:r})=>HH(n,t,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function VP(e,n){const t=[];for(const[r,{migrations:o}]of Object.entries(n)){const s=`com.tldraw.${e}.${r}`;o?"sequenceId"in o?(st(s===o.sequenceId,`sequenceId mismatch for ${r} ${Qf} migrations. Expected '${s}', got '${o.sequenceId}'`),t.push(o)):"sequence"in o?t.push(el({sequenceId:s,retroactive:!1,sequence:o.sequence.map(i=>"id"in i?tM(e,r,i):i)})):t.push(el({sequenceId:s,retroactive:!1,sequence:Object.keys(o.migrators).map(i=>Number(i)).sort((i,a)=>i-a).map(i=>({id:`${s}/${i}`,scope:"record",filter:a=>a.typeName===e&&a.type===r,up:a=>{const l=o.migrators[i].up(a);if(l)return l},down:a=>{const l=o.migrators[i].down(a);if(l)return l}}))})):t.push(el({sequenceId:s,retroactive:!1,sequence:[]}))}return t}function tM(e,n,t){return{id:t.id,dependsOn:t.dependsOn,scope:"record",filter:r=>r.typeName===e&&r.type===n,up:r=>{const o=t.up(r.props);o&&(r.props=o)},down:typeof t.down=="function"?r=>{const o=t.down(r.props);o&&(r.props=o)}:void 0}}const nM=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],tf={lightMode:{id:"light",text:"#000000",background:"rgb(249, 250, 251)",solid:"#fcfffe",black:{solid:"#1d1d1d",fill:"#1d1d1d",note:{fill:"#FCE19C",text:"#000000"},semi:"#e8e8e8",pattern:"#494949",highlight:{srgb:"#fddd00",p3:"color(display-p3 0.972 0.8705 0.05)"}},blue:{solid:"#4465e9",fill:"#4465e9",note:{fill:"#8AA3FF",text:"#000000"},semi:"#dce1f8",pattern:"#6681ee",highlight:{srgb:"#10acff",p3:"color(display-p3 0.308 0.6632 0.9996)"}},green:{solid:"#099268",fill:"#099268",note:{fill:"#6FC896",text:"#000000"},semi:"#d3e9e3",pattern:"#39a785",highlight:{srgb:"#00ffc8",p3:"color(display-p3 0.2536 0.984 0.7981)"}},grey:{solid:"#9fa8b2",fill:"#9fa8b2",note:{fill:"#C0CAD3",text:"#000000"},semi:"#eceef0",pattern:"#bcc3c9",highlight:{srgb:"#cbe7f1",p3:"color(display-p3 0.8163 0.9023 0.9416)"}},"light-blue":{solid:"#4ba1f1",fill:"#4ba1f1",note:{fill:"#9BC4FD",text:"#000000"},semi:"#ddedfa",pattern:"#6fbbf8",highlight:{srgb:"#00f4ff",p3:"color(display-p3 0.1512 0.9414 0.9996)"}},"light-green":{solid:"#4cb05e",fill:"#4cb05e",note:{fill:"#98D08A",text:"#000000"},semi:"#dbf0e0",pattern:"#65cb78",highlight:{srgb:"#65f641",p3:"color(display-p3 0.563 0.9495 0.3857)"}},"light-red":{solid:"#f87777",fill:"#f87777",note:{fill:"#F7A5A1",text:"#000000"},semi:"#f4dadb",pattern:"#fe9e9e",highlight:{srgb:"#ff7fa3",p3:"color(display-p3 0.9988 0.5301 0.6397)"}},"light-violet":{solid:"#e085f4",fill:"#e085f4",note:{fill:"#DFB0F9",text:"#000000"},semi:"#f5eafa",pattern:"#e9acf8",highlight:{srgb:"#ff88ff",p3:"color(display-p3 0.9676 0.5652 0.9999)"}},orange:{solid:"#e16919",fill:"#e16919",note:{fill:"#FAA475",text:"#000000"},semi:"#f8e2d4",pattern:"#f78438",highlight:{srgb:"#ffa500",p3:"color(display-p3 0.9988 0.6905 0.266)"}},red:{solid:"#e03131",fill:"#e03131",note:{fill:"#FC8282",text:"#000000"},semi:"#f4dadb",pattern:"#e55959",highlight:{srgb:"#ff636e",p3:"color(display-p3 0.9992 0.4376 0.45)"}},violet:{solid:"#ae3ec9",fill:"#ae3ec9",note:{fill:"#DB91FD",text:"#000000"},semi:"#ecdcf2",pattern:"#bd63d3",highlight:{srgb:"#c77cff",p3:"color(display-p3 0.7469 0.5089 0.9995)"}},yellow:{solid:"#f1ac4b",fill:"#f1ac4b",note:{fill:"#FED49A",text:"#000000"},semi:"#f9f0e6",pattern:"#fecb92",highlight:{srgb:"#fddd00",p3:"color(display-p3 0.972 0.8705 0.05)"}},white:{solid:"#FFFFFF",fill:"#FFFFFF",semi:"#f5f5f5",pattern:"#f9f9f9",note:{fill:"#FFFFFF",text:"#000000"},highlight:{srgb:"#ffffff",p3:"color(display-p3 1 1 1)"}}},darkMode:{id:"dark",text:"hsl(210, 17%, 98%)",background:"hsl(240, 5%, 6.5%)",solid:"#010403",black:{solid:"#f2f2f2",fill:"#f2f2f2",note:{fill:"#2c2c2c",text:"#f2f2f2"},semi:"#2c3036",pattern:"#989898",highlight:{srgb:"#d2b700",p3:"color(display-p3 0.8078 0.7225 0.0312)"}},blue:{solid:"#4f72fc",fill:"#4f72fc",note:{fill:"#2A3F98",text:"#f2f2f2"},semi:"#262d40",pattern:"#3a4b9e",highlight:{srgb:"#0079d2",p3:"color(display-p3 0.0032 0.4655 0.7991)"}},green:{solid:"#099268",fill:"#099268",note:{fill:"#014429",text:"#f2f2f2"},semi:"#253231",pattern:"#366a53",highlight:{srgb:"#009774",p3:"color(display-p3 0.0085 0.582 0.4604)"}},grey:{solid:"#9398b0",fill:"#9398b0",note:{fill:"#56595F",text:"#f2f2f2"},semi:"#33373c",pattern:"#7c8187",highlight:{srgb:"#9cb4cb",p3:"color(display-p3 0.6299 0.7012 0.7856)"}},"light-blue":{solid:"#4dabf7",fill:"#4dabf7",note:{fill:"#1F5495",text:"#f2f2f2"},semi:"#2a3642",pattern:"#4d7aa9",highlight:{srgb:"#00bdc8",p3:"color(display-p3 0.0023 0.7259 0.7735)"}},"light-green":{solid:"#40c057",fill:"#40c057",note:{fill:"#21581D",text:"#f2f2f2"},semi:"#2a3830",pattern:"#4e874e",highlight:{srgb:"#00a000",p3:"color(display-p3 0.2711 0.6172 0.0195)"}},"light-red":{solid:"#ff8787",fill:"#ff8787",note:{fill:"#923632",text:"#f2f2f2"},semi:"#3b3235",pattern:"#a56767",highlight:{srgb:"#db005b",p3:"color(display-p3 0.7849 0.0585 0.3589)"}},"light-violet":{solid:"#e599f7",fill:"#e599f7",note:{fill:"#762F8E",text:"#f2f2f2"},semi:"#383442",pattern:"#9770a9",highlight:{srgb:"#c400c7",p3:"color(display-p3 0.7024 0.0403 0.753)"}},orange:{solid:"#f76707",fill:"#f76707",note:{fill:"#843906",text:"#f2f2f2"},semi:"#3a2e2a",pattern:"#9f552d",highlight:{srgb:"#d07a00",p3:"color(display-p3 0.7699 0.4937 0.0085)"}},red:{solid:"#e03131",fill:"#e03131",note:{fill:"#89231A",text:"#f2f2f2"},semi:"#36292b",pattern:"#8f3734",highlight:{srgb:"#de002c",p3:"color(display-p3 0.7978 0.0509 0.2035)"}},violet:{solid:"#ae3ec9",fill:"#ae3ec9",note:{fill:"#681683",text:"#f2f2f2"},semi:"#31293c",pattern:"#763a8b",highlight:{srgb:"#9e00ee",p3:"color(display-p3 0.5651 0.0079 0.8986)"}},yellow:{solid:"#ffc034",fill:"#ffc034",note:{fill:"#98571B",text:"#f2f2f2"},semi:"#3c3934",pattern:"#fecb92",highlight:{srgb:"#d2b700",p3:"color(display-p3 0.8078 0.7225 0.0312)"}},white:{solid:"#f3f3f3",fill:"#f3f3f3",semi:"#f5f5f5",pattern:"#f9f9f9",note:{fill:"#eaeaea",text:"#1d1d1d"},highlight:{srgb:"#ffffff",p3:"color(display-p3 1 1 1)"}}}};function ss(e){return e.isDarkMode?tf.darkMode:tf.lightMode}const sr=Yt.defineEnum("tldraw:color",{defaultValue:"black",values:nM}),rM=Yt.defineEnum("tldraw:labelColor",{defaultValue:"black",values:nM}),Ki=Yt.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),Wi=Yt.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill"]}),So=Yt.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),oM={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},vo=Yt.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),sM=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],nf=Yt.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:sM}),rf=Yt.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:sM}),iM={labelColor:rM,color:sr,fill:Wi,dash:Ki,size:vo,arrowheadStart:nf,arrowheadEnd:rf,font:So,start:Hi,end:Hi,bend:de,text:pe,labelPosition:de,scale:Ct},Pa=Gr("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5});function Od(e){return tM("shape","arrow",e)}const aM=el({sequenceId:"com.tldraw.shape.arrow",sequence:[Od({id:Pa.AddLabelColor,up:e=>{e.labelColor="black"},down:"retired"}),Od({id:Pa.AddIsPrecise,up:({start:e,end:n})=>{e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5)),n.type==="binding"&&(n.isPrecise=!(n.normalizedAnchor.x===.5&&n.normalizedAnchor.y===.5))},down:({start:e,end:n})=>{e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise),n.type==="binding"&&(n.isPrecise||(n.normalizedAnchor={x:.5,y:.5}),delete n.isPrecise)}}),Od({id:Pa.AddLabelPosition,up:e=>{e.labelPosition=.5},down:e=>{delete e.labelPosition}}),{id:Pa.ExtractBindings,scope:"store",up:e=>{const n=Object.values(e).filter(t=>t.typeName==="shape"&&t.type==="arrow");for(const t of n){const{start:r,end:o}=t.props;if(r.type==="binding"){const s=Ri(),i={typeName:"binding",id:s,type:"arrow",fromId:t.id,toId:r.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:r.normalizedAnchor,isExact:r.isExact,isPrecise:r.isPrecise}};e[s]=i,t.props.start={x:0,y:0}}else delete t.props.start.type;if(o.type==="binding"){const s=Ri(),i={typeName:"binding",id:s,type:"arrow",fromId:t.id,toId:o.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:o.normalizedAnchor,isExact:o.isExact,isPrecise:o.isPrecise}};e[s]=i,t.props.end={x:0,y:0}}else delete t.props.end.type}}},Od({id:Pa.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}})]}),lM={terminal:ng("start","end"),normalizedAnchor:Hi,isExact:we,isPrecise:we},cM={sequence:[{dependsOn:[Pa.ExtractBindings]}]},qH=Io("camera",Se({typeName:cn("camera"),id:er("camera"),x:de,y:de,z:de,meta:Bt})),ZH=Bn("com.tldraw.camera",{AddMeta:1}),QH=cr({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:ZH.AddMeta,up:e=>{e.meta={}}}]}),lo=Co("camera",{validator:qH,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),JH=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"]),uM=tg(JH),e9=Se({type:uM,rotation:de}),t9=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),n9=tg(t9),r9=new Set(["starting","paused","active","stopping"]),dM=Se({id:pe,points:zt(Hi),size:Jp,color:n9,opacity:de,state:tg(r9),delay:de,shrink:de,taper:we}),hu=er("page"),o9=Io("page",Se({typeName:cn("page"),id:hu,name:pe,index:Ow,meta:Bt})),s9=Bn("com.tldraw.page",{AddMeta:1}),i9=cr({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:s9.AddMeta,up:e=>{e.meta={}}}]}),Qo=Co("page",{validator:o9,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function In(e){return Qo.isId(e)}const a9={id:!1,typeName:!1,currentPageId:!1,opacityForNextShape:!1,stylesForNextShape:!1,followingUserId:!1,highlightedUserIds:!1,brush:!1,cursor:!1,scribbles:!1,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!1,chatMessage:!1,isChatting:!1,isPenMode:!1,isGridMode:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!1,openMenus:!1,isChangingStyle:!1,isReadonly:!0,meta:!1,duplicateProps:!1},hM=e=>e?Fc(e,n=>a9[n]):null;er("instance");function l9(e){const n={};for(const[r,o]of e)n[r]=ZT(o);const t=Io("instance",Se({typeName:cn("instance"),id:er("instance"),currentPageId:hu,followingUserId:pe.nullable(),brush:zc.nullable(),opacityForNextShape:JT,stylesForNextShape:Se(n),cursor:e9,scribbles:zt(dM),isFocusMode:we,isDebugMode:we,isToolLocked:we,exportBackground:we,screenBounds:zc,insets:zt(we),zoomBrush:zc.nullable(),isPenMode:we,isGridMode:we,chatMessage:pe,isChatting:we,highlightedUserIds:zt(pe),isFocused:we,devicePixelRatio:de,isCoarsePointer:we,isHoveringCanvas:we.nullable(),openMenus:zt(pe),isChangingStyle:we,isReadonly:we,meta:Bt,duplicateProps:Se({shapeIds:zt(er("shape")),offset:Se({x:de,y:de})}).nullable()}));return Co("instance",{validator:t,scope:"session",ephemeralKeys:{currentPageId:!1,meta:!1,followingUserId:!0,opacityForNextShape:!0,stylesForNextShape:!0,brush:!0,cursor:!0,scribbles:!0,isFocusMode:!0,isDebugMode:!0,isToolLocked:!0,exportBackground:!0,screenBounds:!0,insets:!0,zoomBrush:!0,isPenMode:!0,isGridMode:!0,chatMessage:!0,isChatting:!0,highlightedUserIds:!0,isFocused:!0,devicePixelRatio:!0,isCoarsePointer:!0,isHoveringCanvas:!0,openMenus:!0,isChangingStyle:!0,isReadonly:!0,duplicateProps:!0}}).withDefaultProperties(()=>({followingUserId:null,opacityForNextShape:1,stylesForNextShape:{},brush:null,scribbles:[],cursor:{type:"default",rotation:0},isFocusMode:!1,exportBackground:!1,isDebugMode:!1,isToolLocked:!1,screenBounds:{x:0,y:0,w:1080,h:720},insets:[!1,!1,!1,!1],zoomBrush:null,isGridMode:!1,isPenMode:!1,chatMessage:"",isChatting:!1,highlightedUserIds:[],isFocused:!1,devicePixelRatio:typeof window>"u"?1:window.devicePixelRatio,isCoarsePointer:!1,isHoveringCanvas:null,openMenus:[],isChangingStyle:!1,isReadonly:!1,meta:{},duplicateProps:null}))}const qe=Bn("com.tldraw.instance",{AddTransparentExportBgs:1,RemoveDialog:2,AddToolLockMode:3,RemoveExtraPropsForNextShape:4,AddLabelColor:5,AddFollowingUserId:6,RemoveAlignJustify:7,AddZoom:8,AddVerticalAlign:9,AddScribbleDelay:10,RemoveUserId:11,AddIsPenModeAndIsGridMode:12,HoistOpacity:13,AddChat:14,AddHighlightedUserIds:15,ReplacePropsForNextShapeWithStylesForNextShape:16,AddMeta:17,RemoveCursorColor:18,AddLonelyProperties:19,ReadOnlyReadonly:20,AddHoveringCanvas:21,AddScribbles:22,AddInset:23,AddDuplicateProps:24,RemoveCanMoveCamera:25}),c9=cr({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:qe.AddTransparentExportBgs,up:e=>({...e,exportBackground:!0})},{id:qe.RemoveDialog,up:({dialog:e,...n})=>n},{id:qe.AddToolLockMode,up:e=>({...e,isToolLocked:!1})},{id:qe.RemoveExtraPropsForNextShape,up:({propsForNextShape:e,...n})=>({...n,propsForNextShape:Object.fromEntries(Object.entries(e).filter(([t])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(t)))})},{id:qe.AddLabelColor,up:({propsForNextShape:e,...n})=>({...n,propsForNextShape:{...e,labelColor:"black"}})},{id:qe.AddFollowingUserId,up:e=>({...e,followingUserId:null})},{id:qe.RemoveAlignJustify,up:e=>{let n=e.propsForNextShape.align;return n==="justify"&&(n="start"),{...e,propsForNextShape:{...e.propsForNextShape,align:n}}}},{id:qe.AddZoom,up:e=>({...e,zoomBrush:null})},{id:qe.AddVerticalAlign,up:e=>({...e,propsForNextShape:{...e.propsForNextShape,verticalAlign:"middle"}})},{id:qe.AddScribbleDelay,up:e=>e.scribble!==null?{...e,scribble:{...e.scribble,delay:0}}:{...e}},{id:qe.RemoveUserId,up:({userId:e,...n})=>n},{id:qe.AddIsPenModeAndIsGridMode,up:e=>({...e,isPenMode:!1,isGridMode:!1})},{id:qe.HoistOpacity,up:({propsForNextShape:{opacity:e,...n},...t})=>({...t,opacityForNextShape:Number(e??"1"),propsForNextShape:n})},{id:qe.AddChat,up:e=>({...e,chatMessage:"",isChatting:!1})},{id:qe.AddHighlightedUserIds,up:e=>({...e,highlightedUserIds:[]})},{id:qe.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:e,...n})=>({...n,stylesForNextShape:{}})},{id:qe.AddMeta,up:e=>({...e,meta:{}})},{id:qe.RemoveCursorColor,up:e=>{const{color:n,...t}=e.cursor;return{...e,cursor:t}}},{id:qe.AddLonelyProperties,up:e=>({...e,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:qe.ReadOnlyReadonly,up:({isReadOnly:e,...n})=>({...n,isReadonly:e})},{id:qe.AddHoveringCanvas,up:e=>({...e,isHoveringCanvas:null})},{id:qe.AddScribbles,up:({scribble:e,...n})=>({...n,scribbles:[]})},{id:qe.AddInset,up:e=>({...e,insets:[!1,!1,!1,!1]}),down:({insets:e,...n})=>({...n})},{id:qe.AddDuplicateProps,up:e=>({...e,duplicateProps:null}),down:({duplicateProps:e,...n})=>({...n})},{id:qe.RemoveCanMoveCamera,up:({canMoveCamera:e,...n})=>({...n}),down:e=>({...e,canMoveCamera:!0})}]}),gn="instance:instance",u9=Io("instance_page_state",Se({typeName:cn("instance_page_state"),id:er("instance_page_state"),pageId:hu,selectedShapeIds:zt(gr),hintingShapeIds:zt(gr),erasingShapeIds:zt(gr),hoveredShapeId:gr.nullable(),editingShapeId:gr.nullable(),croppingShapeId:gr.nullable(),focusedGroupId:gr.nullable(),meta:Bt})),oc=Bn("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),d9=cr({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:oc.AddCroppingId,up(e){e.croppingShapeId=null}},{id:oc.RemoveInstanceIdAndCameraId,up(e){delete e.instanceId,delete e.cameraId}},{id:oc.AddMeta,up:e=>{e.meta={}}},{id:oc.RenameProperties,up:e=>{},down:e=>{}},{id:oc.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}}]}),$r=Co("instance_page_state",{validator:u9,scope:"session",ephemeralKeys:{pageId:!1,selectedShapeIds:!1,editingShapeId:!1,croppingShapeId:!1,meta:!1,hintingShapeIds:!0,erasingShapeIds:!0,hoveredShapeId:!0,focusedGroupId:!0}}).withDefaultProperties(()=>({editingShapeId:null,croppingShapeId:null,selectedShapeIds:[],hoveredShapeId:null,erasingShapeIds:[],hintingShapeIds:[],focusedGroupId:null,meta:{}})),h9=Io("pointer",Se({typeName:cn("pointer"),id:er("pointer"),x:de,y:de,lastActivityTimestamp:de,meta:Bt})),p9=Bn("com.tldraw.pointer",{AddMeta:1}),f9=cr({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:p9.AddMeta,up:e=>{e.meta={}}}]}),Rw=Co("pointer",{validator:h9,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),of=Rw.createId("pointer"),g9=Io("instance_presence",Se({typeName:cn("instance_presence"),id:er("instance_presence"),userId:pe,userName:pe,lastActivityTimestamp:de,followingUserId:pe.nullable(),cursor:Se({x:de,y:de,type:uM,rotation:de}),color:pe,camera:Se({x:de,y:de,z:de}),screenBounds:zc,selectedShapeIds:zt(er("shape")),currentPageId:er("page"),brush:zc.nullable(),scribbles:zt(dM),chatMessage:pe,meta:Bt})),sc=Bn("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5}),m9=cr({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:sc.AddScribbleDelay,up:e=>{e.scribble!==null&&(e.scribble.delay=0)}},{id:sc.RemoveInstanceId,up:e=>{delete e.instanceId}},{id:sc.AddChatMessage,up:e=>{e.chatMessage=""}},{id:sc.AddMeta,up:e=>{e.meta={}}},{id:sc.RenameSelectedShapeIds,up:e=>{}}]}),y9=Co("instance_presence",{validator:g9,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:{}})),S9=Io("document",Se({typeName:cn("document"),id:cn("document:document"),gridSize:de,name:pe,meta:Bt})),YP=Bn("com.tldraw.document",{AddName:1,AddMeta:2}),v9=cr({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:YP.AddName,up:e=>{e.name=""},down:e=>{delete e.name}},{id:YP.AddMeta,up:e=>{e.meta={}}}]}),Lw=Co("document",{validator:S9,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),hv=Lw.createId("document");function x9(e,n){return e.indexn.index?1:0}function XP(e){e.typeName==="asset"&&("src"in e&&(e.src=""),"src"in e.props&&(e.props.src=""))}const w9=({error:e,phase:n,record:t,recordBefore:r})=>{throw xw(e,{tags:{origin:"store.validateRecord",storePhase:n,isExistingValidationIssue:n==="initialize"},extras:{recordBefore:r?XP(rt(r)):void 0,recordAfter:XP(rt(t))}}),e};function b9(){return[Qo.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function P9(e){const n=e.query.ids("page"),t=()=>{if(!e.has(hv))return e.put([Lw.create({id:hv,name:e.props.defaultName})]),t();if(!e.has(of))return e.put([Rw.create({id:of})]),t();const r=n.get();if(r.size===0)return e.put(b9()),t();const o=()=>[...r].map(l=>e.get(l)).sort(x9)[0].id,s=e.get(gn);if(s){if(!r.has(s.currentPageId))return e.put([{...s,currentPageId:o()}]),t()}else return e.put([e.schema.types.instance.create({id:gn,currentPageId:o(),exportBackground:!0})]),t();const i=new Set,a=new Set;for(const l of r){const c=$r.createId(l);e.has(c)||i.add(c);const d=lo.createId(l);e.has(d)||a.add(d)}i.size>0&&e.put([...i].map(l=>$r.create({id:l,pageId:$r.parseId(l)}))),a.size>0&&e.put([...a].map(l=>lo.create({id:l})))};return t}const C9=Dw("bookmark",Se({title:pe,description:pe,image:pe,favicon:pe,src:Ui.nullable()})),qP=Bn("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),I9=cr({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:e=>e.type==="bookmark",sequence:[{id:qP.MakeUrlsValid,up:e=>{Ui.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:qP.AddFavicon,up:e=>{Ui.isValid(e.props.favicon)||(e.props.favicon="")},down:e=>{delete e.props.favicon}}]}),E9=Dw("image",Se({w:de,h:de,fileSize:de,name:pe,isAnimated:we,mimeType:pe.nullable(),src:Ui.nullable()})),Dd=Bn("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4}),k9=cr({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:e=>e.type==="image",sequence:[{id:Dd.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:Dd.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:Dd.MakeUrlsValid,up:e=>{Ui.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:Dd.AddFileSize,up:e=>{e.props.fileSize=-1},down:e=>{delete e.props.fileSize}}]}),_9=Dw("video",Se({w:de,h:de,fileSize:de,name:pe,isAnimated:we,mimeType:pe.nullable(),src:Ui.nullable()})),Rd=Bn("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4}),T9=cr({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:e=>e.type==="video",sequence:[{id:Rd.AddIsAnimated,up:e=>{e.props.isAnimated=!1},down:e=>{delete e.props.isAnimated}},{id:Rd.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:Rd.MakeUrlsValid,up:e=>{Ui.isValid(e.props.src)||(e.props.src="")},down:e=>{}},{id:Rd.AddFileSize,up:e=>{e.props.fileSize=-1},down:e=>{delete e.props.fileSize}}]}),M9=Io("asset",Aw("type",{image:E9,video:_9,bookmark:C9})),j9=Bn("com.tldraw.asset",{AddMeta:1}),A9=cr({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:j9.AddMeta,up:e=>{e.meta={}}}]}),ki=Co("asset",{validator:M9,scope:"document"}).withDefaultProperties(()=>({meta:{}})),pM={w:Ct,h:Ct,assetId:rg.nullable(),url:or},ZP=Gr("bookmark",{NullAssetId:1,MakeUrlsValid:2}),fM={sequence:[{id:ZP.NullAssetId,up:e=>{e.assetId===void 0&&(e.assetId=null)},down:"retired"},{id:ZP.MakeUrlsValid,up:e=>{or.isValid(e.url)||(e.url="")},down:e=>{}}]},gM=Se({type:ng("free","straight"),points:zt(Hi)}),mM={color:sr,fill:Wi,dash:Ki,size:vo,segments:zt(gM),isComplete:we,isClosed:we,isPen:we,scale:Ct},QP=Gr("draw",{AddInPen:1,AddScale:2}),yM={sequence:[{id:QP.AddInPen,up:e=>{const{points:n}=e.segments[0];if(n.length===0){e.isPen=!1;return}let t=!(n[0].z===0||n[0].z===.5);n[1]&&(t=t&&!(n[1].z===0||n[1].z===.5)),e.isPen=t},down:"retired"},{id:QP.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]};var O9={};const JP=/(^\/r\/[^/]+\/?$)/,Oe=e=>{try{return new URL(e)}catch{return}},$u=[{type:"tldraw",title:"tldraw",hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,overridePermissions:{"allow-top-navigation":!0},toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(JP))return e},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(JP))return e}},{type:"figma",title:"Figma",hostnames:["figma.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{if(e.match(/https:\/\/([\w\.-]+\.)?figma.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/)&&!e.includes("figma.com/embed"))return`https://www.figma.com/embed?embed_host=share&url=${e}`},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/embed\/?$/)){const t=n.searchParams.get("url");if(t)return t}}},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,overridePermissions:{"allow-presentation":!0},toEmbedUrl:e=>{if(e.includes("/maps/")){const n=e.match(/@(.*),(.*),(.*)z/);let t;if(n){const[,r,o,s]=n;t=`https://${new URL(e).host.replace("www.","")}/maps/embed/v1/view?key=${O9.NEXT_PUBLIC_GC_API_KEY}¢er=${r},${o}&zoom=${s}`}else t="";return t}},fromEmbedUrl:e=>{const n=Oe(e);if(!n)return;if(n.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&n.searchParams.has("center")&&n.searchParams.get("zoom")){const r=n.searchParams.get("zoom"),[o,s]=n.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 n=Oe(e),t=n&&n.pathname.match(/\/v\/(.+)\/?/);if(t)return`https://www.val.town/embed/${t[1]}`},fromEmbedUrl:e=>{const n=Oe(e),t=n&&n.pathname.match(/\/embed\/(.+)\/?/);if(t)return`https://www.val.town/v/${t[1]}`}},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e),t=n&&n.pathname.match(/\/s\/([^/]+)\/?/);if(t)return`https://codesandbox.io/embed/${t[1]}`},fromEmbedUrl:e=>{const n=Oe(e),t=n&&n.pathname.match(/\/embed\/([^/]+)\/?/);if(t)return`https://codesandbox.io/s/${t[1]}`}},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:e=>{const n=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,t=e.match(n);if(t){const[r,o,s]=t;return`https://codepen.io/${o}/embed/${s}`}},fromEmbedUrl:e=>{const n=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,t=e.match(n);if(t){const[r,o,s]=t;return`https://codepen.io/${o}/pen/${s}`}}},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,toEmbedUrl:e=>{const n=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,t=e.match(n);if(t){const[r,o]=t;return`https://scratch.mit.edu/projects/embed/${o}`}},fromEmbedUrl:e=>{const n=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,t=e.match(n);if(t){const[r,o]=t;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,"allow-popups-to-escape-sandbox":!0},isAspectRatioLocked:!0,toEmbedUrl:e=>{const n=Oe(e);if(!n)return;const t=n.hostname.replace(/^www./,"");if(t==="youtu.be")return`https://www.youtube.com/embed/${n.pathname.split("/").filter(Boolean)[0]}`;if((t==="youtube.com"||t==="m.youtube.com")&&n.pathname.match(/^\/watch/))return`https://www.youtube.com/embed/${n.searchParams.get("v")}`},fromEmbedUrl:e=>{const n=Oe(e);if(!n)return;if(n.hostname.replace(/^www./,"")==="youtube.com"){const r=n.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{type:"google_calendar",title:"Google Calendar",hostnames:["calendar.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,instructionLink:"https://support.google.com/calendar/answer/41207?hl=en",overridePermissions:{"allow-popups-to-escape-sandbox":!0},toEmbedUrl:e=>{const n=Oe(e),t=n==null?void 0:n.searchParams.get("cid");if(n!=null&&n.pathname.match(/\/calendar\/u\/0/)&&t){n.pathname="/calendar/embed";const r=Array.from(n.searchParams.keys());for(const o of r)n.searchParams.delete(o);return n.searchParams.set("src",t),n.href}},fromEmbedUrl:e=>{const n=Oe(e),t=n==null?void 0:n.searchParams.get("src");if(n!=null&&n.pathname.match(/\/calendar\/embed/)&&t){n.pathname="/calendar/u/0";const r=Array.from(n.searchParams.keys());for(const o of r)n.searchParams.delete(o);return n.searchParams.set("cid",t),n.href}}},{type:"google_slides",title:"Google Slides",hostnames:["docs.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,overridePermissions:{"allow-popups-to-escape-sandbox":!0},toEmbedUrl:e=>{const n=Oe(e);if(n!=null&&n.pathname.match(/^\/presentation/)&&(n!=null&&n.pathname.match(/\/pub\/?$/))){n.pathname=n.pathname.replace(/\/pub$/,"/embed");const t=Array.from(n.searchParams.keys());for(const r of t)n.searchParams.delete(r);return n.href}},fromEmbedUrl:e=>{const n=Oe(e);if(n!=null&&n.pathname.match(/^\/presentation/)&&(n!=null&&n.pathname.match(/\/embed\/?$/))){n.pathname=n.pathname.replace(/\/embed$/,"/pub");const t=Array.from(n.searchParams.keys());for(const r of t)n.searchParams.delete(r);return n.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/))return e.split("/").pop()?e:void 0},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/\/([^/]+)\/([^/]+)/))return e.split("/").pop()?e:void 0}},{type:"replit",title:"Replit",hostnames:["replit.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/))return`${e}?embed=true`},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/\/@([^/]+)\/([^/]+)/)&&n.searchParams.has("embed"))return n.searchParams.delete("embed"),n.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/map\//))return n.origin+"/embed"+n.pathname},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/embed\/map\//))return n.pathname=n.pathname.replace(/^\/embed/,""),n.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/(artist|album)\//))return n.origin+"/embed"+n.pathname},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/embed\/(artist|album)\//))return n.origin+n.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.hostname==="vimeo.com"&&n.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+n.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.hostname==="player.vimeo.com"){const t=n.pathname.match(/^\/video\/([^/]+)\/?$/);if(t)return"https://vimeo.com/"+t[1]}}},{type:"excalidraw",title:"Excalidraw",hostnames:["excalidraw.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.hash.match(/#room=/))return e},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.hash.match(/#room=/))return e}},{type:"observable",title:"Observable",hostnames:["observablehq.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!1,backgroundColor:"#fff",toEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}/embed${n.pathname}?cell=*`;if(n&&n.pathname.match(/^\/d\/([^/]+)\/?$/)){const t=n.pathname.replace(/^\/d/,"");return`${n.origin}/embed${t}?cell=*`}},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","")}#cell-*`;if(n&&n.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${n.origin}${n.pathname.replace("/embed","/d")}#cell-*`}},{type:"desmos",title:"Desmos",hostnames:["desmos.com"],width:700,height:450,doesResize:!0,toEmbedUrl:e=>{const n=Oe(e);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search===""&&n.hash==="")return`${e}?embed`},fromEmbedUrl:e=>{const n=Oe(e);if(n&&n.hostname==="www.desmos.com"&&n.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&n.search==="?embed"&&n.hash==="")return e.replace("?embed","")}}],D9={"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},SM={w:Ct,h:Ct,url:pe},Ld=Gr("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),vM={sequence:[{id:Ld.GenOriginalUrlInEmbed,up:e=>{try{const n=e.url,t=new URL(n).host.replace("www.","");let r;for(const o of $u)if(o.hostnames.includes(t))try{r=o.fromEmbedUrl(n)}catch(s){console.warn(s)}e.tmpOldUrl=e.url,e.url=r??""}catch{e.url="",e.tmpOldUrl=e.url}},down:"retired"},{id:Ld.RemoveDoesResize,up:e=>{delete e.doesResize},down:"retired"},{id:Ld.RemoveTmpOldUrl,up:e=>{delete e.tmpOldUrl},down:"retired"},{id:Ld.RemovePermissionOverrides,up:e=>{delete e.overridePermissions},down:"retired"}]},xM={w:Ct,h:Ct,name:pe},wM={sequence:[]},sf=Yt.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),af=Yt.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),Fr=Yt.defineEnum("tldraw:geo",{defaultValue:"rectangle",values:["cloud","rectangle","ellipse","triangle","diamond","pentagon","hexagon","octagon","star","rhombus","rhombus-2","oval","trapezoid","arrow-right","arrow-left","arrow-up","arrow-down","x-box","check-box","heart"]}),bM={geo:Fr,labelColor:rM,color:sr,fill:Wi,dash:Ki,size:vo,font:So,align:sf,verticalAlign:af,url:or,w:Ct,h:Ct,growY:Jp,text:pe,scale:Ct},Mo=Gr("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9}),PM={sequence:[{id:Mo.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:Mo.AddLabelColor,up:e=>{e.labelColor="black"},down:"retired"},{id:Mo.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:Mo.AddCheckBox,up:e=>{},down:"retired"},{id:Mo.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:"retired"},{id:Mo.MigrateLegacyAlign,up:e=>{let n;switch(e.align){case"start":n="start-legacy";break;case"end":n="end-legacy";break;default:n="middle-legacy";break}e.align=n},down:"retired"},{id:Mo.AddCloud,up:e=>{},down:"retired"},{id:Mo.MakeUrlsValid,up:e=>{or.isValid(e.url)||(e.url="")},down:e=>{}},{id:Mo.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},CM={},IM={sequence:[]},EM={color:sr,size:vo,segments:zt(gM),isComplete:we,isPen:we,scale:Ct},R9=Gr("highlight",{AddScale:1}),kM={sequence:[{id:R9.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},L9=Se({topLeft:Hi,bottomRight:Hi}),_M={w:Ct,h:Ct,playing:we,url:or,assetId:rg.nullable(),crop:L9.nullable()},Hm=Gr("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3}),TM={sequence:[{id:Hm.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:Hm.AddCropProp,up:e=>{e.crop=null},down:e=>{delete e.crop}},{id:Hm.MakeUrlsValid,up:e=>{or.isValid(e.url)||(e.url="")},down:e=>{}}]},lf=Yt.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),$9=Se({id:pe,index:Ow,x:de,y:de}),MM={color:sr,dash:Ki,size:vo,spline:lf,points:ef(pe,$9),scale:Ct},ic=Gr("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),jM={sequence:[{id:ic.AddSnapHandles,up:e=>{for(const n of Object.values(e.handles))n.canSnap=!0},down:"retired"},{id:ic.RemoveExtraHandleProps,up:e=>{e.handles=TT(Object.values(e.handles).map(n=>[n.index,{x:n.x,y:n.y}]))},down:e=>{const n=Object.entries(e.handles).map(([t,r])=>({index:t,...r})).sort(on);e.handles=Object.fromEntries(n.map((t,r)=>{const o=r===0?"start":r===n.length-1?"end":`handle:${t.index}`;return[o,{id:o,type:"vertex",canBind:!1,canSnap:!0,index:t.index,x:t.x,y:t.y}]}))}},{id:ic.HandlesToPoints,up:e=>{const n=Object.entries(e.handles).map(([t,{x:r,y:o}])=>({x:r,y:o,index:t})).sort(on);e.points=n.map(({x:t,y:r})=>({x:t,y:r})),delete e.handles},down:e=>{const n=du(e.points.length);e.handles=Object.fromEntries(e.points.map((t,r)=>[n[r],{x:t.x,y:t.y}])),delete e.points}},{id:ic.PointIndexIds,up:e=>{const n=du(e.points.length);e.points=Object.fromEntries(e.points.map((t,r)=>{const o=n[r];return[o,{id:o,index:o,x:t.x,y:t.y}]}))},down:e=>{const n=Object.values(e.points).sort(on);e.points=n.map(({x:t,y:r})=>({x:t,y:r}))}},{id:ic.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},AM={color:sr,size:vo,font:So,fontSizeAdjustment:Jp,align:sf,verticalAlign:af,growY:Jp,url:or,text:pe,scale:Ct},xi=Gr("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7}),OM={sequence:[{id:xi.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:xi.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:xi.MigrateLegacyAlign,up:e=>{switch(e.align){case"start":e.align="start-legacy";return;case"end":e.align="end-legacy";return;default:e.align="middle-legacy";return}},down:"retired"},{id:xi.AddVerticalAlign,up:e=>{e.verticalAlign="middle"},down:"retired"},{id:xi.MakeUrlsValid,up:e=>{or.isValid(e.url)||(e.url="")},down:e=>{}},{id:xi.AddFontSizeAdjustment,up:e=>{e.fontSizeAdjustment=0},down:e=>{delete e.fontSizeAdjustment}},{id:xi.AddScale,up:e=>{e.scale=1},down:e=>{delete e.scale}}]},pv=Yt.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]}),DM={color:sr,size:vo,font:So,textAlign:pv,w:Ct,text:pe,scale:Ct,autoSize:we},eC=Gr("text",{RemoveJustify:1,AddTextAlign:2}),RM={sequence:[{id:eC.RemoveJustify,up:e=>{e.align==="justify"&&(e.align="start")},down:"retired"},{id:eC.AddTextAlign,up:e=>{e.textAlign=e.align,delete e.align},down:e=>{e.align=e.textAlign,delete e.textAlign}}]},LM={w:Ct,h:Ct,time:de,playing:we,url:or,assetId:rg.nullable()},tC=Gr("video",{AddUrlProp:1,MakeUrlsValid:2}),$M={sequence:[{id:tC.AddUrlProp,up:e=>{e.url=""},down:"retired"},{id:tC.MakeUrlsValid,up:e=>{or.isValid(e.url)||(e.url="")},down:e=>{}}]},$d=Bn("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4}),F9=el({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:$d.RemoveCodeAndIconShapeTypes,scope:"store",up:e=>{for(const[n,t]of Fn(e))t.typeName==="shape"&&(t.type==="icon"||t.type==="code")&&delete e[n]}},{id:$d.AddInstancePresenceType,scope:"store",up(e){}},{id:$d.RemoveTLUserAndPresenceAndAddPointer,scope:"store",up:e=>{for(const[n,t]of Fn(e))t.typeName.match(/^(user|user_presence)$/)&&delete e[n]}},{id:$d.RemoveUserDocument,scope:"store",up:e=>{for(const[n,t]of Fn(e))t.typeName.match("user_document")&&delete e[n]}}]}),N9={arrow:{migrations:aM,props:iM},bookmark:{migrations:fM,props:pM},draw:{migrations:yM,props:mM},embed:{migrations:vM,props:SM},frame:{migrations:wM,props:xM},geo:{migrations:PM,props:bM},group:{migrations:IM,props:CM},highlight:{migrations:kM,props:EM},image:{migrations:TM,props:_M},line:{migrations:jM,props:MM},note:{migrations:OM,props:AM},text:{migrations:RM,props:DM},video:{migrations:$M,props:LM}},z9={arrow:{migrations:cM,props:lM}};function B9({shapes:e=N9,bindings:n=z9,migrations:t}={}){const r=new Map;for(const a of gt(e))for(const l of eM(a.props??{}).keys()){if(r.has(l.id)&&r.get(l.id)!==l)throw new Error(`Multiple StyleProp instances with the same id: ${l.id}`);r.set(l.id,l)}const o=XH(e),s=GH(n),i=l9(r);return Mw.create({asset:ki,binding:s,camera:lo,document:Lw,instance:i,instance_page_state:$r,page:Qo,instance_presence:y9,pointer:Rw,shape:o},{migrations:[F9,A9,QH,v9,c9,d9,i9,m9,f9,YH,I9,k9,T9,...VP("shape",e),...VP("binding",n),...t??[]],onValidationFailure:w9,createIntegrityChecker:P9})}const pu=[{locale:"id",label:"Bahasa Indonesia"},{locale:"ca",label:"Català"},{locale:"cs",label:"Čeština"},{locale:"da",label:"Danish"},{locale:"de",label:"Deutsch"},{locale:"en",label:"English"},{locale:"es",label:"Español"},{locale:"fr",label:"Français"},{locale:"gl",label:"Galego"},{locale:"hr",label:"Hrvatski"},{locale:"it",label:"Italiano"},{locale:"hu",label:"Magyar"},{locale:"no",label:"Norwegian"},{locale:"pl",label:"Polski"},{locale:"pt-br",label:"Português - Brasil"},{locale:"pt-pt",label:"Português - Europeu"},{locale:"ro",label:"Română"},{locale:"ru",label:"Russian"},{locale:"sl",label:"Slovenščina"},{locale:"fi",label:"Suomi"},{locale:"sv",label:"Svenska"},{locale:"vi",label:"Tiếng Việt"},{locale:"tr",label:"Türkçe"},{locale:"uk",label:"Ukrainian"},{locale:"he",label:"עברית"},{locale:"ar",label:"عربي"},{locale:"fa",label:"فارسی"},{locale:"ku",label:"کوردی"},{locale:"ne",label:"नेपाली"},{locale:"hi-in",label:"हिन्दी"},{locale:"te",label:"తెలుగు"},{locale:"th",label:"ภาษาไทย"},{locale:"my",label:"မြန်မာစာ"},{locale:"ko-kr",label:"한국어"},{locale:"ja",label:"日本語"},{locale:"zh-cn",label:"简体中文"},{locale:"zh-tw",label:"繁體中文 (台灣)"}];function U9(){const e=typeof window<"u"?window.navigator.languages??["en"]:["en"];return H9(e)}function H9(e){for(const n of e){const t=K9(n);if(t)return t}return"en"}const nC={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function K9(e){const n=pu.find(o=>o.locale===e.toLowerCase());if(n)return n.locale;const[t,r]=e.split(/[-_]/).map(o=>o.toLowerCase());if(r){const o=pu.find(s=>s.locale===t);if(o)return o.locale}return t in nC?nC[t]:null}var FM={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */(function(e){(function(){var n={}.hasOwnProperty;function t(){for(var s="",i=0;i or components");return e}function V9(){return u.jsx("div",{className:"tl-background"})}function Rl(e,n,t,r,o,s){P.useLayoutEffect(()=>{const i=e.current;if(!i||n===void 0)return;let a=`translate(${n}px, ${t}px)`;r!==void 0&&(a+=` scale(${r})`),o!==void 0&&(a+=` rotate(${o}rad)`),s&&(a+=` translate(${s.x}px, ${s.y}px)`),i.style.transform=a})}const jt={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 w{constructor(n=0,t=0,r=1){this.x=n,this.y=t,this.z=r}get pressure(){return this.z}set(n=this.x,t=this.y,r=this.z){return this.x=n,this.y=t,this.z=r,this}setTo({x:n=0,y:t=0,z:r=1}){return this.x=n,this.y=t,this.z=r,this}rot(n){if(n===0)return this;const{x:t,y:r}=this,o=Math.sin(n),s=Math.cos(n);return this.x=t*s-r*o,this.y=t*o+r*s,this}rotWith(n,t){if(t===0)return this;const r=this.x-n.x,o=this.y-n.y,s=Math.sin(t),i=Math.cos(t);return this.x=n.x+(r*i-o*s),this.y=n.y+(r*s+o*i),this}clone(){const{x:n,y:t,z:r}=this;return new w(n,t,r)}sub(n){return this.x-=n.x,this.y-=n.y,this}subXY(n,t){return this.x-=n,this.y-=t,this}subScalar(n){return this.x-=n,this.y-=n,this}add(n){return this.x+=n.x,this.y+=n.y,this}addXY(n,t){return this.x+=n,this.y+=t,this}addScalar(n){return this.x+=n,this.y+=n,this}clamp(n,t){return this.x=Math.max(this.x,n),this.y=Math.max(this.y,n),t!==void 0&&(this.x=Math.min(this.x,t),this.y=Math.min(this.y,t)),this}div(n){return this.x/=n,this.y/=n,this}divV(n){return this.x/=n.x,this.y/=n.y,this}mul(n){return this.x*=n,this.y*=n,this}mulV(n){return this.x*=n.x,this.y*=n.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(n,t){const r=w.Tan(n,this);return this.add(r.mul(t))}neg(){return this.x*=-1,this.y*=-1,this}cross(n){return this.x=this.y*n.z-this.z*n.y,this.y=this.z*n.x-this.x*n.z,this}dpr(n){return w.Dpr(this,n)}cpr(n){return w.Cpr(this,n)}len2(){return w.Len2(this)}len(){return w.Len(this)}pry(n){return w.Pry(this,n)}per(){const{x:n,y:t}=this;return this.x=t,this.y=-n,this}uni(){return w.Uni(this)}tan(n){return w.Tan(this,n)}dist(n){return w.Dist(this,n)}distanceToLineSegment(n,t){return w.DistanceToLineSegment(n,t,this)}slope(n){return w.Slope(this,n)}snapToGrid(n){return this.x=Math.round(this.x/n)*n,this.y=Math.round(this.y/n)*n,this}angle(n){return w.Angle(this,n)}toAngle(){return w.ToAngle(this)}lrp(n,t){return this.x=this.x+(n.x-this.x)*t,this.y=this.y+(n.y-this.y)*t,this}equals(n){return w.Equals(this,n)}equalsXY(n,t){return w.EqualsXY(this,n,t)}norm(){const n=this.len();return this.x=n===0?0:this.x/n,this.y=n===0?0:this.y/n,this}toFixed(){return w.ToFixed(this)}toString(){return w.ToString(w.ToFixed(this))}toJson(){return w.ToJson(this)}toArray(){return w.ToArray(this)}static Add(n,t){return new w(n.x+t.x,n.y+t.y)}static AddXY(n,t,r){return new w(n.x+t,n.y+r)}static Sub(n,t){return new w(n.x-t.x,n.y-t.y)}static SubXY(n,t,r){return new w(n.x-t,n.y-r)}static AddScalar(n,t){return new w(n.x+t,n.y+t)}static SubScalar(n,t){return new w(n.x-t,n.y-t)}static Div(n,t){return new w(n.x/t,n.y/t)}static Mul(n,t){return new w(n.x*t,n.y*t)}static DivV(n,t){return new w(n.x/t.x,n.y/t.y)}static MulV(n,t){return new w(n.x*t.x,n.y*t.y)}static Neg(n){return new w(-n.x,-n.y)}static Per(n){return new w(n.y,-n.x)}static Abs(n){return new w(Math.abs(n.x),Math.abs(n.y))}static Dist(n,t){return((n.y-t.y)**2+(n.x-t.x)**2)**.5}static DistMin(n,t,r){return(n.x-t.x)*(n.x-t.x)+(n.y-t.y)*(n.y-t.y)Math.max(n.x,t.x))return w.Cast(n.x>t.x?n:t);if(i.yMath.max(n.y,t.y))return w.Cast(n.y>t.y?n:t)}return i}static DistanceToLineThroughPoint(n,t,r){return w.Dist(r,w.NearestPointOnLineThroughPoint(n,t,r))}static DistanceToLineSegment(n,t,r,o=!0){return w.Dist(r,w.NearestPointOnLineSegment(n,t,r,o))}static Snap(n,t=1){return new w(Math.round(n.x/t)*t,Math.round(n.y/t)*t)}static Cast(n){return n instanceof w?n:w.From(n)}static Slope(n,t){return n.x===t.y?NaN:(n.y-t.y)/(n.x-t.x)}static IsNaN(n){return isNaN(n.x)||isNaN(n.y)}static Angle(n,t){return Math.atan2(t.y-n.y,t.x-n.x)}static Lrp(n,t,r){return w.Sub(t,n).mul(r).add(n)}static Med(n,t){return new w((n.x+t.x)/2,(n.y+t.y)/2)}static Equals(n,t){return Math.abs(n.x-t.x)<1e-4&&Math.abs(n.y-t.y)<1e-4}static EqualsXY(n,t,r){return n.x===t&&n.y===r}static Clockwise(n,t,r){return(r.x-n.x)*(t.y-n.y)-(t.x-n.x)*(r.y-n.y)<0}static Rescale(n,t){const r=w.Len(n);return new w(t*n.x/r,t*n.y/r)}static ScaleWithOrigin(n,t,r){return w.Sub(n,r).mul(t).add(r)}static ToFixed(n){return new w($o(n.x),$o(n.y))}static ToInt(n){return new w(parseInt(n.x.toFixed(0)),parseInt(n.y.toFixed(0)),parseInt((n.z??0).toFixed(0)))}static ToCss(n){return`${n.x},${n.y}`}static Nudge(n,t,r){return w.Add(n,w.Tan(t,n).mul(r))}static ToString(n){return`${n.x}, ${n.y}`}static ToAngle(n){let t=Math.atan2(n.y,n.x);return t<0&&(t+=Math.PI*2),t}static FromAngle(n,t=1){return new w(Math.cos(n)*t,Math.sin(n)*t)}static ToArray(n){return[n.x,n.y,n.z]}static ToJson(n){const{x:t,y:r,z:o}=n;return{x:t,y:r,z:o}}static Average(n){const t=n.length,r=new w(0,0);if(t===0)return r;for(let o=0;oe<.5?2*e*e:-1+(4-2*e)*e;function Ie(e){return`${N(e.x)},${N(e.y)} `}function Tn(e,n){return`${N((e.x+n.x)/2)},${N((e.y+n.y)/2)} `}const _e=Math.PI,Ve=_e/2,Re=_e*2,X9=Math.sin;function _t(e,n,t){return Math.max(n,typeof t<"u"?Math.min(e,t):e)}function Fd(e,n=1e10){return e?Math.round(e*n)/n:0}function Us(e,n,t=1e-6){return Math.abs(e-n)<=t}function zM(e,n){const t=Math.pow(e-n,2)/Math.pow(e+n,2);return _e*(e+n)*(1+3*t/(10+Math.sqrt(4-3*t)))}function Hs(e){return e=e%Re,e<0?e=e+Re:e===0&&(e=0),e}function Fu(e,n){return e=Hs(e),n=Hs(n),e>n&&(n+=Re),n-e}function BM(e,n){return Re-Fu(e,n)}function Mh(e,n){const t=(n-e)%Re;return 2*t%Re-t}function fv(e){return(Re+e)%Re}function cf(e,n){const t=Re/n;let r=Math.floor((fv(e)+t/2)/t)*t%Re;return r<_e&&(r+=Re),r>_e&&(r-=Re),r}function UM(e,n){return e===n||Us(e%(Math.PI/2)-n%(Math.PI/2),0)}function q9(e){return e*_e/180}function Z9(e){return e*180/_e}function Gi(e,n,t){return new w(e.x,e.y).add(w.FromAngle(t,n))}function Km(e,n,t){const r=e/2,o=n/2,s=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let S=0;Sa&&(a=y),v>c&&(c=v),s.push(new w(y,v))}const d=a-i,h=c-l,p=e-d,f=n-h;if(p!==0||f!==0)for(let S=0;Se.y&&rC(r,o,e)>0&&(t+=1):o.y<=e.y&&rC(r,o,e)<0&&(t-=1)}return t!==0}function N(e){return Math.round(e*1e4)/1e4}function $o(e){return Math.round(e*100)/100}const oC=e=>Math.abs(e)_e){o=Mh(n,r);const s=Mh(r,t);return Math.abs(o).5?1:0:s}}function Q9(e,n,t,r){const o=2*((n-e)%Re)%Re-(n-e)%Re;return r?(Re-Math.abs(o))*(t?1:-1):o}function $w(e,n,t){const r=-2*(e.x*(n.y-t.y)-e.y*(n.x-t.x)+n.x*t.y-t.x*n.y);return new w(((e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y)+(t.x*t.x+t.y*t.y)*(n.y-e.y))/r,((e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x)+(t.x*t.x+t.y*t.y)*(e.x-n.x))/r)}function J9(e,n,t,r,o){if(t===null)return[w.From(e),w.From(n)];const s=[],i=w.Angle(t,e),a=w.Angle(t,n),l=Fu(i,a);for(let c=0;c{const o=P.useRef(null);Rl(o,e.x,e.y);const s=N(Math.max(1,e.w)),i=N(Math.max(1,e.h));return u.jsx("svg",{className:"tl-overlays__item",ref:o,children:n?u.jsxs("g",{className:"tl-brush",opacity:t,children:[u.jsx("rect",{width:s,height:i,fill:n,opacity:.75}),u.jsx("rect",{width:s,height:i,fill:"none",stroke:n,opacity:.1})]}):u.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:s,height:i})})},sC={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.1,.25,.5,1,2,4,8]},iC={onResolveAsset:async e=>(e==null?void 0:e.props.src)||""},Gm={duration:0,easing:jt.easeInOutCubic},aC={CAMERA_MOVE:-10},e7=["top","right","bottom","left"],lC=0,Fw=2,Nd=1,cC=5,t7=128;var Vm={};const n7={},HM=Cn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),wt={logPreventDefaults:Cn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:Cn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:Cn("logElementRemoves",{defaults:{all:!1}}),debugSvg:Cn("debugSvg",{defaults:{all:!1}}),showFps:Cn("showFps",{defaults:{all:!1}}),measurePerformance:Cn("measurePerformance",{defaults:{all:!1}}),throwToBlob:Cn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:Cn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:Cn("debugCursors",{defaults:{all:!1}}),forceSrgb:Cn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:Cn("debugGeometry",{defaults:{all:!1}}),hideShapes:Cn("hideShapes",{defaults:{all:!1}}),editOnType:Cn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const e=Element.prototype.removeChild;aa("element removal logging",()=>{wt.logElementRemoves.get()?Element.prototype.removeChild=function(n){return console.warn("[tldraw] removing child:",n),e.call(this,n)}:Element.prototype.removeChild=e})}function Cn(e,{defaults:n,shouldStoreForSession:t=!0}){return r7({name:e,defaults:n,shouldStoreForSession:t})}function r7(e){const n=s7(e),t=e.shouldStoreForSession?o7(e.name):null,r=Mt(`debug:${e.name}`,t??n);return typeof window<"u"&&(e.shouldStoreForSession&&aa(`debug:${e.name}`,()=>{const o=r.get();o===n?LT(`tldraw_debug:${e.name}`):Cw(`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 o7(e){try{return JSON.parse(RT(`tldraw_debug:${e}`)??"null")}catch{return null}}function Ym(e){try{return e()}catch{return null}}function s7(e){switch(Ym(()=>Vm.TLDRAW_ENV)??Ym(()=>Vm.VERCEL_PUBLIC_TLDRAW_ENV)??Ym(()=>Vm.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 uf(e){if(e instanceof HTMLElement)return e;if(e.parentElement)return uf(e.parentElement);throw Error("Could not find a parent element of an HTML type!")}function Ee(e){e.preventDefault(),wt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",e)}function Nu(e,n){if(e.setPointerCapture(n.pointerId),wt.logPointerCaptures.get()){const t=HM.get();t.set(e,(t.get(e)??0)+1),console.warn("setPointerCapture called on element:",e,n)}}function zu(e,n){if(e.hasPointerCapture(n.pointerId)&&(e.releasePointerCapture(n.pointerId),wt.logPointerCaptures.get())){const t=HM.get();t.get(e)===1?t.delete(e):t.has(e)?t.set(e,t.get(e)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",e,n)}}const Kt=e=>e.stopPropagation(),Jt=(e,n,t)=>{e&&e.style.setProperty(n,t)};function On(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 i7(){const e=B();return P.useMemo(function(){let r,o;function s(g){if(!g.isKilled){if(g.button===Fw){e.dispatch({type:"pointer",target:"canvas",name:"right_click",...On(g)});return}g.button!==0&&g.button!==1&&g.button!==5||(Nu(g.currentTarget,g),e.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...On(g)}))}}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",...On(g)}))}function a(g){g.isKilled||g.button!==0&&g.button!==1&&g.button!==2&&g.button!==5||(r=g.clientX,o=g.clientY,zu(g.currentTarget,g),e.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...On(g)}))}function l(g){if(g.isKilled||e.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const x=g.pointerType==="mouse"||g.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!0:null})}function c(g){if(g.isKilled||e.getInstanceState().isPenMode&&g.pointerType!=="pen")return;const x=g.pointerType==="mouse"||g.pointerType==="pen";e.updateInstanceState({isHoveringCanvas:x?!1:null})}function d(g){g.isKilled=!0,Ee(g)}function h(g){g.isKilled=!0,g.target instanceof HTMLElement&&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 y,v;if(Ee(g),!((v=(y=g.dataTransfer)==null?void 0:y.files)!=null&&v.length))return;const x=Array.from(g.dataTransfer.files);await e.putExternalContent({type:"files",files:x,point:e.screenToPage({x:g.clientX,y:g.clientY}),ignoreParent:!1})}function S(g){Kt(g)}return{onPointerDown:s,onPointerMove:i,onPointerUp:a,onPointerEnter:l,onPointerLeave:c,onDragOver:p,onDrop:f,onTouchStart:d,onTouchEnd:h,onClick:S}},[e])}function a7(){const e=B();P.useEffect(()=>{let n=e.getInstanceState().isCoarsePointer;const t=i=>{const a=i.pointerType!=="mouse";n!==a&&(n=a,e.updateInstanceState({isCoarsePointer:a}))};window.addEventListener("pointerdown",t,{capture:!0});const r=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),o=e.environment.isFirefox&&!e.environment.isAndroid&&!e.environment.isIos,s=()=>{const i=o?!1:r.matches;n===i&&(n=i,e.updateInstanceState({isCoarsePointer:i}))};return r&&(r.addEventListener("change",s),s()),()=>{window.removeEventListener("pointerdown",t,{capture:!0}),r&&r.removeEventListener("change",s)}},[e])}const KM=P.createContext(null);function l7({container:e,children:n}){return u.jsx(KM.Provider,{value:e,children:n})}function un(){return Sr(P.useContext(KM),"useContainer used outside of ")}function c7(){const e=B(),n=un(),t=G("isFocused",()=>e.getInstanceState().isFocused,[e]);P.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=l=>{l.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]),P.useEffect(()=>{if(!t)return;const r=a=>{if(a.altKey&&(e.isIn("zoom")||!e.getPath().endsWith(".idle"))&&!zd()&&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(zd()||e.getIsMenuOpen())return;break}case",":return;case"Escape":{if((e.getEditingShape()||e.getSelectedShapeIds().length>0)&&a.preventDefault(),e.getOpenMenus().length>0)return;e.inputs.keys.has("Escape")||(e.inputs.keys.add("Escape"),e.cancel(),e.focus());return}default:if(zd()||e.getIsMenuOpen())return}const l={type:"keyboard",name:a.repeat?"key_repeat":"key_down",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)},o=a=>{if(a.isKilled||(a.isKilled=!0,zd()||e.getIsMenuOpen())||a.key===",")return;const l={type:"keyboard",name:"key_up",key:a.key,code:a.code,shiftKey:a.shiftKey,altKey:a.altKey,ctrlKey:a.metaKey||a.ctrlKey};e.dispatch(l)};function s(a){var l,c;if(n.contains(a.target)){const d=a.touches[0].pageX,h=a.touches[0].radiusX||0;(d-h<10||d+h>e.getViewportScreenBounds().width-10)&&(((l=a.target)==null?void 0:l.tagName)==="BUTTON"&&((c=a.target)==null||c.click()),Ee(a))}}const i=a=>{n.contains(a.target)&&(a.ctrlKey||a.metaKey)&&Ee(a)};return n.addEventListener("touchstart",s,{passive:!1}),n.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",Ee),document.addEventListener("gesturechange",Ee),document.addEventListener("gestureend",Ee),n.addEventListener("keydown",r),n.addEventListener("keyup",o),()=>{n.removeEventListener("touchstart",s),n.removeEventListener("wheel",i),document.removeEventListener("gesturestart",Ee),document.removeEventListener("gesturechange",Ee),document.removeEventListener("gestureend",Ee),n.removeEventListener("keydown",r),n.removeEventListener("keyup",o)}},[e,n,t])}const u7=["input","select","button","textarea"];function zd(){const{activeElement:e}=document;return!!(e&&(e.getAttribute("contenteditable")||u7.indexOf(e.tagName.toLowerCase())>-1))}const d7=["textarea","input"];function h7(e){const n=B();P.useEffect(()=>{const t=e.current;if(!t)return;const r=o=>{var s;if(o instanceof PointerEvent&&o.pointerType==="pen"){o.isKilled=!0;const{target:i}=o;if(d7.includes((s=i.tagName)==null?void 0:s.toLocaleLowerCase())||n.isIn("select.editing_shape"))return;Ee(o)}};return t.addEventListener("touchstart",r),t.addEventListener("touchend",r),()=>{t.removeEventListener("touchstart",r),t.removeEventListener("touchend",r)}},[n,e])}function p7(e,n,t){return Math.max(n,Math.min(e,t))}const Ut={toVector(e,n){return e===void 0&&(e=n),Array.isArray(e)?e:[e,e]},add(e,n){return[e[0]+n[0],e[1]+n[1]]},sub(e,n){return[e[0]-n[0],e[1]-n[1]]},addTo(e,n){e[0]+=n[0],e[1]+=n[1]},subTo(e,n){e[0]-=n[0],e[1]-=n[1]}};function uC(e,n,t){return n===0||Math.abs(n)===1/0?Math.pow(e,t*5):e*n*t/(n+t*e)}function dC(e,n,t,r=.15){return r===0?p7(e,n,t):et?+uC(e-t,t-n,r)+t:e}function f7(e,[n,t],[r,o]){const[[s,i],[a,l]]=e;return[dC(n,s,i,r),dC(t,a,l,o)]}function g7(e,n){if(typeof e!="object"||e===null)return e;var t=e[Symbol.toPrimitive];if(t!==void 0){var r=t.call(e,n||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(e)}function m7(e){var n=g7(e,"string");return typeof n=="symbol"?n:String(n)}function tn(e,n,t){return n=m7(n),n in e?Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[n]=t,e}function hC(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),t.push.apply(t,r)}return t}function ut(e){for(var n=1;n{var t,r;return n.target===e.currentTarget||((t=e.currentTarget)===null||t===void 0||(r=t.contains)===null||r===void 0?void 0:r.call(t,n.target))})}function mv(e,n){try{const t=n.clientX-e.clientX,r=n.clientY-e.clientY,o=(n.clientX+e.clientX)/2,s=(n.clientY+e.clientY)/2,i=Math.hypot(t,r);return{angle:-(Math.atan2(t,r)*180)/Math.PI,distance:i,origin:[o,s]}}catch{}return null}function I7(e){return C7(e).map(n=>n.identifier)}function fC(e,n){const[t,r]=Array.from(e.touches).filter(o=>n.includes(o.identifier));return mv(t,r)}const gC=40,mC=800;function VM(e){let{deltaX:n,deltaY:t,deltaMode:r}=e;return r===1?(n*=gC,t*=gC):r===2&&(n*=mC,t*=mC),[n,t]}function E7(e){const n={};if("buttons"in e&&(n.buttons=e.buttons),"shiftKey"in e){const{shiftKey:t,altKey:r,metaKey:o,ctrlKey:s}=e;Object.assign(n,{shiftKey:t,altKey:r,metaKey:o,ctrlKey:s})}return n}function df(e,...n){return typeof e=="function"?e(...n):e}function k7(){}function _7(...e){return e.length===0?k7:e.length===1?e[0]:function(){let n;for(const t of e)n=t.apply(this,arguments)||n;return n}}function yC(e,n){return Object.assign({},n,e||{})}const T7=32;class YM{constructor(n,t,r){this.ctrl=n,this.args=t,this.key=r,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(n){this.ctrl.state[this.key]=n}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:n,shared:t,ingKey:r,args:o}=this;t[r]=n._active=n.active=n._blocked=n._force=!1,n._step=[!1,!1],n.intentional=!1,n._movement=[0,0],n._distance=[0,0],n._direction=[0,0],n._delta=[0,0],n._bounds=[[-1/0,1/0],[-1/0,1/0]],n.args=o,n.axis=void 0,n.memo=void 0,n.elapsedTime=n.timeDelta=0,n.direction=[0,0],n.distance=[0,0],n.overflow=[0,0],n._movementBound=[!1,!1],n.velocity=[0,0],n.movement=[0,0],n.delta=[0,0],n.timeStamp=0}start(n){const t=this.state,r=this.config;t._active||(this.reset(),this.computeInitial(),t._active=!0,t.target=n.target,t.currentTarget=n.currentTarget,t.lastOffset=r.from?df(r.from,t):t.offset,t.offset=t.lastOffset,t.startTime=t.timeStamp=n.timeStamp)}computeValues(n){const t=this.state;t._values=n,t.values=this.config.transform(n)}computeInitial(){const n=this.state;n._initial=n._values,n.initial=n.values}compute(n){const{state:t,config:r,shared:o}=this;t.args=this.args;let s=0;if(n&&(t.event=n,r.preventDefault&&n.cancelable&&t.event.preventDefault(),t.type=n.type,o.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,o.locked=!!document.pointerLockElement,Object.assign(o,E7(n)),o.down=o.pressed=o.buttons%2===1||o.touches>0,s=n.timeStamp-t.timeStamp,t.timeStamp=n.timeStamp,t.elapsedTime=t.timeStamp-t.startTime),t._active){const C=t._delta.map(Math.abs);Ut.addTo(t._distance,C)}this.axisIntent&&this.axisIntent(n);const[i,a]=t._movement,[l,c]=r.threshold,{_step:d,values:h}=t;if(r.hasCustomTransform?(d[0]===!1&&(d[0]=Math.abs(i)>=l&&h[0]),d[1]===!1&&(d[1]=Math.abs(a)>=c&&h[1])):(d[0]===!1&&(d[0]=Math.abs(i)>=l&&Math.sign(i)*l),d[1]===!1&&(d[1]=Math.abs(a)>=c&&Math.sign(a)*c)),t.intentional=d[0]!==!1||d[1]!==!1,!t.intentional)return;const p=[0,0];if(r.hasCustomTransform){const[C,k]=h;p[0]=d[0]!==!1?C-d[0]:0,p[1]=d[1]!==!1?k-d[1]:0}else p[0]=d[0]!==!1?i-d[0]:0,p[1]=d[1]!==!1?a-d[1]:0;this.restrictToAxis&&!t._blocked&&this.restrictToAxis(p);const f=t.offset,S=t._active&&!t._blocked||t.active;S&&(t.first=t._active&&!t.active,t.last=!t._active&&t.active,t.active=o[this.ingKey]=t._active,n&&(t.first&&("bounds"in r&&(t._bounds=df(r.bounds,t)),this.setup&&this.setup()),t.movement=p,this.computeOffset()));const[g,x]=t.offset,[[y,v],[b,E]]=t._bounds;t.overflow=[gv?1:0,xE?1:0],t._movementBound[0]=t.overflow[0]?t._movementBound[0]===!1?t._movement[0]:t._movementBound[0]:!1,t._movementBound[1]=t.overflow[1]?t._movementBound[1]===!1?t._movement[1]:t._movementBound[1]:!1;const I=t._active?r.rubberband||[0,0]:[0,0];if(t.offset=f7(t._bounds,t.offset,I),t.delta=Ut.sub(t.offset,f),this.computeMovement(),S&&(!t.last||s>T7)){t.delta=Ut.sub(t.offset,f);const C=t.delta.map(Math.abs);Ut.addTo(t.distance,C),t.direction=t.delta.map(Math.sign),t._direction=t._delta.map(Math.sign),!t.first&&s>0&&(t.velocity=[C[0]/s,C[1]/s],t.timeDelta=s)}}emit(){const n=this.state,t=this.shared,r=this.config;if(n._active||this.clean(),(n._blocked||!n.intentional)&&!n._force&&!r.triggerAllEvents)return;const o=this.handler(ut(ut(ut({},t),n),{},{[this.aliasKey]:n.values}));o!==void 0&&(n.memo=o)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function M7([e,n],t){const r=Math.abs(e),o=Math.abs(n);if(r>o&&r>t)return"x";if(o>r&&o>t)return"y"}class j7 extends YM{constructor(...n){super(...n),tn(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=Ut.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Ut.sub(this.state.offset,this.state.lastOffset)}axisIntent(n){const t=this.state,r=this.config;if(!t.axis&&n){const o=typeof r.axisThreshold=="object"?r.axisThreshold[P7(n)]:r.axisThreshold;t.axis=M7(t._movement,o)}t._blocked=(r.lockDirection||!!r.axis)&&!t.axis||!!r.axis&&r.axis!==t.axis}restrictToAxis(n){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":n[1]=0;break;case"y":n[0]=0;break}}}const A7=e=>e,SC=.15,XM={enabled(e=!0){return e},eventOptions(e,n,t){return ut(ut({},t.shared.eventOptions),e)},preventDefault(e=!1){return e},triggerAllEvents(e=!1){return e},rubberband(e=0){switch(e){case!0:return[SC,SC];case!1:return[0,0];default:return Ut.toVector(e)}},from(e){if(typeof e=="function")return e;if(e!=null)return Ut.toVector(e)},transform(e,n,t){const r=e||t.shared.transform;return this.hasCustomTransform=!!r,r||A7},threshold(e){return Ut.toVector(e,0)}},O7=0,Bu=ut(ut({},XM),{},{axis(e,n,{axis:t}){if(this.lockDirection=t==="lock",!this.lockDirection)return t},axisThreshold(e=O7){return e},bounds(e={}){if(typeof e=="function")return s=>Bu.bounds(e(s));if("current"in e)return()=>e.current;if(typeof HTMLElement=="function"&&e instanceof HTMLElement)return e;const{left:n=-1/0,right:t=1/0,top:r=-1/0,bottom:o=1/0}=e;return[[n,t],[r,o]]}}),Uu=typeof window<"u"&&window.document&&window.document.createElement;function qM(){return Uu&&"ontouchstart"in window}function D7(){return qM()||Uu&&window.navigator.maxTouchPoints>1}function R7(){return Uu&&"onpointerdown"in window}function L7(){return Uu&&"exitPointerLock"in window.document}function $7(){try{return"constructor"in GestureEvent}catch{return!1}}const vr={isBrowser:Uu,gesture:$7(),touch:qM(),touchscreen:D7(),pointer:R7(),pointerLock:L7()},F7=250,N7=180,z7=.5,B7=50,U7=250,H7=10,vC={mouse:0,touch:0,pen:8};ut(ut({},Bu),{},{device(e,n,{pointer:{touch:t=!1,lock:r=!1,mouse:o=!1}={}}){return this.pointerLock=r&&vr.pointerLock,vr.touch&&t?"touch":this.pointerLock?"mouse":vr.pointer&&!o?"pointer":vr.touch?"touch":"mouse"},preventScrollAxis(e,n,{preventScroll:t}){if(this.preventScrollDelay=typeof t=="number"?t:t||t===void 0&&e?F7:void 0,!(!vr.touchscreen||t===!1))return e||(t!==void 0?"y":void 0)},pointerCapture(e,n,{pointer:{capture:t=!0,buttons:r=1,keys:o=!0}={}}){return this.pointerButtons=r,this.keys=o,!this.pointerLock&&this.device==="pointer"&&t},threshold(e,n,{filterTaps:t=!1,tapsThreshold:r=3,axis:o=void 0}){const s=Ut.toVector(e,t?r:o?1:0);return this.filterTaps=t,this.tapsThreshold=r,s},swipe({velocity:e=z7,distance:n=B7,duration:t=U7}={}){return{velocity:this.transform(Ut.toVector(e)),distance:this.transform(Ut.toVector(n)),duration:t}},delay(e=0){switch(e){case!0:return N7;case!1:return 0;default:return e}},axisThreshold(e){return e?ut(ut({},vC),e):vC},keyboardDisplacement(e=H7){return e}});function ZM(e){const[n,t]=e.overflow,[r,o]=e._delta,[s,i]=e._direction;(n<0&&r>0&&s<0||n>0&&r<0&&s>0)&&(e._movement[0]=e._movementBound[0]),(t<0&&o>0&&i<0||t>0&&o<0&&i>0)&&(e._movement[1]=e._movementBound[1])}const K7=30,W7=100;class G7 extends YM{constructor(...n){super(...n),tn(this,"ingKey","pinching"),tn(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const n=this.state;n._touchIds=[],n.canceled=!1,n.cancel=this.cancel.bind(this),n.turns=0}computeOffset(){const{type:n,movement:t,lastOffset:r}=this.state;n==="wheel"?this.state.offset=Ut.add(t,r):this.state.offset=[(1+t[0])*r[0],t[1]+r[1]]}computeMovement(){const{offset:n,lastOffset:t}=this.state;this.state.movement=[n[0]/t[0],n[1]-t[1]]}axisIntent(){const n=this.state,[t,r]=n._movement;if(!n.axis){const o=Math.abs(t)*K7-Math.abs(r);o<0?n.axis="angle":o>0&&(n.axis="scale")}}restrictToAxis(n){this.config.lockDirection&&(this.state.axis==="scale"?n[1]=0:this.state.axis==="angle"&&(n[0]=0))}cancel(){const n=this.state;n.canceled||setTimeout(()=>{n.canceled=!0,n._active=!1,this.compute(),this.emit()},0)}touchStart(n){this.ctrl.setEventIds(n);const t=this.state,r=this.ctrl.touchIds;if(t._active&&t._touchIds.every(s=>r.has(s))||r.size<2)return;this.start(n),t._touchIds=Array.from(r).slice(0,2);const o=fC(n,t._touchIds);o&&this.pinchStart(n,o)}pointerStart(n){if(n.buttons!=null&&n.buttons%2!==1)return;this.ctrl.setEventIds(n),n.target.setPointerCapture(n.pointerId);const t=this.state,r=t._pointerEvents,o=this.ctrl.pointerIds;if(t._active&&Array.from(r.keys()).every(i=>o.has(i))||(r.size<2&&r.set(n.pointerId,n),t._pointerEvents.size<2))return;this.start(n);const s=mv(...Array.from(r.values()));s&&this.pinchStart(n,s)}pinchStart(n,t){const r=this.state;r.origin=t.origin,this.computeValues([t.distance,t.angle]),this.computeInitial(),this.compute(n),this.emit()}touchMove(n){if(!this.state._active)return;const t=fC(n,this.state._touchIds);t&&this.pinchMove(n,t)}pointerMove(n){const t=this.state._pointerEvents;if(t.has(n.pointerId)&&t.set(n.pointerId,n),!this.state._active)return;const r=mv(...Array.from(t.values()));r&&this.pinchMove(n,r)}pinchMove(n,t){const r=this.state,o=r._values[1],s=t.angle-o;let i=0;Math.abs(s)>270&&(i+=Math.sign(s)),this.computeValues([t.distance,t.angle-360*i]),r.origin=t.origin,r.turns=i,r._movement=[r._values[0]/r._initial[0]-1,r._values[1]-r._initial[1]],this.compute(n),this.emit()}touchEnd(n){this.ctrl.setEventIds(n),this.state._active&&this.state._touchIds.some(t=>!this.ctrl.touchIds.has(t))&&(this.state._active=!1,this.compute(n),this.emit())}pointerEnd(n){const t=this.state;this.ctrl.setEventIds(n);try{n.target.releasePointerCapture(n.pointerId)}catch{}t._pointerEvents.has(n.pointerId)&&t._pointerEvents.delete(n.pointerId),t._active&&t._pointerEvents.size<2&&(t._active=!1,this.compute(n),this.emit())}gestureStart(n){n.cancelable&&n.preventDefault();const t=this.state;t._active||(this.start(n),this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY],this.compute(n),this.emit())}gestureMove(n){if(n.cancelable&&n.preventDefault(),!this.state._active)return;const t=this.state;this.computeValues([n.scale,n.rotation]),t.origin=[n.clientX,n.clientY];const r=t._movement;t._movement=[n.scale-1,n.rotation],t._delta=Ut.sub(t._movement,r),this.compute(n),this.emit()}gestureEnd(n){this.state._active&&(this.state._active=!1,this.compute(n),this.emit())}wheel(n){const t=this.config.modifierKey;t&&(Array.isArray(t)?!t.find(r=>n[r]):!n[t])||(this.state._active?this.wheelChange(n):this.wheelStart(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(n){this.start(n),this.wheelChange(n)}wheelChange(n){"uv"in n||n.cancelable&&n.preventDefault();const r=this.state;r._delta=[-VM(n)[1]/W7*r.offset[0],0],Ut.addTo(r._movement,r._delta),ZM(r),this.state.origin=[n.clientX,n.clientY],this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){const t=this.config.device;t&&(n(t,"start",this[t+"Start"].bind(this)),n(t,"change",this[t+"Move"].bind(this)),n(t,"end",this[t+"End"].bind(this)),n(t,"cancel",this[t+"End"].bind(this)),n("lostPointerCapture","",this[t+"End"].bind(this))),this.config.pinchOnWheel&&n("wheel","",this.wheel.bind(this),{passive:!1})}}const V7=ut(ut({},XM),{},{device(e,n,{shared:t,pointer:{touch:r=!1}={}}){if(t.target&&!vr.touch&&vr.gesture)return"gesture";if(vr.touch&&r)return"touch";if(vr.touchscreen){if(vr.pointer)return"pointer";if(vr.touch)return"touch"}},bounds(e,n,{scaleBounds:t={},angleBounds:r={}}){const o=i=>{const a=yC(df(t,i),{min:-1/0,max:1/0});return[a.min,a.max]},s=i=>{const a=yC(df(r,i),{min:-1/0,max:1/0});return[a.min,a.max]};return typeof t!="function"&&typeof r!="function"?[o(),s()]:i=>[o(i),s(i)]},threshold(e,n,t){return this.lockDirection=t.axis==="lock",Ut.toVector(e,this.lockDirection?[.1,3]:0)},modifierKey(e){return e===void 0?"ctrlKey":e},pinchOnWheel(e=!0){return e}});ut(ut({},Bu),{},{mouseOnly:(e=!0)=>e});class Y7 extends j7{constructor(...n){super(...n),tn(this,"ingKey","wheeling")}wheel(n){this.state._active||this.start(n),this.wheelChange(n),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(n){const t=this.state;t._delta=VM(n),Ut.addTo(t._movement,t._delta),ZM(t),this.compute(n),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(n){n("wheel","",this.wheel.bind(this))}}const X7=Bu;ut(ut({},Bu),{},{mouseOnly:(e=!0)=>e});const Nw=new Map,yv=new Map;function q7(e){Nw.set(e.key,e.engine),yv.set(e.key,e.resolver)}const Z7={key:"pinch",engine:G7,resolver:V7},Q7={key:"wheel",engine:Y7,resolver:X7};function J7(e,n){if(e==null)return{};var t={},r=Object.keys(e),o,s;for(s=0;s=0)&&(t[o]=e[o]);return t}function eK(e,n){if(e==null)return{};var t=J7(e,n),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(t[r]=e[r])}return t}const tK={target(e){if(e)return()=>"current"in e?e.current:e},enabled(e=!0){return e},window(e=vr.isBrowser?window:void 0){return e},eventOptions({passive:e=!0,capture:n=!1}={}){return{passive:e,capture:n}},transform(e){return e}},nK=["target","eventOptions","window","enabled","transform"];function jh(e={},n){const t={};for(const[r,o]of Object.entries(n))switch(typeof o){case"function":t[r]=o.call(t,e[r],r,e);break;case"object":t[r]=jh(e[r],o);break;case"boolean":o&&(t[r]=e[r]);break}return t}function rK(e,n,t={}){const r=e,{target:o,eventOptions:s,window:i,enabled:a,transform:l}=r,c=eK(r,nK);if(t.shared=jh({target:o,eventOptions:s,window:i,enabled:a,transform:l},tK),n){const d=yv.get(n);t[n]=jh(ut({shared:t.shared},c),d)}else for(const d in c){const h=yv.get(d);h&&(t[d]=jh(ut({shared:t.shared},c[d]),h))}return t}class QM{constructor(n,t){tn(this,"_listeners",new Set),this._ctrl=n,this._gestureKey=t}add(n,t,r,o,s){const i=this._listeners,a=b7(t,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=ut(ut({},l),s);n.addEventListener(a,o,c);const d=()=>{n.removeEventListener(a,o,c),i.delete(d)};return i.add(d),d}clean(){this._listeners.forEach(n=>n()),this._listeners.clear()}}class oK{constructor(){tn(this,"_timeouts",new Map)}add(n,t,r=140,...o){this.remove(n),this._timeouts.set(n,window.setTimeout(t,r,...o))}remove(n){const t=this._timeouts.get(n);t&&window.clearTimeout(t)}clean(){this._timeouts.forEach(n=>void window.clearTimeout(n)),this._timeouts.clear()}}class sK{constructor(n){tn(this,"gestures",new Set),tn(this,"_targetEventStore",new QM(this)),tn(this,"gestureEventStores",{}),tn(this,"gestureTimeoutStores",{}),tn(this,"handlers",{}),tn(this,"config",{}),tn(this,"pointerIds",new Set),tn(this,"touchIds",new Set),tn(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),iK(this,n)}setEventIds(n){if(GM(n))return this.touchIds=new Set(I7(n)),this.touchIds;if("pointerId"in n)return n.type==="pointerup"||n.type==="pointercancel"?this.pointerIds.delete(n.pointerId):n.type==="pointerdown"&&this.pointerIds.add(n.pointerId),this.pointerIds}applyHandlers(n,t){this.handlers=n,this.nativeHandlers=t}applyConfig(n,t){this.config=rK(n,t,this.config)}clean(){this._targetEventStore.clean();for(const n of this.gestures)this.gestureEventStores[n].clean(),this.gestureTimeoutStores[n].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...n){const t=this.config.shared,r={};let o;if(!(t.target&&(o=t.target(),!o))){if(t.enabled){for(const i of this.gestures){const a=this.config[i],l=xC(r,a.eventOptions,!!o);if(a.enabled){const c=Nw.get(i);new c(this,n,i).bind(l)}}const s=xC(r,t.eventOptions,!!o);for(const i in this.nativeHandlers)s(i,"",a=>this.nativeHandlers[i](ut(ut({},this.state.shared),{},{event:a,args:n})),void 0,!0)}for(const s in r)r[s]=_7(...r[s]);if(!o)return r;for(const s in r){const{device:i,capture:a,passive:l}=w7(s);this._targetEventStore.add(o,i,"",r[s],{capture:a,passive:l})}}}}function ga(e,n){e.gestures.add(n),e.gestureEventStores[n]=new QM(e,n),e.gestureTimeoutStores[n]=new oK}function iK(e,n){n.drag&&ga(e,"drag"),n.wheel&&ga(e,"wheel"),n.scroll&&ga(e,"scroll"),n.move&&ga(e,"move"),n.pinch&&ga(e,"pinch"),n.hover&&ga(e,"hover")}const xC=(e,n,t)=>(r,o,s,i={},a=!1)=>{var l,c;const d=(l=i.capture)!==null&&l!==void 0?l:n.capture,h=(c=i.passive)!==null&&c!==void 0?c:n.passive;let p=a?r:v7(r,o,d);t&&h&&(p+="Passive"),e[p]=e[p]||[],e[p].push(s)},aK=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function lK(e){const n={},t={},r=new Set;for(let o in e)aK.test(o)?(r.add(RegExp.lastMatch),t[o]=e[o]):n[o]=e[o];return[t,n,r]}function ma(e,n,t,r,o,s){if(!e.has(t)||!Nw.has(r))return;const i=t+"Start",a=t+"End",l=c=>{let d;return c.first&&i in n&&n[i](c),t in n&&(d=n[t](c)),c.last&&a in n&&n[a](c),d};o[r]=l,s[r]=s[r]||{}}function cK(e,n){const[t,r,o]=lK(e),s={};return ma(o,t,"onDrag","drag",s,n),ma(o,t,"onWheel","wheel",s,n),ma(o,t,"onScroll","scroll",s,n),ma(o,t,"onPinch","pinch",s,n),ma(o,t,"onMove","move",s,n),ma(o,t,"onHover","hover",s,n),{handlers:s,config:n,nativeHandlers:r}}function uK(e,n={},t,r){const o=xe.useMemo(()=>new sK(e),[]);if(o.applyHandlers(e,r),o.applyConfig(n,t),xe.useEffect(o.effect.bind(o)),xe.useEffect(()=>o.clean.bind(o),[]),n.target===void 0)return o.bind.bind(o)}function dK(e){return e.forEach(q7),function(t,r){const{handlers:o,nativeHandlers:s,config:i}=cK(t,r||{});return uK(o,i,void 0,s)}}const wC=10,hK=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function JM(e){let{deltaY:n,deltaX:t}=e,r=0;return e.ctrlKey||e.altKey||e.metaKey?r=(Math.abs(n)>wC?wC*Math.sign(n):n)/100:e.shiftKey&&!hK&&(t=n,n=0),{x:-t,y:-n,z:-r}}const pK=dK([Q7,Z7]);let ya;const fK=e=>ya===void 0?(ya=e,!1):e-ya>120&&e-ya<160?(ya=e,!0):(ya=e,!1);function gK(e){const n=B(),t=P.useMemo(()=>{let r="not sure";const o=({event:g})=>{if(!n.getInstanceState().isFocused||(r="not sure",fK(Date.now())))return;const x=n.getEditingShapeId();if(x){const b=n.getShape(x);if(b&&n.getShapeUtil(b).canScroll(b)){const I=n.getShapePageBounds(x);if(I!=null&&I.containsPoint(n.inputs.currentPagePoint))return}}Ee(g),Kt(g);const y=JM(g);if(y.x===0&&y.y===0)return;const v={type:"wheel",name:"wheel",delta:y,point:new w(g.clientX,g.clientY),shiftKey:g.shiftKey,altKey:g.altKey,ctrlKey:g.metaKey||g.ctrlKey};n.dispatch(v)};let s=1,i=1,a=1,l=0;const c=new w,d=new w,h=g=>{const x=e.current;r="not sure";const{event:y,origin:v,da:b}=g;y instanceof WheelEvent||(y.target===x||x!=null&&x.contains(y.target))&&(d.x=v[0],d.y=v[1],c.x=v[0],c.y=v[1],s=b[0],i=n.getZoomLevel(),n.dispatch({type:"pinch",name:"pinch_start",point:{x:v[0],y:v[1],z:n.getZoomLevel()},delta:{x:0,y:0},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey}))},p=g=>{if(g&&(r="zooming"),r==="zooming")return;const x=Math.abs(l-s),y=w.Dist(c,d);switch(r){case"not sure":{x>24?r="zooming":y>16&&(r="panning");break}case"panning":{x>64&&(r="zooming");break}}};return{onWheel:o,onPinchStart:h,onPinchEnd:g=>{const x=e.current,{event:y,origin:v,offset:b}=g;if(y instanceof WheelEvent||!(y.target===x||x!=null&&x.contains(y.target)))return;const E=b[0];r="not sure",n.timers.requestAnimationFrame(()=>{n.dispatch({type:"pinch",name:"pinch_end",point:{x:v[0],y:v[1],z:E},delta:{x:v[0],y:v[1]},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey})})},onPinch:g=>{const x=e.current,{event:y,origin:v,offset:b,da:E}=g;if(y instanceof WheelEvent||!(y.target===x||x!=null&&x.contains(y.target)))return;const I=g.type==="gesturechange"||g.type==="gestureend";l=E[0];const C=v[0]-d.x,k=v[1]-d.y;switch(d.x=v[0],d.y=v[1],p(I),r){case"zooming":{a=b[0],n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:a},delta:{x:C,y:k},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey});break}case"panning":{n.dispatch({type:"pinch",name:"pinch",point:{x:v[0],y:v[1],z:i},delta:{x:C,y:k},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey});break}}}}},[n,e]);pK(t,{target:e,eventOptions:{passive:!1},pinch:{from:()=>[n.getZoomLevel(),0],scaleBounds:()=>({from:n.getZoomLevel(),max:8,min:.05})}})}function Xm(e,n,t){const r=e.getShape(n),o=e.getShapeHandles(r);return{shape:r,handle:o.find(s=>s.id===t)}}function mK(e,n){const t=B();return P.useMemo(()=>{const r=l=>{if(l.isKilled)return;const c=uf(l.currentTarget);Nu(c,l);const{shape:d,handle:h}=Xm(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:d,name:"pointer_down",...On(l)})};let o,s;return{onPointerDown:r,onPointerMove:l=>{if(l.isKilled||l.clientX===o&&l.clientY===s)return;o=l.clientX,s=l.clientY;const{shape:c,handle:d}=Xm(t,e,n);d&&t.dispatch({type:"pointer",target:"handle",handle:d,shape:c,name:"pointer_move",...On(l)})},onPointerUp:l=>{if(l.isKilled)return;const c=uf(l.currentTarget);zu(c,l);const{shape:d,handle:h}=Xm(t,e,n);h&&t.dispatch({type:"pointer",target:"handle",handle:h,shape:d,name:"pointer_up",...On(l)})}}},[t,e,n])}const Qe=class Qe{constructor(n=0,t=0,r=0,o=0){m(this,"x",0);m(this,"y",0);m(this,"w",0);m(this,"h",0);this.x=n,this.y=t,this.w=r,this.h=o}get point(){return new w(this.x,this.y)}set point(n){this.x=n.x,this.y=n.y}get minX(){return this.x}set minX(n){this.x=n}get midX(){return this.x+this.w/2}get maxX(){return this.x+this.w}get minY(){return this.y}set minY(n){this.y=n}get midY(){return this.y+this.h/2}get maxY(){return this.y+this.h}get width(){return this.w}set width(n){this.w=n}get height(){return this.h}set height(n){this.h=n}get aspectRatio(){return this.width/this.height}get center(){return new w(this.midX,this.midY)}set center(n){this.minX=n.x-this.width/2,this.minY=n.y-this.height/2}get corners(){return[new w(this.minX,this.minY),new w(this.maxX,this.minY),new w(this.maxX,this.maxY),new w(this.minX,this.maxY)]}get cornersAndCenter(){return[new w(this.minX,this.minY),new w(this.maxX,this.minY),new w(this.maxX,this.maxY),new w(this.minX,this.maxY),this.center]}get sides(){const{corners:n}=this;return[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]]}get size(){return new w(this.w,this.h)}toFixed(){return this.x=Fd(this.x),this.y=Fd(this.y),this.w=Fd(this.w),this.h=Fd(this.h),this}setTo(n){return this.x=n.x,this.y=n.y,this.w=n.w,this.h=n.h,this}set(n=0,t=0,r=0,o=0){return this.x=n,this.y=t,this.w=r,this.h=o,this}expand(n){const t=Math.min(this.minX,n.minX),r=Math.min(this.minY,n.minY),o=Math.max(this.maxX,n.maxX),s=Math.max(this.maxY,n.maxY);return this.x=t,this.y=r,this.w=o-t,this.h=s-r,this}expandBy(n){return this.x-=n,this.y-=n,this.w+=n*2,this.h+=n*2,this}scale(n){return this.x/=n,this.y/=n,this.w/=n,this.h/=n,this}clone(){const{x:n,y:t,w:r,h:o}=this;return new Qe(n,t,r,o)}translate(n){return this.x+=n.x,this.y+=n.y,this}snapToGrid(n){const t=Math.round(this.minX/n)*n,r=Math.round(this.minY/n)*n,o=Math.round(this.maxX/n)*n,s=Math.round(this.maxY/n)*n;this.minX=t,this.minY=r,this.width=Math.max(1,o-t),this.height=Math.max(1,s-r)}collides(n){return Qe.Collides(this,n)}contains(n){return Qe.Contains(this,n)}includes(n){return Qe.Includes(this,n)}containsPoint(n,t=0){return Qe.ContainsPoint(this,n,t)}getHandlePoint(n){switch(n){case"top_left":return new w(this.minX,this.minY);case"top_right":return new w(this.maxX,this.minY);case"bottom_left":return new w(this.minX,this.maxY);case"bottom_right":return new w(this.maxX,this.maxY);case"top":return new w(this.midX,this.minY);case"right":return new w(this.maxX,this.midY);case"bottom":return new w(this.midX,this.maxY);case"left":return new w(this.minX,this.midY)}}toJson(){return{x:this.minX,y:this.minY,w:this.w,h:this.h}}resize(n,t,r){const{minX:o,minY:s,maxX:i,maxY:a}=this;let{minX:l,minY:c,maxX:d,maxY:h}=this;switch(n){case"left":case"top_left":case"bottom_left":{l+=t;break}case"right":case"top_right":case"bottom_right":{d+=t;break}}switch(n){case"top":case"top_left":case"top_right":{c+=r;break}case"bottom":case"bottom_left":case"bottom_right":{h+=r;break}}const p=(d-l)/(i-o),f=(h-c)/(a-s),S=p<0,g=f<0;if(S){const x=d;d=l,l=x}if(g){const x=h;h=c,c=x}this.minX=l,this.minY=c,this.width=Math.abs(d-l),this.height=Math.abs(h-c)}union(n){const t=Math.min(this.minX,n.x),r=Math.min(this.minY,n.y),o=Math.max(this.maxX,n.w+n.x),s=Math.max(this.maxY,n.h+n.y);return this.x=t,this.y=r,this.width=o-t,this.height=s-r,this}static From(n){return new Qe(n.x,n.y,n.w,n.h)}static FromCenter(n,t){return new Qe(n.x-t.x/2,n.y-t.y/2,t.x,t.y)}static FromPoints(n){if(n.length===0)return new Qe;let t=1/0,r=1/0,o=-1/0,s=-1/0,i;for(let a=0,l=n.length;a0?1:-1)).toFixed(5),scaleY:+(v.height/n.height*(g>0?1:-1)).toFixed(5)}}equals(n){return Qe.Equals(this,n)}static Equals(n,t){return t.x===n.x&&t.y===n.y&&t.w===n.w&&t.h===n.h}zeroFix(){return this.w=Math.max(1,this.w),this.h=Math.max(1,this.h),this}static ZeroFix(n){return new Qe(n.x,n.y,Math.max(1,n.w),Math.max(1,n.h))}};m(Qe,"Collides",(n,t)=>!(n.maxXt.maxX||n.maxYt.maxY)),m(Qe,"Contains",(n,t)=>n.minXt.maxY&&n.maxX>t.maxX),m(Qe,"Includes",(n,t)=>Qe.Collides(n,t)||Qe.Contains(n,t)),m(Qe,"ContainsPoint",(n,t,r=0)=>!(t.xn.maxX+r||t.y>n.maxY+r)),m(Qe,"Common",n=>{let t=1/0,r=1/0,o=-1/0,s=-1/0;for(let i=0;i{const{corners:r}=n;return[[r[0],r[1]],[r[1],r[2]],[r[2],r[3]],[r[3],r[0]]]});let Z=Qe;function yK(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 SK(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 vK(e){return e==="top_left"||e==="top_right"||e==="bottom_right"||e==="bottom_left"}function xK(e){const n=B();P.useLayoutEffect(()=>{let t=new Z;function r(){const c=e.current;if(!c)return null;const d=c.getBoundingClientRect(),h=new Z(d.left||d.x,d.top||d.y,Math.max(d.width,1),Math.max(d.height,1));t.equals(h)||(n.updateViewportScreenBounds(h),t=h)}r();const o=fw(r,200,{trailing:!0}),s=n.timers.setInterval(o,1e3);window.addEventListener("resize",o);const i=new ResizeObserver(c=>{c[0].contentRect&&o()}),a=e.current;let l=null;return a&&(i.observe(a),l=wK(a),l.addEventListener("scroll",o)),()=>{clearInterval(s),window.removeEventListener("resize",o),i.disconnect(),l==null||l.removeEventListener("scroll",o),o.cancel()}},[n,e])}/*! * Author: excalidraw * MIT License: https://github.com/excalidraw/excalidraw/blob/master/LICENSE * https://github.com/excalidraw/excalidraw/blob/48c3465b19f10ec755b3eb84e21a01a468e96e43/packages/excalidraw/utils.ts#L600 */const wK=e=>{let n=e.parentElement;for(;n;){if(n===document.body)return document;const{overflowY:t}=window.getComputedStyle(n);if(n.scrollHeight>n.clientHeight&&(t==="auto"||t==="scroll"||t==="overlay"))return n;n=n.parentElement}return document},De=class De{constructor(n,t,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=n,this.b=t,this.c=r,this.d=o,this.e=s,this.f=i}equals(n){return this===n||this.a===n.a&&this.b===n.b&&this.c===n.c&&this.d===n.d&&this.e===n.e&&this.f===n.f}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.e=0,this.f=0,this}multiply(n){const t=n,{a:r,b:o,c:s,d:i,e:a,f:l}=this;return this.a=r*t.a+s*t.b,this.c=r*t.c+s*t.d,this.e=r*t.e+s*t.f+a,this.b=o*t.a+i*t.b,this.d=o*t.c+i*t.d,this.f=o*t.e+i*t.f+l,this}rotate(n,t,r){return n===0?this:t===void 0?this.multiply(De.Rotate(n)):this.translate(t,r).multiply(De.Rotate(n)).translate(-t,-r)}translate(n,t){return this.multiply(De.Translate(n,t))}scale(n,t){return this.multiply(De.Scale(n,t))}invert(){const{a:n,b:t,c:r,d:o,e:s,f:i}=this,a=n*o-t*r;return this.a=o/a,this.b=t/-a,this.c=r/-a,this.d=n/a,this.e=(o*s-r*i)/-a,this.f=(t*s-n*i)/a,this}applyToPoint(n){return De.applyToPoint(this,n)}applyToPoints(n){return De.applyToPoints(this,n)}rotation(){return De.Rotation(this)}point(){return De.Point(this)}decomposed(){return De.Decompose(this)}toCssString(){return De.toCssString(this)}setTo(n){return Object.assign(this,n),this}decompose(){return De.Decompose(this)}clone(){return new De(this.a,this.b,this.c,this.d,this.e,this.f)}static Identity(){return new De(1,0,0,1,0,0)}static Translate(n,t){return new De(1,0,0,1,n,t)}static Rotate(n,t,r){if(n===0)return De.Identity();const o=Math.cos(n),s=Math.sin(n),i=new De(o,s,-s,o,0,0);return t===void 0?i:De.Compose(De.Translate(t,r),i,De.Translate(-t,-r))}static Multiply(n,t){return{a:n.a*t.a+n.c*t.b,c:n.a*t.c+n.c*t.d,e:n.a*t.e+n.c*t.f+n.e,b:n.b*t.a+n.d*t.b,d:n.b*t.c+n.d*t.d,f:n.b*t.e+n.d*t.f+n.f}}static Inverse(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/-t,f:(n.b*n.e-n.a*n.f)/t}}static Absolute(n){const t=n.a*n.d-n.b*n.c;return{a:n.d/t,b:n.b/-t,c:n.c/-t,d:n.a/t,e:(n.d*n.e-n.c*n.f)/t,f:(n.b*n.e-n.a*n.f)/-t}}static Compose(...n){const t=De.Identity();for(let r=0,o=n.length;r0?-1:1)}else if(n.b!==0||n.d!==0){const r=(n.b*n.b+n.d*n.d)**.5;t=Ve+Math.acos(n.b/r)*(n.d>0?-1:1)}else t=0;return fv(t)}static Decompose(n){let t,r,o;if(n.a!==0||n.c!==0){const s=(n.a*n.a+n.c*n.c)**.5;t=s,r=(n.a*n.d-n.b*n.c)/s,o=Math.acos(n.a/s)*(n.c>0?-1:1)}else if(n.b!==0||n.d!==0){const s=(n.b*n.b+n.d*n.d)**.5;t=(n.a*n.d-n.b*n.c)/s,r=s,o=Ve+Math.acos(n.b/s)*(n.d>0?-1:1)}else t=0,r=0,o=0;return{x:n.e,y:n.f,scaleX:t,scaleY:r,rotation:fv(o)}}static Smooth(n,t=1e10){return n.a=Math.round(n.a*t)/t,n.b=Math.round(n.b*t)/t,n.c=Math.round(n.c*t)/t,n.d=Math.round(n.d*t)/t,n.e=Math.round(n.e*t)/t,n.f=Math.round(n.f*t)/t,n}static toCssString(n){return`matrix(${N(n.a)}, ${N(n.b)}, ${N(n.c)}, ${N(n.d)}, ${N(n.e)}, ${N(n.f)})`}static applyToPoint(n,t){return new w(n.a*t.x+n.c*t.y+n.e,n.b*t.x+n.d*t.y+n.f,t.z)}static applyToXY(n,t,r){return[n.a*t+n.c*r+n.e,n.b*t+n.d*r+n.f]}static applyToPoints(n,t){return t.map(r=>new w(n.a*r.x+n.c*r.y+n.e,n.b*r.x+n.d*r.y+n.f,r.z))}static applyToBounds(n,t){return new Z(n.e+t.minX,n.f+t.minY,t.width,t.height)}static From(n){return new De(n.a,n.b,n.c,n.d,n.e,n.f)}static Cast(n){return n instanceof De?n:De.From(n)}};m(De,"Scale",(n,t,r,o)=>{const s=new De(n,0,0,t,0,0);return r===void 0?s:De.Compose(De.Translate(r,o),s,De.Translate(-r,-o))});let oe=De;function e2(e,n){return n===0?e:e2(n,e%n)}function t2(e){const n=e.toString().split(".")[1];if(!n)return 1;const t=Math.pow(10,n.length),r=parseInt(n,10);return t/e2(r,t)}class ai{constructor(n){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");m(this,"_length");this.isFilled=n.isFilled,this.isClosed=n.isClosed,this.isLabel=n.isLabel??!1,this.debugColor=n.debugColor,this.ignore=n.ignore}hitTestPoint(n,t=0,r=!1){return this.isClosed&&(this.isFilled||r)&&tr(n,this.vertices)?!0:w.Dist2(n,this.nearestPoint(n))<=t*t}distanceToPoint(n,t=!1){return n.dist(this.nearestPoint(n))*(this.isClosed&&(this.isFilled||t)&&tr(n,this.vertices)?-1:1)}distanceToLineSegment(n,t){if(n.equals(t))return this.distanceToPoint(n);const{vertices:r}=this;let o,s=1/0,i,a,l;for(let c=0;cr.maxX+t||n.y>r.maxY+t)}get vertices(){return this._vertices||(this._vertices=this.getVertices()),this._vertices}getBounds(){return Z.FromPoints(this.vertices)}get bounds(){return this._bounds||(this._bounds=this.getBounds()),this._bounds}get center(){return this.bounds.center}get area(){return this._area||(this._area=this.getArea()),this._area}getArea(){if(!this.isClosed)return 0;const{vertices:n}=this;let t=0;for(let r=0,o=n.length;r!t.isLabel).flatMap(t=>t.vertices)}nearestPoint(t){let r=1/0,o;const{children:s}=this;if(s.length===0)throw Error("no children");let i,a;for(const l of s)i=l.nearestPoint(t),a=w.Dist2(i,t),ao.distanceToPoint(t,r||s>0)))}hitTestPoint(t,r,o){return!!this.children.filter(s=>!s.isLabel).find(s=>s.hitTestPoint(t,r,o))}hitTestLineSegment(t,r,o){return!!this.children.filter(s=>!s.isLabel).find(s=>s.hitTestLineSegment(t,r,o))}getArea(){return this.children[0].area}toSimpleSvgPath(){let t="";for(const o of this.children)t+=o.toSimpleSvgPath();const r=Z.FromPoints(this.vertices).corners;for(let o=0,s=r.length;or.isLabel?t:t+r.length,0)}getSvgPathData(){return this.children.map((t,r)=>t.isLabel?"":t.getSvgPathData(r===0)).join(" ")}}function bK(e=!0){const[n,t]=P.useState(0),r=B();P.useEffect(()=>{if(!e)return;const o=()=>t(s=>s+1);return r.on("tick",o),()=>{r.off("tick",o)}},[r,e])}const PK=lr(function({showStroke:n=!0,showVertices:t=!0,showClosestPointOnOutline:r=!0}){const o=B();bK(r);const s=o.getZoomLevel(),i=o.getRenderingShapes(),{inputs:{currentPagePoint:a}}=o;return u.jsx("svg",{style:{position:"absolute",pointerEvents:"none",zIndex:999999999,top:0,left:0,overflow:"visible"},children:i.map(l=>{const c=o.getShape(l.id);if(c.type==="group")return null;const d=o.getShapeGeometry(c),h=o.getShapePageTransform(c),p=o.getPointInShapeSpace(c,a),f=d.nearestPoint(p),S=d.distanceToPoint(p,!0),g=Math.abs(S)*s,x=S<0,{vertices:y}=d;return u.jsxs("g",{transform:h.toCssString(),strokeLinecap:"round",strokeLinejoin:"round",children:[n&&u.jsx("g",{stroke:d.debugColor??"red",opacity:"1",strokeWidth:2/s,fill:"none",children:u.jsx(n2,{geometry:d})}),t&&y.map((v,b)=>u.jsx("circle",{cx:v.x,cy:v.y,r:2/s,fill:`hsl(${fl(b,[0,y.length-1],[120,200])}, 100%, 50%)`,stroke:"black",strokeWidth:1/s},`v${b}`)),r&&g<150&&u.jsx("line",{x1:f.x,y1:f.y,x2:p.x,y2:p.y,opacity:1-g/150,stroke:x?"goldenrod":"dodgerblue",strokeWidth:2/s})]},l.id+"_outline")})})});function n2({geometry:e}){return e instanceof Hr?u.jsx(u.Fragment,{children:[...e.children,...e.ignoredChildren].map((n,t)=>u.jsx(n2,{geometry:n},t))}):u.jsx("path",{d:e.toSimpleSvgPath()})}function r2(e){return _6(e)}function CK(){const e=B(),n=xH("userIds",()=>r2(e.getCollaborators().map(t=>t.userId)).sort(),{isEqual:(t,r)=>{var o;return t.join(",")===((o=r.join)==null?void 0:o.call(r,","))}},[e]);return G(n)}function o2(e){const n=B();return G(`latestPresence:${e}`,()=>n.getCollaborators().find(r=>r.userId===e),[n,e])??null}const IK=lr(function(){const n=CK();return u.jsx(u.Fragment,{children:n.map(t=>u.jsx(EK,{collaboratorId:t},t))})}),EK=lr(function({collaboratorId:n}){const t=B(),r=o2(n),o=_K(t,r);if(!(r&&r.currentPageId===t.getCurrentPageId()))return null;switch(o){case"inactive":{const{followingUserId:s,highlightedUserIds:i}=t.getInstanceState();if(!(s===r.userId||i.includes(r.userId)))return null;break}case"idle":{const{highlightedUserIds:s}=t.getInstanceState();if(r.followingUserId===t.user.getId()&&!(r.chatMessage||s.includes(r.userId)))return null;break}}return u.jsx(kK,{latestPresence:r})}),kK=lr(function({latestPresence:n}){const t=B(),{CollaboratorBrush:r,CollaboratorScribble:o,CollaboratorCursor:s,CollaboratorHint:i,CollaboratorShapeIndicator:a}=it(),l=t.getZoomLevel(),c=t.getViewportPageBounds(),{userId:d,chatMessage:h,brush:p,scribbles:f,selectedShapeIds:S,userName:g,cursor:x,color:y}=n,v=!(x.xc.maxX-12/l||x.y>c.maxY-16/l);return u.jsxs(u.Fragment,{children:[p&&r?u.jsx(r,{className:"tl-collaborator__brush",brush:p,color:y,opacity:.1},d+"_brush"):null,v&&s?u.jsx(s,{className:"tl-collaborator__cursor",point:x,color:y,zoom:l,name:g!=="New User"?g:null,chatMessage:h},d+"_cursor"):i?u.jsx(i,{className:"tl-collaborator__cursor-hint",point:x,color:y,zoom:l,viewport:c},d+"_cursor_hint"):null,o&&f.length?u.jsx(u.Fragment,{children:f.map(b=>u.jsx(o,{className:"tl-collaborator__scribble",scribble:b,color:y,zoom:l,opacity:b.color==="laser"?.5:.1},d+"_scribble_"+b.id))}):null,a&&S.map(b=>u.jsx(a,{className:"tl-collaborator__shape-indicator",shapeId:b,color:y,opacity:.5},d+"_"+b))]})});function bC(e,n){return n>e.options.collaboratorInactiveTimeoutMs?"inactive":n>e.options.collaboratorIdleTimeoutMs?"idle":"active"}function _K(e,n){const t=P.useRef((n==null?void 0:n.lastActivityTimestamp)??-1),[r,o]=P.useState(()=>bC(e,Date.now()-t.current));return P.useEffect(()=>{const s=e.timers.setInterval(()=>{o(bC(e,Date.now()-t.current))},e.options.collaboratorCheckIntervalMs);return()=>clearInterval(s)},[e]),n&&(t.current=n.lastActivityTimestamp),r}const s2=P.memo(function({id:n,shape:t,util:r,index:o,backgroundIndex:s,opacity:i,dprMultiple:a}){const l=B(),{ShapeErrorFallback:c}=it(),d=P.useRef(null),h=P.useRef(null),p=P.useRef({transform:"",clipPath:"none",width:0,height:0,x:0,y:0,isCulled:!1});Bs("set shape stuff",()=>{const g=l.getShape(n);if(!g)return;const x=p.current,y=l.getShapeClipPath(n)??"none";y!==x.clipPath&&(Jt(d.current,"clip-path",y),Jt(h.current,"clip-path",y),x.clipPath=y);const v=l.getShapePageTransform(n),b=oe.toCssString(v),E=l.getShapeGeometry(g).bounds;b!==x.transform&&(Jt(d.current,"transform",b),Jt(h.current,"transform",b),x.transform=b);const I=E.w%a,C=E.h%a,k=I===0?E.w:E.w+(a-I),T=C===0?E.h:E.h+(a-C);(k!==x.width||T!==x.height)&&(Jt(d.current,"width",Math.max(k,a)+"px"),Jt(d.current,"height",Math.max(T,a)+"px"),Jt(h.current,"width",Math.max(k,a)+"px"),Jt(h.current,"height",Math.max(T,a)+"px"),x.width=k,x.height=T)},[l]),Bs("set opacity and z-index",()=>{const g=d.current,x=h.current;Jt(g,"opacity",i),Jt(x,"opacity",i),Jt(g,"z-index",o),Jt(x,"z-index",s)},[i,o,s]),Bs("set display",()=>{if(!l.getShape(n))return;const y=l.getCulledShapes().has(n);y!==p.current.isCulled&&(Jt(d.current,"display",y?"none":"block"),Jt(h.current,"display",y?"none":"block"),p.current.isCulled=y)},[l]);const f=P.useCallback(g=>l.annotateError(g,{origin:"shape",willCrashApp:!1}),[l]);if(!t)return null;const S="fill"in t.props&&t.props.fill!=="none";return u.jsxs(u.Fragment,{children:[r.backgroundComponent&&u.jsx("div",{ref:h,className:"tl-shape tl-shape-background","data-shape-type":t.type,draggable:!1,children:u.jsx(fu,{fallback:c,onError:f,children:u.jsx(MK,{shape:t,util:r})})}),u.jsx("div",{ref:d,className:"tl-shape","data-shape-type":t.type,"data-shape-is-filled":S,draggable:!1,children:u.jsx(fu,{fallback:c,onError:f,children:u.jsx(TK,{shape:t,util:r})})})]})}),TK=P.memo(function({shape:n,util:t}){return Jf("InnerShape:"+n.type,()=>t.component(t.editor.store.unsafeGetWithoutCapture(n.id)))},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta),MK=P.memo(function({shape:n,util:t}){return Jf("InnerShape:"+n.type,()=>{var r;return(r=t.backgroundComponent)==null?void 0:r.call(t,t.editor.store.unsafeGetWithoutCapture(n.id))})},(e,n)=>e.shape.props===n.shape.props&&e.shape.meta===n.shape.meta);function jK({className:e}){const n=B(),{Background:t,SvgDefs:r}=it(),o=P.useRef(null),s=P.useRef(null),i=P.useRef(null),a=un();xK(o),c7(),a7(),gK(o),h7(o);const l=P.useRef({lodDisableTextOutline:!1,allowTextOutline:!0});Bs("position layers",function(){const{x:y,y:v,z:b}=n.getCamera();if(l.current.allowTextOutline&&n.environment.isSafari&&(a.style.setProperty("--tl-text-outline","none"),l.current.allowTextOutline=!1),l.current.allowTextOutline&&b=1?fl(b,[1,8],[.125,.5],!0):fl(b,[.1,1],[-2,.125],!0),I=`scale(${N(b)}) translate(${N(y+E)}px,${N(v+E)}px)`;Jt(s.current,"transform",I),Jt(i.current,"transform",I)},[n,a]);const c=i7(),d=G("shapeSvgDefs",()=>{const x=new Map;for(const y of gt(n.shapeUtils)){if(!y)return;const v=y.getCanvasSvgDefs();for(const{key:b,component:E}of v)x.has(b)||x.set(b,u.jsx(E,{},b))}return[...x.values()]},[n]),h=G("debug_shapes",()=>wt.hideShapes.get(),[wt]),p=G("debug_svg",()=>wt.debugSvg.get(),[wt]),f=G("debug_geometry",()=>wt.debugGeometry.get(),[wt]),S=G("isEditingAnything",()=>n.getEditingShapeId()!==null,[n]),g=G("isSelectingAnything",()=>!!n.getSelectedShapeIds().length,[n]);return u.jsxs("div",{ref:o,draggable:!1,"data-iseditinganything":S,"data-isselectinganything":g,className:ce("tl-canvas",e),"data-testid":"canvas",...c,children:[u.jsx("svg",{className:"tl-svg-context",children:u.jsxs("defs",{children:[d,u.jsx(WK,{}),u.jsx(GK,{}),r&&u.jsx(r,{})]})}),t&&u.jsx("div",{className:"tl-background__wrapper",children:u.jsx(t,{})}),u.jsx(AK,{}),u.jsxs("div",{ref:s,className:"tl-html-layer tl-shapes",draggable:!1,children:[u.jsx(qK,{}),u.jsx(XK,{}),h?null:p?u.jsx(zK,{}):u.jsx(UK,{})]}),u.jsx("div",{className:"tl-overlays",children:u.jsxs("div",{ref:i,className:"tl-html-layer",children:[f?u.jsx(PK,{}):null,u.jsx($K,{}),u.jsx(DK,{}),u.jsx(OK,{}),u.jsx(RK,{}),u.jsx(HK,{}),u.jsx(KK,{}),u.jsx(LK,{}),u.jsx(YK,{}),u.jsx(IK,{})]})}),u.jsx(ZK,{})]})}function AK(){const e=B(),n=G("gridSize",()=>e.getDocumentSettings().gridSize,[e]),{x:t,y:r,z:o}=G("camera",()=>e.getCamera(),[e]),s=G("isGridMode",()=>e.getInstanceState().isGridMode,[e]),{Grid:i}=it();return i&&s?u.jsx(i,{x:t,y:r,z:o,size:n}):null}function OK(){const e=B(),n=G("scribbles",()=>e.getInstanceState().scribbles,[e]),t=G("zoomLevel",()=>e.getZoomLevel(),[e]),{Scribble:r}=it();return r&&n.length?u.jsx(u.Fragment,{children:n.map(o=>u.jsx(r,{className:"tl-user-scribble",scribble:o,zoom:t},o.id))}):null}function DK(){const e=B(),n=G("brush",()=>e.getInstanceState().brush,[e]),{Brush:t}=it();return t&&n?u.jsx(t,{className:"tl-user-brush",brush:n}):null}function RK(){const e=B(),n=G("zoomBrush",()=>e.getInstanceState().zoomBrush,[e]),{ZoomBrush:t}=it();return t&&n?u.jsx(t,{className:"tl-user-brush tl-zoom-brush",brush:n}):null}function LK(){const e=B(),n=G("snapLines",()=>e.snaps.getIndicators(),[e]),t=G("zoomLevel",()=>e.getZoomLevel(),[e]),{SnapIndicator:r}=it();return r&&n.length>0?u.jsx(u.Fragment,{children:n.map(o=>u.jsx(r,{className:"tl-user-snapline",line:o,zoom:t},o.id))}):null}function $K(){const e=B(),n=G("handles shapeIdWithHandles",()=>{const{isReadonly:t,isChangingStyle:r}=e.getInstanceState();if(t||r)return!1;const o=e.getOnlySelectedShape();return!o||!e.getShapeHandles(o)?!1:o.id},[e]);return n?u.jsx(FK,{shapeId:n}):null}function FK({shapeId:e}){const n=B(),{Handles:t}=it(),r=G("zoomLevel",()=>n.getZoomLevel(),[n]),o=G("coarse pointer",()=>n.getInstanceState().isCoarsePointer,[n]),s=G("handles transform",()=>n.getShapePageTransform(e),[n,e]),i=G("handles",()=>{const a=n.getShapeHandles(e);if(!a)return null;const l=(o?n.options.coarseHandleRadius:n.options.handleRadius)/r*2;return a.filter(c=>c.type!=="virtual"||!a.some(d=>d!==c&&d.type==="vertex"&&w.Dist(c,d)c.type==="vertex"?1:-1)},[n,r,o,e]);return!t||!i||!s?null:u.jsx(t,{children:u.jsx("g",{transform:oe.toCssString(s),children:i.map(a=>u.jsx(NK,{shapeId:e,handle:a,zoom:r,isCoarse:o},a.id))})})}function NK({shapeId:e,handle:n,zoom:t,isCoarse:r}){const o=mK(e,n.id),{Handle:s}=it();return s?u.jsx("g",{"aria-label":"handle",transform:`translate(${n.x}, ${n.y})`,...o,children:u.jsx(s,{shapeId:e,handle:n,zoom:t,isCoarse:r})}):null}function zK(){const e=B(),n=G("rendering shapes",()=>e.getRenderingShapes(),[e]),t=G("dpr multiple",()=>t2(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return u.jsx(u.Fragment,{children:n.map(r=>u.jsxs(P.Fragment,{children:[u.jsx(s2,{...r,dprMultiple:t}),u.jsx(VK,{id:r.id})]},r.id+"_fragment"))})}function BK(){const e=B(),n=P.useRef(new Set);return Bs("reflow for culled shapes",()=>{const t=e.getCulledShapes();if(n.current.size===t.size&&[...t].every(o=>n.current.has(o)))return;n.current=t;const r=document.getElementsByClassName("tl-canvas");r.length!==0&&r[0].offsetHeight},[e]),null}function UK(){const e=B(),n=G("rendering shapes",()=>e.getRenderingShapes(),[e]),t=G("dpr multiple",()=>t2(Math.floor(e.getInstanceState().devicePixelRatio*100)/100),[e]);return u.jsxs(u.Fragment,{children:[n.map(r=>u.jsx(s2,{...r,dprMultiple:t},r.id+"_shape")),e.environment.isSafari&&u.jsx(BK,{})]})}function HK(){const e=B(),n=G("rendering shapes",()=>e.getRenderingShapes(),[e]),t=P.useRef(new Set),r=G("should display selected ids",()=>{const s=t.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 l of a)i.add(l);if(e.isInAny("select.idle","select.editing_shape")){const l=e.getInstanceState();if(l.isHoveringCanvas&&!l.isCoarsePointer){const c=e.getHoveredShapeId();c&&i.add(c)}}}if(s.size!==i.size)return t.current=i,i;for(const a of i)if(!s.has(a))return t.current=i,i;return s},[e]),{ShapeIndicator:o}=it();return o?u.jsx(u.Fragment,{children:n.map(({id:s})=>u.jsx(o,{shapeId:s,hidden:!r.has(s)},s+"_indicator"))}):null}function KK(){const e=B(),{ShapeIndicator:n}=it(),t=G("hinting shape ids",()=>vw(e.getHintingShapeIds()),[e]);return!t.length||!n?null:u.jsx(u.Fragment,{children:t.map(r=>u.jsx(n,{className:"tl-user-indicator__hint",shapeId:r},r+"_hinting"))})}function WK(){return u.jsxs("g",{id:"cursor",children:[u.jsxs("g",{fill:"rgba(0,0,0,.2)",transform:"translate(-11,-11)",children:[u.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),u.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),u.jsxs("g",{fill:"white",transform:"translate(-12,-12)",children:[u.jsx("path",{d:"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z"}),u.jsx("path",{d:"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z"})]}),u.jsxs("g",{fill:"currentColor",transform:"translate(-12,-12)",children:[u.jsx("path",{d:"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z"}),u.jsx("path",{d:"m13 10.814v11.188l2.969-2.866.428-.139h4.768z"})]})]})}function GK(){return u.jsx("path",{id:"cursor_hint",fill:"currentColor",d:"M -2,-5 2,0 -2,5 Z"})}function VK({id:e}){const n=B(),[t,r]=P.useState(null),o=G("is in root",()=>{const s=n.getShape(e);return(s==null?void 0:s.parentId)===n.getCurrentPageId()},[n,e]);return P.useEffect(()=>{if(!o)return;let s=null;const i=aa("shape to svg",async()=>{const a=Math.random();s=a;const c=n.isShapeOfType(e,"frame")?0:10;let d=n.getShapePageBounds(e);if(!d)return;d=d.clone().expandBy(c);const h=await n.getSvgString([e],{padding:c,background:n.getInstanceState().exportBackground});if(s!==a||!h)return;const p=`data:image/svg+xml;utf8,${encodeURIComponent(h.svg)}`;r({src:p,bounds:d})});return()=>{s=null,i()}},[n,e,o]),!o||!t?null:u.jsx("img",{src:t.src,width:t.bounds.width,height:t.bounds.height,referrerPolicy:"no-referrer",style:{position:"absolute",top:0,left:0,transform:`translate(${t.bounds.x}px, ${t.bounds.maxY+12}px)`,outline:"1px solid black",maxWidth:"none"}})}function YK(){const e=B(),n=G("selection rotation",()=>e.getSelectionRotation(),[e]),t=G("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionForeground:r}=it();return!t||!r?null:u.jsx(r,{bounds:t,rotation:n})}function XK(){const e=B(),n=G("selection rotation",()=>e.getSelectionRotation(),[e]),t=G("selection bounds",()=>e.getSelectionRotatedPageBounds(),[e]),{SelectionBackground:r}=it();return!t||!r?null:u.jsx(r,{bounds:t,rotation:n})}function qK(){const{OnTheCanvas:e}=it();return e?u.jsx(e,{}):null}function ZK(){const e=B(),n=G("camera state",()=>e.getCameraState(),[e]);return u.jsx("div",{className:ce("tl-hit-test-blocker",{"tl-hit-test-blocker__hidden":n==="idle"})})}function QK({className:e,zoom:n,point:t,color:r,viewport:o,opacity:s=1}){const i=P.useRef(null);return Rl(i,_t(t.x,o.minX+5/n,o.maxX-5/n),_t(t.y,o.minY+5/n,o.maxY-5/n),1/n,w.Angle(o.center,t)),u.jsxs("svg",{ref:i,className:ce("tl-overlays__item",e),children:[u.jsx("use",{href:"#cursor_hint",color:r,strokeWidth:3,stroke:"var(--color-background)"}),u.jsx("use",{href:"#cursor_hint",color:r,opacity:s})]})}const PC=P.memo(function({className:n,zoom:t,point:r,color:o,name:s,chatMessage:i}){const a=P.useRef(null);return Rl(a,r==null?void 0:r.x,r==null?void 0:r.y,1/t),r?u.jsxs("div",{ref:a,className:ce("tl-overlays__item",n),children:[u.jsx("svg",{className:"tl-cursor",children:u.jsx("use",{href:"#cursor",color:o})}),i?u.jsxs(u.Fragment,{children:[s&&u.jsx("div",{className:"tl-nametag-title",style:{color:o},children:s}),u.jsx("div",{className:"tl-nametag-chat",style:{backgroundColor:o},children:i})]}):s&&u.jsx("div",{className:"tl-nametag",style:{backgroundColor:o},children:s})]}):null});function JK({x:e,y:n,z:t,size:r}){const o=B(),{gridSteps:s}=o.options;return u.jsxs("svg",{className:"tl-grid",version:"1.1",xmlns:"http://www.w3.org/2000/svg",children:[u.jsx("defs",{children:s.map(({min:i,mid:a,step:l},c)=>{const d=l*r*t,h=.5+e*t,p=.5+n*t,f=h>0?h%d:d+h%d,S=p>0?p%d:d+p%d,g=tu.jsx("rect",{width:"100%",height:"100%",fill:`url(#grid-${i})`},`grid-rect-${a}`))]})}function eW({handle:e,isCoarse:n,className:t,zoom:r}){const o=B(),s=(n?o.options.coarseHandleRadius:o.options.handleRadius)/r;if(e.type==="clone"){const a=3/r,l=`M0,${-a} A${a},${a} 0 0,1 0,${a}`,c=e7.indexOf(e.id);return u.jsxs("g",{className:ce(`tl-handle tl-handle__${e.type}`,t),children:[u.jsx("circle",{className:"tl-handle__bg",r:s}),u.jsx("path",{className:"tl-handle__fg",d:l,transform:`rotate(${-90+90*c})`})]})}const i=(e.type==="create"&&n?3:4)/Math.max(r,.25);return u.jsxs("g",{className:ce(`tl-handle tl-handle__${e.type}`,t),children:[u.jsx("circle",{className:"tl-handle__bg",r:s}),u.jsx("circle",{className:"tl-handle__fg",r:i})]})}const tW=({children:e})=>u.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}),nW=()=>{const{Spinner:e}=it();return u.jsx(Jw,{children:e?u.jsx(e,{}):null})};function zw(e,n=!0){const t=e.length;if(t<2)return"";let r=e[0],o=e[1];if(t===2)return`M${Ie(r)}L${Ie(o)}`;let s="";for(let i=2,a=t-1;i3?"T":""}${s}L${Ie(e[t-1])}`}function CC({scribble:e,zoom:n,color:t,opacity:r,className:o}){return e.points.length?u.jsx("svg",{className:o&&ce("tl-overlays__item",o),children:u.jsx("path",{className:"tl-scribble",d:zw(e.points,!1),stroke:t??`var(--color-${e.color})`,fill:"none",strokeWidth:8/n,opacity:r??e.opacity})}):null}function i2({bounds:e,rotation:n}){const t=P.useRef(null);return Rl(t,e.x,e.y,1,n),P.useLayoutEffect(()=>{const r=t.current;r&&(r.style.width=N(Math.max(1,e.width))+"px",r.style.height=N(Math.max(1,e.height))+"px")},[e.width,e.height]),u.jsx("div",{ref:t,className:"tl-selection__bg",draggable:!1})}function rW({bounds:e,rotation:n}){const t=B(),r=P.useRef(null),o=G("only selected shape",()=>t.getOnlySelectedShape(),[t]),s=o?t.getShapeUtil(o).expandSelectionOutlinePx(o):0;return Rl(r,e==null?void 0:e.x,e==null?void 0:e.y,1,n,{x:-s,y:-s}),e=e.clone().expandBy(s).zeroFix(),u.jsx("svg",{ref:r,className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:u.jsx("rect",{className:ce("tl-selection__fg__outline"),width:N(e.width),height:N(e.height)})})}const oW=()=>u.jsx("div",{className:"tl-shape-error-boundary"}),sW=({shape:e,util:n})=>Jf("Indicator: "+e.type,()=>n.indicator(n.editor.store.unsafeGetWithoutCapture(e.id))),iW=({editor:e,id:n})=>{const t=G("shape for indicator",()=>e.store.get(n),[e,n]),{ShapeIndicatorErrorFallback:r}=it();return!t||t.isLocked?null:u.jsx(fu,{fallback:r,onError:o=>e.annotateError(o,{origin:"react.shapeIndicator",willCrashApp:!1}),children:u.jsx(sW,{shape:t,util:e.getShapeUtil(t)},t.id)})},IC=P.memo(function({shapeId:n,className:t,color:r,hidden:o,opacity:s}){const i=B(),a=P.useRef(null);return Bs("indicator transform",()=>{const l=a.current;if(!l)return;const c=i.getShapePageTransform(n);c&&l.style.setProperty("transform",c.toCssString())},[i,n]),P.useLayoutEffect(()=>{const l=a.current;l&&l.style.setProperty("display",o?"none":"block")},[o]),u.jsx("svg",{ref:a,className:ce("tl-overlays__item",t),children:u.jsx("g",{className:"tl-shape-indicator",stroke:r??"var(--color-selected)",opacity:s,children:u.jsx(iW,{editor:i,id:n})})})}),aW=()=>u.jsx("circle",{cx:4,cy:4,r:8,strokeWidth:"1",stroke:"red"});function lW({points:e,zoom:n}){const t=2.5/n,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 l,c,d,h;return a?(l=r,c=s,d=o,h=i):(l=r,c=i,d=o,h=s),u.jsxs("g",{className:"tl-snap-indicator",stroke:"lime",children:[u.jsx("line",{x1:l,y1:c,x2:d,y2:h}),e.map((p,f)=>u.jsx("g",{transform:`translate(${p.x},${p.y})`,children:u.jsx("path",{className:"tl-snap-point",d:`M ${-t},${-t} L ${t},${t} M ${-t},${t} L ${t},${-t}`})},f))]})}function cW({gaps:e,direction:n,zoom:t}){const r=3.5/t;let o=[-1/0,1/0],s=null;const i=n==="horizontal";for(const l of e){if(s=Or(o[0],o[1],i?l.startEdge[0].y:l.startEdge[0].x,i?l.startEdge[1].y:l.startEdge[1].x),s)o=s;else continue;if(s=Or(o[0],o[1],i?l.endEdge[0].y:l.endEdge[0].x,i?l.endEdge[1].y:l.endEdge[1].x),s)o=s;else continue}if(o===null)return null;const a=(o[0]+o[1])/2;return u.jsx("g",{className:"tl-snap-indicator",stroke:"cyan",children:e.map(({startEdge:l,endEdge:c},d)=>u.jsx(P.Fragment,{children:i?u.jsxs(u.Fragment,{children:[u.jsx("line",{x1:l[0].x,y1:a-2*r,x2:l[1].x,y2:a+2*r}),u.jsx("line",{x1:c[0].x,y1:a-2*r,x2:c[1].x,y2:a+2*r}),u.jsx("line",{x1:l[0].x,y1:a,x2:c[0].x,y2:a}),u.jsx("line",{x1:(l[0].x+c[0].x)/2,y1:a-r,x2:(l[0].x+c[0].x)/2,y2:a+r})]}):u.jsxs(u.Fragment,{children:[u.jsx("line",{x1:a-2*r,y1:l[0].y,x2:a+2*r,y2:l[1].y}),u.jsx("line",{x1:a-2*r,y1:c[0].y,x2:a+2*r,y2:c[1].y}),u.jsx("line",{x1:a,y1:l[0].y,x2:a,y2:c[0].y}),u.jsx("line",{x1:a-r,y1:(l[0].y+c[0].y)/2,x2:a+r,y2:(l[0].y+c[0].y)/2})]})},d))})}function uW({className:e,line:n,zoom:t}){return u.jsx("svg",{className:ce("tl-overlays__item",e),children:n.type==="points"?u.jsx(lW,{...n,zoom:t}):n.type==="gaps"?u.jsx(cW,{...n,zoom:t}):null})}function Bw(){return u.jsx("svg",{width:16,height:16,viewBox:"0 0 16 16",children:u.jsxs("g",{strokeWidth:2,fill:"none",fillRule:"evenodd",children:[u.jsx("circle",{strokeOpacity:.25,cx:8,cy:8,r:7,stroke:"currentColor"}),u.jsx("path",{strokeLinecap:"round",d:"M15 8c0-4.5-4.5-7-7-7",stroke:"currentColor",children:u.jsx("animateTransform",{attributeName:"transform",type:"rotate",from:"0 8 8",to:"360 8 8",dur:"1s",repeatCount:"indefinite"})})]})})}const dW=()=>null;function a2(e,n){const t=P.useRef(e);return n(e,t.current)?t.current:(t.current=e,e)}function Bc(e){return a2(e,j6)}function Uw(e){return a2(e,MT)}const l2=P.createContext(null);function hW({overrides:e={},children:n}){const t=Uw(e);return u.jsx(l2.Provider,{value:P.useMemo(()=>({Background:V9,SvgDefs:dW,Brush:Wm,ZoomBrush:Wm,CollaboratorBrush:Wm,Cursor:PC,CollaboratorCursor:PC,CollaboratorHint:QK,CollaboratorShapeIndicator:IC,Grid:JK,Scribble:CC,SnapIndicator:uW,Handles:tW,Handle:eW,CollaboratorScribble:CC,ErrorFallback:u2,ShapeErrorFallback:oW,ShapeIndicatorErrorFallback:aW,Spinner:Bw,SelectionBackground:i2,SelectionForeground:rW,ShapeIndicator:IC,OnTheCanvas:null,InFrontOfTheCanvas:null,Canvas:jK,LoadingScreen:nW,...t}),[t]),children:n})}function it(){const e=P.useContext(l2);if(!e)throw new Error("useEditorComponents must be used inside of ");return e}const Hw={openWindow:(e,n)=>window.open(e,n,"noopener noreferrer"),refreshPage:()=>window.location.reload(),hardReset:async()=>{var e;return await((e=window.__tldraw__hardReset)==null?void 0:e.call(window))}};function c2(){Hw.hardReset()}function pW(){Hw.refreshPage()}const fW="https://github.com/tldraw/tldraw/issues/new",u2=({error:e,editor:n})=>{const t=P.useRef(null),[r,o]=P.useState(!1),[s,i]=P.useState(!1),[a,l]=P.useState(!1);let c=null;try{c=it().Canvas??null}catch{}const d=e instanceof Error?e.message:String(e),h=e instanceof Error?e.stack:null,p=G("isDarkMode",()=>{try{if(n)return n.user.getIsDarkMode()}catch{}return null},[n]),[f,S]=P.useState(null);P.useLayoutEffect(()=>{var I;p!==null&&S(p);let b=(I=t.current)==null?void 0:I.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){S(null);return}S(window.matchMedia("(prefers-color-scheme: dark)").matches)},[p]),P.useEffect(()=>{if(s){const b=n==null?void 0:n.timers.setTimeout(()=>{i(!1)},2e3);return()=>clearTimeout(b)}},[s,n]);const g=()=>{const b=document.createElement("textarea");b.value=h??d,document.body.appendChild(b),b.select(),document.execCommand("copy"),b.remove(),i(!0)},x=()=>{pW()},y=async()=>{c2()},v=new URL(fW);return v.searchParams.set("title",d),v.searchParams.set("labels","bug"),v.searchParams.set("body",`Hey, I ran into an error while using tldraw: \`\`\`js ${h??d} \`\`\` My browser: ${navigator.userAgent}`),u.jsxs("div",{ref:t,className:ce("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[u.jsx("div",{className:"tl-error-boundary__overlay"}),n&&u.jsx(NM,{onError:Wp,fallback:()=>null,children:u.jsx(og.Provider,{value:n,children:u.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:c?u.jsx(c,{}):null})})}),u.jsx("div",{className:ce("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?u.jsxs(u.Fragment,{children:[u.jsx("h2",{children:"Are you sure?"}),u.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),u.jsxs("div",{className:"tl-error-boundary__content__actions",children:[u.jsx("button",{onClick:()=>l(!1),children:"Cancel"}),u.jsx("button",{className:"tl-error-boundary__reset",onClick:y,children:"Reset data"})]})]}):u.jsxs(u.Fragment,{children:[u.jsx("h2",{children:"Something's gone wrong."}),u.jsxs("p",{children:["Sorry, we encountered an error. Please refresh the page to continue. If you keep seeing this error, you can ",u.jsx("a",{href:v.toString(),children:"create a GitHub issue"})," or"," ",u.jsx("a",{href:"https://discord.gg/Cq6cPsTfNy",children:"ask for help on Discord"}),"."]}),r&&u.jsxs(u.Fragment,{children:["Message:",u.jsx("h4",{children:u.jsx("code",{children:d})}),"Stack trace:",u.jsxs("div",{className:"tl-error-boundary__content__error",children:[u.jsx("pre",{children:u.jsx("code",{children:h??d})}),u.jsx("button",{onClick:g,children:s?"Copied!":"Copy"})]})]}),u.jsxs("div",{className:"tl-error-boundary__content__actions",children:[u.jsx("button",{onClick:()=>o(!r),children:r?"Hide details":"Show details"}),u.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[u.jsx("button",{className:"tl-error-boundary__reset",onClick:()=>l(!0),children:"Reset data"}),u.jsx("button",{className:"tl-error-boundary__refresh",onClick:x,children:"Refresh Page"})]})]})]})})]})};function ot(){return Lu()}const d2="TLDRAW_USER_DATA_v3",h2=Se({id:pe,name:pe.nullable().optional(),locale:pe.nullable().optional(),color:pe.nullable().optional(),colorScheme:ng("light","dark","system").optional(),animationSpeed:de.nullable().optional(),edgeScrollSpeed:de.nullable().optional(),isSnapMode:we.nullable().optional(),isWrapMode:we.nullable().optional(),isDynamicSizeMode:we.nullable().optional()}),vs={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5,AddDynamicSizeMode:6,AllowSystemColorScheme:7},Kw=Math.max(...Object.values(vs));function gW(e){e.version"u"?!1:((n=(e=window.matchMedia)==null?void 0:e.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:n.matches)??!1}const gs=Object.freeze({name:"New User",locale:U9(),color:mW(),edgeScrollSpeed:1,animationSpeed:yW()?0:1,isSnapMode:!1,isWrapMode:!1,isDynamicSizeMode:!1});function qm(){return{id:ot()}}function p2(e){if(e===null||typeof e!="object"||!("version"in e)||!("user"in e)||typeof e.version!="number")return qm();const n=rt(e);gW(n);try{return h2.validate(n.user)}catch{return qm()}}function SW(){const e=JSON.parse(bw(d2)||"null")??null;return p2(e)}const gu=Mt("globalUserData",null);function vW(){Pw(d2,JSON.stringify({version:Kw,user:gu.get()}))}function xW(e){h2.validate(e),gu.set(e),vW(),bW()}const wW=typeof process<"u"&&!1,tl=typeof BroadcastChannel<"u"&&!wW?new BroadcastChannel("tldraw-user-sync"):null;tl==null||tl.addEventListener("message",e=>{const n=e.data;(n==null?void 0:n.type)===g2&&(n==null?void 0:n.origin)!==f2()&&gu.set(p2(n.data))});let Zm=null;function f2(){return Zm===null&&(Zm=ot()),Zm}const g2="tldraw-user-preferences-change";function bW(){tl==null||tl.postMessage({type:g2,origin:f2(),data:{user:m2(),version:Kw}})}function m2(){let e=gu.get();return e||(e=SW(),gu.set(e)),e}function y2(e={}){return{derivePresenceState:e.derivePresenceState??(()=>V("presence",()=>null)),userPreferences:e.userPreferences??V("userPreferences",()=>m2()),setUserPreferences:e.setUserPreferences??xW}}var S2={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function o(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function s(l,c,d,h,p){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new o(d,h||l,p),S=t?t+c:c;return l._events[S]?l._events[S].fn?l._events[S]=[l._events[S],f]:l._events[S].push(f):(l._events[S]=f,l._eventsCount++),l}function i(l,c){--l._eventsCount===0?l._events=new r:delete l._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],d,h;if(this._eventsCount===0)return c;for(h in d=this._events)n.call(d,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(d)):c},a.prototype.listeners=function(c){var d=t?t+c:c,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,S=new Array(f);p";go&&(go[nl]=hf,IW()?Cw(nl,hf):LT(nl));go==null||go.addEventListener("beforeunload",()=>{Cw(nl,hf)});const v2={Initial:0},sg=Math.max(...Object.values(v2));function EW(e){e.version{const t=e.get(gn);if(!t)return null;const r=[...n.get()];return{version:sg,currentPageId:t.currentPageId,exportBackground:t.exportBackground,isFocusMode:t.isFocusMode,isDebugMode:t.isDebugMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,pageStates:r.map(o=>{const s=e.get($r.createId(o)),i=e.get(lo.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 b2(e,n){const t=kW(n);if(!t)return;const r=e.schema.types.instance.create({id:gn,...hM(e.get(gn)),currentPageId:t.currentPageId,isDebugMode:t.isDebugMode,isFocusMode:t.isFocusMode,isToolLocked:t.isToolLocked,isGridMode:t.isGridMode,exportBackground:t.exportBackground}),o=e.allRecords().filter(s=>s.typeName==="instance_page_state"||s.typeName==="camera");e.atomic(()=>{e.remove(o.map(s=>s.id));for(const s of t.pageStates)e.put([lo.create({id:lo.createId(s.pageId),x:s.camera.x,y:s.camera.y,z:s.camera.z}),$r.create({id:$r.createId(s.pageId),pageId:s.pageId,selectedShapeIds:s.selectedShapeIds,focusedGroupId:s.focusedGroupId})]);e.put([r]),e.ensureStoreIsUsable()})}function _W(e){var o;const n=[];for(const s of Object.values(e))(o=s.typeName)!=null&&o.match(/^(instance.*|pointer|camera)$/)&&n.push(s);const t=n.filter(s=>s.typeName==="instance"&&s.id!==gn)[0];if(!t)return null;const r={version:sg,currentPageId:t.currentPageId,exportBackground:!!t.exportBackground,isFocusMode:!!t.isFocusMode,isDebugMode:!!t.isDebugMode,isToolLocked:!!t.isToolLocked,isGridMode:!1,pageStates:n.filter(s=>s.typeName==="instance_page_state"&&s.instanceId===t.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 x2.validate(r),r}catch{return null}}function P2(e,n){let t={};if("store"in n){const o=e.schema.migrateStoreSnapshot(n);if(o.type!=="success")throw new Error("Failed to migrate store snapshot: "+o.reason);t.document={schema:e.schema.serialize(),store:Fc(o.value,(s,{typeName:i})=>e.scopedTypes.document.has(i))}}else t=n;const r=hM(e.get(gn));e.atomic(()=>{t.document&&e.loadStoreSnapshot(t.document),r&&e.update(gn,o=>({...o,...r})),t.session&&b2(e,t.session)})}const TW=new Zo;function MW(e){const t=TW.get(e,w2).get();if(!t)throw new Error("Session state is not ready yet");return{document:e.getStoreSnapshot(),session:t}}function C2(e){const n=[],t=new Set;for(const r of e){if(t.has(r.type))throw new Error(`Binding type "${r.type}" is defined more than once`);n.push(r),t.add(r.type)}return n}function Ys({children:e,className:n="",...t}){return u.jsx("svg",{...t,className:ce("tl-svg-container",n),children:e})}function Ww(e,n,t,r){const o=e.x-t.x,s=e.y-t.y,i=r.x-t.x,a=r.y-t.y,l=n.x-e.x,c=n.y-e.y,d=i*s-a*o,h=l*s-c*o,p=a*l-i*c;if(d===0||h===0||p===0)return null;if(p!==0){const f=d/p,S=h/p;if(0<=f&&f<=1&&0<=S&&S<=1)return w.AddXY(e,f*l,f*c)}return null}function Hu(e,n,t,r){const o=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),s=2*((n.x-e.x)*(e.x-t.x)+(n.y-e.y)*(e.y-t.y)),i=t.x*t.x+t.y*t.y+e.x*e.x+e.y*e.y-2*(t.x*e.x+t.y*e.y)-r*r,a=s*s-4*o*i;if(a<0||a===0)return null;const l=Math.sqrt(a),c=(-s+l)/(2*o),d=(-s-l)/(2*o);if((c<0||c>1)&&(d<0||d>1))return null;const h=[];return 0<=c&&c<=1&&h.push(w.Lrp(e,n,c)),0<=d&&d<=1&&h.push(w.Lrp(e,n,d)),h.length===0?null:h}function jW(e,n,t){const r=[];let o;for(let s=0,i=t.length-1;s(n.y-e.y)*(t.x-e.x)}function Vw(e,n,t,r){return Bd(e,t,r)!==Bd(n,t,r)&&Bd(e,n,t)!==Bd(e,n,r)}function _C(e,n){const t=new Map;let r,o,s,i;for(let a=0,l=e.length;aw.Angle(n,t)-w.Angle(n,r))}function I2(e,n){let t,r,o,s;for(let i=0,a=e.length;iMath.max(r.x,o.x))return r.x>o.x?r:o;const c=r.y+s.y*a;return cMath.max(r.y,o.y)?r.y>o.y?r:o:new w(l,c)}hitTestLineSegment(t,r,o=0){return Vw(t,r,this.start,this.end)||this.distanceToLineSegment(t,r)<=o}getSvgPathData(t=!0){const{start:r,end:o}=this;return`${t?`M${r.toFixed()}`:""} L${o.toFixed()}`}}class Ll extends ai{constructor(t){super({isClosed:!1,isFilled:!1,...t});m(this,"points");m(this,"_segments");const{points:r}=t;this.points=r}get segments(){if(!this._segments){this._segments=[];const{vertices:t}=this;for(let r=0,o=t.length-1;rt+r.length,0)}getVertices(){return this.points}nearestPoint(t){const{segments:r}=this;let o=this.points[0],s=1/0,i,a;for(let l=0;ls===0?`M ${o.x} ${o.y}`:`${r} L ${o.x} ${o.y}`,"")}}class vt extends Ll{constructor(n){super({...n}),this.isClosed=!0}}class Jo extends vt{constructor(t){const{x:r=0,y:o=0,width:s,height:i}=t;super({...t,points:[new w(r,o),new w(r+s,o),new w(r+s,o+i),new w(r,o+i)]});m(this,"x");m(this,"y");m(this,"w");m(this,"h");this.x=r,this.y=o,this.w=s,this.h=i}getBounds(){return new Z(this.x,this.y,this.w,this.h)}getSvgPathData(){const{x:t,y:r,w:o,h:s}=this;return`M${t},${r} h${o} v${s} h-${o}z`}}class Br{constructor(n){m(this,"canSnap",()=>!0);m(this,"canScroll",()=>!1);m(this,"canEdit",()=>!1);m(this,"canResize",()=>!0);m(this,"canEditInReadOnly",()=>!1);m(this,"canCrop",()=>!1);m(this,"canBeLaidOut",()=>!0);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=n}canBind(n){return!0}providesBackgroundForChildren(n){return!1}canReceiveNewChildrenOfType(n,t){return!1}canDropShapes(n,t){return!1}expandSelectionOutlinePx(n){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(n){return{}}getHandleSnapGeometry(n){return{}}}m(Br,"props"),m(Br,"migrations"),m(Br,"type");function RW(e,n,t={}){const{closed:r=!1,snap:o=1,start:s="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,d=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(s==="outset"?(e+=c/2,f+=c/2):s==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),d=Math.floor(e/c/(2*h)),d-=d%o,d<3&&l==="dashed"?e/n<5?(c=e,d=1,p=0):(c=e*.333,p=e*.333):(d=Math.max(d,3),c=e/d/(2*h),r?(f=c/2,p=(e-d*c)/d):p=(e-d*c)/Math.max(1,d-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}function TC({bounds:e,className:n}){const t=B(),r=G("zoom level",()=>t.getZoomLevel(),[t]);return u.jsx("g",{className:n,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:e.sides.map((o,s)=>{const{strokeDasharray:i,strokeDashoffset:a}=RW(o[0].dist(o[1]),1/r,{style:"dashed",lengthRatio:4});return u.jsx("line",{x1:o[0].x,y1:o[0].y,x2:o[1].x,y2:o[1].y,strokeDasharray:i,strokeDashoffset:a},s)})})}class Ah extends Br{constructor(){super(...arguments);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"canBind",()=>!1);m(this,"onChildrenChange",t=>{const r=this.editor.getSortedChildIdsForParent(t.id);if(r.length===0){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([t.id]);return}else if(r.length===1){this.editor.getCurrentPageState().focusedGroupId===t.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(r,t.parentId),this.editor.deleteShapes([t.id]);return}})}getDefaultProps(){return{}}getGeometry(t){const r=this.editor.getSortedChildIdsForParent(t.id);return r.length===0?new Jo({width:1,height:1,isFilled:!1}):new Hr({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 vt({points:a,isFilled:!0}):new Ll({points:a})})})}component(t){const r=this.editor.getErasingShapeIds().includes(t.id),{hintingShapeIds:o}=this.editor.getCurrentPageState(),s=o.length>0&&o.some(l=>l!==t.id&&this.editor.isShapeOfType(this.editor.getShape(l),"group")),i=this.editor.getCurrentPageState().focusedGroupId!==t.id;if(!r&&(i||s))return null;const a=this.editor.getShapeGeometry(t).bounds;return u.jsx(Ys,{id:t.id,children:u.jsx(TC,{className:"tl-group",bounds:a})})}indicator(t){const r=this.editor.getShapeGeometry(t).bounds;return u.jsx(TC,{className:"",bounds:r})}}m(Ah,"type","group"),m(Ah,"props",CM),m(Ah,"migrations",IM);const E2=[Ah],LW=new Set(E2.map(e=>e.type));function k2(e){const n=[...E2],t=new Set;for(const r of e){if(LW.has(r.type))throw new Error(`Shape type "${r.type}" is a core shapes type and cannot be overridden`);if(t.has(r.type))throw new Error(`Shape type "${r.type}" is defined more than once`);n.push(r),t.add(r.type)}return n}const $W={maxShapesPerPage:4e3,maxPages:40,animationMediumMs:320,followChaseViewportSnap:2,doubleClickDurationMs:450,multiClickDurationMs:200,coarseDragDistanceSquared:36,dragDistanceSquared:16,defaultSvgPadding:32,cameraSlideFriction:.09,maxPointsPerDrawShape:500,gridSteps:[{min:-1,mid:.15,step:64},{min:.05,mid:.375,step:16},{min:.15,mid:1,step:4},{min:.7,mid:2.5,step:1}],collaboratorInactiveTimeoutMs:6e4,collaboratorIdleTimeoutMs:3e3,collaboratorCheckIntervalMs:1200,cameraMovingTimeoutMs:64,hitTestMargin:8,edgeScrollDelay:200,edgeScrollEaseDuration:200,edgeScrollSpeed:25,edgeScrollDistance:8,coarsePointerWidth:12,coarseHandleRadius:20,handleRadius:12,longPressDurationMs:500,textShadowLod:.35,adjacentShapeMargin:10,flattenImageBoundsExpand:64,flattenImageBoundsPadding:16};function MC(e,n){if(!n)return!1;switch(e.type){case"mixed":return n.type==="mixed";case"shared":return n.type==="shared"&&e.value===n.value;default:throw an(e)}}class FW{constructor(n){m(this,"map");this.map=new Map(n)}get(n){return this.map.get(n)}getAsKnownValue(n){const t=this.get(n);if(t&&t.type!=="mixed")return t.value}get size(){return this.map.size}equals(n){if(this.size!==n.size)return!1;const t=new Set;for(const[r,o]of this){if(!MC(o,n.get(r)))return!1;t.add(r)}for(const[r,o]of n)if(!t.has(r)&&!MC(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 vv extends FW{set(n,t){this.map.set(n,t)}applyValue(n,t){const r=this.get(n);if(!r){this.set(n,{type:"shared",value:t});return}switch(r.type){case"mixed":return;case"shared":r.value!==t&&this.set(n,{type:"mixed"});return;default:an(r,"type")}}}function NW(e,n,t){return yo(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],n,{type:t})})}function zW(e,n){var o;let t=e;const r=new Set(n);for(;r.has(t);)t=(o=/^.*(\d+)$/.exec(t))!=null&&o[1]?t.replace(/(\d+)(?=\D?)$/,s=>(+s+1).toString()):`${t} 1`;return t}function Ud(e,n,t){if(t.length===0)return[];const r=new Map;for(const s of me(t.map(i=>e.getShape(i)))){const{parentId:i}=s;r.has(i)||r.set(i,{children:me(e.getSortedChildIdsForParent(i).map(a=>e.getShape(a))),moving:new Set}),r.get(i).moving.add(s)}const o=[];switch(n){case"toBack":{r.forEach(({moving:s,children:i})=>BW(s,i,o));break}case"toFront":{r.forEach(({moving:s,children:i})=>UW(s,i,o));break}case"forward":{r.forEach(({moving:s,children:i})=>HW(s,i,o));break}case"backward":{r.forEach(({moving:s,children:i})=>KW(s,i,o));break}}return o}function BW(e,n,t){const r=n.length;if(e.size===r)return;let o,s;for(let i=0;i({...a,index:i[l]})))}}function UW(e,n,t){const r=n.length;if(e.size===r)return;let o,s;for(let i=r-1;i>-1;i--){const a=n[i];if(e.has(a))s=a.index,e.delete(a);else{o=a.index;break}}if(e.size!==0){const i=gl(o,s,e.size);t.push(...Array.from(e.values()).sort(on).map((a,l)=>({...a,index:i[l]})))}}function HW(e,n,t){var s;const r=n.length;if(e.size===r)return;let o={name:"skipping"};for(let i=0;it.push({...n[l+d],index:c})),o={name:"skipping"};break}}}}function KW(e,n,t){var s;const r=n.length;if(e.size===r)return;let o={name:"skipping"};for(let i=r-1;i>-1;i--){const a=e.has(n[i]);switch(o.name){case"skipping":{if(!a)continue;o={name:"selecting",selectIndex:i};break}case"selecting":{if(a)continue;gl((s=n[i-1])==null?void 0:s.index,n[i].index,o.selectIndex-i).forEach((l,c)=>{t.push({...n[i+c+1],index:l})}),o={name:"skipping"};break}}}}function _2({editor:e}){const n=e.getSelectedShapes(),t=e.getSelectionRotation(),r=e.getSelectionRotatedPageBounds(),{inputs:{originPagePoint:o}}=e;if(!r)return null;const s=r.center.clone().rotWith(r.point,t);return{selectionPageCenter:s,initialCursorAngle:s.angle(o),initialSelectionRotation:t,shapeSnapshots:n.map(i=>({shape:rt(i),initialPagePoint:e.getShapePageTransform(i.id).point()}))}}function Oh({delta:e,editor:n,snapshot:t,stage:r}){const{selectionPageCenter:o,shapeSnapshots:s}=t;n.updateShapes(s.map(({shape:a,initialPagePoint:l})=>{const c=kn(a.parentId)?n.getShapePageTransform(a.parentId):oe.Identity(),d=w.RotWith(l,o,e),h=oe.applyToPoint(oe.Inverse(c),d),p=Hs(a.rotation+e);return{id:a.id,type:a.type,x:h.x,y:h.y,rotation:p}}));const i=[];s.forEach(({shape:a})=>{var h,p,f;const l=n.getShape(a.id);if(!l)return;const c=n.getShapeUtil(a);if(r==="start"||r==="one-off"){const S=(h=c.onRotateStart)==null?void 0:h.call(c,a);S&&i.push(S)}const d=(p=c.onRotate)==null?void 0:p.call(c,a,l);if(d&&i.push(d),r==="end"||r==="one-off"){const S=(f=c.onRotateEnd)==null?void 0:f.call(c,a,l);S&&i.push(S)}}),i.length>0&&n.updateShapes(i)}const WW=e=>{const{store:n}=e,t=n.query.filterHistory("binding"),r=n.query.records("binding");function o(){const s=r.get(),i=new Map;for(const a of s){const{fromId:l,toId:c}=a,d=i.get(l);d?d.push(a):i.set(l,[a]);const h=i.get(c);h?h.push(a):i.set(c,[a])}return i}return V("arrowBindingsIndex",(s,i)=>{if(Di(s))return o();const a=s,l=t.getDiffSince(i);if(l===Jn)return o();let c;function d(f){c??(c=new Map(a));const S=c.get(f.fromId),g=S==null?void 0:S.filter(v=>v.id!==f.id);g!=null&&g.length?c.set(f.fromId,g):c.delete(f.fromId);const x=c.get(f.toId),y=x==null?void 0:x.filter(v=>v.id!==f.id);y!=null&&y.length?c.set(f.toId,y):c.delete(f.toId)}function h(f){c??(c=new Map(a));let S=c.get(f);return S?S===a.get(f)&&(S=S.slice(0),c.set(f,S)):(S=[],c.set(f,S)),S}function p(f){h(f.fromId).push(f),h(f.toId).push(f)}for(const f of l){for(const S of gt(f.added))p(S);for(const[S,g]of gt(f.updated))d(S),p(g);for(const S of gt(f.removed))d(S)}return c??a})};function GW(e,n,t){const r=e.getShapeMaskedPageBounds(n);return r===void 0?!0:!t.includes(r)}const VW=e=>{function n(t){const r=t.getCurrentPageShapeIds(),o=t.getViewportPageBounds(),s=new Set;return r.forEach(i=>{GW(t,i,o)&&s.add(i)}),s}return V("getCulledShapes",t=>{if(Di(t))return n(e);const r=n(e);if(t.size!==r.size)return r;for(const o of t)if(!r.has(o))return r;return t})},YW=e=>{const n=e.query.ids("shape"),t=e.query.filterHistory("shape");function r(){const o={},s=n.get(),i=Array(s.size);return s.forEach(a=>i.push(e.get(a))),i.sort(on),i.forEach(a=>{o[a.parentId]||(o[a.parentId]=[]),o[a.parentId].push(a.id)}),o}return V("parentsToChildrenWithIndexes",(o,s)=>{if(Di(o))return r();const i=t.getDiffSince(s);if(i===Jn)return r();if(i.length===0)return o;let a=null;const l=h=>{a||(a={...o}),a[h]?a[h]===o[h]&&(a[h]=[...a[h]]):a[h]=[]},c=new Set;let d;for(let h=0,p=i.length;he.get(f)));p.sort(on),h.splice(0,h.length,...p.map(f=>f.id))}return a??o})},Jm=(e,n,t)=>{for(;!In(t.parentId);){const r=e.get(t.parentId);if(!r)return!1;t=r}return t.parentId===n},XW=(e,n)=>{const t=e.query.ids("shape");let r=null;function o(){const s=n();return r=s,new Set([...t.get()].filter(i=>Jm(e,s,e.get(i))))}return V("_shapeIdsInCurrentPage",(s,i)=>{if(Di(s))return o();const a=n();if(a!==r)return o();const l=e.history.getDiffSince(i);if(l===Jn)return o();const c=new kh(s);for(const h of l){for(const p of Object.values(h.added))Ua(p)&&Jm(e,a,p)&&c.add(p.id);for(const[p,f]of Object.values(h.updated))Ua(f)&&(Jm(e,a,f)?c.add(f.id):c.remove(f.id));for(const p of Object.keys(h.removed))kn(p)&&c.remove(p)}const d=c.get();return d?Cc(d.value,d.diff):s})},T2=P.createContext(null);function qW({context:e,editor:n,children:t}){return u.jsx(og.Provider,{value:n,children:u.jsx(T2.Provider,{value:e,children:t})})}function M2(){const e=P.useContext(T2);return e?{isDarkMode:e.isDarkMode}:null}async function ZW(e,n,t={}){var I,C;const r=typeof n[0]=="string"?n:n.map(k=>k.id);if(r.length===0)return;if(!window.document)throw Error("No document");const{scale:o=1,background:s=!1,padding:i=e.options.defaultSvgPadding,preserveAspectRatio:a=!1}=t,l=t.darkMode??e.user.getIsDarkMode(),c=ss({isDarkMode:l}),d=e.getShapeAndDescendantIds(r),h=e.getUnorderedRenderingShapes(!1).filter(({id:k})=>d.has(k));let p=null;if(t.bounds)p=t.bounds;else for(const{id:k}of h){const T=e.getShapeMaskedPageBounds(k);T&&(p?p.union(T):p=T.clone())}if(!p)return;const f=r.length===1&&e.isShapeOfType(e.getShape(r[0]),"frame")?r[0]:null;f||p.expandBy(i);const S=p.width*o,g=p.height*o;try{(C=(I=document.body).focus)==null||C.call(I)}catch{}const x=[],y=new Map,v={isDarkMode:l,addExportDef:k=>{if(y.has(k.key))return;const T=(async()=>{const O=await k.getElement();O&&x.push(u.jsx(P.Fragment,{children:O},x.length))})();y.set(k.key,T)}},b=(await Promise.all(h.map(async({id:k,opacity:T,index:O,backgroundIndex:_})=>{var z,U;if(k===f)return[];const j=e.getShape(k);if(e.isShapeOfType(j,"group"))return[];const L=e.getShapeUtil(j);let A=await((z=L.toSvg)==null?void 0:z.call(L,j,v)),R=await((U=L.toBackgroundSvg)==null?void 0:U.call(L,j,v));if(!A&&!R){const X=e.getShapePageBounds(j);A=u.jsx("rect",{width:X.w,height:X.h,fill:c.solid,stroke:c.grey.pattern,strokeWidth:1})}let F=e.getShapePageTransform(j).toCssString();"scale"in j.props&&j.props.scale!==1&&(F=`${F} scale(${j.props.scale}, ${j.props.scale})`),A&&(A=u.jsx("g",{transform:F,opacity:T,children:A},j.id)),R&&(R=u.jsx("g",{transform:F,opacity:T,children:R},`bg_${j.id}`));const W=e.getShapeMask(j.id);if(W){const X=`mask_${j.id.replace(":","_")}`;x.push(u.jsx("clipPath",{id:X,children:u.jsx("path",{d:`M${W.map(({x:J,y:le})=>`${J},${le}`).join("L")}Z`})},x.length)),A&&(A=u.jsx("g",{clipPath:`url(#${X})`,children:A},j.id)),R&&(R=u.jsx("g",{clipPath:`url(#${X})`,children:R},`bg_${j.id}`))}const K=[];return A&&K.push({zIndex:O,element:A}),R&&K.push({zIndex:_,element:R}),K}))).flat();return await Promise.all(y.values()),{jsx:u.jsx(qW,{editor:e,context:v,children:u.jsxs("svg",{preserveAspectRatio:a||void 0,direction:"ltr",width:S,height:g,viewBox:`${p.minX} ${p.minY} ${p.width} ${p.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:s?f?c.solid:c.background:"transparent"},children:[u.jsx("defs",{children:x}),b.sort((k,T)=>k.zIndex-T.zIndex).map(({element:k})=>k)]})}),width:S,height:g}}const QW=40;class JW{constructor(n){m(this,"_clickId","");m(this,"_clickTimeout");m(this,"_clickScreenPoint");m(this,"_previousScreenPoint");m(this,"_getClickTimeout",(n,t=ot())=>{this._clickId=t,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===n&&this._clickId===t){switch(this._clickState){case"pendingTriple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"double_click",phase:"settle"});break}case"pendingQuadruple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"triple_click",phase:"settle"});break}case"pendingOverflow":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"settle"});break}}this._clickState="idle"}},n==="idle"||n==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)});m(this,"_clickState","idle");m(this,"lastPointerInfo",{});m(this,"handlePointerEvent",n=>{switch(n.name){case"pointer_down":{if(!this._clickState)return n;switch(this._clickScreenPoint=w.From(n.point),this._previousScreenPoint&&w.Dist2(this._previousScreenPoint,this._clickScreenPoint)>QW**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=n,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...n,type:"click",name:"quadruple_click",phase:"down"};case"idle":{this._clickState="pendingDouble";break}case"pendingOverflow":{this._clickState="overflow";break}}return this._clickTimeout=this._getClickTimeout(this._clickState),n}case"pointer_up":{if(!this._clickState)return n;switch(this._clickScreenPoint=w.From(n.point),this._clickState){case"pendingTriple":return{...this.lastPointerInfo,type:"click",name:"double_click",phase:"up"};case"pendingQuadruple":return{...this.lastPointerInfo,type:"click",name:"triple_click",phase:"up"};case"pendingOverflow":return{...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"up"}}return n}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&w.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),n}return n});m(this,"cancelDoubleClickTimeout",()=>{this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"});this.editor=n}get clickState(){return this._clickState}}class eG{constructor(n){m(this,"_isEdgeScrolling",!1);m(this,"_edgeScrollDuration",-1);this.editor=n}updateEdgeScrolling(n){const{editor:t}=this,r=this.getEdgeScroll();if(r.x===0&&r.y===0)this._isEdgeScrolling&&(this._isEdgeScrolling=!1,this._edgeScrollDuration=0);else if(this._isEdgeScrolling||(this._isEdgeScrolling=!0,this._edgeScrollDuration=0),this._edgeScrollDuration+=n,this._edgeScrollDuration>t.options.edgeScrollDelay){const o=t.options.edgeScrollEaseDuration>0?jt.easeInCubic(Math.min(1,this._edgeScrollDuration/(t.options.edgeScrollDelay+t.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*o,y:r.y*o})}}getEdgeProximityFactors(n,t,r,o,s){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=n-l,d=n+l,h=o?0:a,p=s?t:t-a;return cp?-Math.min(1,(d-p)/a):0}getEdgeScroll(){const{editor:n}=this,{inputs:{currentScreenPoint:{x:t,y:r}}}=n,o=n.getViewportScreenBounds(),{isCoarsePointer:s,insets:[i,a,l,c]}=n.getInstanceState(),d=this.getEdgeProximityFactors(t,o.w,s,c,a),h=this.getEdgeProximityFactors(r,o.h,s,i,l);return{x:d,y:h}}moveCameraWhenCloseToEdge(n){const{editor:t}=this;if(!t.inputs.isDragging||t.inputs.isPanning||t.getCameraOptions().isLocked||n.x===0&&n.y===0)return;const r=t.getViewportScreenBounds(),o=r.w<1e3?.612:1,s=r.h<1e3?.612:1,i=t.getZoomLevel(),a=t.user.getEdgeScrollSpeed()*t.options.edgeScrollSpeed,l=a*n.x*o/i,c=a*n.y*s/i,{x:d,y:h,z:p}=t.getCamera();t.setCamera(new w(d+l,h+c,p))}}class tG{constructor(n){m(this,"isSafari");m(this,"isIos");m(this,"isChromeForIos");m(this,"isFirefox");m(this,"isAndroid");this.editor=n,typeof window<"u"&&"navigator"in window?(this.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),this.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),this.isFirefox=/firefox/i.test(navigator.userAgent),this.isAndroid=/android/i.test(navigator.userAgent)):(this.isSafari=!1,this.isIos=!1,this.isChromeForIos=!1,this.isFirefox=!1,this.isAndroid=!1)}}class nG{constructor(n,t){m(this,"disposeSideEffectListener");this.editor=n,this.disposeSideEffectListener=n.sideEffects.registerAfterChangeHandler("instance",(o,s)=>{o.isFocused!==s.isFocused&&(s.isFocused?this.focus():this.blur(),this.updateContainerClass())});const r=n.getInstanceState().isFocused;t!==r&&n.updateInstanceState({isFocused:!!t}),this.updateContainerClass()}updateContainerClass(){const n=this.editor.getContainer();this.editor.getInstanceState().isFocused?n.classList.add("tl-container__focused"):n.classList.remove("tl-container__focused")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var n;(n=this.disposeSideEffectListener)==null||n.call(this)}}function lc(e){return oG}class rG{constructor(){m(this,"length",0);m(this,"head",null);m(this,"tail",this)}push(n){return new Yw(n,this)}toArray(){return Ho}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const oG=new rG;class Yw{constructor(n,t){m(this,"length");this.head=n,this.tail=t,this.length=t.length+1}push(n){return new Yw(n,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let n=this;return{next(){if(n.length){const t=n.head;return n=n.tail,{value:t,done:!1}}else return{value:void 0,done:!0}}}}}class sG{constructor(n){m(this,"store");m(this,"dispose");m(this,"state","recording");m(this,"pendingDiff",new aG);m(this,"stacks",Mt("HistoryManager.stacks",{undos:lc(),redos:lc()},{isEqual:(n,t)=>n.undos===t.undos&&n.redos===t.redos}));m(this,"annotateError");m(this,"onBatchComplete",()=>{});m(this,"_isInBatch",!1);m(this,"batch",(n,t)=>{const r=this.state;r!=="paused"&&(t!=null&&t.history)&&(this.state=iG[t.history]);try{if(this._isInBatch)return n(),this;this._isInBatch=!0;try{zs(()=>{n(),this.onBatchComplete()})}catch(o){throw this.annotateError(o),o}finally{this._isInBatch=!1}return this}finally{this.state=r}});m(this,"_undo",({pushToRedoStack:n,toMark:t=void 0})=>{var o;const r=this.state;this.state="paused";try{let{undos:s,redos:i}=this.stacks.get();const a=this.pendingDiff.clear(),l=zT(a),c=lv(a);n&&!l&&(i=i.push({type:"diff",diff:a}));let d=!1;if(l)for(;((o=s.head)==null?void 0:o.type)==="stop";){const h=s.head;if(s=s.tail,n&&(i=i.push(h)),h.id===t){d=!0;break}}if(!d)e:for(;s.head;){const h=s.head;switch(s=s.tail,n&&(i=i.push(h)),h.type){case"diff":Nc(c,[lv(h.diff)]);break;case"stop":if(!t||h.id===t)break e;break;default:an(h)}}this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:s,redos:i})}finally{this.state=r}return this});m(this,"undo",()=>(this._undo({pushToRedoStack:!0}),this));m(this,"redo",()=>{var t;const n=this.state;this.state="paused";try{this.flushPendingDiff();let{undos:r,redos:o}=this.stacks.get();if(o.length===0)return this;for(;((t=o.head)==null?void 0:t.type)==="stop";)r=r.push(o.head),o=o.tail;const s=Gp();for(;o.head;){const i=o.head;if(r=r.push(i),o=o.tail,i.type==="diff")Nc(s,[i.diff]);else break}this.store.applyDiff(s,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:o})}finally{this.state=n}return this});m(this,"bail",()=>(this._undo({pushToRedoStack:!1}),this));m(this,"bailToMark",n=>(this._undo({pushToRedoStack:!1,toMark:n}),this));m(this,"squashToMark",n=>{var s;let t=this.stacks.get().undos;const r=[];for(;t.head&&!(t.head.type==="stop"&&t.head.id===n);)t.head.type==="diff"&&r.push(t.head.diff),t=t.tail;if(!t.head||((s=t.head)==null?void 0:s.id)!==n)return console.error("Could not find mark to squash to: ",n),this;if(r.length===0)return this;const o=Gp();return Nc(o,r.reverse()),this.stacks.update(({redos:i})=>({undos:t.push({type:"diff",diff:o}),redos:i})),this});m(this,"mark",(n=ot())=>(zs(()=>{this.flushPendingDiff(),this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"stop",id:n}),redos:r}))}),n));this.store=n.store,this.annotateError=n.annotateError??Wp,this.dispose=this.store.addHistoryInterceptor((t,r)=>{if(r==="user")switch(this.state){case"recording":this.pendingDiff.apply(t.changes),this.stacks.update(({undos:o})=>({undos:o,redos:lc()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(t.changes);break;case"paused":break;default:an(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const n=this.pendingDiff.clear();this.stacks.update(({undos:t,redos:r})=>({undos:t.push({type:"diff",diff:n}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}ignore(n){return this.batch(n,{history:"ignore"})}clear(){this.stacks.set({undos:lc(),redos:lc()}),this.pendingDiff.clear()}debug(){const{undos:n,redos:t}=this.stacks.get();return{undos:n.toArray(),redos:t.toArray(),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const iG={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class aG{constructor(){m(this,"diff",Gp());m(this,"isEmptyAtom",Mt("PendingDiff.isEmpty",!0))}clear(){const n=this.diff;return this.diff=Gp(),this.isEmptyAtom.set(!0),n}isEmpty(){return this.isEmptyAtom.get()}apply(n){Nc(this.diff,[n]),this.isEmptyAtom.set(zT(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}class lG{constructor(n){m(this,"scribbleItems",new Map);m(this,"state","paused");m(this,"addScribble",(n,t=ot())=>{const r={id:t,scribble:{id:t,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...n,state:"starting"},timeoutMs:0,delayRemaining:n.delay??0,prev:null,next:null};return this.scribbleItems.set(t,r),r});m(this,"stop",n=>{const t=this.scribbleItems.get(n);if(!t)throw Error(`Scribble with id ${n} not found`);return t.delayRemaining=Math.min(t.delayRemaining,200),t.scribble.state="stopping",t});m(this,"addPoint",(n,t,r)=>{const o=this.scribbleItems.get(n);if(!o)throw Error(`Scribble with id ${n} not found`);const{prev:s}=o,i={x:t,y:r,z:.5};return(!s||w.Dist(s,i)>=1)&&(o.next=i),o});m(this,"tick",n=>{this.scribbleItems.size!==0&&this.editor.batch(()=>{this.scribbleItems.forEach(t=>{if(t.scribble.state==="starting"){const{next:l,prev:c}=t;l&&l!==c&&(t.prev=l,t.scribble.points.push(l)),t.scribble.points.length>8&&(t.scribble.state="active");return}t.delayRemaining>0&&(t.delayRemaining=Math.max(0,t.delayRemaining-n)),t.timeoutMs+=n,t.timeoutMs>=16&&(t.timeoutMs=0);const{delayRemaining:r,timeoutMs:o,prev:s,next:i,scribble:a}=t;switch(a.state){case"active":{i&&i!==s?(t.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):o===0&&(a.points.length>1?a.points.shift():t.delayRemaining=a.delay);break}case"stopping":{if(t.delayRemaining===0&&o===0){if(a.points.length===1){this.scribbleItems.delete(t.id);return}a.shrink&&(a.size=Math.max(1,a.size*(1-a.shrink))),a.points.shift()}break}}}),this.editor.updateInstanceState({scribbles:Array.from(this.scribbleItems.values()).map(({scribble:t})=>({...t,points:[...t.points]})).slice(-5)})})});this.editor=n}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}}var cG=Object.defineProperty,uG=Object.getOwnPropertyDescriptor,ig=(e,n,t,r)=>{for(var o=uG(n,t),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(n,t,o)||o);return o&&cG(n,t,o),o};const ue=e=>Math.round(e*10**8)/10**8;function Ao(e,n,t,r,o){const s=e.filter(a=>(r==="forward"?a.startNode.id===n:a.endNode.id===n)&&ue(a.length)===ue(t)&&Or(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));if(s.length===0)return[];const i=new Set;return s.forEach(a=>{const l=r==="forward"?a.endNode.id:a.startNode.id;if(!i.has(l)){i.add(l);const c=Ao(e,l,t,r,Or(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));s.push(...c)}}),s}function dG(e){e.sort((n,t)=>t.gaps.length-n.gaps.length);for(let n=e.length-1;n>0;n--){const t=e[n];for(let r=n-1;r>=0;r--){const o=e[r];if(o.direction===t.direction&&t.gaps.every(s=>o.gaps.some(i=>ue(s.startEdge[0].x)===ue(i.startEdge[0].x)&&ue(s.startEdge[0].y)===ue(i.startEdge[0].y)&&ue(s.startEdge[1].x)===ue(i.startEdge[1].x)&&ue(s.startEdge[1].y)===ue(i.startEdge[1].y))&&o.gaps.some(i=>ue(s.endEdge[0].x)===ue(i.endEdge[0].x)&&ue(s.endEdge[0].y)===ue(i.endEdge[0].y)&&ue(s.endEdge[1].x)===ue(i.endEdge[1].x)&&ue(s.endEdge[1].y)===ue(i.endEdge[1].y)))){e.splice(n,1);break}}}}class Ku{constructor(n){m(this,"editor");this.manager=n,this.editor=n.editor}getSnapPointsCache(){const{editor:n}=this;return n.store.createComputedCache("snapPoints",t=>{const r=n.getShapePageTransform(t.id);if(!r)return;const s=n.getShapeUtil(t).getBoundsSnapGeometry(t).points??n.getShapeGeometry(t).bounds.cornersAndCenter;if(!(!r||!s))return s.map((i,a)=>{const{x:l,y:c}=oe.applyToPoint(r,i);return{x:l,y:c,id:`${t.id}:${a}`}})})}getSnapPoints(n){return this.getSnapPointsCache().get(n)??[]}getSnappablePoints(){const n=this.getSnapPointsCache(),t=this.manager.getSnappableShapes(),r=[];for(const o of t){const s=n.get(o);s&&r.push(...s)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),n=>({id:n,pageBounds:Sr(this.editor.getShapePageBounds(n))}))}getVisibleGaps(){const n=[],t=[];let r,o;const s=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;aa.pageBounds.minY-l.pageBounds.minY);for(let a=0;a({id:"selection:"+E,x:v+o.x,y:b+o.y})),c=i,d=[],h=[],p=new w(s,s);this.collectPointSnaps({minOffset:p,nearestSnapsX:d,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:d,nearestSnapsY:h,minOffset:p});const f=new w(n==="x"?0:((x=d[0])==null?void 0:x.nudge)??0,n==="y"?0:((y=h[0])==null?void 0:y.nudge)??0);p.x=0,p.y=0,d.length=0,h.length=0,l.forEach(v=>{v.x+=f.x,v.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:d,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:d,nearestSnapsY:h,minOffset:p});const S=this.getPointSnapLines({nearestSnapsX:d,nearestSnapsY:h}),g=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:d,nearestSnapsY:h});return this.manager.setIndicators([...g,...S]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:n,dragDelta:t,handle:r,isAspectRatioLocked:o,isResizingFromCenter:s}){var k,T;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=Z.Resize(n,r,s?t.x*2:t.x,s?t.y*2:t.y,o);let d=r;l<0&&(d=SK(d)),c<0&&(d=yK(d)),s&&(a.center=n.center);const h=d==="top"||d==="bottom",p=d==="left"||d==="right",f=jC(d,a),S=this.getSnappablePoints(),g=[],x=[],y=new w(i,i);this.collectPointSnaps({minOffset:y,nearestSnapsX:g,nearestSnapsY:x,otherNodeSnapPoints:S,selectionSnapPoints:f});const v=new w(h?0:((k=g[0])==null?void 0:k.nudge)??0,p?0:((T=x[0])==null?void 0:T.nudge)??0);if(o&&vK(d)&&v.len()!==0){const O=g.length&&x.length?Math.abs(v.x)n.width&&ue(Math.abs(c))<=ue(t.x)){ue(Math.abs(c))E==="gap_center"),b=v&&Or(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)]=y:(!v||!b)&&r.push(y)}const h=a.startNode.pageBounds.minX-a.length,p=n.maxX,f=h-p;ue(Math.abs(f))<=ue(t.x)&&(ue(Math.abs(f))n.height&&ue(Math.abs(c))<=ue(t.y)){ue(Math.abs(c))E==="gap_center"),b=v&&ac(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)]=y:(!v||!b)&&o.push(y);continue}const h=a.startNode.pageBounds.minY-a.length,p=n.maxY,f=h-p;ue(Math.abs(f))<=ue(t.y)&&(ue(Math.abs(f))0){for(const s of n)if(s.type==="points"){const i=ue(s.points.otherPoint.x);r[i]||(r[i]=[]),r[i].push(s.points)}}if(t.length>0){for(const s of t)if(s.type==="points"){const i=ue(s.points.otherPoint.y);o[i]||(o[i]=[]),o[i].push(s.points)}}return Object.values(r).concat(Object.values(o)).map(s=>({id:ot(),type:"points",points:vw(s.map(i=>w.From(i.otherPoint)).concat(s.map(i=>w.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:n,nearestSnapsX:t,nearestSnapsY:r}){const{vertical:o,horizontal:s}=this.getVisibleGaps(),i={top:n.sides[0],right:n.sides[1],bottom:[n.corners[3],n.corners[2]],left:[n.corners[0],n.corners[3]]},a=[];if(t.length>0)for(const l of t){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:d,startNode:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const g=(f-n.width)/2,x=Or(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ot(),gaps:[...Ao(s,h.id,g,"backward",x),{startEdge:d,endEdge:i.left},{startEdge:i.right,endEdge:S},...Ao(s,p.id,g,"forward",x)]});break}case"gap_duplicate":{const g=Or(c[0],c[1],n.minY,n.maxY);a.push({type:"gaps",direction:"horizontal",id:ot(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:d.map(x=>x.clone().addXY(-h.pageBounds.width,0))},{startEdge:d,endEdge:S},...Ao(s,p.id,f,"forward",g)]:[...Ao(s,h.id,f,"backward",g),{startEdge:d,endEdge:S},{startEdge:S.map(x=>x.clone().addXY(l.gap.endNode.pageBounds.width,0)),endEdge:i.left}]});break}}}if(r.length>0)for(const l of r){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:d,startNode:h,endNode:p,length:f,endEdge:S}}=l;switch(l.type){case"gap_center":{const g=(f-n.height)/2,x=Or(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ot(),gaps:[...Ao(o,h.id,g,"backward",x),{startEdge:d,endEdge:i.top},{startEdge:i.bottom,endEdge:S},...Ao(o,l.gap.endNode.id,g,"forward",x)]});break}case"gap_duplicate":{const g=Or(c[0],c[1],n.minX,n.maxX);a.push({type:"gaps",direction:"vertical",id:ot(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:d.map(x=>x.clone().addXY(0,-h.pageBounds.height))},{startEdge:d,endEdge:S},...Ao(o,p.id,f,"forward",g)]:[...Ao(o,h.id,f,"backward",g),{startEdge:d,endEdge:S},{startEdge:S.map(x=>x.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return dG(a),a}}ig([V],Ku.prototype,"getSnapPointsCache");ig([V],Ku.prototype,"getSnappablePoints");ig([V],Ku.prototype,"getSnappableGapNodes");ig([V],Ku.prototype,"getVisibleGaps");function jC(e,n){const{minX:t,maxX:r,minY:o,maxY:s}=n,i=[];switch(e){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:t,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:t,y:s})}return i}var hG=Object.defineProperty,pG=Object.getOwnPropertyDescriptor,fG=(e,n,t,r)=>{for(var o=pG(n,t),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(n,t,o)||o);return o&&hG(n,t,o),o};const gG=()=>null,mG=()=>[];class j2{constructor(n){m(this,"editor");this.manager=n,this.editor=n.editor}getSnapGeometryCache(){const{editor:n}=this;return n.store.createComputedCache("handle snap geometry",t=>{const r=n.getShapeUtil(t).getHandleSnapGeometry(t);return{outline:r.outline===void 0?n.getShapeGeometry(t):r.outline,points:r.points??[],getSelfSnapOutline:r.getSelfSnapOutline??gG,getSelfSnapPoints:r.getSelfSnapPoints??mG}})}*iterateSnapPointsInPageSpace(n,t){var o,s;const r=(o=this.getSnapGeometryCache().get(n))==null?void 0:o.getSelfSnapPoints(t);if(r&&r.length){const i=Sr(this.editor.getShapePageTransform(n));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.points;if(!a||!a.length)continue;const l=Sr(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(n,t){var o,s;const r=(o=this.getSnapGeometryCache().get(n))==null?void 0:o.getSelfSnapOutline(t);r&&(yield{shapeId:n,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===n)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:r}){const o=this.manager.getSnapThreshold();let s=o,i=null;for(const c of this.iterateSnapPointsInPageSpace(n,t))w.DistMin(r,c,s)&&(s=w.Dist(r,c),i=c);if(i)return i;let a=o,l=null;for(const{shapeId:c,outline:d}of this.iterateSnapOutlines(n,t)){const h=Sr(this.editor.getShapePageTransform(c)),p=this.editor.getPointInShapeSpace(c,r),f=d.nearestPoint(p),S=h.applyToPoint(f);w.DistMin(r,S,a)&&(a=w.Dist(r,S),l=S)}return l||null}snapHandle({currentShapeId:n,handle:t}){const o=Sr(this.editor.getShapePageTransform(n)).applyToPoint(t),s=this.getHandleSnapPosition({currentShapeId:n,handle:t,handleInPageSpace:o});return s?(this.manager.setIndicators([{id:ot(),type:"points",points:[s]}]),{nudge:w.Sub(s,o)}):null}}fG([V],j2.prototype,"getSnapGeometryCache");var yG=Object.defineProperty,SG=Object.getOwnPropertyDescriptor,Xw=(e,n,t,r)=>{for(var o=SG(n,t),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(n,t,o)||o);return o&&yG(n,t,o),o};class ag{constructor(n){m(this,"shapeBounds");m(this,"handles");m(this,"_snapIndicators",Mt("snapLines",void 0));this.editor=n,this.shapeBounds=new Ku(this),this.handles=new j2(this)}getIndicators(){return this._snapIndicators.get()??Ho}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(n){this._snapIndicators.set(n)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:n}=this,t=n.getViewportPageBounds(),r=n.getSelectedShapeIds(),o=new Set,s=i=>{if(kn(i)){const l=n.getShape(i);l&&n.isShapeOfType(l,"frame")&&o.add(i)}const a=n.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=n.getShape(l);if(!c||!n.getShapeUtil(c).canSnap(c))continue;const h=n.getShapePageBounds(l);if(h&&t.includes(h)){if(n.isShapeOfType(c,"group")){s(l);continue}o.add(l)}}};return s(this.getCurrentCommonAncestor()??n.getCurrentPageId()),o}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}}Xw([V],ag.prototype,"getSnapThreshold");Xw([V],ag.prototype,"getSnappableShapes");Xw([V],ag.prototype,"getCurrentCommonAncestor");const vG=/\r?\n|\r/g;function AC(e){return e.replace(vG,` `).split(` `).map(n=>n||" ").join(` `)}const xG={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},wG=/\s/;class bG{constructor(n){m(this,"baseElm");m(this,"measureText",(n,t)=>{var i;const r=(i=this.baseElm)==null?void 0:i.cloneNode();this.baseElm.insertAdjacentElement("afterend",r),r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("font-family",t.fontFamily),r.style.setProperty("font-style",t.fontStyle),r.style.setProperty("font-weight",t.fontWeight),r.style.setProperty("font-size",t.fontSize+"px"),r.style.setProperty("line-height",t.lineHeight*t.fontSize+"px"),r.style.setProperty("max-width",t.maxWidth===null?null:t.maxWidth+"px"),r.style.setProperty("min-width",t.minWidth===null?null:t.minWidth+"px"),r.style.setProperty("padding",t.padding),r.style.setProperty("overflow-wrap",t.disableOverflowWrapBreaking?"normal":"break-word"),r.textContent=AC(n);const o=r.scrollWidth,s=r.getBoundingClientRect();return r.remove(),{x:0,y:0,w:s.width,h:s.height,scrollWidth:o}});this.editor=n;const t=this.editor.getContainer(),r=document.createElement("div");r.classList.add("tl-text"),r.classList.add("tl-text-measure"),r.tabIndex=-1,t.appendChild(r),this.baseElm=r,n.disposables.add(()=>{r.remove()})}measureElementTextNodeSpans(n,{shouldTruncateToFirstLine:t=!1}={}){const r=[],o=n.getBoundingClientRect(),s=-o.left,i=-o.top,a=new Range,l=n.childNodes[0];let c=0,d=null,h=null,p=0,f=0,S=!1;for(const g of n.childNodes)if(g.nodeType===Node.TEXT_NODE)for(const x of g.textContent??""){a.setStart(l,c),a.setEnd(l,c+x.length);const y=a.getClientRects(),v=y[y.length-1],b=v.top+i,E=v.left+s,I=v.right+s,C=E{var n;this.isPaused=!1,(n=this.cancelRaf)==null||n.call(this),this.cancelRaf=OC(this.tick),this.now=Date.now()});m(this,"tick",()=>{if(this.isPaused)return;const n=Date.now(),t=n-this.now;this.now=n,this.updatePointerVelocity(t),this.editor.emit("frame",t),this.editor.emit("tick",t),this.cancelRaf=OC(this.tick)});m(this,"dispose",()=>{var n;this.isPaused=!0,(n=this.cancelRaf)==null||n.call(this)});m(this,"prevPoint",new w);m(this,"updatePointerVelocity",n=>{const{prevPoint:t,editor:{inputs:{currentScreenPoint:r,pointerVelocity:o}}}=this;if(n===0)return;const s=w.Sub(r,t);this.prevPoint=r.clone();const i=s.len(),a=i?s.div(i):new w(0,0),l=o.clone().lrp(a.mul(i/n),.5);Math.abs(l.x)<.01&&(l.x=0),Math.abs(l.y)<.01&&(l.y=0),o.equals(l)||(this.editor.inputs.pointerVelocity=l)});this.editor=n,this.editor.disposables.add(this.dispose),this.start()}}var CG=Object.defineProperty,IG=Object.getOwnPropertyDescriptor,Vr=(e,n,t,r)=>{for(var o=IG(n,t),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(n,t,o)||o);return o&&CG(n,t,o),o};class kr{constructor(n,t){m(this,"systemColorScheme",Mt("systemColorScheme","light"));m(this,"updateUserPreferences",n=>{this.user.setUserPreferences({...this.user.userPreferences.get(),...n})});var r;if(this.user=n,this.inferDarkMode=t,window){const o=(r=window.matchMedia)==null?void 0:r.call(window,"(prefers-color-scheme: dark)");o!=null&&o.matches&&this.systemColorScheme.set("dark"),o==null||o.addEventListener("change",s=>{s.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")})}}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),isSnapMode:this.getIsSnapMode(),colorScheme:this.user.userPreferences.get().colorScheme,isDarkMode:this.getIsDarkMode(),isWrapMode:this.getIsWrapMode(),isDynamicResizeMode:this.getIsDynamicResizeMode()}}getIsDarkMode(){switch(this.user.userPreferences.get().colorScheme){case"dark":return!0;case"light":return!1;case"system":return this.systemColorScheme.get()==="dark";default:return this.inferDarkMode?this.systemColorScheme.get()==="dark":!1}}getEdgeScrollSpeed(){return this.user.userPreferences.get().edgeScrollSpeed??gs.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??gs.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??gs.name}getLocale(){return this.user.userPreferences.get().locale??gs.locale}getColor(){return this.user.userPreferences.get().color??gs.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??gs.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??gs.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??gs.isDynamicSizeMode}}Vr([V],kr.prototype,"getUserPreferences");Vr([V],kr.prototype,"getIsDarkMode");Vr([V],kr.prototype,"getEdgeScrollSpeed");Vr([V],kr.prototype,"getAnimationSpeed");Vr([V],kr.prototype,"getId");Vr([V],kr.prototype,"getName");Vr([V],kr.prototype,"getLocale");Vr([V],kr.prototype,"getColor");Vr([V],kr.prototype,"getIsSnapMode");Vr([V],kr.prototype,"getIsWrapMode");Vr([V],kr.prototype,"getIsDynamicResizeMode");const EG={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"},kG=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class se{constructor(n,t){m(this,"performanceTracker");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",(n,t={})=>{var s;const r=n.split(".");let o=this;for(let i=0;i{var o;const t=EG[n.name],r=this._current.__unsafe__getWithoutCapture();(o=this[t])==null||o.call(this,n),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(n)});m(this,"enter",(n,t)=>{var r;if(wt.measurePerformance.get()&&kG.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,n,t),this.children&&this.initial&&this.getIsActive()){const o=this.children[this.initial];this._current.set(o),o.enter(n,t)}});m(this,"exit",(n,t)=>{var r,o;wt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,n,t),this.getIsActive()||(o=this.getCurrent())==null||o.exit(n,t)});m(this,"_currentToolIdMask",Mt("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=n;const{id:r,children:o,initial:s}=this.constructor;this.id=r,this._isActive=Mt("toolIsActive"+this.id,!1),this._current=Mt("toolState"+this.id,void 0),this._path=V("toolPath"+this.id,()=>{const i=this.getCurrent();return this.id+(i?`.${i.getPath()}`:"")}),this.parent=t??{},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]))),this.performanceTracker=new bT}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(n){this._currentToolIdMask.set(n)}}m(se,"id"),m(se,"initial"),m(se,"children");class Dh extends se{constructor(){super(...arguments);m(this,"onKeyDown",t=>{var r;switch(t.code){case"KeyZ":{if(!(t.shiftKey||t.ctrlKey)){const o=this.getCurrent();o&&((r=o.getCurrent())==null?void 0:r.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...t,onInteractionEnd:o.id})}break}}})}}m(Dh,"id","root"),m(Dh,"initial",""),m(Dh,"children",()=>[]);var _G=Object.defineProperty,TG=Object.getOwnPropertyDescriptor,ne=(e,n,t,r)=>{for(var o=TG(n,t),s=e.length-1,i;s>=0;s--)(i=e[s])&&(o=i(n,t,o)||o);return o&&_G(n,t,o),o};class Q extends CW{constructor({store:t,user:r,shapeUtils:o,bindingUtils:s,tools:i,getContainer:a,cameraOptions:l,assetOptions:c,initialState:d,autoFocus:h,inferDarkMode:p,options:f}){super();m(this,"options");m(this,"store");m(this,"root");m(this,"disposables",new Set);m(this,"isDisposed",!1);m(this,"_tickManager");m(this,"snaps");m(this,"timers");m(this,"user");m(this,"textMeasure");m(this,"environment");m(this,"scribbles");m(this,"sideEffects");m(this,"edgeScrollManager");m(this,"focusManager");m(this,"getContainer");m(this,"shapeUtils");m(this,"styleProps");m(this,"bindingUtils");m(this,"history");m(this,"_crashingError",null);m(this,"_updateInstanceState",(t,r)=>{this.batch(()=>{this.store.put([{...this.getInstanceState(),...t}])},r)});m(this,"_isChangingStyleTimeout",-1);m(this,"setCursor",t=>(this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...t}}),this));m(this,"_updateCurrentPageState",(t,r)=>{this.batch(()=>{this.store.update(t.id??this.getCurrentPageState().id,o=>({...o,...t}))},{history:"ignore",...r})});m(this,"_cameraOptions",Mt("camera options",sC));m(this,"_viewportAnimation",null);m(this,"_willSetInitialBounds",!0);m(this,"_isLockedOnFollowingUser",Mt("isLockedOnFollowingUser",!1));m(this,"_cameraState",Mt("camera state","idle"));m(this,"_cameraStateTimeoutRemaining",0);m(this,"_decayCameraStateTimeout",t=>{this._cameraStateTimeoutRemaining-=t,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"))});m(this,"_tickCameraState",()=>{this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))});m(this,"_currentPageShapeIds");m(this,"_assetOptions",Mt("asset options",iC));m(this,"_parentIdsToChildIds");m(this,"animatingShapes",new Map);m(this,"_updateShapes",t=>{this.getInstanceState().isReadonly||this.batch(()=>{var i,a;const r=[];let o,s;for(let l=0,c=t.length;l{this.inputs.shiftKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Shift",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,code:"ShiftLeft"})});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,"performanceTracker");m(this,"performanceTrackerTimeout",-1);m(this,"dispatch",t=>(this._pendingEventsForNextTick.push(t),t.type==="pointer"&&t.name==="pointer_move"||t.type==="wheel"||t.type==="pinch"||this._flushEventsForTick(0),this));m(this,"_pendingEventsForNextTick",[]);m(this,"_flushEventForTick",t=>{if(this.getCrashingError())return this;const{inputs:r}=this,{type:o}=t;if(t.type==="misc"){(t.name==="cancel"||t.name==="complete")&&(this.inputs.isDragging=!1,this.inputs.isPanning&&(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0}))),this.root.handleEvent(t);return}t.shiftKey?(clearTimeout(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,r.shiftKey=!0):!t.shiftKey&&r.shiftKey&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=this.timers.setTimeout(this._setShiftKeyTimeout,150)),t.altKey?(clearTimeout(this._altKeyTimeout),this._altKeyTimeout=-1,r.altKey=!0):!t.altKey&&r.altKey&&this._altKeyTimeout===-1&&(this._altKeyTimeout=this.timers.setTimeout(this._setAltKeyTimeout,150)),t.ctrlKey?(clearTimeout(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,r.ctrlKey=!0):!t.ctrlKey&&r.ctrlKey&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=this.timers.setTimeout(this._setCtrlKeyTimeout,150));const{originPagePoint:s,currentPagePoint:i}=r;r.isPointing||(r.isDragging=!1);const a=this.store.unsafeGetWithoutCapture(gn),l=this.store.get(this._getCurrentPageStateId()),c=this._cameraOptions.__unsafe__getWithoutCapture();switch(o){case"pinch":{if(c.isLocked)return;switch(clearTimeout(this._longPressTimeout),this._updateInputsFromEvent(t),t.name){case"pinch_start":{if(r.isPinching)return;r.isEditing||(this._pinchStart=this.getCamera().z,this._selectedShapeIdsAtPointerDown.length||(this._selectedShapeIdsAtPointerDown=[...l.selectedShapeIds]),this._didPinch=!0,r.isPinching=!0,this.interrupt());return}case"pinch":{if(!r.isPinching)return;const{point:{z:d=1},delta:{x:h,y:p}}=t,{x:f,y:S}=w.SubXY(t.point,a.screenBounds.x,a.screenBounds.y);this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:g,y:x,z:y}=Um(()=>this.getCamera()),{panSpeed:v,zoomSpeed:b}=c;this._setCamera(new w(g+h*v/y-f/y+f/(d*b),x+p*v/y-S/y+S/(d*b),d*b),{immediate:!0});return}case"pinch_end":{if(!r.isPinching)return this;r.isPinching=!1;const{_selectedShapeIdsAtPointerDown:d}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,d.length>0&&this.once("tick",()=>{this._didPinch||this.setSelectedShapes(d)}));return}}}case"wheel":{if(c.isLocked)return;if(this._updateInputsFromEvent(t),!this.getIsMenuOpen()){const{panSpeed:d,zoomSpeed:h,wheelBehavior:p}=c;if(p!=="none"){this.stopCameraAnimation(),a.followingUserId&&this.stopFollowingUser();const{x:f,y:S,z:g}=Um(()=>this.getCamera()),{x,y,z:v=0}=t.delta;let b=p;switch(r.ctrlKey&&(b=p==="pan"?"zoom":"pan"),b){case"zoom":{const{x:E,y:I}=this.inputs.currentScreenPoint;let C=v;p==="zoom"&&(Math.abs(y)>10?C=10*Math.sign(y)/100:C=y/100);const k=g+(C??0)*h*g;this._setCamera(new w(f+(E/k-E)-(E/g-E),S+(I/k-I)-(I/g-I),k),{immediate:!0}),this.maybeTrackPerformance("Zooming");return}case"pan":{this._setCamera(new w(f+x*d/g,S+y*d/g,g),{immediate:!0}),this.maybeTrackPerformance("Panning");return}}}}break}case"pointer":{if(r.isPinching)return;this._updateInputsFromEvent(t);const{isPen:d}=t,{isPenMode:h}=a;switch(t.name){case"pointer_down":{if(h&&!d)return;if(this.clearOpenMenus(),this.inputs.isPanning||(this._longPressTimeout=this.timers.setTimeout(()=>{this.dispatch({...t,point:this.inputs.currentScreenPoint,name:"long_press"})},this.options.longPressDurationMs)),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),t.button===lC&&(this.capturedPointerId=t.pointerId),r.buttons.add(t.button),r.isPointing=!0,r.isDragging=!1,!h&&d&&this.updateInstanceState({isPenMode:!0}),t.button===cC?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):t.button===Nd&&(this.inputs.isPanning||(this._prevCursor=this.getInstanceState().cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout)),this.inputs.isPanning)return this.stopCameraAnimation(),this.setCursor({type:"grabbing",rotation:0}),this;break}case"pointer_move":{if(!d&&h)return;const{x:p,y:f,z:S}=Um(()=>this.getCamera());if(this.inputs.isPanning&&this.inputs.isPointing){const{currentScreenPoint:g,previousScreenPoint:x}=this.inputs,{panSpeed:y}=c,v=w.Sub(g,x);this.setCamera(new w(p+v.x*y/S,f+v.y*y/S,S),{immediate:!0}),this.maybeTrackPerformance("Panning");return}r.isPointing&&!r.isDragging&&w.Dist2(s,i)*this.getZoomLevel()>(a.isCoarsePointer?this.options.coarseDragDistanceSquared:this.options.dragDistanceSquared)/S&&(r.isDragging=!0,clearTimeout(this._longPressTimeout));break}case"pointer_up":{if(r.isDragging=!1,r.isPointing=!1,clearTimeout(this._longPressTimeout),r.buttons.delete(t.button),this.getIsMenuOpen()||a.isPenMode&&!d)return;if(this.capturedPointerId===t.pointerId&&(this.capturedPointerId=null,t.button=0),r.isPanning){r.keys.has("Space")||(r.isPanning=!1);const p=this.inputs.pointerVelocity,f=Math.min(2,p.len());switch(t.button){case lC:{this.setCursor({type:"grab",rotation:0});break}case Nd:this.inputs.keys.has(" ")?this.setCursor({type:"grab",rotation:0}):this.setCursor({type:this._prevCursor,rotation:0})}f>0&&this.slideCamera({speed:f,direction:p})}else t.button===cC&&(this.complete(),this.setCurrentTool(this._restoreToolId));break}}break}case"keyboard":{switch(t.key==="ShiftRight"&&(t.key="ShiftLeft"),t.key==="AltRight"&&(t.key="AltLeft"),t.code==="ControlRight"&&(t.code="ControlLeft"),t.name){case"key_down":{r.keys.add(t.code),t.code==="Space"&&!t.ctrlKey&&(this.inputs.isPanning||(this._prevCursor=a.cursor.type),this.inputs.isPanning=!0,clearTimeout(this._longPressTimeout),this.setCursor({type:this.inputs.isPointing?"grabbing":"grab",rotation:0}));break}case"key_up":{r.keys.delete(t.code),t.code==="Space"&&(this.inputs.buttons.has(Nd)||(this.inputs.isPanning=!1,this.setCursor({type:this._prevCursor,rotation:0})));break}}break}}if(t.type==="pointer"){t.button===Nd?t.name="middle_click":t.button===Fw&&(t.name="right_click");const{isPenMode:d}=this.store.unsafeGetWithoutCapture(gn);if(t.isPen===d){const h=this._clickManager.handlePointerEvent(t);if(t.name!==h.name){this.root.handleEvent(t),this.emit("event",t),this.root.handleEvent(h),this.emit("event",h);return}}}return this.root.handleEvent(t),this.emit("event",t),this});this.options={...$W,...f},this.store=t,this.disposables.add(this.store.dispose.bind(this.store)),this.history=new sG({store:t,annotateError:_=>{this.annotateError(_,{origin:"history.batch",willCrashApp:!0}),this.crash(_)}}),this.snaps=new ag(this),this.timers=new Z6,this.disposables.add(this.timers.dispose.bind(this.timers)),this._cameraOptions.set({...sC,...l}),this._assetOptions.set({...iC,...c}),this.user=new kr(r??y2(),p??!1),this.getContainer=a??(()=>document.body),this.textMeasure=new bG(this),this._tickManager=new PG(this);class S extends Dh{}m(S,"initial",d??""),this.root=new S(this),this.root.children={};const g=k2(o),x={},y={},v=new Map;for(const _ of g){const j=new _(this);x[_.type]=j;const L=eM(_.props??{});y[_.type]=L;for(const A of L.keys())if(!v.has(A.id))v.set(A.id,A);else if(v.get(A.id)!==A)throw Error(`Multiple style props with id "${A.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=x,this.styleProps=y;const b=C2(s),E={};for(const _ of b){const j=new _(this);E[_.type]=j}this.bindingUtils=E;for(const _ of[...i]){if(fo(this.root.children,_.id))throw Error(`Can't override tool with id "${_.id}"`);this.root.children[_.id]=new _(this,this.root)}this.environment=new tG(this),this.scribbles=new lG(this);const I=(_,j)=>{let L=null;const A=_.selectedShapeIds.filter(W=>!j.has(W));A.length!==_.selectedShapeIds.length&&(L||(L={..._}),L.selectedShapeIds=A);const R=_.erasingShapeIds.filter(W=>!j.has(W));R.length!==_.erasingShapeIds.length&&(L||(L={..._}),L.erasingShapeIds=R),_.hoveredShapeId&&j.has(_.hoveredShapeId)&&(L||(L={..._}),L.hoveredShapeId=null),_.editingShapeId&&j.has(_.editingShapeId)&&(L||(L={..._}),L.editingShapeId=null);const F=_.hintingShapeIds.filter(W=>!j.has(W));return F.length!==_.hintingShapeIds.length&&(L||(L={..._}),L.hintingShapeIds=F),_.focusedGroupId&&j.has(_.focusedGroupId)&&(L||(L={..._}),L.focusedGroupId=null),L};this.sideEffects=this.store.sideEffects;let C=new Map;const k=new Set,T=new Set;let O=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var _,j,L,A;k.clear();for(const R of T){T.delete(R);const F=this.getShape(R);if(!F)continue;const W=this.getShapeUtil(F),K=(_=W.onChildrenChange)==null?void 0:_.call(W,F);K!=null&&K.length&&this.updateShapes(K)}if(O.size){const R=O;O=new Set;for(const F of R){const W=this.getBindingUtil(F);(j=W.onOperationComplete)==null||j.call(W)}}if(C.size){const R=C;C=new Map;for(const F of R.values())(A=(L=this.getBindingUtil(F.binding)).onAfterDelete)==null||A.call(L,F)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(_,j)=>{var L,A,R,F;for(const W of this.getBindingsInvolvingShape(j))O.add(W.type),W.fromId===j.id&&((A=(L=this.getBindingUtil(W)).onAfterChangeFromShape)==null||A.call(L,{binding:W,shapeBefore:_,shapeAfter:j})),W.toId===j.id&&((F=(R=this.getBindingUtil(W)).onAfterChangeToShape)==null||F.call(R,{binding:W,shapeBefore:_,shapeAfter:j}));if(_.parentId!==j.parentId){const W=K=>{var U,X,J,le;const z=this.getShape(K);if(z)for(const ye of this.getBindingsInvolvingShape(z))O.add(ye.type),ye.fromId===z.id&&((X=(U=this.getBindingUtil(ye)).onAfterChangeFromShape)==null||X.call(U,{binding:ye,shapeBefore:z,shapeAfter:z})),ye.toId===z.id&&((le=(J=this.getBindingUtil(ye)).onAfterChangeToShape)==null||le.call(J,{binding:ye,shapeBefore:z,shapeAfter:z}))};W(j.id),this.visitDescendants(j.id,W)}if(_.parentId!==j.parentId&&In(j.parentId)){const W=new Set([_.id]);this.visitDescendants(_.id,K=>{W.add(K)});for(const K of this.getPageStates()){if(K.pageId===j.parentId)continue;const z=I(K,W);z&&this.store.put([z])}}_.parentId&&kn(_.parentId)&&T.add(_.parentId),j.parentId!==_.parentId&&kn(j.parentId)&&T.add(j.parentId)},beforeDelete:_=>{var R,F,W,K;if(k.has(_.id))return;_.parentId&&kn(_.parentId)&&T.add(_.parentId),k.add(_.id);const j=[];for(const z of this.getBindingsInvolvingShape(_)){O.add(z.type),j.push(z.id);const U=this.getBindingUtil(z);z.fromId===_.id?((R=U.onBeforeIsolateToShape)==null||R.call(U,{binding:z,removedShape:_}),(F=U.onBeforeDeleteFromShape)==null||F.call(U,{binding:z,shape:_})):((W=U.onBeforeIsolateFromShape)==null||W.call(U,{binding:z,removedShape:_}),(K=U.onBeforeDeleteToShape)==null||K.call(U,{binding:z,shape:_}))}j.length&&this.deleteBindings(j);const L=new Set([_.id]),A=me(this.getPageStates().map(z=>I(z,L)));A.length&&this.store.put(A)}},binding:{beforeCreate:_=>{var L,A;const j=(A=(L=this.getBindingUtil(_)).onBeforeCreate)==null?void 0:A.call(L,{binding:_});return j||_},afterCreate:_=>{var j,L;O.add(_.type),(L=(j=this.getBindingUtil(_)).onAfterCreate)==null||L.call(j,{binding:_})},beforeChange:(_,j)=>{var A,R;const L=(R=(A=this.getBindingUtil(j)).onBeforeChange)==null?void 0:R.call(A,{bindingBefore:_,bindingAfter:j});return L||j},afterChange:(_,j)=>{var L,A;O.add(j.type),(A=(L=this.getBindingUtil(j)).onAfterChange)==null||A.call(L,{bindingBefore:_,bindingAfter:j})},beforeDelete:_=>{var j,L;(L=(j=this.getBindingUtil(_)).onBeforeDelete)==null||L.call(j,{binding:_})},afterDelete:_=>{var j,L;(L=(j=this.getBindingUtil(_)).onAfterDelete)==null||L.call(j,{binding:_}),O.add(_.type)}},page:{afterCreate:_=>{const j=lo.createId(_.id),L=$r.createId(_.id);this.store.has(j)||this.store.put([lo.create({id:j})]),this.store.has(L)||this.store.put([$r.create({id:L,pageId:_.id})])},afterDelete:(_,j)=>{var R,F;if(((R=this.getInstanceState())==null?void 0:R.currentPageId)===_.id){const W=(F=this.getPages().find(K=>K.id!==_.id))==null?void 0:F.id;W?this.store.put([{...this.getInstanceState(),currentPageId:W}]):j==="user"&&this.store.ensureStoreIsUsable()}const L=lo.createId(_.id),A=$r.createId(_.id);this.store.remove([L,A])}},instance:{afterChange:(_,j,L)=>{var A;if(!this.store.has(j.currentPageId)){const R=this.store.has(_.currentPageId)?_.currentPageId:(A=this.getPages()[0])==null?void 0:A.id;R?this.store.update(j.id,F=>({...F,currentPageId:R})):L==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(_,j)=>{if((_==null?void 0:_.selectedShapeIds)!==(j==null?void 0:j.selectedShapeIds)){const L=j.selectedShapeIds.filter(R=>{var W,K;let F=(W=this.getShape(R))==null?void 0:W.parentId;for(;kn(F);){if(j.selectedShapeIds.includes(F))return!1;F=(K=this.getShape(F))==null?void 0:K.parentId}return!0});let A=null;if(L.length>0){const R=this.findCommonAncestor(me(L.map(F=>this.getShape(F))),F=>this.isShapeOfType(F,"group"));R&&(A=R)}else j!=null&&j.focusedGroupId&&(A=j.focusedGroupId);(L.length!==j.selectedShapeIds.length||A!==j.focusedGroupId)&&this.store.put([{...j,selectedShapeIds:L,focusedGroupId:A??null}])}}}})),this._currentPageShapeIds=XW(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=YW(this.store),this.disposables.add(this.store.listen(_=>{this.emit("change",_)})),this.disposables.add(this.history.dispose),this.history.ignore(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})}),d&&this.root.children[d]===void 0)throw Error(`No state found for initialState "${d}".`);this.root.enter(void 0,"initial"),this.edgeScrollManager=new eG(this),this.focusManager=new nG(this,h),this.disposables.add(this.focusManager.dispose.bind(this.focusManager)),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this.on("tick",this._flushEventsForTick),this.timers.requestAnimationFrame(()=>{this._tickManager.start()}),this.performanceTracker=new bT}dispose(){this.disposables.forEach(t=>t()),this.disposables.clear(),this.isDisposed=!0}getShapeUtil(t){const r=typeof t=="string"?t:t.type,o=An(this.shapeUtils,r);return st(o,`No shape util found for type "${r}"`),o}getBindingUtil(t){const r=typeof t=="string"?t:t.type,o=An(this.bindingUtils,r);return st(o,`No binding util found for type "${r}"`),o}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(t){return this.history.mark(t),this}bail(){return this.history.bail(),this}bailToMark(t){return this.history.bailToMark(t),this}batch(t,r){return this.history.batch(t,r),this}annotateError(t,{origin:r,willCrashApp:o,tags:s,extras:i}){const a=this.createErrorAnnotations(r,o);return xw(t,{tags:{...a.tags,...s},extras:{...a.extras,...i}}),o&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(t,r){try{const o=this.getEditingShapeId();return{tags:{origin:t,willCrashApp:r},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:o?this.getShape(o):void 0,inputs:this.inputs}}}catch{return{tags:{origin:t,willCrashApp:r},extras:{}}}}getCrashingError(){return this._crashingError}crash(t){return this._crashingError=t,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:t}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(t){const r=t.split(".").reverse();let 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(...t){return t.some(r=>this.isIn(r))}setCurrentTool(t,r={}){return this.root.transition(t,r),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const t=this.getCurrentTool();return t?t.getCurrentToolIdMask()??t.id:""}getStateDescendant(t){var s;const r=t.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(hv)}updateDocumentSettings(t){return this.history.ignore(()=>{this.store.put([{...this.getDocumentSettings(),...t}])}),this}getInstanceState(){return this.store.get(gn)}updateInstanceState(t,r){return this._updateInstanceState(t,{history:"ignore",...r}),t.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),t.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},2e3))),this}getOpenMenus(){return this.getInstanceState().openMenus}addOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)||(r.add(t),this.updateInstanceState({openMenus:[...r]})),this}deleteOpenMenu(t){const r=new Set(this.getOpenMenus());return r.has(t)&&(r.delete(t),this.updateInstanceState({openMenus:[...r]})),this}clearOpenMenus(){return this.getOpenMenus().length&&this.updateInstanceState({openMenus:[]}),this}getIsMenuOpen(){return this.getOpenMenus().length>0}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return $r.createId(this.getCurrentPageId())}updateCurrentPageState(t,r){return this._updateCurrentPageState(t,r),this}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:t}=this.getCurrentPageState();return me(t.map(r=>this.store.get(r)))}setSelectedShapes(t){return this.batch(()=>{const r=t.map(i=>typeof i=="string"?i:i.id),{selectedShapeIds:o}=this.getCurrentPageState(),s=new Set(o);if(r.length===s.size&&r.every(i=>s.has(i)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:r}])},{history:"record-preserveRedoStack"})}isAncestorSelected(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null,o=this.getShape(r);if(!o)return!1;const s=this.getSelectedShapeIds();return!!this.findShapeAncestor(o,i=>s.includes(i.id))}select(...t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);return this.setSelectedShapes(r),this}deselect(...t){const r=typeof t[0]=="string"?t:t.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 t=this.getSortedChildIdsForParent(this.getCurrentPageId());return t.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(t)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var t;return((t=this.getOnlySelectedShape())==null?void 0:t.id)??null}getOnlySelectedShape(){const t=this.getSelectedShapes();return t.length===1?t[0]:null}getSelectionPageBounds(){const t=this.getCurrentPageState().selectedShapeIds;return t.length===0?null:Z.Common(me(t.map(r=>this.getShapePageBounds(r))))}getSelectionRotation(){const t=this.getSelectedShapeIds();let r=!1,o=0;for(let s=0,i=t.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 t=this.getSelectionRotatedPageBounds();if(!t)return;const{x:r,y:o}=this.pageToScreen(t.point),s=this.getZoomLevel();return new Z(r,o,t.width*s,t.height*s)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const t=this.getFocusedGroupId();return t?this.getShape(t):void 0}setFocusedGroup(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==null){const 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.batch(()=>{this.store.update(this.getCurrentPageState().id,o=>({...o,focusedGroupId:r}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const t=this.getFocusedGroup();if(t){const r=this.findShapeAncestor(t,o=>this.isShapeOfType(o,"group"));this.setFocusedGroup((r==null?void 0:r.id)??null),this.select(t.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const t=this.getEditingShapeId();return t?this.getShape(t):void 0}setEditingShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;if(r!==this.getEditingShapeId()){if(r){const o=this.getShape(r);if(o&&this.getShapeUtil(o).canEdit(o))return this._updateCurrentPageState({editingShapeId:r}),this}this._updateCurrentPageState({editingShapeId:null})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const t=this.getHoveredShapeId();return t?this.getShape(t):void 0}setHoveredShape(t){const r=typeof t=="string"?t:(t==null?void 0:t.id)??null;return r===this.getHoveredShapeId()?this:(this.updateCurrentPageState({hoveredShapeId:r},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const t=this.getHintingShapeIds();return me(t.map(r=>this.getShape(r)))}setHintingShapes(t){const r=typeof t[0]=="string"?t:t.map(o=>o.id);return this.updateCurrentPageState({hintingShapeIds:vw(r)},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const t=this.getErasingShapeIds();return me(t.map(r=>this.getShape(r)))}setErasingShapes(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);r.sort();const o=this.getErasingShapeIds();return this.history.ignore(()=>{if(r.length===o.length){for(let s=0;sp.userId===t);if(!r)return null;const{w:o,h:s}=r.screenBounds,{x:i,y:a,z:l}=r.camera,c=new Z(-i,-a,o/l,s/l),d=this.getViewportScreenBounds().clone(),h=d.width/d.height;return d.width=c.width,d.height=d.width/h,d.heightb){const{x:A,y:R,z:F}=o,W=-A+h.w/F/2,K=-R+h.h/F/2;a=_t(a,E,b);const z=-A+h.w/a/2,U=-R+h.h/a/2;s=A+z-W,i=R+U-K}const I=S/a-g.x,C=f/a-g.y,k=(h.w-S*2)/a-g.w,T=(h.h-f*2)/a-g.h,O=I+k*p.origin.x,_=C+T*p.origin.y,j=typeof p.behavior=="string"?p.behavior:p.behavior.x,L=typeof p.behavior=="string"?p.behavior:p.behavior.y;if(r!=null&&r.reset)s=O,i=_;else{switch(j){case"fixed":{s=O;break}case"contain":{ad||a{const l={...o,x:s,y:i,z:a};this.history.ignore(()=>{this.store.put([l])});const{currentScreenPoint:c,currentPagePoint:d}=this.inputs,{screenBounds:h}=this.store.unsafeGetWithoutCapture(gn);if(c.x/a-s!==d.x||c.y/a-i!==d.y){const p={type:"pointer",target:"canvas",name:"pointer_move",point:w.AddXY(c,h.x,h.y),pointerId:aC.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,button:0,isPen:this.getInstanceState().isPenMode??!1};r!=null&&r.immediate?this._flushEventForTick(p):this.dispatch(p)}this._tickCameraState()}),this)}setCamera(t,r){const{isLocked:o}=this._cameraOptions.__unsafe__getWithoutCapture();if(o&&!(r!=null&&r.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const s=w.Cast(t);Number.isFinite(s.x)||(s.x=0),Number.isFinite(s.y)||(s.y=0),(s.z===void 0||!Number.isFinite(s.z))&&(t.z=this.getZoomLevel());const i=this.getConstrainedCamera(s,r);if(r!=null&&r.animation){const{width:a,height:l}=this.getViewportScreenBounds();this._animateToViewport(new Z(-i.x,-i.y,a/i.z,l/i.z),r)}else this._setCamera(i,{...r,force:!0});return this}centerOnPoint(t,r){if(this.getCameraOptions().isLocked)return this;const{width:o,height:s}=this.getViewportPageBounds();return this.setCamera(new w(-(t.x-o/2),-(t.y-s/2),this.getCamera().z),r),this}zoomToFit(t){const r=[...this.getCurrentPageShapeIds()];if(r.length<=0)return this;const o=Z.Common(me(r.map(s=>this.getShapePageBounds(s))));return this.zoomToBounds(o,t),this}resetZoom(t=this.getViewportScreenCenter(),r){const{isLocked:o,constraints:s}=this.getCameraOptions();if(o)return this;const i=this.getCamera(),{x:a,y:l,z:c}=i,{x:d,y:h}=t;let p=1;if(s){const f=this.getInitialZoom();c!==f&&(p=f)}return this.setCamera(new w(a+(d/p-d)-(d/c-d),l+(h/p-h)-(h/c-h),p),r),this}zoomIn(t=this.getViewportScreenCenter(),r){if(this.getCameraOptions().isLocked)return this;const{x:o,y:s,z:i}=this.getCamera(),{zoomSteps:a}=this.getCameraOptions();if(a!==null&&a.length>1){const l=this.getBaseZoom();let c=Nt(a)*l;for(let d=1;d1){const s=this.getBaseZoom(),{x:i,y:a,z:l}=this.getCamera();let c=o[0]*s;for(let d=o.length-1;d>0;d--){const h=o[d-1]*s,p=o[d]*s;if(!(p-l>=(p-h)/2)){c=h;break}}this.setCamera(new w(i+(t.x/c-t.x)-(t.x/l-t.x),a+(t.y/c-t.y)-(t.y/l-t.y),c),r)}return this}zoomToSelection(t){if(this.getCameraOptions().isLocked)return this;const r=this.getSelectionPageBounds();return r&&this.zoomToBounds(r,{targetZoom:Math.max(1,this.getZoomLevel()),...t}),this}zoomToBounds(t,r){const o=this._cameraOptions.__unsafe__getWithoutCapture();if(o.isLocked)return this;const s=this.getViewportScreenBounds(),i=(r==null?void 0:r.inset)??Math.min(t7,s.width*.28),a=this.getBaseZoom(),l=o.zoomSteps[0],c=Nt(o.zoomSteps);let d=_t(Math.min((s.width-i)/t.w,(s.height-i)/t.h),l*a,c*a);return(r==null?void 0:r.targetZoom)!==void 0&&(d=Math.min(r.targetZoom,d)),this.setCamera(new w(-t.x+(s.width-t.w*d)/2/d,-t.y+(s.height-t.h*d)/2/d,d),r),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(t){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=t;const{elapsed:r,easing:o,duration:s,start:i,end:a}=this._viewportAnimation;if(r>s){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new w(-a.x,-a.y,this.getViewportScreenBounds().width/a.width));return}const l=s-r,c=o(1-l/s),d=i.minX+(a.minX-i.minX)*c,h=i.minY+(a.minY-i.minY)*c,p=i.maxX+(a.maxX-i.maxX)*c;this._setCamera(new w(-d,-h,this.getViewportScreenBounds().width/(p-d)),{force:!0})}_animateToViewport(t,r={animation:Gm}){const{animation:o,...s}=r;if(!o)return;const{duration:i=0,easing:a=jt.easeInOutCubic}=o,l=this.user.getAnimationSpeed(),c=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),i===0||l===0?this._setCamera(new w(-t.x,-t.y,this.getViewportScreenBounds().width/t.width),{...s}):(this._viewportAnimation={elapsed:0,duration:i/l,easing:a,start:c.clone(),end:t.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(t={}){if(this.getCameraOptions().isLocked)return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:o,friction:s=this.options.cameraSlideFriction,direction:i,speedThreshold:a=.01}=t;let l=Math.min(o,1);const c=()=>{this.off("tick",d),this.off("stop-camera-animation",c)};this.once("stop-camera-animation",c);const d=h=>{const{x:p,y:f,z:S}=this.getCamera(),g=w.Mul(i,l*h/S);l*=1-s,ls.userId===t);return o?(this.batch(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const s=o.currentPageId===this.getCurrentPageId();s||this.setCurrentPage(o.currentPageId),r&&r.animation&&!s&&(r.animation=void 0),this.centerOnPoint(o.cursor,r);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,t]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(t);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(t,r=!1){t.width=Math.max(t.width,1),t.height=Math.max(t.height,1);const o=[t.minY!==0,!Us(document.body.scrollWidth,t.maxX,1),!Us(document.body.scrollHeight,t.maxY,1),t.minX!==0],{screenBounds:s,insets:i}=this.getInstanceState();if(t.equals(s)&&o.every((l,c)=>l===i[c]))return this;const{_willSetInitialBounds:a}=this;if(this._willSetInitialBounds=!1,a)this.updateInstanceState({screenBounds:t.toJson(),insets:o}),this.setCamera(this.getCamera());else if(r&&!this.getInstanceState().followingUserId){const l=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:t.toJson(),insets:o}),this.centerOnPoint(l)}else this.updateInstanceState({screenBounds:t.toJson(),insets:o}),this._setCamera(w.From({...this.getCamera()}));return this._tickCameraState(),this}getViewportScreenBounds(){const{x:t,y:r,w:o,h:s}=this.getInstanceState().screenBounds;return new Z(t,r,o,s)}getViewportScreenCenter(){const t=this.getViewportScreenBounds();return new w(t.midX-t.minX,t.midY-t.minY)}getViewportPageBounds(){const{w:t,h:r}=this.getViewportScreenBounds(),{x:o,y:s,z:i}=this.getCamera();return new Z(-o,-s,t/i,r/i)}screenToPage(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(gn),{x:o,y:s,z:i=1}=this.getCamera();return new w((t.x-r.x)/i-o,(t.y-r.y)/i-s,t.z??.5)}pageToScreen(t){const{screenBounds:r}=this.store.unsafeGetWithoutCapture(gn),{x:o,y:s,z:i=1}=this.getCamera();return new w((t.x+o)*i+r.x,(t.y+s)*i+r.y,t.z??.5)}pageToViewport(t){const{x:r,y:o,z:s=1}=this.getCamera();return new w((t.x+r)*s,(t.y+o)*s,t.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const t=this._getCollaboratorsQuery().get();return t.length?[...new Set(t.map(o=>o.userId))].sort().map(o=>t.filter(i=>i.userId===o).sort((i,a)=>a.lastActivityTimestamp-i.lastActivityTimestamp)[0]):Ho}getCollaboratorsOnCurrentPage(){const t=this.getCurrentPageId();return this.getCollaborators().filter(r=>r.currentPageId===t)}startFollowingUser(t){this.stopFollowingUser();const r=this._getCollaboratorsQuery().get().filter(i=>i.userId===t);if(!r.length)return console.warn("User not found"),this;const o=this.user.getId();if(o||console.warn("You should set the userId for the current instance before following a user"),r.some(i=>i.followingUserId===o))return this;const s=V("latestLeaderPresence",()=>this.getCollaborators().find(i=>i.userId===t));return zs(()=>{this.updateInstanceState({followingUserId:t},{history:"ignore"});const i=aa("update current page",()=>{const c=s.get();if(!c){this.stopFollowingUser();return}c.currentPageId!==this.getCurrentPageId()&&this.getPage(c.currentPageId)&&this.history.ignore(()=>{this.store.put([{...this.getInstanceState(),currentPageId:c.currentPageId}]),this._isLockedOnFollowingUser.set(!0)})}),a=()=>{i(),this._isLockedOnFollowingUser.set(!1),this.off("frame",l),this.off("stop-following",a)},l=()=>{if(!s.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const d=this.user.getAnimationSpeed();if(d===0){this._isLockedOnFollowingUser.set(!0);return}const h=this.getViewportPageBoundsForFollowing();if(!h){this.stopFollowingUser();return}const p=this.getViewportPageBounds(),f=Math.abs(h.minX-p.minX)+Math.abs(h.maxX-p.maxX),S=Math.abs(h.minY-p.minY)+Math.abs(h.maxY-p.maxY);if(f{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")}),this}getUnorderedRenderingShapes(t){const r=[];let o=this.options.maxShapesPerPage*2,s=this.options.maxShapesPerPage;const i=this.getErasingShapeIds(),a=(c,d,h)=>{const p=this.getShape(c);if(!p)return;d*=p.opacity;let f=!1;const S=this.getShapeUtil(p);t&&(f=!h&&i.includes(c),f&&(d*=.32)),r.push({id:c,shape:p,util:S,index:o,backgroundIndex:s,opacity:d}),o+=1,s+=1;const g=this.getSortedChildIdsForParent(c);if(!g.length)return;let x=null;S.providesBackgroundForChildren(p)&&(x=s,s=o,o+=this.options.maxShapesPerPage);for(const y of g)a(y,d,h||f);x!==null&&(s=x)},l=t?[this.getCurrentPage()]:this.getPages();for(const c of l)for(const d of this.getSortedChildIdsForParent(c.id))a(d,1,!1);return r}getCameraState(){return this._cameraState.get()}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(W6)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return this._getAllPagesQuery().get().sort(on)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(t){return this.store.get(typeof t=="string"?t:t.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(t){const r=typeof t=="string"?t:t.id,o=this.store.query.exec("shape",{parentId:{eq:r}});return this.getShapeAndDescendantIds(o.map(s=>s.id))}setCurrentPage(t){const r=typeof t=="string"?t:t.id;return this.store.has(r)?(this.stopFollowingUser(),this.complete(),this.batch(()=>this.store.put([{...this.getInstanceState(),currentPageId:r}]),{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(t){return this.getInstanceState().isReadonly?this:this.getPage(t.id)?this.batch(()=>this.store.update(t.id,o=>({...o,...t}))):this}createPage(t){return this.history.batch(()=>{if(this.getInstanceState().isReadonly||this.getPages().length>=this.options.maxPages)return;const r=this.getPages(),o=zW(t.name??"Page 1",r.map(a=>a.name));let s=t.index;(!s||r.some(a=>a.index===s))&&(s=Lo(r[r.length-1].index));const i=Qo.create({meta:{},...t,name:o,index:s});this.store.put([i])}),this}deletePage(t){const r=typeof t=="string"?t:t.id;return this.batch(()=>{if(this.getInstanceState().isReadonly)return;const o=this.getPages();if(o.length===1)return;const s=this.getPage(r);if(s){if(r===this.getCurrentPageId()){const i=o.findIndex(l=>l.id===r),a=o[i-1]??o[i+1];this.setCurrentPage(a.id)}this.store.remove([s.id])}}),this}duplicatePage(t,r=Qo.createId()){if(this.getPages().length>=this.options.maxPages)return this;const o=typeof t=="string"?t:t.id,s=this.getPage(o);if(!s)return this;const i={...this.getCamera()},a=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(s.id));return this.batch(()=>{var d;const l=this.getPages(),c=uu(s.index,(d=l[l.indexOf(s)+1])==null?void 0:d.index);if(this.createPage({name:s.name+" Copy",id:r,index:c}),this.setCurrentPage(r),this.setCamera(i),a)return this.putContentOntoCurrentPage(a)}),this}renamePage(t,r){const o=typeof t=="string"?t:t.id;return this.getInstanceState().isReadonly?this:(this.updatePage({id:o,name:r}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.history.ignore(()=>this.store.put(t)),this)}updateAssets(t){return this.getInstanceState().isReadonly?this:t.length<=0?this:(this.history.ignore(()=>{this.store.put(t.map(r=>({...this.store.get(r.id),...r})))}),this)}deleteAssets(t){if(this.getInstanceState().isReadonly)return this;const r=typeof t[0]=="string"?t:t.map(o=>o.id);return r.length<=0?this:(this.history.ignore(()=>this.store.remove(r)),this)}getAsset(t){return this.store.get(typeof t=="string"?t:t.id)}async resolveAssetUrl(t,r){if(!t)return"";const o=this.getAsset(t);if(!o)return"";const{screenScale:s,shouldResolveToOriginalImage:i}=r,l=Math.max(.125,(h=>Math.pow(2,Math.ceil(Math.log2(h))))(s||1)),c="connection"in navigator?navigator.connection.effectiveType:null,d=this.getInstanceState().devicePixelRatio;return await this._assetOptions.get().onResolveAsset(o,{screenScale:s||1,steppedScreenScale:l,dpr:d,networkEffectiveType:c,shouldResolveToOriginalImage:i})}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",t=>this.getShapeUtil(t).getGeometry(t),(t,r)=>t.props===r.props)}getShapeGeometry(t){return this._getShapeGeometryCache().get(typeof t=="string"?t:t.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",t=>{var r,o;return(o=(r=this.getShapeUtil(t)).getHandles)==null?void 0:o.call(r,t)})}getShapeHandles(t){return this._getShapeHandlesCache().get(typeof t=="string"?t:t.id)}getShapeLocalTransform(t){const r=typeof t=="string"?t:t.id,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",t=>{if(In(t.parentId))return this.getShapeLocalTransform(t);const r=this._getShapePageTransformCache().get(t.parentId)??oe.Identity();return oe.Compose(r,this.getShapeLocalTransform(t))})}getShapeParentTransform(t){const r=typeof t=="string"?t:t.id,o=this.getShape(r);return!o||In(o.parentId)?oe.Identity():this._getShapePageTransformCache().get(o.parentId)??oe.Identity()}getShapePageTransform(t){const r=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(r)??oe.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",t=>{const r=this._getShapePageTransformCache().get(t.id);return r?Z.FromPoints(oe.applyToPoints(r,this.getShapeGeometry(t).vertices)):new Z})}getShapePageBounds(t){return this._getShapePageBoundsCache().get(typeof t=="string"?t:t.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",t=>{const r=this._getShapeMaskCache().get(t.id);if(!r)return;if(r.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const o=this._getShapePageTransformCache().get(t.id);return o?`polygon(${oe.applyToPoints(oe.Inverse(o),r).map(i=>`${i.x}px ${i.y}px`).join(",")})`:void 0})}getShapeClipPath(t){return this._getShapeClipPathCache().get(typeof t=="string"?t:t.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",t=>{if(In(t.parentId))return;const r=this.getShapeAncestors(t.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=_C(s,i);return a?a.map(w.Cast):[]})})}getShapeMask(t){return this._getShapeMaskCache().get(typeof t=="string"?t:t.id)}getShapeMaskedPageBounds(t){return typeof t!="string"&&(t=t.id),this._getShapeMaskedPageBoundsCache().get(t)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",t=>{const r=this._getShapePageBoundsCache().get(t.id);if(!r)return;const o=this._getShapeMaskCache().get(t.id);if(o){if(o.length===0)return;const{corners:s}=r;if(s.every((a,l)=>a&&w.Equals(a,o[l])))return r.clone();const i=_C(o,s);return i?Z.FromPoints(i):void 0}return r})}getShapeAncestors(t,r=[]){const o=typeof t=="string"?t:t.id,s=this.getShape(o);if(!s)return r;const i=s.parentId;if(In(i))return r.reverse(),r;const a=this.store.get(i);return a?(r.push(a),this.getShapeAncestors(a,r)):r}findShapeAncestor(t,r){const o=typeof t=="string"?t:t.id,s=this.getShape(o);if(!s)return;const i=s.parentId;if(In(i))return;const a=this.getShape(i);if(a)return r(a)?a:this.findShapeAncestor(a,r)}hasAncestor(t,r){const o=typeof t=="string"?t:t==null?void 0:t.id,s=o&&this.getShape(o);return s?s.parentId===r?!0:this.hasAncestor(this.getShapeParent(s),r):!1}findCommonAncestor(t,r){var c;if(t.length===0)return;const o=typeof t[0]=="string"?t:t.map(d=>d.id),s=me(o.map(d=>this.getShape(d)));if(s.length===1){const d=s[0].parentId;return In(d)?void 0:r?(c=this.findShapeAncestor(s[0],r))==null?void 0:c.id:d}const[i,...a]=s;let l=this.getShapeParent(i);for(;l;){if(r&&!r(l)){l=this.getShapeParent(l);continue}if(a.every(d=>this.hasAncestor(d,l.id)))return l.id;l=this.getShapeParent(l)}}isShapeOrAncestorLocked(t){const r=typeof t=="string"?this.getShape(t):t;return r===void 0?!1:r.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(r))}_notVisibleShapes(){return VW(this)}getCulledShapes(){const t=this._notVisibleShapes().get(),r=this.getSelectedShapeIds(),o=this.getEditingShapeId(),s=new Set(t);return o&&s.delete(o),r.forEach(i=>{s.delete(i)}),s}getCurrentPageBounds(){let t;return this.getCurrentPageShapeIdsSorted().forEach(r=>{const o=this.getShapeMaskedPageBounds(r);o&&(t?t=t.expand(o):t=o.clone())}),t}getSelectedShapeAtPoint(t){const r=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(o=>o.type!=="group"&&r.includes(o.id)).reverse().find(o=>this.isPointInShape(o,t,{hitInside:!0,margin:0}))}getShapeAtPoint(t,r={}){const o=this.getZoomLevel(),s=this.getViewportPageBounds(),{filter:i,margin:a=0,hitLocked:l=!1,hitLabels:c=!1,hitInside:d=!1,hitFrameInside:h=!1}=r;let p=1/0,f=null,S=1/0,g=null;const x=(r.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(y=>{if(y.isLocked&&!l||this.isShapeOfType(y,"group"))return!1;const v=this.getShapeMask(y);return v&&!tr(t,v)?!1:i?i(y):!0});for(let y=x.length-1;y>=0;y--){const v=x[y],b=this.getShapeGeometry(v),E=b instanceof Hr,I=this.getPointInShapeSpace(v,t);if((this.isShapeOfType(v,"arrow")||this.isShapeOfType(v,"geo")&&v.props.fill==="none")&&v.props.text.trim()){for(const k of b.children)if(k.isLabel&&k.isPointInBounds(I))return v}if(this.isShapeOfType(v,"frame")){const k=b.distanceToPoint(I,d);if(Math.abs(k)<=a)return g||v;if(b.hitTestPoint(I,0,!0))return g||f||(h?v:void 0);continue}let C;if(E){let k=1/0;for(const T of b.children){if(T.isLabel&&!c)continue;const O=T.distanceToPoint(I,d);Othis.isPointInShape(o,t,r))}isPointInShape(t,r,o={}){const{hitInside:s=!1,margin:i=0}=o,a=typeof t=="string"?t:t.id,l=this.getShapeMask(a);return l&&!tr(r,l)?!1:this.getShapeGeometry(a).hitTestPoint(this.getPointInShapeSpace(t,r),i,s)}getPointInShapeSpace(t,r){const o=typeof t=="string"?t:t.id;return this._getShapePageTransformCache().get(o).clone().invert().applyToPoint(r)}getPointInParentSpace(t,r){const o=typeof t=="string"?t:t.id,s=this.getShape(o);if(!s)return new w(0,0);if(In(s.parentId))return w.From(r);const i=this.getShapePageTransform(s.parentId);return i?i.clone().invert().applyToPoint(r):w.From(r)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),t=>this.store.get(t))}getCurrentPageShapesSorted(){const t=[],r=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let o=0,s=r.length;o!t.has(r))}isShapeOfType(t,r){const o=typeof t=="string"?this.getShape(t):t;return o?o.type===r:!1}getShape(t){const r=typeof t=="string"?t:t.id;if(kn(r))return this.store.get(r)}getShapeParent(t){const r=typeof t=="string"?t:t==null?void 0:t.id;if(!r)return;const o=this.getShape(r);if(!(o===void 0||!kn(o.parentId)))return this.store.get(o.parentId)}getShapeNearestSibling(t,r){return r?r.parentId===t.parentId?r:this.findShapeAncestor(r,s=>s.parentId===t.parentId):void 0}isShapeInPage(t,r=this.getCurrentPageId()){const o=typeof t=="string"?t:t.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(t){const r=typeof t=="string"?t:t==null?void 0:t.id,o=r&&this.getShape(r);if(o)return In(o.parentId)?o.parentId:this.getAncestorPageId(this.getShape(o.parentId))}reparentShapes(t,r,o){const s=typeof t[0]=="string"?t:t.map(S=>S.id);if(s.length===0)return this;const i=[],a=In(r)?oe.Identity():this.getShapePageTransform(r),l=a.rotation();let c=[];const d=me(this.getSortedChildIdsForParent(r).map(S=>this.getShape(S)));if(o){const S=d.find(g=>g.index===o);if(S){const g=d[d.indexOf(S)+1];g?c=gl(o,g.index,s.length):c=zm(o,s.length)}else{const g=d.sort(on).find(x=>x.index>o);g?c=gl(o,g.index,s.length):c=zm(o,s.length)}}else{const S=d.length&&d[d.length-1];c=S?zm(S.index,s.length):du(s.length)}const h=a.clone().invert(),p=me(s.map(S=>this.getShape(S))),f=p.filter(S=>S.isLocked);f.length&&this.updateShapes(f.map(({id:S,type:g})=>({id:S,type:g,isLocked:!1})));for(let S=0;Sthis.getShape(s)).sort(on))r.add(o.id),this.visitDescendants(o,s=>{r.add(s)});return r}getDroppingOverShape(t,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(l=>l.id===i.id||this.hasAncestor(i,l.id)))continue;const a=this.getShapeMaskedPageBounds(i.id);if(a&&a.containsPoint(t)&&this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(i,t),0,!0))return i}}getOutermostSelectableShape(t,r){const o=typeof t=="string"?t:t.id,s=this.getShape(o);let i=s,a=s;const l=this.getFocusedGroup();for(;a;){if(this.isShapeOfType(a,"group")&&(l==null?void 0:l.id)!==a.id&&!this.hasAncestor(l,a.id)&&((r==null?void 0:r(a))??!0))i=a;else if((l==null?void 0:l.id)===a.id)break;a=this.getShapeParent(a)}return i}_getBindingsIndexCache(){const t=WW(this);return this.store.createComputedCache("bindingsIndex",r=>t.get().get(r.id))}getBinding(t){return this.store.get(t)}getBindingsFromShape(t,r){const o=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(o).filter(s=>s.fromId===o&&s.type===r)}getBindingsToShape(t,r){const o=typeof t=="string"?t:t.id;return this.getBindingsInvolvingShape(o).filter(s=>s.toId===o&&s.type===r)}getBindingsInvolvingShape(t,r){const o=typeof t=="string"?t:t.id,s=this._getBindingsIndexCache().get(o)??Ho;return r?s.filter(i=>i.type===r):s}createBindings(t){const r=[];for(const o of t){const s=this.getShape(o.fromId),i=this.getShape(o.toId);if(!s||!i||!this.canBindShapes({fromShape:s,toShape:i,binding:o}))continue;const l=this.getBindingUtil(o.type).getDefaultProps(),c=this.store.schema.types.binding.create({...o,id:o.id??Ri(),props:{...l,...o.props}});r.push(c)}return this.store.put(r),this}createBinding(t){return this.createBindings([t])}updateBindings(t){const r=[];for(const o of t){if(!o)continue;const s=this.getBinding(o.id);if(!s)continue;const i=jo(s,o);if(i===s)continue;const a=this.getShape(i.fromId),l=this.getShape(i.toId);!a||!l||this.canBindShapes({fromShape:a,toShape:l,binding:i})&&r.push(i)}return this.store.put(r),this}updateBinding(t){return this.updateBindings([t])}deleteBindings(t,{isolateShapes:r=!1}={}){const o=t.map(s=>typeof s=="string"?s:s.id);return r?this.store.atomic(()=>{var s,i;for(const a of o){const l=this.getBinding(a);if(!l)continue;const c=this.getBindingUtil(l);(s=c.onBeforeIsolateFromShape)==null||s.call(c,{binding:l,removedShape:this.getShape(l.toId)}),(i=c.onBeforeIsolateToShape)==null||i.call(c,{binding:l,removedShape:this.getShape(l.fromId)}),this.store.remove([a])}}):this.store.remove(o),this}deleteBinding(t,r){return this.deleteBindings([t],r)}canBindShapes({fromShape:t,toShape:r,binding:o}){const s=typeof t=="string"?t:t.type,i=typeof r=="string"?r:r.type,a=typeof o=="string"?o:o.type,l={fromShapeType:s,toShapeType:i,bindingType:a};return s===i?this.getShapeUtil(s).canBind(l):this.getShapeUtil(s).canBind(l)&&this.getShapeUtil(i).canBind(l)}rotateShapesBy(t,r){if((typeof t[0]=="string"?t:t.map(i=>i.id)).length<=0)return this;const s=_2({editor:this});return s?(Oh({delta:r,snapshot:s,editor:this,stage:"one-off"}),this):this}getChangesToTranslateShape(t,r){var i,a,l;let o=t;const s=this.getShapeUtil(t);return o=jo(o,((i=s.onTranslateStart)==null?void 0:i.call(s,o))??void 0),o=jo(o,{id:t.id,type:t.type,x:r.x,y:r.y}),o=jo(o,((a=s.onTranslate)==null?void 0:a.call(s,t,o))??void 0),o=jo(o,((l=s.onTranslateEnd)==null?void 0:l.call(s,t,o))??void 0),o}nudgeShapes(t,r){const o=typeof t[0]=="string"?t:t.map(i=>i.id);if(o.length<=0)return this;const s=[];for(const i of o){const a=this.getShape(i),l=w.From(r),c=this.getShapeParentTransform(a);c&&l.rot(-c.rotation()),s.push(this.getChangesToTranslateShape(a,l.add(a)))}return this.updateShapes(s),this}duplicateShapes(t,r){return this.history.batch(()=>{const o=typeof t[0]=="string"?t:t.map(p=>p.id);if(o.length<=0)return this;const s=new Set(o),i=this.getShapeAndDescendantIds(o),a=[...i].reverse(),l=new Map;for(const p of i)l.set(p,$e());const{shapesToCreate:c,bindingsToCreate:d}=DC(this,i,p=>{const f=[];for(const g of p){const x=this.getBinding(g);if(!x)continue;const y=Ri();f.push({...x,id:y,fromId:Sr(l.get(x.fromId)),toId:Sr(l.get(x.toId))})}const S=[];for(const g of a){const x=Sr(l.get(g)),y=this.getShape(g);if(!y)continue;let v=0,b=0;if(r&&s.has(g)){const _=this.getShapeParentTransform(y),j=new w(r.x,r.y).rot(-_.rotation());v=j.x,b=j.y}const E=y.parentId,I=this.getSortedChildIdsForParent(E),C=I.indexOf(y.id),k=I[C+1],T=k?this.getShape(k):null,O=T?uu(y.index,T.index):Lo(y.index);S.push({...y,id:x,x:y.x+v,y:y.y+b,index:O,parentId:l.get(y.parentId)??y.parentId})}return{shapesToCreate:S,bindingsToCreate:f}});if(c.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage){Hd(this);return}if(this.createShapes(c),this.createBindings(d),this.setSelectedShapes(me(o.map(p=>l.get(p)))),r!==void 0){const p=this.getSelectionPageBounds(),f=this.getViewportPageBounds();p&&!f.contains(p)&&this.centerOnPoint(p.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(t,r){const o=typeof t[0]=="string"?t:t.map(l=>l.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>this.options.maxShapesPerPage)return Hd(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(t){const r=typeof t[0]=="string"?t:t.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 l=this.getShape(a);l&&(i.push(l),l.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(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id),o=Ud(this,"toBack",r);return o&&this.updateShapes(o),this}sendBackward(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id),o=Ud(this,"backward",r);return o&&this.updateShapes(o),this}bringForward(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id),o=Ud(this,"forward",r);return o&&this.updateShapes(o),this}bringToFront(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id),o=Ud(this,"toFront",r);return o&&this.updateShapes(o),this}flipShapes(t,r){const o=typeof t[0]=="string"?t:t.map(a=>a.id);if(this.getInstanceState().isReadonly)return this;let s=me(o.map(a=>this.getShape(a)));if(!s.length)return this;s=me(s.map(a=>this.isShapeOfType(a,"group")?this.getSortedChildIdsForParent(a.id).map(l=>this.getShape(l)):a).flat());const i=Z.Common(me(s.map(a=>this.getShapePageBounds(a)))).center;return this.batch(()=>{for(const a of s){const l=this.getShapeGeometry(a).bounds,c=this.getShapePageTransform(a.id);c&&this.resizeShape(a.id,{x:r==="horizontal"?-1:1,y:r==="vertical"?-1:1},{initialBounds:l,initialPageTransform:c,initialShape:a,mode:"scale_shape",isAspectRatioLocked:this.getShapeUtil(a).isAspectRatioLocked(a),scaleOrigin:i,scaleAxisRotation:0})}}),this}stackShapes(t,r,o){const s=typeof t[0]=="string"?t:t.map(x=>x.id);if(this.getInstanceState().isReadonly)return this;const i=s.map(x=>this.getShape(x)).filter(x=>x?this.getShapeUtil(x).canBeLaidOut(x):!1),a=i.length;if(o===0&&a<3||a<2)return this;const l=Object.fromEntries(i.map(x=>[x.id,this.getShapePageBounds(x)]));let c,d,h,p;r==="horizontal"?(c="x",d="minX",h="maxX",p="width"):(c="y",d="minY",h="maxY",p="height");let f;if(o===0){const x=[];i.sort((v,b)=>l[v.id][d]-l[b.id][d]);for(let v=0;vO.gap===k);T?T.count++:x.push({gap:k,count:1})}let y=0;x.forEach(v=>{v.count>y&&(y=v.count,f=v.gap)}),y===1&&(f=Math.max(0,x.reduce((v,b)=>v+b.gap*b.count,0)/(a-1)))}else f=o;const S=[];let g=l[i[0].id][h];return i.forEach((x,y)=>{var C,k;if(y===0)return;const v={x:0,y:0};v[c]=g+f-l[x.id][c];const b=this.getShapeParent(x),E=b?w.Rot(v,-this.getShapePageTransform(b).decompose().rotation):v,I=(k=(C=this.getShapeUtil(x)).onTranslateStart)==null?void 0:k.call(C,x);S.push(I?{...I,[c]:x[c]+E[c]}:{id:x.id,type:x.type,[c]:x[c]+E[c]}),g+=l[x.id][p]+f}),this.updateShapes(S),this}packShapes(t,r){var k,T;const o=typeof t[0]=="string"?t:t.map(O=>O.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=o.map(O=>this.getShape(O)).filter(O=>O?this.getShapeUtil(O).canBeLaidOut(O):!1),i={},a={};let l,c,d=0;for(let O=0;Oi[_.id].height-i[O.id].height);const f=Math.max(Math.ceil(Math.sqrt(d/.95)),p),S=[new Z(h.x,h.y,f,1/0)];let g=0,x=0,y,v;for(let O=0;O=0;_--)if(y=S[_],!(c.width>y.width||c.height>y.height)){c.x=y.x,c.y=y.y,x=Math.max(x,c.maxY),g=Math.max(g,c.maxX),c.width===y.width&&c.height===y.height?(v=S.pop(),_c.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=me(o.map(c=>this.getShape(c))),i=Object.fromEntries(s.map(c=>[c.id,this.getShapePageBounds(c)])),a=Z.Common(me(Object.values(i))),l=[];return s.forEach(c=>{const d=i[c.id];if(!d)return;const h={x:0,y:0};switch(r){case"top":{h.y=a.minY-d.minY;break}case"center-vertical":{h.y=a.midY-d.minY-d.height/2;break}case"bottom":{h.y=a.maxY-d.minY-d.height;break}case"left":{h.x=a.minX-d.minX;break}case"center-horizontal":{h.x=a.midX-d.minX-d.width/2;break}case"right":{h.x=a.maxX-d.minX-d.width;break}}const p=this.getShapeParent(c),f=p?w.Rot(h,-this.getShapePageTransform(p).decompose().rotation):h;l.push(this.getChangesToTranslateShape(c,w.Add(c,f)))}),this.updateShapes(l),this}distributeShapes(t,r){const o=typeof t[0]=="string"?t:t.map(b=>b.id);if(this.getInstanceState().isReadonly)return this;if(o.length<3)return this;const s=o.length,i=me(o.map(b=>this.getShape(b))),a=Object.fromEntries(i.map(b=>[b.id,this.getShapePageBounds(b)]));let l,c,d,h,p;r==="horizontal"?(l="x",c="minX",d="maxX",h="midX",p="width"):(l="y",c="minY",d="maxY",h="midY",p="height");const f=[],S=i.sort((b,E)=>a[b.id][c]-a[E.id][c])[0],g=i.sort((b,E)=>a[E.id][d]-a[b.id][d])[0],x=a[S.id][h],y=(a[g.id][h]-x)/(s-1),v=x+y;return i.filter(b=>b!==S&&b!==g).sort((b,E)=>a[b.id][h]-a[E.id][h]).forEach((b,E)=>{const I={x:0,y:0};I[l]=v+y*E-a[b.id][p]/2-a[b.id][l];const C=this.getShapeParent(b),k=C?w.Rot(I,-this.getShapePageTransform(C).rotation()):I;f.push(this.getChangesToTranslateShape(b,w.Add(b,k)))}),this.updateShapes(f),this}stretchShapes(t,r){const o=typeof t[0]=="string"?t:t.map(c=>c.id);if(this.getInstanceState().isReadonly)return this;if(o.length<2)return this;const s=me(o.map(c=>this.getShape(c))),i=Object.fromEntries(o.map(c=>[c,this.getShapeGeometry(c).bounds])),a=Object.fromEntries(o.map(c=>[c,this.getShapePageBounds(c)])),l=Z.Common(me(Object.values(a)));switch(r){case"vertical":{this.batch(()=>{for(const c of s){if(this.getShapePageTransform(c).rotation()%Re)continue;const h=i[c.id],p=a[c.id],f=new w(0,l.minY-p.minY),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:g,y:x}=w.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:g,y:x}]);const y=new w(1,l.height/p.height);this.resizeShape(c.id,y,{initialBounds:h,scaleOrigin:new w(p.center.x,l.minY),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}case"horizontal":{this.batch(()=>{for(const c of s){const d=i[c.id],h=a[c.id];if(this.getShapePageTransform(c).rotation()%Re)continue;const f=new w(l.minX-h.minX,0),S=this.getShapeParentTransform(c);S&&f.rot(-S.rotation());const{x:g,y:x}=w.Add(f,c);this.updateShapes([{id:c.id,type:c.type,x:g,y:x}]);const y=new w(l.width/h.width,1);this.resizeShape(c.id,y,{initialBounds:d,scaleOrigin:new w(l.minX,h.center.y),isAspectRatioLocked:this.getShapeUtil(c).isAspectRatioLocked(c),scaleAxisRotation:0})}});break}}return this}resizeShape(t,r,o={}){var S,g,x;const s=typeof t=="string"?t:t.id;if(this.getInstanceState().isReadonly)return this;Number.isFinite(r.x)||(r=new w(1,r.y)),Number.isFinite(r.y)||(r=new w(r.x,1));const i=o.initialShape??this.getShape(s);if(!i)return this;const a=o.scaleOrigin??((S=this.getShapePageBounds(s))==null?void 0:S.center);if(!a)return this;const l=o.initialPageTransform?oe.Cast(o.initialPageTransform):this.getShapePageTransform(s);if(!l)return this;const c=l.rotation();if(c==null)return this;const d=o.scaleAxisRotation??c,h=o.initialBounds??this.getShapeGeometry(s).bounds;if(!h)return this;const p=o.isAspectRatioLocked??this.getShapeUtil(i).isAspectRatioLocked(i);if(!UM(c,d))return this._resizeUnalignedShape(s,r,{...o,initialBounds:h,scaleOrigin:a,scaleAxisRotation:d,initialPageTransform:l,isAspectRatioLocked:p,initialShape:i});const f=this.getShapeUtil(i);if(p&&(Math.abs(r.x)>Math.abs(r.y)?r=new w(r.x,Math.sign(r.y)*Math.abs(r.x)):r=new w(Math.sign(r.x)*Math.abs(r.y),r.y)),f.onResize&&f.canResize(i)){const y=this._scalePagePoint(oe.applyToPoint(l,new w(0,0)),a,r,d),v=this.getPointInParentSpace(i.id,y),b=new w(r.x,r.y),E=Us((c-d)%Math.PI,0);b.x=E?r.x:r.y,b.y=E?r.y:r.x;const I=oe.applyToPoint(l,new w),{x:C,y:k}=this.getPointInParentSpace(i.id,I);let T=i;o.skipStartAndEndCallbacks||(T=jo(i,((g=f.onResizeStart)==null?void 0:g.call(f,i))??void 0)),T=jo(T,{id:s,type:i.type,x:v.x,y:v.y,...f.onResize({...i,x:C,y:k},{newPoint:v,handle:o.dragHandle??"bottom_right",mode:o.mode??"scale_shape",scaleX:b.x,scaleY:b.y,initialBounds:h,initialShape:i})}),o.skipStartAndEndCallbacks||(T=jo(T,((x=f.onResizeEnd)==null?void 0:x.call(f,i,T))??void 0)),this.updateShapes([T])}else{const y=oe.applyToPoint(l,h.center),v=this._scalePagePoint(y,a,r,d),b=this.getPointInParentSpace(i.id,y),E=this.getPointInParentSpace(i.id,v),I=w.Sub(E,b);this.updateShapes([{id:s,type:i.type,x:i.x+I.x,y:i.y+I.y}])}return this}_scalePagePoint(t,r,o,s){const i=w.RotWith(t,r,-s).sub(r),a=w.MulV(i,o);return w.Add(a,r).rotWith(r,s)}_resizeUnalignedShape(t,r,o){const{type:s}=o.initialShape,i=new w(r.x,r.y);if(Math.abs(r.x)>Math.abs(r.y)?i.x=Math.sign(r.x)*Math.abs(r.y):i.y=Math.sign(r.y)*Math.abs(r.x),this.resizeShape(t,i,{initialShape:o.initialShape,initialBounds:o.initialBounds,isAspectRatioLocked:o.isAspectRatioLocked}),Math.sign(r.x)*Math.sign(r.y)<0){let{rotation:y}=oe.Decompose(o.initialPageTransform);y-=2*y,this.updateShapes([{id:t,type:s,rotation:y}])}const a=oe.applyToPoint(o.initialPageTransform,o.initialBounds.center),l=this._scalePagePoint(a,o.scaleOrigin,r,o.scaleAxisRotation),c=this.getShapePageBounds(t),d=this.getShapePageTransform(t),h=c.center,p=d.point();if(!h||!p)return this;const f=w.Sub(l,h),S=w.Add(p,f),{x:g,y:x}=this.getPointInParentSpace(t,S);return this.updateShapes([{id:t,type:s,x:g,y:x}]),this}getInitialMetaForShape(t){return{}}createShape(t){return this.createShapes([t]),this}createShapes(t){if(!Array.isArray(t))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getInstanceState().isReadonly)return this;if(t.length<=0)return this;const r=this.getCurrentPageShapeIds();if(t.length+r.size>this.options.maxShapesPerPage)return Hd(this),this;const s=this.getFocusedGroupId();return this.batch(()=>{var h,p;const i=this.getCurrentPageShapesSorted(),a=t.map(f=>{if(f.id||(f={id:$e(),...f}),!f.parentId||!(this.store.has(f.parentId)||t.some(S=>S.id===f.parentId))){let S=this.getFocusedGroupId();for(let x=i.length-1;x>=0;x--){const y=i[x];if(this.getShapeUtil(y).canReceiveNewChildrenOfType(y,f.type)&&this.isPointInShape(y,{x:f.x??0,y:f.y??0},{margin:0,hitInside:!0})){S=y.id;break}}const g=f.parentId;if(S===f.id&&(S=s),S!==g&&(f={...f},f.parentId=S,kn(S))){const x=this.getPointInShapeSpace(this.getShape(S),{x:f.x??0,y:f.y??0});f.x=x.x,f.y=x.y,f.rotation=-this.getShapePageTransform(S).rotation()+(f.rotation??0)}}return f}),l=new Map,c=[],{opacityForNextShape:d}=this.getInstanceState();for(const f of a){const S=this.getShapeUtil(f);let g=f.index;if(!g){const b=f.parentId??s;l.has(b)||l.set(b,this.getHighestIndexForParent(b)),g=l.get(b),l.set(b,Lo(g))}const x=S.getDefaultProps();for(const[b,E]of this.styleProps[f.type])x[E]=this.getStyleForNextShape(b);let y=this.store.schema.types.shape.create({...f,index:g,opacity:f.opacity??d,parentId:f.parentId??s,props:"props"in f?{...x,...f.props}:x});if(y.index===void 0)throw Error("no index!");const v=(p=(h=this.getShapeUtil(y)).onBeforeCreate)==null?void 0:p.call(h,y);v&&(y=v),c.push(y)}c.forEach(f=>{f.meta={...this.getInitialMetaForShape(f),...f.meta}}),this.store.put(c)})}animateShape(t,r={animation:Gm}){return this.animateShapes([t],r)}animateShapes(t,r={animation:Gm}){if(!r.animation)return this;const{duration:o=500,easing:s=jt.linear}=r.animation,i=ot();let a=o,l;const c=[];let d,h;for(let S=0,g=t.length;S{if(a-=S,a<0){const{animatingShapes:v}=this,b=t.filter(E=>E&&v.get(E.id)===i);b.length&&this.updateShapes(b),this.off("tick",f);return}l=s(1-a/o);const{animatingShapes:g}=this,x=[];let y;for(let v=0,b=c.length;v(E[I]=C+(k-C)*l,E),{})});this._updateShapes(x)};return this.on("tick",f),this}groupShapes(t,r={}){var g;const{groupId:o=$e(),select:s=!0}=r;if(!Array.isArray(t))throw Error("Editor.groupShapes: must provide an array of shapes or shape ids");if(this.getInstanceState().isReadonly)return this;const i=typeof t[0]=="string"?t:t.map(x=>x.id);if(i.length<=1)return this;const a=me(this._getUnlockedShapeIds(i).map(x=>this.getShape(x))),l=a.sort(on).map(x=>x.id),c=Z.Common(me(a.map(x=>this.getShapePageBounds(x)))),{x:d,y:h}=c.point,p=this.findCommonAncestor(a)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const f=a.filter(x=>x.parentId===p).sort(on),S=(g=f[f.length-1])==null?void 0:g.index;return this.batch(()=>{this.createShapes([{id:o,type:"group",parentId:p,index:S,x:d,y:h,opacity:1,props:{}}]),this.reparentShapes(l,o),s&&this.select(o)}),this}ungroupShapes(t,r={}){const{select:o=!0}=r,s=typeof t[0]=="string"?t:t.map(l=>l.id);if(this.getInstanceState().isReadonly)return this;if(s.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const i=new Set,a=[];return me(s.map(l=>this.getShape(l))).forEach(l=>{this.isShapeOfType(l,"group")?a.push(l):i.add(l.id)}),a.length===0?this:(this.batch(()=>{let l;for(let c=0,d=a.length;cc.id)),o&&this.select(...i)}),this)}updateShape(t){return this.updateShapes([t]),this}updateShapes(t){const r=Array(t.length);for(let o=0,s=t.length;o{var o;return!((o=this.getShape(r))!=null&&o.isLocked)})}deleteShapes(t){if(!Array.isArray(t))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const r=this._getUnlockedShapeIds(typeof t[0]=="string"?t:t.map(i=>i.id));if(this.getInstanceState().isReadonly)return this;if(r.length===0)return this;const o=new Set(r);for(const i of r)this.visitDescendants(i,a=>{o.add(a)});const s=[...o];return this.batch(()=>this.store.remove(s))}deleteShape(t){return this.deleteShapes([typeof t=="string"?t:t.id]),this}_extractSharedStyles(t,r){if(this.isShapeOfType(t,"group")){const o=this._parentIdsToChildIds.get()[t.id];if(!o)return;for(let s=0,i=o.length;s0)return this._getSelectionSharedStyles();const t=this.root.getCurrent(),r=new vv;if(!t)return r;if(t.shapeType)for(const o of this.styleProps[t.shapeType].keys())r.applyValue(o,this.getStyleForNextShape(o));return r}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const t=[],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 t.push(i)};for(const s of this.getSelectedShapeIds())r(s);let o=null;for(const s of t)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(t,r){return this.updateInstanceState({opacityForNextShape:t},r),this}setOpacityForSelectedShapes(t){const r=this.getSelectedShapes();if(r.length>0){const o=[],s=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i);for(const l of a)s(this.getShape(l))}else o.push(i)};for(const i of r)s(i);this.updateShapes(o.map(i=>({id:i.id,type:i.type,opacity:t})))}return this}setStyleForNextShapes(t,r,o){const s=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...s,[t.id]:r}},o),this}setStyleForSelectedShapes(t,r){const o=this.getSelectedShapes();if(o.length>0){const s=[],i=a=>{if(this.isShapeOfType(a,"group")){const l=this.getSortedChildIdsForParent(a.id);for(const c of l)i(this.getShape(c))}else{const l=this.getShapeUtil(a),c=this.styleProps[a.type].get(t);if(c){const d={id:a.id,type:a.type,props:{[c]:r}};s.push({util:l,originalShape:a,updatePartial:d})}}};for(const a of o)i(a);this.updateShapes(s.map(({updatePartial:a})=>a))}return this}registerExternalAssetHandler(t,r){return this.externalAssetContentHandlers[t]=r,this}async getAssetForExternalContent(t){var r,o;return await((o=(r=this.externalAssetContentHandlers)[t.type])==null?void 0:o.call(r,t))}hasExternalAssetHandler(t){return!!this.externalAssetContentHandlers[t]}registerExternalContentHandler(t,r){return this.externalContentHandlers[t]=r,this}async putExternalContent(t){var r,o;return(o=(r=this.externalContentHandlers)[t.type])==null?void 0:o.call(r,t)}getContentFromCurrentPage(t){const r=typeof t[0]=="string"?t:t.map(s=>s.id);if(!r||r.length===0)return;const o=this.getShapeAndDescendantIds(r);return DC(this,o,s=>{const i=[];for(const h of s){const p=this.getBinding(h);p&&i.push(p)}const a=[],l=[];for(const h of o){const p=this.getShape(h);if(!p)continue;if(!o.has(p.parentId)){const S=this.getShapePageTransform(p.id),g=S.point();l.push({...p,x:g.x,y:g.y,rotation:S.rotation(),parentId:this.getCurrentPageId()}),a.push(p.id)}else l.push(p)}const c=[],d=new Set;for(const h of l){if(!("assetId"in h.props))continue;const p=h.props.assetId;if(!p||d.has(p))continue;d.add(p);const f=this.getAsset(p);f&&c.push(f)}return{schema:this.store.schema.serialize(),shapes:l,rootShapeIds:a,bindings:i,assets:c}})}async resolveAssetsInContent(t){if(!t)return;const r=[];return await Promise.allSettled(t.assets.map(async o=>{var s,i;if((o.type==="image"||o.type==="video")&&!((s=o.props.src)!=null&&s.startsWith("data:image"))&&!((i=o.props.src)!=null&&i.startsWith("http"))){const a=rt(o),l=await this._assetOptions.get().onResolveAsset(o,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginalImage:!0});a.props.src=await Oi.blobToDataUrl(await yo(l).then(c=>c.blob())),r.push(a)}else r.push(o)})),t.assets=r,t}putContentOntoCurrentPage(t,r={}){var j,L;if(this.getInstanceState().isReadonly)return this;if(!t.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 l=this.getCurrentPageId(),{rootShapeIds:c}=t,d=[],h=[],p=[],f={store:{...Object.fromEntries(t.assets.map(A=>[A.id,A])),...Object.fromEntries(t.shapes.map(A=>[A.id,A])),...Object.fromEntries(((j=t.bindings)==null?void 0:j.map(A=>[A.id,A]))??[])},schema:t.schema},S=this.store.schema.migrateStoreSnapshot(f);if(S.type==="error")throw Error("Could not put content: could not migrate content");for(const A of Object.values(S.value))switch(A.typeName){case"asset":{d.push(A);break}case"shape":{h.push(A);break}case"binding":{p.push(A);break}}const g=new Map(s?h.map(A=>[A.id,A.id]):h.map(A=>[A.id,$e()])),x=new Map(s?p.map(A=>[A.id,A.id]):p.map(A=>[A.id,Ri()]));let y=this.getCurrentPageId(),v=1/0,b=[];for(const A of this.getSelectedShapes()){if(v===0)break;const R=this.isShapeOfType(A,"frame"),F=this.getShapeAncestors(A);R&&F.push(A);const W=R?F.length+1:F.length;if(WF.id===c[0]);this.isShapeOfType(A,"frame")&&this.isShapeOfType(R,"frame")&&R.props.w===(A==null?void 0:A.props.w)&&R.props.h===(A==null?void 0:A.props.h)&&(E=!0)}}else y=l}E||(E=g.has(y)),E&&(y=this.getShape(y).parentId);let I=this.getHighestIndexForParent(y);const C=[],k=h.map(A=>{const R=g.get(A.id),F={...A,id:R};return c.includes(A.id)&&(F.parentId=l,C.push(F)),g.has(F.parentId)?F.parentId=g.get(A.parentId):(c.push(F.id),F.index=I,I=Lo(I)),F});if(k.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage)return Hd(this),this;const T=p.map(A=>({...A,id:Sr(x.get(A.id)),fromId:Sr(g.get(A.fromId)),toId:Sr(g.get(A.toId))})),O=[],_=[];for(const A of d)this.store.has(A.id)||((A.type==="image"||A.type==="video")&&((L=A.props.src)!=null&&L.startsWith("data:image"))&&(_.push(rt(A)),A.props.src=null),O.push(A));return Promise.allSettled(_.map(async A=>{const R=await NW(A.props.src,A.props.name,A.props.mimeType??"image/png"),F=await this.getAssetForExternalContent({type:"file",file:R});if(!F){this.deleteAssets([A.id]);return}this.updateAssets([{...F,id:A.id}])})),this.batch(()=>{O.length>0&&this.createAssets(O),this.createShapes(k),this.createBindings(T),o&&this.select(...C.map(K=>K.id)),y!==l&&this.reparentShapes(C.map(K=>K.id),y);const A=k.map(K=>this.getShape(K.id)),R=Z.Common(A.map(K=>this.getShapePageBounds(K)));if(a===void 0)if(In(y)){const K=this.getViewportPageBounds();i||K.includes(Z.From(R))?a=R.center:a=K.center}else{const K=this.getShape(y);a=oe.applyToPoint(this.getShapePageTransform(K),this.getShapeGeometry(K).bounds.center)}if(C.length===1){const K=C[0];if(this.isShapeOfType(K,"frame"))for(;this.getShapesAtPoint(a).some(z=>this.isShapeOfType(z,"frame")&&z.props.w===K.props.w&&z.props.h===K.props.h);)a.x+=R.w+16}const F=Z.Common(me(C.map(({id:K})=>this.getShapePageBounds(K)))).center,W=w.Sub(a,F);this.updateShapes(C.map(({id:K})=>{const z=this.getShape(K),U=this.getShapeParentTransform(K).decompose().rotation,X=w.Rot(W,-U);return{id:z.id,type:z.type,x:z.x+X.x,y:z.y+X.y}}))}),this}async getSvgElement(t,r={}){const o=await ZW(this,t,r);if(!o)return;const s=document.createDocumentFragment(),i=w_(s);ra.flushSync(()=>{i.render(o.jsx)});const a=s.firstElementChild;return st(a instanceof SVGSVGElement,"Expected an SVG element"),i.unmount(),{svg:a,width:o.width,height:o.height}}async getSvgString(t,r={}){const o=await this.getSvgElement(t,r);return o?{svg:new XMLSerializer().serializeToString(o.svg),width:o.width,height:o.height}:void 0}async getSvg(t,r={}){const o=await this.getSvgElement(t,r);if(o)return o.svg}_updateInputsFromEvent(t){const{pointerVelocity:r,previousScreenPoint:o,previousPagePoint:s,currentScreenPoint:i,currentPagePoint:a}=this.inputs,{screenBounds:l}=this.store.unsafeGetWithoutCapture(gn),{x:c,y:d,z:h}=this.store.unsafeGetWithoutCapture(this.getCameraId()),p=t.point.x-l.x,f=t.point.y-l.y,S=t.point.z??.5;o.setTo(i),s.setTo(a),i.set(p,f);const g=p/h-c,x=f/h-d;isFinite(g)&&isFinite(x)&&a.set(g,x,S),this.inputs.isPen=t.type==="pointer"&&t.isPen,(t.name==="pointer_down"||this.inputs.isPinching)&&(r.set(0,0),this.inputs.originScreenPoint.setTo(i),this.inputs.originPagePoint.setTo(a)),this.history.ignore(()=>{var y;this.store.put([{id:of,typeName:"pointer",x:a.x,y:a.y,lastActivityTimestamp:t.type==="pointer"&&t.pointerId===aC.CAMERA_MOVE?((y=this.store.unsafeGetWithoutCapture(of))==null?void 0:y.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}focus({focusContainer:t=!0}={}){return t&&this.focusManager.focus(),this.updateInstanceState({isFocused:!0}),this}blur({blurContainer:t=!0}={}){return this.getIsFocused()?(t?this.focusManager.blur():this.complete(),this.updateInstanceState({isFocused:!1}),this):this}getIsFocused(){return this.getInstanceState().isFocused}getSnapshot(){return MW(this.store)}loadSnapshot(t){return P2(this.store,t),this}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_flushEventsForTick(t){this.batch(()=>{if(this._pendingEventsForNextTick.length>0){const r=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const o of r)this._flushEventForTick(o)}t>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:t}),this.scribbles.tick(t)})}maybeTrackPerformance(t){wt.measurePerformance.get()&&(this.performanceTracker.isStarted()?clearTimeout(this.performanceTrackerTimeout):this.performanceTracker.start(t),this.performanceTrackerTimeout=this.timers.setTimeout(()=>{this.performanceTracker.stop()},50))}}ne([V],Q.prototype,"getCanUndo");ne([V],Q.prototype,"getCanRedo");ne([V],Q.prototype,"getPath");ne([V],Q.prototype,"getCurrentTool");ne([V],Q.prototype,"getCurrentToolId");ne([V],Q.prototype,"getDocumentSettings");ne([V],Q.prototype,"getInstanceState");ne([V],Q.prototype,"getOpenMenus");ne([V],Q.prototype,"getIsMenuOpen");ne([V],Q.prototype,"getPageStates");ne([V],Q.prototype,"_getPageStatesQuery");ne([V],Q.prototype,"getCurrentPageState");ne([V],Q.prototype,"_getCurrentPageStateId");ne([V],Q.prototype,"getSelectedShapeIds");ne([V],Q.prototype,"getSelectedShapes");ne([V],Q.prototype,"getOnlySelectedShapeId");ne([V],Q.prototype,"getOnlySelectedShape");ne([V],Q.prototype,"getSelectionPageBounds");ne([V],Q.prototype,"getSelectionRotation");ne([V],Q.prototype,"getSelectionRotatedPageBounds");ne([V],Q.prototype,"getSelectionRotatedScreenBounds");ne([V],Q.prototype,"getFocusedGroupId");ne([V],Q.prototype,"getFocusedGroup");ne([V],Q.prototype,"getEditingShapeId");ne([V],Q.prototype,"getEditingShape");ne([V],Q.prototype,"getHoveredShapeId");ne([V],Q.prototype,"getHoveredShape");ne([V],Q.prototype,"getHintingShapeIds");ne([V],Q.prototype,"getHintingShape");ne([V],Q.prototype,"getErasingShapeIds");ne([V],Q.prototype,"getErasingShapes");ne([V],Q.prototype,"getCameraId");ne([V],Q.prototype,"getCamera");ne([V],Q.prototype,"getViewportPageBoundsForFollowing");ne([V],Q.prototype,"getCameraForFollowing");ne([V],Q.prototype,"getZoomLevel");ne([V],Q.prototype,"getViewportScreenBounds");ne([V],Q.prototype,"getViewportScreenCenter");ne([V],Q.prototype,"getViewportPageBounds");ne([V],Q.prototype,"_getCollaboratorsQuery");ne([V],Q.prototype,"getCollaborators");ne([V],Q.prototype,"getCollaboratorsOnCurrentPage");ne([V],Q.prototype,"getRenderingShapes");ne([V],Q.prototype,"_getAllPagesQuery");ne([V],Q.prototype,"getPages");ne([V],Q.prototype,"getCurrentPageId");ne([V],Q.prototype,"getCurrentPageShapeIdsSorted");ne([V],Q.prototype,"_getAllAssetsQuery");ne([V],Q.prototype,"_getShapeGeometryCache");ne([V],Q.prototype,"_getShapeHandlesCache");ne([V],Q.prototype,"_getShapePageTransformCache");ne([V],Q.prototype,"_getShapePageBoundsCache");ne([V],Q.prototype,"_getShapeClipPathCache");ne([V],Q.prototype,"_getShapeMaskCache");ne([V],Q.prototype,"_getShapeMaskedPageBoundsCache");ne([V],Q.prototype,"_notVisibleShapes");ne([V],Q.prototype,"getCulledShapes");ne([V],Q.prototype,"getCurrentPageBounds");ne([V],Q.prototype,"getCurrentPageShapes");ne([V],Q.prototype,"getCurrentPageShapesSorted");ne([V],Q.prototype,"getCurrentPageRenderingShapesSorted");ne([V],Q.prototype,"_getBindingsIndexCache");ne([V],Q.prototype,"_getSelectionSharedStyles");ne([V({isEqual:(e,n)=>e.equals(n)})],Q.prototype,"getSharedStyles");ne([V],Q.prototype,"getSharedOpacity");ne([V],Q.prototype,"getIsFocused");function Hd(e,n=e.getCurrentPageId()){const t=e.getPage(n).name;e.emit("max-shapes",{name:t,pageId:n,count:e.options.maxShapesPerPage})}function jo(e,n){if(!n)return e;let t=null;const r=Object.entries(n);for(let o=0,s=r.length;o{const o=e.store.extractingChanges(()=>{const s=new Set,i=new Set;for(const a of n)if(e.getShape(a))for(const c of e.getBindingsInvolvingShape(a)){const d=n.has(c.fromId),h=n.has(c.toId);if(d&&h){s.add(c.id);continue}(!d||!h)&&i.add(c.id)}e.deleteBindings([...i],{isolateShapes:!0});try{r=Ns.ok(t(s))}catch(a){r=Ns.err(a)}});e.store.applyDiff(lv(o))}),r.ok)return r.value;throw r.error}function RC(e,n){if(!n.constraints)throw Error("Should have constraints here");const{padding:{x:t,y:r}}=n.constraints,o=e.getViewportScreenBounds(),s=Z.From(n.constraints.bounds),i=(o.w-t*2)/s.w,a=(o.h-r*2)/s.h;return{zx:i,zy:a}}function Wu(){const e=B(),n=M2();return G("isDarkMode",()=>(n==null?void 0:n.isDarkMode)??e.user.getIsDarkMode(),[n,e])}const LC="",$C="",Kd='';function ms(e,n,t,r,o,s=16,i=16){const a=(-t-n)*(_e/180),l=Math.sin(a),c=Math.cos(a),d=1*c-1*l,h=1*l+1*c;return`url("data:image/svg+xml,`+e.replaceAll('"',"'")+`") ${s} ${i}, pointer`}const MG=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],jG={none:()=>"none","ew-resize":(e,n,t)=>ms($C,e,0,n,t),"ns-resize":(e,n,t)=>ms($C,e,90,n,t),"nesw-resize":(e,n,t)=>ms(LC,e,0,n,t),"nwse-resize":(e,n,t)=>ms(LC,e,90,n,t),"nwse-rotate":(e,n,t)=>ms(Kd,e,0,n,t),"nesw-rotate":(e,n,t)=>ms(Kd,e,90,n,t),"senw-rotate":(e,n,t)=>ms(Kd,e,180,n,t),"swne-rotate":(e,n,t)=>ms(Kd,e,270,n,t)};function Gn(e,n=0,t="black"){return jG[e](Z9(n),!1,t)}function AG(){const e=B(),n=un(),t=Wu();Bs("useCursor",()=>{const{type:r,rotation:o}=e.getInstanceState().cursor;if(MG.includes(r)){n.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}n.style.setProperty("--tl-cursor",Gn(r,o,t?"white":"black"))},[e,n,t])}function OG(){const e=B(),n=un(),t=Wu(),r=G(wt.forceSrgb);xe.useEffect(()=>{t?(n.setAttribute("data-color-mode","dark"),n.classList.remove("tl-theme__light"),n.classList.add("tl-theme__dark")):(n.setAttribute("data-color-mode","light"),n.classList.remove("tl-theme__dark"),n.classList.add("tl-theme__light")),r?n.classList.add("tl-theme__force-sRGB"):n.classList.remove("tl-theme__force-sRGB")},[e,n,r,t])}function qw(e){const n=P.useRef();return P.useLayoutEffect(()=>{n.current=e}),P.useDebugValue(e),P.useCallback((...t)=>{const r=n.current;return st(r,"fn does not exist"),r(...t)},[])}function DG(){const[e,n]=P.useState(0);P.useEffect(()=>n(t=>t+1),[])}function RG(){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 LG(){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 $G=(e,n)=>n.some(t=>e instanceof t);let FC,NC;function FG(){return FC||(FC=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function NG(){return NC||(NC=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const O2=new WeakMap,xv=new WeakMap,D2=new WeakMap,ey=new WeakMap,Zw=new WeakMap;function zG(e){const n=new Promise((t,r)=>{const o=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{t(Ko(e.result)),o()},i=()=>{r(e.error),o()};e.addEventListener("success",s),e.addEventListener("error",i)});return n.then(t=>{t instanceof IDBCursor&&O2.set(t,e)}).catch(()=>{}),Zw.set(n,e),n}function BG(e){if(xv.has(e))return;const n=new Promise((t,r)=>{const o=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{t(),o()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)});xv.set(e,n)}let wv={get(e,n,t){if(e instanceof IDBTransaction){if(n==="done")return xv.get(e);if(n==="objectStoreNames")return e.objectStoreNames||D2.get(e);if(n==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return Ko(e[n])},set(e,n,t){return e[n]=t,!0},has(e,n){return e instanceof IDBTransaction&&(n==="done"||n==="store")?!0:n in e}};function UG(e){wv=e(wv)}function HG(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(n,...t){const r=e.call(ty(this),n,...t);return D2.set(r,n.sort?n.sort():[n]),Ko(r)}:NG().includes(e)?function(...n){return e.apply(ty(this),n),Ko(O2.get(this))}:function(...n){return Ko(e.apply(ty(this),n))}}function KG(e){return typeof e=="function"?HG(e):(e instanceof IDBTransaction&&BG(e),$G(e,FG())?new Proxy(e,wv):e)}function Ko(e){if(e instanceof IDBRequest)return zG(e);if(ey.has(e))return ey.get(e);const n=KG(e);return n!==e&&(ey.set(e,n),Zw.set(n,e)),n}const ty=e=>Zw.get(e);function R2(e,n,{blocked:t,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(e,n),a=Ko(i);return r&&i.addEventListener("upgradeneeded",l=>{r(Ko(i.result),l.oldVersion,l.newVersion,Ko(i.transaction),l)}),t&&i.addEventListener("blocked",l=>t(l.oldVersion,l.newVersion,l)),a.then(l=>{s&&l.addEventListener("close",()=>s()),o&&l.addEventListener("versionchange",c=>o(c.oldVersion,c.newVersion,c))}).catch(()=>{}),a}function WG(e,{blocked:n}={}){const t=indexedDB.deleteDatabase(e);return n&&t.addEventListener("blocked",r=>n(r.oldVersion,r)),Ko(t).then(()=>{})}const GG=["get","getKey","getAll","getAllKeys","count"],VG=["put","add","delete","clear"],ny=new Map;function zC(e,n){if(!(e instanceof IDBDatabase&&!(n in e)&&typeof n=="string"))return;if(ny.get(n))return ny.get(n);const t=n.replace(/FromIndex$/,""),r=n!==t,o=VG.includes(t);if(!(t in(r?IDBIndex:IDBObjectStore).prototype)||!(o||GG.includes(t)))return;const s=async function(i,...a){const l=this.transaction(i,o?"readwrite":"readonly");let c=l.store;return r&&(c=c.index(a.shift())),(await Promise.all([c[t](...a),o&&l.done]))[0]};return ny.set(n,s),s}UG(e=>({...e,get:(n,t,r)=>zC(n,t)||e.get(n,t,r),has:(n,t)=>!!zC(n,t)||e.has(n,t)}));const lg="TLDRAW_DOCUMENT_v2",L2="TLDRAW_DB_NAME_INDEX_v2",Le={Records:"records",Schema:"schema",SessionState:"session_state"};async function cg(e,n){QG(e);const t=await R2(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 n(t)}finally{t.close()}}async function YG({persistenceKey:e,sessionId:n,didCancel:t}){const r=lg+e;if(Qw().includes(r))return await ZG({persistenceKey:e,didCancel:t}),await cg(r,async o=>{var h,p;if(t!=null&&t())return;const s=o.transaction([Le.Records,Le.Schema,Le.SessionState],"readonly"),i=s.objectStore(Le.Records),a=s.objectStore(Le.Schema),l=s.objectStore(Le.SessionState);let c=n?(h=await l.get(n))==null?void 0:h.snapshot:null;c||(c=(p=(await l.getAll()).sort((S,g)=>S.updatedAt-g.updatedAt).pop())==null?void 0:p.snapshot);const d={records:await i.getAll(),schema:await a.get(Le.Schema),sessionStateSnapshot:c};if(t!=null&&t()){s.abort();return}return await s.done,d})}async function XG({persistenceKey:e,schema:n,changes:t,sessionId:r,sessionStateSnapshot:o,didCancel:s}){const i=lg+e;await cg(i,async a=>{const l=a.transaction([Le.Records,Le.Schema,Le.SessionState],"readwrite"),c=l.objectStore(Le.Records),d=l.objectStore(Le.Schema),h=l.objectStore(Le.SessionState);for(const[p,f]of Object.entries(t.added))await c.put(f,p);for(const[p,f]of Object.values(t.updated))await c.put(f,f.id);for(const p of Object.keys(t.removed))await c.delete(p);if(d.put(n.serialize(),Le.Schema),o&&r?h.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together"),s!=null&&s())return l.abort();await l.done})}async function qG({persistenceKey:e,schema:n,snapshot:t,sessionId:r,sessionStateSnapshot:o,didCancel:s}){const i=lg+e;await cg(i,async a=>{const l=a.transaction([Le.Records,Le.Schema,Le.SessionState],"readwrite"),c=l.objectStore(Le.Records),d=l.objectStore(Le.Schema),h=l.objectStore(Le.SessionState);await c.clear();for(const[p,f]of Object.entries(t))await c.put(f,p);if(d.put(n.serialize(),Le.Schema),o&&r?h.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together"),s!=null&&s())return l.abort();await l.done})}async function ZG({persistenceKey:e,didCancel:n}){await cg(lg+e,async t=>{const r=t.transaction([Le.SessionState],"readwrite"),o=r.objectStore(Le.SessionState),s=(await o.getAll()).sort((a,l)=>a.updatedAt-l.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(n!=null&&n())return r.abort();await r.done})}function Qw(){const e=JSON.parse(bw(L2)||"[]")??[];return Array.isArray(e)?e:[]}function QG(e){const n=new Set(Qw());n.add(e),Pw(L2,JSON.stringify([...n]))}const JG=350,eV=1e4,BC=Symbol("UPDATE_INSTANCE_STATE"),tV=e=>e;class nV{constructor(n){m(this,"onmessage")}postMessage(n){}close(){}}const rV=typeof BroadcastChannel>"u"?nV:BroadcastChannel;class oV{constructor(n,{persistenceKey:t,sessionId:r=hf,onLoad:o,onLoadError:s},i=new rV(`tldraw-tab-sync-${t}`)){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=n,this.channel=i,typeof window<"u"&&(window.tlsync=this),this.persistenceKey=t,this.sessionId=r,this.serializedSchema=this.store.schema.serialize(),this.$sessionStateSnapshot=w2(this.store),this.disposables.add(n.listen(({changes:a})=>{this.diffQueue.push(a),this.channel.postMessage(tV({type:"diff",storeId:this.store.id,changes:a,schema:this.serializedSchema})),this.schedulePersist()},{source:"user",scope:"document"})),this.disposables.add(n.listen(()=>{this.diffQueue.push(BC),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(...n){this.isDebugging&&console.debug(...n)}async connect(n,t){this.debug("connecting");let r;try{r=await YG({persistenceKey:this.persistenceKey,sessionId:this.sessionId,didCancel:()=>this.didDispose})}catch(o){t(o),LG(),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??_W(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),t(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&&b2(this.store,s)}this.channel.onmessage=({data:o})=>{var a,l;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){t(new Error("Schema mismatch, please close other tabs and reload the page"));return}this.debug("reloading"),this.isReloading=!0,(l=(a=window==null?void 0:window.location)==null?void 0:a.reload)==null||l.call(a);return}s.type==="diff"&&(this.debug("applying diff"),zs(()=>{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()}),n(this)}catch(o){if(this.debug("error loading data from store",o),this.didDispose)return;t(o);return}}close(){this.debug("closing"),this.didDispose=!0,this.disposables.forEach(n=>n())}schedulePersist(){this.debug("schedulePersist",this.scheduledPersistTimeout),!this.scheduledPersistTimeout&&(this.scheduledPersistTimeout=setTimeout(()=>{this.scheduledPersistTimeout=null,this.persistIfNeeded()},this.didLastWriteError?eV:JG))}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(){st(!this.isPersisting,"persist already in progress"),this.isPersisting=!0,this.debug("doPersist start");const n=this.diffQueue;this.diffQueue=[];try{if(this.shouldDoFullDBWrite)this.shouldDoFullDBWrite=!1,await qG({persistenceKey:this.persistenceKey,schema:this.store.schema,snapshot:this.store.serialize(),didCancel:()=>this.didDispose,sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()});else{const t=Iw(n.filter(r=>r!==BC));await XG({persistenceKey:this.persistenceKey,changes:t,schema:this.store.schema,didCancel:()=>this.didDispose,sessionId:this.sessionId,sessionStateSnapshot:this.$sessionStateSnapshot.get()})}this.didLastWriteError=!1}catch(t){this.shouldDoFullDBWrite=!0,this.didLastWriteError=!0,console.error("failed to store changes in indexed db",t),RG(),typeof window<"u"&&window.location.reload()}this.isPersisting=!1,this.debug("doPersist end"),this.schedulePersist()}}function $2({initialData:e,defaultName:n="",id:t,...r}={}){const o="schema"in r&&r.schema?r.schema:B9({shapes:"shapeUtils"in r&&r.shapeUtils?UC(k2(r.shapeUtils)):void 0,bindings:"bindingUtils"in r&&r.bindingUtils?UC(C2(r.bindingUtils)):void 0,migrations:"migrations"in r?r.migrations:void 0});return new Tw({id:t,schema:o,initialData:e,props:{defaultName:n}})}function UC(e){return Object.fromEntries(e.map(n=>[n.type,{props:n.props,migrations:n.migrations}]))}function HC(e){const n=$2(e);return e.snapshot&&P2(n,e.snapshot),{store:n,opts:e}}function F2(e){const[n,t]=P.useState(()=>HC(e));if(!MT(n.opts,e)){const r=HC(e);return t(r),r.store}return n.store}function sV({persistenceKey:e,sessionId:n,...t}){const[r,o]=P.useState(null),s=F2(t);return P.useEffect(()=>{const i=ot();if(!e){o({id:i,storeWithStatus:{status:"not-synced",store:s}});return}o({id:i,storeWithStatus:{status:"loading"}});const a=c=>{o(d=>(d==null?void 0:d.id)===i?{id:i,storeWithStatus:c}:d)},l=new oV(s,{sessionId:n,persistenceKey:e,onLoad(){a({store:s,status:"synced-local"})},onLoadError(c){a({status:"error",error:c})}});return()=>{o(c=>(c==null?void 0:c.id)===i?null:c),l.close()}},[e,s,n]),(r==null?void 0:r.storeWithStatus)??{status:"loading"}}function iV(){const e=B(),n=un();P.useEffect(()=>{const t=s=>n.style.setProperty("--tl-zoom",s.toString()),r=CT(t,100),o=new Dl("useZoomCss",()=>{e.getCurrentPageShapeIds().size<300?t(e.getZoomLevel()):r(e.getZoomLevel())});return o.attach(),o.execute(),()=>{o.detach(),r.cancel()}},[e,n])}const aV=[],lV=[],cV=[],uV=P.memo(function({store:n,components:t,className:r,user:o,...s}){const[i,a]=xe.useState(null),l=P.useMemo(()=>o??y2(),[o]),c=(t==null?void 0:t.ErrorFallback)===void 0?u2:t==null?void 0:t.ErrorFallback,d={...s,shapeUtils:s.shapeUtils??aV,bindingUtils:s.bindingUtils??lV,tools:s.tools??cV,components:t};return u.jsx("div",{ref:a,draggable:!1,className:ce("tl-container tl-theme__light",r),onPointerDown:Kt,tabIndex:-1,children:u.jsx(fu,{fallback:c,onError:h=>xw(h,{tags:{origin:"react.tldraw-before-app"}}),children:i&&u.jsx(l7,{container:i,children:u.jsx(hW,{overrides:t,children:n?n instanceof Tw?u.jsx(z2,{...d,store:n,user:l}):u.jsx(N2,{...d,store:n,user:l}):u.jsx(dV,{...d,store:n,user:l})})})})})});function dV(e){const{defaultName:n,snapshot:t,initialData:r,shapeUtils:o,bindingUtils:s,persistenceKey:i,sessionId:a,user:l}=e,c=sV({shapeUtils:o,bindingUtils:s,initialData:r,persistenceKey:i,sessionId:a,defaultName:n,snapshot:t});return u.jsx(N2,{...e,store:c,user:l})}const N2=P.memo(function({store:n,user:t,...r}){const o=un();P.useLayoutEffect(()=>{t.userPreferences.get().colorScheme==="dark"&&(o.classList.remove("tl-theme__light"),o.classList.add("tl-theme__dark"))},[o,t]);const{LoadingScreen:s}=it();switch(n.status){case"error":throw n.error;case"loading":return s?u.jsx(s,{}):null}return u.jsx(z2,{...r,store:n.store,user:t})});function z2({onMount:e,children:n,store:t,tools:r,shapeUtils:o,bindingUtils:s,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:d,assetOptions:h,options:p}){const{ErrorFallback:f}=it(),S=un(),g=P.useRef(null),[x,y]=P.useState(null),v=g.current;x!==v&&y(v);const[b]=P.useState(l);P.useLayoutEffect(()=>{const C=new Q({store:t,shapeUtils:o,bindingUtils:s,tools:r,getContainer:()=>S,user:i,initialState:a,autoFocus:b,inferDarkMode:c,cameraOptions:d,assetOptions:h,options:p});return g.current=C,y(C),()=>{C.dispose()}},[S,o,s,r,t,i,a,b,c,d,h,p]);const E=P.useSyncExternalStore(P.useCallback(C=>v?(v.on("crash",C),()=>v.off("crash",C)):()=>{},[v]),()=>(v==null?void 0:v.getCrashingError())??null),{Canvas:I}=it();return v?u.jsx(fu,{fallback:f,onError:C=>v.annotateError(C,{origin:"react.tldraw",willCrashApp:!0}),children:E?u.jsx(pV,{crashingError:E}):u.jsx(og.Provider,{value:v,children:u.jsx(hV,{onMount:e,children:n??(I?u.jsx(I,{}):null)})})}):null}function hV({children:e,onMount:n}){return iV(),AG(),OG(),DG(),fV(n),u.jsx(u.Fragment,{children:e})}function pV({crashingError:e}){throw e}function Jw({children:e}){return u.jsx("div",{className:"tl-loading",children:e})}function B2({children:e}){return u.jsx("div",{className:"tl-loading",children:e})}function fV(e){const n=B(),t=qw(r=>{let o;return r.history.ignore(()=>{o=e==null?void 0:e(r),r.emit("mount")}),window.tldrawReady=!0,o});xe.useLayoutEffect(()=>{if(n)return t==null?void 0:t(n)},[n,t])}function Vi({children:e,className:n="",...t}){return u.jsx("div",{...t,className:ce("tl-html-container",n),children:e})}class Rh{constructor(n){this.editor=n}}m(Rh,"props"),m(Rh,"migrations"),m(Rh,"type");function U2(e,n,t={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:d=1/0}=t;let h=e.props.w*s,p=e.props.h*i;const f=new w(0,0);if(h>0){if(h0){if(pU2(t,r))}getGeometry(t){return new Jo({width:t.props.w,height:t.props.h,isFilled:!0})}getHandleSnapGeometry(t){return{points:this.getGeometry(t).bounds.cornersAndCenter}}}var jy;let gV=(jy=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(jy,"id","idle"),jy);var Ay;let mV=(Ay=class extends se{constructor(){super(...arguments);m(this,"markId","");m(this,"wasFocusedOnEnter",!1);m(this,"onEnter",()=>{this.wasFocusedOnEnter=!this.editor.getIsMenuOpen()});m(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,o=this.parent.shapeType,s=$e();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",{...t,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:t}=this.editor.inputs;if(!this.wasFocusedOnEnter)return;this.editor.mark(this.markId);const r=this.parent.shapeType,o=$e();this.editor.mark(this.markId),this.editor.createShapes([{id:o,type:r,x:t.x,y:t.y}]);const s=this.editor.getShape(o);if(!s){this.cancel();return}let{w:i,h:a}=s.props;const l=new w(i/2,a/2),c=this.editor.getShapeParentTransform(s);c&&l.rot(-c.rotation());let d=1;this.editor.user.getIsDynamicResizeMode()&&(d=1/this.editor.getZoomLevel(),i*=d,a*=d,l.mul(d));const h=rt(s);h.x=s.x-l.x,h.y=s.y-l.y,h.props.w=i,h.props.h=a,"scale"in s.props&&(h.props.scale=d),this.editor.updateShape(h),this.editor.setSelectedShapes([o]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},m(Ay,"id","pointing"),Ay);class Lh extends se{constructor(){super(...arguments);m(this,"onCreate")}}m(Lh,"id","box"),m(Lh,"initial","idle"),m(Lh,"children",()=>[gV,mV]);function ug(e){const n=B();return G("isEditing",()=>n.getEditingShapeId()===e,[n,e])}function yV(){return P.useId().replace(/:/g,"_")}function no(e){const n=B();return P.useMemo(function(){const o=c=>{if(c.isKilled)return;if(c.button===Fw){n.dispatch({type:"pointer",target:"selection",handle:e,name:"right_click",...On(c)});return}if(c.button!==0)return;const d=uf(c.currentTarget);function h(){d.removeEventListener("pointerup",h),zu(d,c)}Nu(d,c),d.addEventListener("pointerup",h),n.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:e,...On(c)}),Kt(c)};let s,i;function a(c){c.isKilled||c.button===0&&(c.clientX===s&&c.clientY===i||(s=c.clientX,i=c.clientY,n.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:e,...On(c)})))}return{onPointerDown:o,onPointerMove:a,onPointerUp:c=>{c.isKilled||c.button===0&&n.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:e,...On(c)})}}},[n,e])}const SV=20,vV=8;function e0(e,n=SV){return Math.max(vV,Math.ceil(e/n))}class Ha extends ai{constructor(t){super({...t,isFilled:!1,isClosed:!1});m(this,"_center");m(this,"radius");m(this,"start");m(this,"end");m(this,"largeArcFlag");m(this,"sweepFlag");m(this,"measure");m(this,"angleStart");m(this,"angleEnd");const{center:r,sweepFlag:o,largeArcFlag:s,start:i,end:a}=t;if(i.equals(a))throw Error("Arc must have different start and end points.");this.angleStart=w.Angle(r,i),this.angleEnd=w.Angle(r,a),this.radius=w.Dist(r,i),this.measure=Q9(this.angleStart,this.angleEnd,o,s),this.start=i,this.end=a,this.sweepFlag=o,this.largeArcFlag=s,this._center=r}nearestPoint(t){const{_center:r,measure:o,radius:s,angleEnd:i,angleStart:a,start:l,end:c}=this,d=gv(o,a,i,r.angle(t));if(d<=0)return l;if(d>=1)return c;const h=r.clone().add(t.clone().sub(r).uni().mul(s));let p,f=1/0,S;for(const g of[l,c,h])S=w.Dist2(t,g),S{const h=gv(i,a,l,o.angle(d));return h>=0&&h<=1})}getVertices(){const{_center:t,measure:r,length:o,radius:s,angleStart:i}=this,a=[];for(let l=0,c=e0(Math.abs(o));lt+r.length,0)}getVertices(){const t=this.segments.reduce((r,o)=>r.concat(o.vertices),[]);return t.push(this.points[this.points.length-1]),t}nearestPoint(t){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(t),s=w.Dist2(i,t),so.hitTestLineSegment(t,r))}getSvgPathData(){let t=this.segments.reduce((r,o,s)=>r+o.getSvgPathData(s===0),"");return this.isClosed&&(t+="Z"),t}}class wV extends ai{constructor(t){super({...t,isClosed:!0});m(this,"w");m(this,"h");m(this,"_edges");this.config=t;const{width:r,height:o}=t;this.w=r,this.h=o}get edges(){if(!this._edges){const{vertices:t}=this;this._edges=[];for(let r=0,o=t.length;ro.hitTestLineSegment(t,r))}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{w:t,h:r}=this,o=t/2,s=r/2,i=Math.max(0,o),a=Math.max(0,s);return zM(i,a)}getSvgPathData(t=!1){const{w:r,h:o}=this,s=r/2,i=o/2,a=Math.max(0,s),l=Math.max(0,i);return`${t?`M${s-a},${i}`:""} a${a},${l},0,1,1,${a*2},0a${a},${l},0,1,1,-${a*2},0`}}class bV extends ai{constructor(t){super({...t,isClosed:!0});m(this,"w");m(this,"h");m(this,"a");m(this,"b");m(this,"c");m(this,"d");this.config=t;const{width:r,height:o}=t;if(this.w=r,this.h=o,o>r){const s=r/2;this.a=new Ha({start:new w(0,s),end:new w(r,s),center:new w(r/2,s),sweepFlag:1,largeArcFlag:1}),this.b=new zo({start:new w(r,s),end:new w(r,o-s)}),this.c=new Ha({start:new w(r,o-s),end:new w(0,o-s),center:new w(r/2,o-s),sweepFlag:1,largeArcFlag:1}),this.d=new zo({start:new w(0,o-s),end:new w(0,s)})}else{const s=o/2;this.a=new Ha({start:new w(s,o),end:new w(s,0),center:new w(s,s),sweepFlag:1,largeArcFlag:1}),this.b=new zo({start:new w(s,0),end:new w(r-s,0)}),this.c=new Ha({start:new w(r-s,0),end:new w(r-s,o),center:new w(r-s,s),sweepFlag:1,largeArcFlag:1}),this.d=new zo({start:new w(r-s,o),end:new w(s,o)})}}nearestPoint(t){let r,o=1/0,s,i;const{a,b:l,c,d}=this;for(const h of[a,l,c,d])i=h.nearestPoint(t),s=w.Dist2(i,t),sl.hitTestLineSegment(t,r))}getVertices(){const{a:t,b:r,c:o,d:s}=this;return[t,r,o,s].reduce((i,a)=>(i.push(...a.vertices),i),[])}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{h:t,w:r}=this;return t>r?(_e*(r/2)+(t-r))*2:(_e*(t/2)+(r-t))*2}getSvgPathData(){const{a:t,b:r,c:o,d:s}=this;return[t,r,o,s].map((i,a)=>i.getSvgPathData(a===0)).join(" ")+" Z"}}async function PV({shouldReload:e=!0}={}){V6(),await Promise.all(Qw().map(n=>WG(n))),G6(),e&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=PV);function CV(e,n="_blank"){Hw.openWindow(e,n)}const H2="TLDRAW_ASSET_STORE_v1",ml={Assets:"assets"};async function K2(e,n){const t=await R2(e,1,{upgrade(r){r.objectStoreNames.contains(ml.Assets)||r.createObjectStore(ml.Assets)}});try{return await n(t)}finally{t.close()}}async function IV({persistenceKey:e,assetId:n}){const t=H2+e;return await K2(t,async r=>await r.transaction([ml.Assets],"readwrite").objectStore(ml.Assets).get(n))}async function EV({persistenceKey:e,assetId:n,blob:t}){const r=H2+e;await K2(r,async o=>{const s=o.transaction([ml.Assets],"readwrite");await s.objectStore(ml.Assets).put(t,n),await s.done})}function kV({children:e}){const n=B();return G("shouldDisplayHandles",()=>{if(n.isInAny("select.idle","select.pointing_handle","select.pointing_shape"))return!0;if(n.isInAny("select.editing_shape")){const r=n.getOnlySelectedShape();return r&&n.isShapeOfType(r,"note")}return!1},[n])?u.jsx("svg",{className:"tl-user-handles tl-overlays__item",children:e}):null}const{PI:_V}=Math,rl=_V+1e-4;function W2(e,n={}){const{size:t=16,smoothing:r=.5}=n;if(e.length===0||t<=0)return{left:[],right:[]};const o=e[0],s=e[e.length-1],i=s.runningLength,a=Math.pow(t*r,2),l=[],c=[];let d=e[0].vector,h=e[0].point,p=h,f=h,S=p,g=!1,x;for(let y=0;y-.62&&i-x.runningLength>x.radius){const _=d.clone().mul(x.radius);d.clone().cpr(I)<0?(f=w.Add(v,_),S=w.Sub(v,_)):(f=w.Sub(v,_),S=w.Add(v,_)),l.push(f),c.push(S)}else{const _=d.clone().mul(x.radius).per(),j=w.Sub(x.input,_);for(let L=1/13,A=0;A<1;A+=L)f=w.RotWith(j,x.input,rl*A),l.push(f),S=w.RotWith(j,x.input,rl+rl*-A),c.push(S)}h=f,p=S,T&&(g=!0);continue}if(g=!1,x===o||x===s){const _=w.Per(b).mul(x.radius);l.push(w.Sub(v,_)),c.push(w.Add(v,_));continue}const O=w.Lrp(I,b,C).per().mul(x.radius);f=w.Sub(v,O),(y<=1||w.Dist2(h,f)>a)&&(l.push(f),h=f),S=w.Add(v,O),(y<=1||w.Dist2(p,S)>a)&&(c.push(S),p=S),d=b}return{left:l,right:c}}function n0(e,n={}){const{size:t=16,start:r={},end:o={},last:s=!1}=n,{cap:i=!0}=r,{cap:a=!0}=o;if(e.length===0||t<=0)return[];const l=e[0],c=e[e.length-1],d=c.runningLength,h=r.taper===!1?0:r.taper===!0?Math.max(t,d):r.taper,p=o.taper===!1?0:o.taper===!0?Math.max(t,d):o.taper,{left:f,right:S}=W2(e,n),g=l.point,x=e.length>1?e[e.length-1].point:w.AddXY(l.point,1,1);if(e.length===1&&(!(h||p)||s)){const E=w.Add(g,w.Sub(g,x).uni().per().mul(-l.radius)),I=[];for(let C=1/13,k=C;k<=1;k+=C)I.push(w.RotWith(E,g,rl*2*k));return I}const y=[];if(!(h||p&&e.length===1))if(i)for(let E=1/8,I=E;I<=1;I+=E){const C=w.RotWith(S[0],g,rl*I);y.push(C)}else{const E=w.Sub(f[0],S[0]),I=w.Mul(E,.5),C=w.Mul(E,.51);y.push(w.Sub(g,I),w.Sub(g,C),w.Add(g,C),w.Add(g,I))}const v=[],b=c.vector.clone().per().neg();if(p||h&&e.length===1)v.push(x);else if(a){const E=w.Add(x,w.Mul(b,c.radius));for(let I=1/29,C=I;C<1;C+=I)v.push(w.RotWith(E,x,rl*3*C))}else v.push(w.Add(x,w.Mul(b,c.radius)),w.Add(x,w.Mul(b,c.radius*.99)),w.Sub(x,w.Mul(b,c.radius*.99)),w.Sub(x,w.Mul(b,c.radius)));return f.concat(v,S.reverse(),y)}const TV=.025,MV=.01;function xo(e,n={}){var x;const{streamline:t=.5,size:r=16,simulatePressure:o=!1}=n;if(e.length===0)return[];const s=.15+(1-t)*.85;let i=e.map(w.From),a=0;if(!o){let y=i[0];for(;y&&!(y.z>=TV);)i.shift(),y=i[0]}if(!o){let y=i[i.length-1];for(;y&&!(y.z>=MV);)i.pop(),y=i[i.length-1]}if(i.length===0)return[{point:w.From(e[0]),input:w.From(e[0]),pressure:o?.5:.15,vector:new w(1,1),distance:0,runningLength:0,radius:1}];let l=i[1];for(;l&&!(w.Dist2(l,i[0])>(r/3)**2);)i[0].z=Math.max(i[0].z,l.z),i.splice(1,1),l=i[1];const c=i.pop();for(l=i[i.length-1];l&&!(w.Dist2(l,c)>(r/3)**2);)i.pop(),l=i[i.length-1],a++;i.push(c);const d=n.last||!n.simulatePressure||i.length>1&&w.Dist2(i[i.length-1],i[i.length-2])0;if(i.length===2&&n.simulatePressure){const y=i[1];i=i.slice(0,-1);for(let v=1;v<5;v++){const b=w.Lrp(i[0],y,v/4);b.z=(i[0].z+(y.z-i[0].z))*v/4,i.push(b)}}const h=[{point:i[0],input:i[0],pressure:o?.5:i[0].z,vector:new w(1,1),distance:0,runningLength:0,radius:1}];let p=0,f=h[0],S,g;d&&t>0&&i.push(i[i.length-1].clone());for(let y=1,v=i.length;yv.pressure));h.forEach(v=>v.pressure=y)}return h}const{min:ys}=Math,ry=.275;function dg(e,n){const{size:t=16,thinning:r=.5,simulatePressure:o=!0,easing:s=x=>x,start:i={},end:a={}}=n,{easing:l=jt.easeOutQuad}=i,{easing:c=jt.easeOutCubic}=a,d=e[e.length-1].runningLength;let h,p=e[0].pressure,f;if(!o&&dMath.max(y,v.pressure),.5);return e.forEach(y=>{y.pressure=x,y.radius=t*s(.5-r*(.5-y.pressure))}),e}else{let x;for(let y=0,v=e.length;yt*5));y++){const b=ys(1,f.distance/t);if(o){const E=ys(1,1-b);x=ys(1,p+(E-p)*(b*ry))}else x=ys(1,p+(f.pressure-p)*.5);p=p+(x-p)*.5}for(let y=0;y{const t=B();return G("should display",()=>t.isInAny("select.idle","select.brushing","select.scribble_brushing","select.pointing_shape","select.pointing_selection","text.resizing"),[t])?u.jsx(i2,{bounds:e,rotation:n}):null};function is(){const e=B();return G("isReadonlyMode",()=>e.getInstanceState().isReadonly,[e])}function OV({size:e,width:n,height:t,hideAlternateHandles:r}){const o=N(e/3),s=o/2;return u.jsxs("svg",{className:"tl-overlays__item",children:[u.jsx("polyline",{className:"tl-corner-crop-handle",points:` ${N(0-s)},${N(e)} ${N(0-s)},${N(0-s)} ${N(e)},${N(0-s)}`,strokeWidth:o,"data-testid":"selection.crop.top_left","aria-label":"top_left handle"}),u.jsx("line",{className:ce("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(n/2-e),y1:N(0-s),x2:N(n/2+e),y2:N(0-s),strokeWidth:o,"data-testid":"selection.crop.top","aria-label":"top handle"}),u.jsx("polyline",{className:ce("tl-corner-crop-handle",{"tl-hidden":r}),points:` ${N(n-e)},${N(0-s)} ${N(n+s)},${N(0-s)} ${N(n+s)},${N(e)}`,strokeWidth:o,"data-testid":"selection.crop.top_right","aria-label":"top_right handle"}),u.jsx("line",{className:ce("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(n+s),y1:N(t/2-e),x2:N(n+s),y2:N(t/2+e),strokeWidth:o,"data-testid":"selection.crop.right","aria-label":"right handle"}),u.jsx("polyline",{className:"tl-corner-crop-handle",points:` ${N(n+s)},${N(t-e)} ${N(n+s)},${N(t+s)} ${N(n-e)},${N(t+s)}`,strokeWidth:o,"data-testid":"selection.crop.bottom_right","aria-label":"bottom_right handle"}),u.jsx("line",{className:ce("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(n/2-e),y1:N(t+s),x2:N(n/2+e),y2:N(t+s),strokeWidth:o,"data-testid":"selection.crop.bottom","aria-label":"bottom handle"}),u.jsx("polyline",{className:ce("tl-corner-crop-handle",{"tl-hidden":r}),points:` ${N(0+e)},${N(t+s)} ${N(0-s)},${N(t+s)} ${N(0-s)},${N(t-e)}`,strokeWidth:o,"data-testid":"selection.crop.bottom_left","aria-label":"bottom_left handle"}),u.jsx("line",{className:ce("tl-corner-crop-edge-handle",{"tl-hidden":r}),x1:N(0-s),y1:N(t/2-e),x2:N(0-s),y2:N(t/2+e),strokeWidth:o,"data-testid":"selection.crop.left","aria-label":"left handle"})]})}const DV=lr(function({bounds:n,rotation:t}){const r=B(),o=P.useRef(null),s=is(),i=no("top"),a=no("right"),l=no("bottom"),c=no("left"),d=no("top_left"),h=no("top_right"),p=no("bottom_right"),f=no("bottom_left"),S=!r.getIsMenuOpen()&&r.getInstanceState().cursor.type==="default",g=r.getInstanceState().isCoarsePointer,x=r.getOnlySelectedShape(),y=x&&r.isShapeOrAncestorLocked(x),v=x?r.getShapeUtil(x).expandSelectionOutlinePx(x):0;if(Rl(o,n==null?void 0:n.x,n==null?void 0:n.y,1,r.getSelectionRotation(),{x:-v,y:-v}),!n)return null;n=n.clone().expandBy(v).zeroFix();const b=r.getZoomLevel(),E=r.getInstanceState().isChangingStyle,I=n.width,C=n.height,k=8/b,T=I=4;return u.jsx("svg",{className:"tl-overlays__item tl-selection__fg","data-testid":"selection-foreground",children:u.jsxs("g",{ref:o,children:[U&&u.jsx("rect",{className:"tl-selection__fg__outline",width:N(I),height:N(C)}),u.jsx(Wd,{"data-testid":"selection.rotate.top-left",cx:0,cy:0,targetSize:F,corner:"top_left_rotate",cursor:S?Gn("nwse-rotate",t):void 0,isHidden:je}),u.jsx(Wd,{"data-testid":"selection.rotate.top-right",cx:I+F*3,cy:0,targetSize:F,corner:"top_right_rotate",cursor:S?Gn("nesw-rotate",t):void 0,isHidden:je}),u.jsx(Wd,{"data-testid":"selection.rotate.bottom-left",cx:0,cy:C+F*3,targetSize:F,corner:"bottom_left_rotate",cursor:S?Gn("swne-rotate",t):void 0,isHidden:je}),u.jsx(Wd,{"data-testid":"selection.rotate.bottom-right",cx:I+F*3,cy:C+F*3,targetSize:F,corner:"bottom_right_rotate",cursor:S?Gn("senw-rotate",t):void 0,isHidden:je}),u.jsx(LV,{"data-testid":"selection.rotate.mobile",cx:_?-F*1.5:I/2,cy:_?C/2:-F*1.5,size:k,isHidden:at}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.top","aria-label":"top target",pointerEvents:"all",x:0,y:N(0-(j?K*2:K)),width:N(I),height:N(Math.max(1,K*2)),style:S?{cursor:Gn("ns-resize",t)}:void 0,...i}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Xt}),"data-testid":"selection.resize.right","aria-label":"right target",pointerEvents:"all",x:N(I-(_?0:W)),y:0,height:N(C),width:N(Math.max(1,W*2)),style:S?{cursor:Gn("ew-resize",t)}:void 0,...a}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":St}),"data-testid":"selection.resize.bottom","aria-label":"bottom target",pointerEvents:"all",x:0,y:N(C-(j?0:K)),width:N(I),height:N(Math.max(1,K*2)),style:S?{cursor:Gn("ns-resize",t)}:void 0,...l}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Xt}),"data-testid":"selection.resize.left","aria-label":"left target",pointerEvents:"all",x:N(0-(_?W*2:W)),y:0,height:N(C),width:N(Math.max(1,W*2)),style:S?{cursor:Gn("ew-resize",t)}:void 0,...c}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Ne}),"data-testid":"selection.target.top-left","aria-label":"top-left target",pointerEvents:"all",x:N(0-(_?W*2:W*1.5)),y:N(0-(j?K*2:K*1.5)),width:N(W*3),height:N(K*3),style:S?{cursor:Gn("nwse-resize",t)}:void 0,...d}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Kn}),"data-testid":"selection.target.top-right","aria-label":"top-right target",pointerEvents:"all",x:N(I-(_?0:W*1.5)),y:N(0-(j?K*2:K*1.5)),width:N(W*3),height:N(K*3),style:S?{cursor:Gn("nesw-resize",t)}:void 0,...h}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Pn}),"data-testid":"selection.target.bottom-right","aria-label":"bottom-right target",pointerEvents:"all",x:N(I-(_?W:W*1.5)),y:N(C-(j?K:K*1.5)),width:N(W*3),height:N(K*3),style:S?{cursor:Gn("nwse-resize",t)}:void 0,...p}),u.jsx("rect",{className:ce("tl-transparent",{"tl-hidden":Rt}),"data-testid":"selection.target.bottom-left","aria-label":"bottom-left target",pointerEvents:"all",x:N(0-(_?W*3:W*1.5)),y:N(C-(j?0:K*1.5)),width:N(W*3),height:N(K*3),style:S?{cursor:Gn("nesw-resize",t)}:void 0,...f}),Me&&u.jsxs(u.Fragment,{children:[u.jsx("rect",{"data-testid":"selection.resize.top-left",className:ce("tl-corner-handle",{"tl-hidden":Ne}),"aria-label":"top_left handle",x:N(0-k/2),y:N(0-k/2),width:N(k),height:N(k)}),u.jsx("rect",{"data-testid":"selection.resize.top-right",className:ce("tl-corner-handle",{"tl-hidden":Kn}),"aria-label":"top_right handle",x:N(I-k/2),y:N(0-k/2),width:N(k),height:N(k)}),u.jsx("rect",{"data-testid":"selection.resize.bottom-right",className:ce("tl-corner-handle",{"tl-hidden":Pn}),"aria-label":"bottom_right handle",x:N(I-k/2),y:N(C-k/2),width:N(k),height:N(k)}),u.jsx("rect",{"data-testid":"selection.resize.bottom-left",className:ce("tl-corner-handle",{"tl-hidden":Rt}),"aria-label":"bottom_left handle",x:N(0-k/2),y:N(C-k/2),width:N(k),height:N(k)})]}),Bl&&u.jsxs(u.Fragment,{children:[u.jsx("rect",{"data-testid":"selection.text-resize.left.handle",className:"tl-text-handle","aria-label":"bottom_left handle",x:N(0-k/4),y:N(C/2-ko/2),rx:k/4,width:N(k/2),height:N(ko)}),u.jsx("rect",{"data-testid":"selection.text-resize.right.handle",className:"tl-text-handle","aria-label":"bottom_left handle",rx:k/4,x:N(I-k/4),y:N(C/2-ko/2),width:N(k/2),height:N(ko)})]}),X&&u.jsx(OV,{size:k,width:I,height:C,hideAlternateHandles:Ae})]})})}),Wd=function({cx:n,cy:t,targetSize:r,corner:o,cursor:s,isHidden:i,"data-testid":a}){const l=no(o);return u.jsx("rect",{className:ce("tl-transparent","tl-rotate-corner",{"tl-hidden":i}),"data-testid":a,"aria-label":`${o} target`,pointerEvents:"all",x:N(n-r*3),y:N(t-r*3),width:N(Math.max(1,r*3)),height:N(Math.max(1,r*3)),cursor:s,...l})},RV=Math.sqrt(Math.PI),LV=function({cx:n,cy:t,size:r,isHidden:o,"data-testid":s}){const i=no("mobile_rotate"),a=B(),l=G("zoom level",()=>a.getZoomLevel(),[a]),c=Math.max(14*(1/l),20/Math.max(1,l));return u.jsxs("g",{children:[u.jsx("circle",{"data-testid":s,pointerEvents:"all",className:ce("tl-transparent","tl-mobile-rotate__bg",{"tl-hidden":o}),cx:n,cy:t,r:c,...i}),u.jsx("circle",{className:ce("tl-mobile-rotate__fg",{"tl-hidden":o}),cx:n,cy:t,r:r/RV})]})};function bv(e,n,t){const{arrowheadStart:r,arrowheadEnd:o}=n.props,s=Ka(e,n,t),i=s.start.clone(),a=s.end.clone(),l=w.Med(i,a);if(w.Equals(i,a))return{bindings:t,isStraight:!0,start:{handle:i,point:i,arrowhead:n.props.arrowheadStart},end:{handle:a,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:!1,length:0};const c=w.Sub(a,i).uni(),d=pf(e,n,"start"),h=pf(e,n,"end"),p=e.getShapePageTransform(n);WC(a,s.start,p,h),WC(i,s.end,p,d);let f=0,S=0,g=0,x=0,y=Wa*n.props.scale;const v=d&&h&&d.shape===h.shape,b=d&&h?r0(e,d.shape.id,h.shape.id):"safe";b==="safe"&&d&&h&&!v&&!d.isExact&&!h.isExact&&(h.didIntersect&&!d.didIntersect?d.isClosed&&i.setTo(a.clone().add(c.clone().mul(Wa*n.props.scale))):h.didIntersect||h.isClosed&&a.setTo(i.clone().sub(c.clone().mul(Wa*n.props.scale))));const E=w.Sub(a,i),I=w.Len(E)?E.uni():w.From(E),C=!w.Equals(I,c);v||(b!=="start-contains-end"&&d&&r!=="none"&&!d.isExact&&(g=Ts[n.props.size]/2+("size"in d.shape.props?Ts[d.shape.props.size]/2:0),f=(ff+g)*n.props.scale,y+=g*n.props.scale),b!=="end-contains-start"&&h&&o!=="none"&&!h.isExact&&(x=Ts[n.props.size]/2+("size"in h.shape.props?Ts[h.shape.props.size]/2:0),S=(ff+x)*n.props.scale,y+=x*n.props.scale));const k=i.clone().add(I.clone().mul(f*(C?-1:1))),T=a.clone().sub(I.clone().mul(S*(C?-1:1)));w.DistMin(k,T,y)&&(f!==0&&S!==0?(f*=-1.5,S*=-1.5):f!==0?f*=-1:S!==0&&(S*=-1)),i.add(I.clone().mul(f*(C?-1:1))),a.sub(I.clone().mul(S*(C?-1:1))),C?(d&&h&&a.setTo(w.Add(i,I.clone().mul(-Wa*n.props.scale))),l.setTo(w.Med(s.start,s.end))):l.setTo(w.Med(i,a));const O=w.Dist(i,a);return{bindings:t,isStraight:!0,start:{handle:s.start,point:i,arrowhead:n.props.arrowheadStart},end:{handle:s.end,point:a,arrowhead:n.props.arrowheadEnd},middle:l,isValid:O>0,length:O}}function WC(e,n,t,r){if(r===void 0||r.isExact)return;const o=oe.applyToPoint(t,n),s=oe.applyToPoint(t,e),i=oe.applyToPoint(oe.Inverse(r.transform),o),a=oe.applyToPoint(oe.Inverse(r.transform),s),l=r.isClosed,d=(l?Gw:jW)(i,a,r.outline);let h;if(d!==null&&(h=d.sort((S,g)=>w.Dist2(S,i)-w.Dist2(g,i))[0]??(l?void 0:a)),h===void 0)return;const p=oe.applyToPoint(r.transform,h),f=oe.applyToPoint(oe.Inverse(t),p);e.setTo(f),r.didIntersect=!0}function $V(e,n,t){const{arrowheadEnd:r,arrowheadStart:o}=n.props,s=n.props.bend;if(Math.abs(s)>Math.abs(n.props.bend*(UV*n.props.scale)))return bv(e,n,t);const i=Ka(e,n,t),a=w.Med(i.start,i.end),l=w.Sub(i.end,i.start),c=w.Len(l)?l.uni():w.From(l),d=w.Add(a,c.per().mul(-s)),h=pf(e,n,"start"),p=pf(e,n,"end"),f=i.start.clone(),S=i.end.clone(),g=d.clone();if(w.Equals(f,S))return{bindings:t,isStraight:!0,start:{handle:f,point:f,arrowhead:n.props.arrowheadStart},end:{handle:S,point:S,arrowhead:n.props.arrowheadEnd},middle:g,isValid:!1,length:0};const x=n.props.bend<0,y=x?Fu:BM,v=GC(f,S,g),b=w.Angle(v.center,f),E=w.Angle(v.center,S),I=y(b,E);if(v.length===0||v.size===0||!oC(v.length)||!oC(v.size))return bv(e,n,t);const C=f.clone(),k=S.clone(),T=g.clone(),O=e.getShapePageTransform(n);let _=0,j=0,L=Wa*n.props.scale;if(h&&!h.isExact){const X=oe.applyToPoint(O,C),J=oe.applyToPoint(O,v.center),le=oe.applyToPoint(O,k),ye=oe.Inverse(h.transform),Me=oe.applyToPoint(ye,X),ae=oe.applyToPoint(ye,J),Ue=oe.applyToPoint(ye,le),{isClosed:Ae}=h,et=Ae?Sv:kC;let je,at=et(ae,v.radius,h.outline);if(at){const Ne=ae.angle(Me),Kn=ae.angle(Ue),Rt=y(Ne,Kn);at=at.filter(St=>y(Ne,ae.angle(St))<=Rt);const Pn=Rt*.25;at.sort(Ae?(St,Xt)=>Math.abs(y(Ne,ae.angle(St))-Pn)y(Ne,ae.angle(St))y(Ne,ae.angle(St))<=Rt),at.sort(Ae?(St,Xt)=>Math.abs(y(Ne,ae.angle(St))-Pn)y(Ne,ae.angle(St))y(b,R))&&k.setTo(v.center).add(w.FromAngle(A+F*(Math.min(.9,Wa*n.props.scale/W)*(x?1:-1))).mul(v.radius)))}FV(v.center,v.radius,C,k,T,I,x),C.equals(k)&&(C.setTo(T.clone().addXY(1,1)),k.setTo(T.clone().subXY(1,1))),f.setTo(C),S.setTo(k),g.setTo(T);const U=GC(f,S,g);return{bindings:t,isStraight:!1,start:{point:f,handle:i.start,arrowhead:n.props.arrowheadStart},end:{point:S,handle:i.end,arrowhead:n.props.arrowheadEnd},middle:g,handleArc:v,bodyArc:U,isValid:U.length!==0&&isFinite(U.center.x)&&isFinite(U.center.y)}}function GC(e,n,t){const r=$w(e,n,t),o=w.Dist(r,e),s=+w.Clockwise(e,t,n),i=((e.y-n.y)**2+(e.x-n.x)**2)**.5,a=((n.y-t.y)**2+(n.x-t.x)**2)**.5,l=((t.y-e.y)**2+(t.x-e.x)**2)**.5,c=Math.acos((a*a+l*l-i*i)/(2*a*l))*2,d=+(_e>c),h=(Re-c)*(s?1:-1),p=h*o;return{center:r,radius:o,size:h,length:p,largeArcFlag:d,sweepFlag:s}}function FV(e,n,t,r,o,s,i){const a=w.Angle(e,t),l=w.Angle(e,r);let c=Fu(a,l);if(i||(c=Re-c),o.setTo(e).add(w.FromAngle(a+c*(.5*(i?1:-1))).mul(n)),c>s){o.rotWith(e,_e);const d=r.clone();r.setTo(t),t.setTo(d)}}const NV=8;function zV(e){return Math.abs(e.props.bend)l.props.terminal===t);if(!r)return;const o=e.getShape(r.toId);if(!o)return;const s=e.getShapePageTransform(o),i=e.getShapeGeometry(o),a=i instanceof Hr?i.children[0].vertices:i.vertices;return{shape:o,transform:s,isClosed:i.isClosed,isExact:r.props.isExact,didIntersect:!1,outline:a}}function VC(e,n,t,r){const o=e.getShape(t.toId);if(o){const{point:s,size:i}=e.getShapeGeometry(o).bounds,a=w.Add(s,w.MulV(t.props.isPrecise||r?t.props.normalizedAnchor:{x:.5,y:.5},i)),l=oe.applyToPoint(e.getShapePageTransform(o),a);return oe.applyToPoint(oe.Inverse(n),l)}else return new w(0,0)}function Mn(e,n){const t=e.getBindingsFromShape(n,"arrow");return{start:t.find(r=>r.props.terminal==="start"),end:t.find(r=>r.props.terminal==="end")}}const BV=TH("arrow info",(e,n)=>{const t=Mn(e,n);return zV(n)?bv(e,n,t):$V(e,n,t)});function co(e,n){const t=typeof n=="string"?n:n.id;return BV.get(e,t)}function Ka(e,n,t){var a,l;const r=e.getShapePageTransform(n),o=r0(e,(a=t.start)==null?void 0:a.toId,(l=t.end)==null?void 0:l.toId),s=t.start?VC(e,r,t.start,o==="double-bound"||o==="start-contains-end"):w.From(n.props.start),i=t.end?VC(e,r,t.end,o==="double-bound"||o==="end-contains-start"):w.From(n.props.end);return{start:s,end:i}}function cc(e,n,t,r){const o=typeof n=="string"?n:n.id,s=typeof t=="string"?t:t.id,i=e.getBindingsFromShape(o,"arrow").filter(l=>l.props.terminal===r.terminal);i.length>1&&e.deleteBindings(i.slice(1));const a=i[0];a?e.updateBinding({...a,toId:s,props:r}):e.createBinding({type:"arrow",fromId:o,toId:s,props:r})}function $h(e,n,t){const r=e.getBindingsFromShape(n,"arrow").filter(o=>o.props.terminal===t);e.deleteBindings(r)}const Wa=10,ff=10,UV=10,Ts={s:2,m:3.5,l:5,xl:10};function r0(e,n,t){if(!n||!t)return"safe";if(n===t)return"double-bound";const r=e.getShapePageBounds(n),o=e.getShapePageBounds(t);if(r&&o){if(r.contains(o))return"start-contains-end";if(o.contains(r))return"end-contains-start"}return"safe"}class Fh extends Rh{getDefaultProps(){return{isPrecise:!1,isExact:!1,normalizedAnchor:{x:.5,y:.5}}}onAfterCreate({binding:n}){oy(this.editor,this.editor.getShape(n.fromId))}onAfterChange({bindingAfter:n}){oy(this.editor,this.editor.getShape(n.fromId))}onAfterChangeFromShape({shapeAfter:n}){oy(this.editor,n)}onAfterChangeToShape({binding:n}){G2(this.editor,n.fromId)}onBeforeIsolateFromShape({binding:n}){const t=this.editor.getShape(n.fromId);t&&gf({editor:this.editor,arrow:t,terminal:n.props.terminal})}}m(Fh,"type","arrow"),m(Fh,"props",lM),m(Fh,"migrations",cM);function G2(e,n){var x;const t=e.getShape(n);if(!t)return;const r=Mn(e,t),{start:o,end:s}=r,i=o?e.getShape(o.toId):void 0,a=s?e.getShape(s.toId):void 0,l=e.getAncestorPageId(t);if(!l)return;let c;if(i&&a)c=e.findCommonAncestor([i,a])??l;else if(i||a){const y=(x=i||a)==null?void 0:x.parentId;y&&y===t.parentId?c=t.parentId:c=l}else return;c&&c!==t.parentId&&e.reparentShapes([n],c);const d=e.getShape(n);if(!d)throw Error("no reparented arrow");const h=e.getShapeNearestSibling(d,i),p=e.getShapeNearestSibling(d,a);let f;if(h&&p)f=h.index>p.index?h:p;else if(h&&!p)f=h;else if(p&&!h)f=p;else return;let S;const g=e.getSortedChildIdsForParent(f.parentId).map(y=>e.getShape(y)).filter(y=>y.index>f.index);if(g.length){const y=g.find(v=>v.type!=="arrow");if(d.index>f.index&&(!y||d.index * MIT license */function GV(e,n){var t=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(t!=null){var r,o,s,i,a=[],l=!0,c=!1;try{if(s=(t=t.call(e)).next,n===0){if(Object(t)!==t)return;l=!1}else for(;!(l=(r=s.call(t)).done)&&(a.push(r.value),a.length!==n);l=!0);}catch(d){c=!0,o=d}finally{try{if(!l&&t.return!=null&&(i=t.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function YC(e,n){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),t.push.apply(t,r)}return t}function Vn(e){for(var n=1;n=0)&&(t[o]=e[o]);return t}function XV(e,n){if(e==null)return{};var t=YV(e,n),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(t[r]=e[r])}return t}function XC(e,n){return ZV(e)||GV(e,n)||Y2(e,n)||eY()}function Gd(e){return qV(e)||QV(e)||Y2(e)||JV()}function qV(e){if(Array.isArray(e))return Pv(e)}function ZV(e){if(Array.isArray(e))return e}function QV(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Y2(e,n){if(e){if(typeof e=="string")return Pv(e,n);var t=Object.prototype.toString.call(e).slice(8,-1);if(t==="Object"&&e.constructor&&(t=e.constructor.name),t==="Map"||t==="Set")return Array.from(e);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Pv(e,n)}}function Pv(e,n){(n==null||n>e.length)&&(n=e.length);for(var t=0,r=new Array(n);t=s;){var l=n||t?a:1,c=n||r?a:1;o.push([l,c]),a-=i}return o}function Vd(e){var n=window&&"HTMLCanvasElement"in window,t=window&&"OffscreenCanvas"in window,r=Date.now(),o=e.onError,s=e.onSuccess,i=XV(e,rY),a=null;if(!n)return!1;if(e.useWorker&&t){var l=` var canvasTest = `.concat(Uc.toString(),`; onmessage = function(e) { canvasTest(e.data); }; `),c=new Blob([l],{type:"application/javascript"}),d=URL.createObjectURL(c);a=new Worker(d),URL.revokeObjectURL(d),a.onmessage=function(h){var p=h.data,f=p.width,S=p.height,g=p.benchmark,x=p.isTestPass;x?(uc[r].onSuccess(f,S,g),delete uc[r]):uc[r].onError(f,S,g)}}if(e.usePromise)return new Promise(function(h,p){var f=Vn(Vn({},e),{},{onError:function(y,v,b){var E;if(e.sizes.length===0)E=!0;else{var I=e.sizes.slice(-1),C=XC(I,1),k=XC(C[0],2),T=k[0],O=k[1];E=y===T&&v===O}o(y,v,b),E&&p({width:y,height:v,benchmark:b})},onSuccess:function(y,v,b){s(y,v,b),h({width:y,height:v,benchmark:b})}});if(a){var S=f.onError,g=f.onSuccess;uc[r]={onError:S,onSuccess:g},a.postMessage(i)}else Uc(f)});if(a)uc[r]={onError:o,onSuccess:s},a.postMessage(i);else return Uc(e)}var ay={maxArea:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=iy({width:n.max,height:n.max,min:n.min,step:n.step,sizes:Gd(sy.area)}),r=Vn(Vn(Vn({},Ga),n),{},{sizes:t});return Vd(r)},maxHeight:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=iy({width:1,height:n.max,min:n.min,step:n.step,sizes:Gd(sy.height)}),r=Vn(Vn(Vn({},Ga),n),{},{sizes:t});return Vd(r)},maxWidth:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=iy({width:n.max,height:1,min:n.min,step:n.step,sizes:Gd(sy.width)}),r=Vn(Vn(Vn({},Ga),n),{},{sizes:t});return Vd(r)},test:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=Vn(Vn({},Ga),n);return t.sizes=Gd(t.sizes),t.width&&t.height&&(t.sizes=[[t.width,t.height]]),Vd(t)}};let ly=null;function oY(){return ly||(ly=sY()),ly}async function sY(){const e=await ay.maxWidth({usePromise:!0}),n=await ay.maxHeight({usePromise:!0}),t=await ay.maxArea({usePromise:!0});return{maxWidth:e.width,maxHeight:n.height,maxArea:t.width*t.height}}const qC=8192,iY=4096*4096;async function aY(e,n){if(e<=qC&&n<=qC&&e*n<=iY)return[e,n];const{maxWidth:t,maxHeight:r,maxArea:o}=await oY(),s=e/n;if(e>t&&(e=t,n=e/s),n>r&&(n=r,e=n*s),e*n>o){const i=Math.sqrt(o/(e*n));e*=i,n*=i}return[e,n]}function lY(e,n){const t=e.w/n.w,r=e.h/n.h;return t<=1&&r<=1?e:t>r?{w:e.w/t,h:e.h/t}:{w:e.w/r,h:e.h/r}}function cY(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function uY(e){const n=new URL(e).host.replace("www.","");for(const t of $u)if(X2(t.hostnames,n)){const r=t.fromEmbedUrl(e);if(r)return{definition:t,url:r,embedUrl:e}}}const dY=e=>e.split("*").map(n=>cY(n)).join(".+"),X2=(e,n)=>!!e.find(t=>{const r=new RegExp(dY(t));return n.match(r)});function hY(e){const n=new URL(e).host.replace("www.","");for(const t of $u)if(X2(t.hostnames,n)){const r=t.toEmbedUrl(e);if(r)return{definition:t,embedUrl:r,url:e}}}function q2(e){return hY(e)??uY(e)}function Ms(e){try{return q2(e)}catch(n){console.error(n)}}/*! * MIT License * Adapted (mostly copied) the work of https://github.com/fregante/text-field-edit * Copyright (c) Federico Brigante (bfred.it) */const Va=" ",pn=class pn{static insertTextFirefox(n,t){n.setRangeText(t,n.selectionStart||0,n.selectionEnd||0,"end"),n.dispatchEvent(new InputEvent("input",{data:t,inputType:"insertText",isComposing:!1}))}static insert(n,t){const r=n.ownerDocument,o=r.activeElement;o!==n&&n.focus(),r.execCommand("insertText",!1,t)||pn.insertTextFirefox(n,t),o===r.body?n.blur():o instanceof HTMLElement&&o!==n&&o.focus()}static set(n,t){n.select(),pn.insert(n,t)}static getSelection(n){const{selectionStart:t,selectionEnd:r}=n;return n.value.slice(t||void 0,r||void 0)}static wrapSelection(n,t,r){const{selectionStart:o,selectionEnd:s}=n,i=pn.getSelection(n);pn.insert(n,t+i+(r??t)),n.selectionStart=(o||0)+t.length,n.selectionEnd=(s||0)+t.length}static replace(n,t,r){let o=0;n.value.replace(t,(...s)=>{const i=o+s[s.length-2],a=s[0].length;n.selectionStart=i,n.selectionEnd=i+a;const l=typeof r=="string"?r:r(...s);return pn.insert(n,l),n.selectionStart=i,o+=l.length-a,l})}static findLineEnd(n,t){const r=n.lastIndexOf(` `,t-1)+1;return n.charAt(r)!==" "?t:r+1}static indent(n){var a;const{selectionStart:t,selectionEnd:r,value:o}=n,s=o.slice(t,r),i=(a=/\n/g.exec(s))==null?void 0:a.length;if(i&&i>0){const l=o.lastIndexOf(` `,t-1)+1,c=n.value.slice(l,r-1),d=c.replace(/^|\n/g,`$&${Va}`),h=d.length-c.length;n.setSelectionRange(l,r-1),pn.insert(n,d),n.setSelectionRange(t+1,r+h)}else pn.insert(n,Va)}static unindent(n){const{selectionStart:t,selectionEnd:r,value:o}=n,s=o.lastIndexOf(` `,t-1)+1,i=pn.findLineEnd(o,r),a=n.value.slice(s,i),l=a.replace(/(^|\n)(\t| {1,2})/g,"$1"),c=a.length-l.length;n.setSelectionRange(s,i),pn.insert(n,l);const d=/\t| {1,2}/.exec(o.slice(s,t)),h=d?d[0].length:0,p=t-h;n.setSelectionRange(t-h,Math.max(p,r-c))}static indentCE(n){var l;const t=window.getSelection(),r=n.innerText,o=Yd(n)??0,s=Yd(n)??0,i=r.slice(o,s),a=(l=/\n/g.exec(i))==null?void 0:l.length;if(a&&a>0){const c=r.lastIndexOf(` `,o-1)+1,d=r.slice(c,s-1),p=d.replace(/^|\n/g,`$&${Va}`).length-d.length;t&&t.setBaseAndExtent(n,o+1,n,s+p)}else{const c=window.getSelection();n.innerText=r.slice(0,o)+Va+r.slice(o),c==null||c.setBaseAndExtent(n,o+1,n,o+2)}}static unindentCE(n){const t=window.getSelection(),r=n.innerText,o=Yd(n)??0,s=Yd(n)??0,i=r.lastIndexOf(` `,o-1)+1,a=pn.findLineEnd(r,s),l=r.slice(i,a),c=l.replace(/(^|\n)(\t| {1,2})/g,"$1"),d=l.length-c.length;if(t){t.setBaseAndExtent(n,i,n,a);const h=/\t| {1,2}/.exec(r.slice(i,o)),p=h?h[0].length:0,f=o-p;t.setBaseAndExtent(n,o-p,n,Math.max(f,s-d))}}static normalizeText(n){return n.replace(pn.fixNewLines,` `)}static normalizeTextForDom(n){return n.replace(pn.fixNewLines,` `).split(` `).map(t=>t||" ").join(` `)}};m(pn,"fixNewLines",/\r?\n|\r/g);let Sl=pn;function Yd(e){if(typeof window.getSelection>"u")return;const n=window.getSelection();if(!n)return;let t=0;if(n.rangeCount!==0){const r=n.getRangeAt(0),o=r.cloneRange();o.selectNodeContents(e),o.setEnd(r.endContainer,r.endOffset),t=o.toString().length}return t}const pY=/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;function Z2(e){return pY.test(e)}function fY(e){return e.replace(/\t/g,Va)}function gY(e){const n=e.split(` `);for(;n[0]&&n[0].trim().length===0;)n.shift();let t=1/0;for(const r of n)if(r.trim().length>0){const o=r.length-r.trimStart().length;t=Math.min(t,o)}return n.map(r=>r.slice(t)).join(` `)}function mY(e){return e.replace(/[ \t]+$/gm,"").replace(/\n+$/,"")}function yY(e){return mY(gY(fY(e)))}function SY(e,{maxImageDimension:n,maxAssetSize:t,acceptedImageMimeTypes:r,acceptedVideoMimeTypes:o},{toasts:s,msg:i},a){e.registerExternalAssetHandler("file",async({file:l})=>{const c=l.name;let d=l;const h=r.includes(d.type),p=o.includes(d.type);st(h||p,`File type not allowed: ${d.type}`),st(d.size<=t,`File size too big: ${(d.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),d.type==="video/quicktime"&&(d=new Blob([d],{type:"video/mp4"}));let f=h?await ao.getImageSize(d):await ao.getVideoSize(d);const S=await ao.isAnimated(d)||p,g=await A6(await d.arrayBuffer());if(isFinite(n)){const v=lY(f,{w:n,h:n});f!==v&&ao.isStaticImageType(d.type)&&(f=v)}const x=ki.createId(g),y={id:x,type:h?"image":"video",typeName:"asset",props:{name:c,src:"",w:f.w,h:f.h,fileSize:d.size,mimeType:d.type,isAnimated:S}};return a?(y.props.src=x,await EV({persistenceKey:a,assetId:x,blob:d})):y.props.src=await Oi.blobToDataUrl(d),ki.create(y)}),e.registerExternalAssetHandler("url",async({url:l})=>{var d,h,p,f,S;let c;try{const x=await(await yo(l,{method:"GET",mode:"no-cors"})).text(),y=new DOMParser().parseFromString(x,"text/html");c={image:((d=y.head.querySelector('meta[property="og:image"]'))==null?void 0:d.getAttribute("content"))??"",favicon:((h=y.head.querySelector('link[rel="apple-touch-icon"]'))==null?void 0:h.getAttribute("href"))??((p=y.head.querySelector('link[rel="icon"]'))==null?void 0:p.getAttribute("href"))??"",title:((f=y.head.querySelector('meta[property="og:title"]'))==null?void 0:f.getAttribute("content"))??l,description:((S=y.head.querySelector('meta[property="og:description"]'))==null?void 0:S.getAttribute("content"))??""},c.image.startsWith("/")&&(c.image=new URL(c.image,l).href),c.favicon.startsWith("/")&&(c.favicon=new URL(c.favicon,l).href)}catch(g){console.error(g),s.addToast({title:i("assets.url.failed"),severity:"error"}),c={image:"",favicon:"",title:"",description:""}}return{id:ki.createId(ov(l)),typeName:"asset",type:"bookmark",props:{src:l,description:c.description,image:c.image,favicon:c.favicon,title:c.title},meta:{}}}),e.registerExternalContentHandler("svg-text",async({point:l,text:c})=>{const d=l??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),h=new DOMParser().parseFromString(c,"image/svg+xml").querySelector("svg");if(!h)throw new Error("No element present");let p=parseFloat(h.getAttribute("width")||"0"),f=parseFloat(h.getAttribute("height")||"0");if(!(p&&f)){document.body.appendChild(h);const g=h.getBoundingClientRect();document.body.removeChild(h),p=g.width,f=g.height}const S=await e.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});if(!S)throw Error("Could not create an asset");ZC(e,[S],d)}),e.registerExternalContentHandler("embed",({point:l,url:c,embed:d})=>{const h=l??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),{width:p,height:f}=d,S=$e(),g={id:S,type:"embed",x:h.x-(p||450)/2,y:h.y-(f||450)/2,props:{w:p,h:f,url:c}};e.createShapes([g]).select(S)}),e.registerExternalContentHandler("files",async({point:l,files:c})=>{const d=l??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),h=new w(d.x,d.y),p=[];await Promise.all(c.map(async(f,S)=>{if(f.size>t)return console.warn(`File size too big: ${(f.size/1024).toFixed()}kb > ${(t/1024).toFixed()}kb`),null;if(!f.type)throw new Error("No mime type");if(!r.concat(o).includes(f.type))return console.warn(`${f.name} not loaded - Extension not allowed.`),null;try{const g=await e.getAssetForExternalContent({type:"file",file:f});if(!g)throw Error("Could not create an asset");p[S]=g}catch(g){return s.addToast({title:i("assets.files.upload-failed"),severity:"error"}),console.error(g),null}})),ZC(e,me(p),h)}),e.registerExternalContentHandler("text",async({point:l,text:c})=>{const d=l??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),h=e.getShapeUtil("text").getDefaultProps(),p=yY(c),f=e.getOnlySelectedShape();if(f&&"text"in f.props){e.updateShapes([{id:f.id,type:f.type,props:{text:p}}]);return}let S,g,x,y="middle";const v=p.split(` `).length>1,b=Z2(p);v&&(y=v?b?"end":"start":"middle");const E=e.textMeasure.measureText(p,{...Wt,fontFamily:mo[h.font],fontSize:yl[h.size],maxWidth:null}),I=Math.min(v?e.getViewportPageBounds().width*.9:920,Math.max(200,e.getViewportPageBounds().width*.9));if(E.w>I){const C=e.textMeasure.measureText(p,{...Wt,fontFamily:mo[h.font],fontSize:yl[h.size],maxWidth:I});S=C.w,g=C.h,x=!1,y=b?"end":"start"}else S=E.w,g=E.h,x=!0;d.y-g/2{const d=Ms(c);if(d)return e.putExternalContent({type:"embed",url:d.url,point:l,embed:d.definition});const h=l??(e.inputs.shiftKey?e.inputs.currentPagePoint:e.getViewportPageBounds().center),p=ki.createId(ov(c)),f=vY(e,c,h);let S=e.getAsset(p),g=!1;if(!S){g=!0;try{const x=await e.getAssetForExternalContent({type:"url",url:c});if(!x)throw Error("Could not create an asset");S=x}catch{s.addToast({title:i("assets.url.failed"),severity:"error"});return}}e.batch(()=>{g&&e.createAssets([S]),e.updateShapes([{id:f.id,type:f.type,props:{assetId:S.id}}])})})}async function ZC(e,n,t){if(!n.length)return[];const r=w.From(t),o=[];for(let s=0;s{const s=n.filter(i=>!e.getAsset(i.id));s.length&&e.createAssets(s),e.createShapes(o).select(...o.map(i=>i.id)),Q2(e,t)}),o.map(s=>s.id)}function Q2(e,n){const t=e.getViewportPageBounds();let r=e.getSelectionPageBounds();if(r){const o=r.center.sub(n);e.updateShapes(e.getSelectedShapes().map(s=>{const i=e.getShapeParentTransform(s).decompose().rotation,a=w.Rot(o,-i);return{id:s.id,type:s.type,x:s.x-a.x,y:s.y-a.y}}))}r=e.getSelectionPageBounds(),r&&!t.contains(r)&&e.zoomToSelection()}function vY(e,n,t){const r={id:$e(),type:"bookmark",x:t.x-150,y:t.y-160,opacity:1,props:{assetId:null,url:n}};return e.batch(()=>{e.createShapes([r]).select(r.id),Q2(e,t)}),e.getShape(r.id)}const xY=new Zo,wY=e=>async n=>!n||!n.props.src?null:e&&n.props.src.startsWith("asset:")?await xY.get(n,async()=>await bY(e,n.id)):n.type==="video"?n.props.src:n.type!=="image"?null:n.props.src;async function bY(e,n){const t=await IV({assetId:n,persistenceKey:e});return t?URL.createObjectURL(t):null}var Oy;let PY=(Oy=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")});m(this,"onKeyUp",t=>{var r;if(t.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",{...t,target:"shape",shape:o}))}})}},m(Oy,"id","idle"),Oy);var Dy;let CY=(Dy=class extends se{constructor(){super(...arguments);m(this,"shape");m(this,"markId","");m(this,"onEnter",()=>{this.didTimeout=!1;const t=this.editor.getShapeAtPoint(this.editor.inputs.currentPagePoint,{filter:r=>!r.isLocked&&this.editor.canBindShapes({fromShape:"arrow",toShape:r,binding:"arrow"}),margin:0,hitInside:!0,renderingOnly:!0});t?this.editor.setHintingShapes([t.id]):this.createArrowShape(),this.startPreciseTimeout()});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:{id:"end",type:"vertex",index:"a3",x:0,y:0},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 d;const{originPagePoint:t}=this.editor.inputs,r=$e();this.markId=`creating:${r}`,this.editor.mark(this.markId),this.editor.createShape({id:r,type:"arrow",x:t.x,y:t.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const 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,l=s.find(h=>h.id==="start"),c=(d=i.onHandleDrag)==null?void 0:d.call(i,o,{handle:{...l,x:0,y:0},isPrecise:!0,initial:a});c&&this.editor.updateShapes([c]),this.shape=this.editor.getShape(r),this.editor.select(r)}updateArrowShapeEndHandle(){var o,s;const t=this.shape;if(!t)throw Error("expected shape");const r=this.editor.getShapeHandles(t);if(!r)throw Error("expected handles for arrow");{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=r.find(d=>d.id==="start"),c=(o=i.onHandleDrag)==null?void 0:o.call(i,t,{handle:{...l,x:0,y:0},isPrecise:this.didTimeout,initial:a});c&&this.editor.updateShapes([c])}{const i=this.editor.getShapeUtil("arrow"),a=this.shape,l=this.editor.getPointInShapeSpace(t,this.editor.inputs.currentPagePoint),c=r.find(h=>h.id==="end"),d=(s=i.onHandleDrag)==null?void 0:s.call(i,this.editor.getShape(t),{handle:{...c,x:l.x,y:l.y},isPrecise:!1,initial:a});d&&this.editor.updateShapes([d])}this.shape=this.editor.getShape(t.id)}startPreciseTimeout(){this.preciseTimeout=this.editor.timers.setTimeout(()=>{this.getIsActive()&&(this.didTimeout=!0)},320)}clearPreciseTimeout(){clearTimeout(this.preciseTimeout)}},m(Dy,"id","pointing"),Dy);class Nh extends se{constructor(){super(...arguments);m(this,"shapeType","arrow")}}m(Nh,"id","arrow"),m(Nh,"initial","idle"),m(Nh,"children",()=>[PY,CY]);class o0 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,"isPenOrStylus",!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",t=>{this.markId=null,this.info=t,this.canDraw=!this.editor.getIsMenuOpen(),this.lastRecordedPoint=this.editor.inputs.currentPagePoint.clone(),this.canDraw&&this.startShape()});m(this,"onPointerMove",()=>{const{inputs:t}=this.editor;if(this.isPen&&!t.isPen){if(this.markId){this.editor.bailToMark(this.markId),this.startShape();return}}else!this.canDraw&&t.isDragging&&(this.startShape(),this.canDraw=!0);this.canDraw&&(this.isPenOrStylus?w.Dist(t.currentPagePoint,this.lastRecordedPoint)>=1/this.editor.getZoomLevel()?(this.lastRecordedPoint=t.currentPagePoint.clone(),this.mergeNextPoint=!1):this.mergeNextPoint=!0:this.mergeNextPoint=!1,this.updateDrawingShape())});m(this,"onKeyDown",t=>{if(t.key==="Shift")switch(this.segmentMode){case"free":{this.segmentMode="starting_straight",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_free":this.segmentMode="starting_straight"}this.updateDrawingShape()});m(this,"onKeyUp",t=>{if(t.key==="Shift")switch(this.editor.snaps.clearIndicators(),this.segmentMode){case"straight":{this.segmentMode="starting_free",this.pagePointWhereNextSegmentChanged=this.editor.inputs.currentPagePoint.clone();break}case"starting_straight":{this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";break}}this.updateDrawingShape()});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(t,r){if(!this.canClose())return!1;const o=At[r],s=t[0].points[0],i=t[t.length-1],a=i.points[i.points.length-1];return s!==a&&this.currentLineLength>o*4&&w.DistMin(s,a,o*2)}startShape(){const{inputs:{originPagePoint:t,isPen:r}}=this.editor;this.markId="draw start "+ot(),this.editor.mark(this.markId);const{z:o=.5}=this.info.point;this.isPen=r,this.isPenOrStylus=r||o>0&&o<.5||o>.5&&o<1;const s=this.isPenOrStylus?o*1.25:.5;if(this.segmentMode=this.editor.inputs.shiftKey?"straight":"free",this.didJustShiftClickToExtendPreviousShapeLine=!1,this.lastRecordedPoint=t.clone(),this.initialShape){const a=this.editor.getShape(this.initialShape.id);if(a&&this.segmentMode==="straight"){this.didJustShiftClickToExtendPreviousShapeLine=!0;const l=Nt(a.props.segments);if(!l)throw Error("Expected a previous segment!");const c=Nt(l.points);if(!c)throw Error("Expected a previous point!");const{x:d,y:h}=this.editor.getPointInShapeSpace(a,t).toFixed(),p={type:this.segmentMode,points:[{x:c.x,y:c.y,z:+s.toFixed(2)},{x:d,y:h,z:+s.toFixed(2)}]},f=oe.applyToPoint(this.editor.getShapePageTransform(a.id),c);this.pagePointWhereCurrentSegmentChanged=f,this.pagePointWhereNextSegmentChanged=null;const S=[...a.props.segments,p];this.currentLineLengththis.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="straight";const g=Nt(a);if(!g)throw Error("Expected a previous segment!");const x=Nt(g.points);if(!x)throw Error("Expected a previous last point!");let y;const v=this.editor.getPointInShapeSpace(i,this.pagePointWhereCurrentSegmentChanged).toFixed().toJson();if(g.type==="straight"){this.currentLineLength+=w.Dist(x,v),y={type:"straight",points:[{...x},v]};const E=this.editor.getShapePageTransform(i);this.pagePointWhereCurrentSegmentChanged=oe.applyToPoint(E,x)}else y={type:"straight",points:[v,p]};const b={id:o,type:this.shapeType,props:{segments:[...a,y]}};this.canClose()&&(b.props.isClosed=this.getIsClosed(a,s)),this.editor.updateShapes([b])}break}case"starting_free":{const{pagePointWhereNextSegmentChanged:f}=this;if(f===null)throw Error("We should have a point where the segment changed");if(w.Dist2(f,r.currentPagePoint)>this.editor.options.dragDistanceSquared){this.pagePointWhereCurrentSegmentChanged=this.pagePointWhereNextSegmentChanged.clone(),this.pagePointWhereNextSegmentChanged=null,this.segmentMode="free";const g=a.slice(),x=g[g.length-1],y=Nt(x.points);if(!y)throw Error("No previous point!");const v={type:"free",points:[...w.PointsBetween(y,p,6).map(I=>({x:$o(I.x),y:$o(I.y),z:$o(I.z)}))]},b=[...g,v];this.currentLineLength2){let O,_=8/this.editor.getZoomLevel();for(let j=0,L=a.length-2;jthis.editor.options.maxPointsPerDrawShape){this.editor.updateShapes([{id:o,type:this.shapeType,props:{isComplete:!0}}]);const y=$e(),v=this.editor.getShape(o).props;this.editor.createShapes([{id:y,type:this.shapeType,x:$o(r.currentPagePoint.x),y:$o(r.currentPagePoint.y),props:{isPen:this.isPenOrStylus,scale:v.scale,segments:[{type:"free",points:[{x:0,y:0,z:this.isPenOrStylus?+(d*1.25).toFixed():.5}]}]}}]),this.initialShape=rt(this.editor.getShape(y)),this.mergeNextPoint=!1,this.lastRecordedPoint=r.currentPagePoint.clone(),this.currentLineLength=0}break}}}getLineLength(t){let r=0;for(const o of t)for(let s=0;s{this.parent.transition("drawing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Ry,"id","idle"),Ry);class zh extends se{constructor(){super(...arguments);m(this,"shapeType","draw");m(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}m(zh,"id","draw"),m(zh,"initial","idle"),m(zh,"children",()=>[J2,o0]);class Cv extends Lh{constructor(){super(...arguments);m(this,"shapeType","frame");m(this,"onCreate",t=>{if(!t)return;const r=this.editor.getShapePageBounds(t),o=[],s=this.editor.getShapeAncestors(t).map(i=>i.id);this.editor.getSortedChildIdsForParent(t.parentId).map(i=>{const a=this.editor.getShape(i);if(!a||a.id===t.id||a.isLocked)return;const l=this.editor.getShapePageBounds(a);l&&r.contains(l)&&IY(a,s,t)&&o.push(a.id)}),this.editor.reparentShapes(o,t.id),this.editor.getInstanceState().isToolLocked?this.editor.setCurrentTool("frame"):this.editor.setCurrentTool("select.idle")})}}m(Cv,"id","frame"),m(Cv,"initial","idle");function IY(e,n,t){return n.includes(e.id)?!1:e.parentId===t.parentId}var Ly;let EY=(Ly=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onKeyUp",t=>{var r;if(t.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",{...t,target:"shape",shape:o}))}});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Ly,"id","idle"),Ly);var $y;let kY=($y=class extends se{constructor(){super(...arguments);m(this,"markId","");m(this,"onPointerUp",()=>{this.complete()});m(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{originPagePoint:r}=this.editor.inputs,o=$e();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(Fr),scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]).select(o).setCurrentTool("select.resizing",{...t,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:t}=this.editor.inputs,r=$e();this.markId=`creating:${r}`,this.editor.mark(this.markId);const o=this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1,s=this.editor.getStyleForNextShape(Fr),i=s==="star"?{w:200,h:190}:s==="cloud"?{w:300,h:180}:{w:200,h:200};this.editor.createShapes([{id:r,type:"geo",x:t.x,y:t.y,props:{geo:this.editor.getStyleForNextShape(Fr),scale:o,...i}}]);const a=this.editor.getShape(r);if(!a)return;const{w:l,h:c}=a.props,d=new w(l/2,c/2).mul(o),h=this.editor.getShapeParentTransform(a);h&&d.rot(-h.rotation()),this.editor.select(r),this.editor.updateShape({id:a.id,type:"geo",x:a.x-d.x,y:a.y-d.y,props:{geo:this.editor.getStyleForNextShape(Fr),w:l*o,h:c*o}}),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select",{})}cancel(){this.parent.transition("idle")}},m($y,"id","pointing"),$y);class Bh extends se{constructor(){super(...arguments);m(this,"shapeType","geo")}}m(Bh,"id","geo"),m(Bh,"initial","idle"),m(Bh,"children",()=>[EY,kY]);class Uh extends se{constructor(){super(...arguments);m(this,"shapeType","highlight");m(this,"onExit",()=>{const t=this.children.drawing;t.initialShape=void 0})}}m(Uh,"id","highlight"),m(Uh,"initial","idle"),m(Uh,"children",()=>[J2,o0]);var Fy;let _Y=(Fy=class extends se{constructor(){super(...arguments);m(this,"shapeId","");m(this,"onEnter",t=>{this.shapeId=t.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(Fy,"id","idle"),Fy);const QC=2;var Ny;let TY=(Ny=class extends se{constructor(){super(...arguments);m(this,"shape",{});m(this,"markId");m(this,"onEnter",t=>{const{inputs:r}=this.editor,{currentPagePoint:o}=r;this.markId=void 0;const s=t.shapeId&&this.editor.getShape(t.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(on),l=a[a.length-1],c=a[a.length-2],d=oe.applyToPoint(this.editor.getShapeParentTransform(this.shape),new w(this.shape.x,this.shape.y)),h=w.Sub(o,d).addXY(.1,.1),p=rt(this.shape.props.points);if(w.DistMin(l,c,QC)||w.DistMin(h,l,QC))p[l.id]={id:l.id,index:l.index,x:h.x,y:h.y};else{const f=Lo(l.index);p[f]={id:f,index:f,x:h.x,y:h.y}}this.editor.updateShapes([{id:this.shape.id,type:this.shape.type,props:{points:p}}])}else{const i=$e();this.markId=`creating:${i}`,this.editor.mark(this.markId),this.editor.createShapes([{id:i,type:"line",x:o.x,y:o.y,props:{scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}}]),this.editor.select(i),this.shape=this.editor.getShape(i)}});m(this,"onPointerMove",()=>{if(this.shape&&this.editor.inputs.isDragging){const t=this.editor.getShapeHandles(this.shape);if(!t)throw this.markId&&this.editor.bailToMark(this.markId),Error("No handles found");const r=Nt(t);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(Ny,"id","pointing"),Ny);class Hh extends se{constructor(){super(...arguments);m(this,"shapeType","line")}}m(Hh,"id","line"),m(Hh,"initial","idle"),m(Hh,"children",()=>[_Y,TY]);var zy;let MY=(zy=class extends se{constructor(){super(...arguments);m(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(zy,"id","idle"),zy);function Ke(e,n){var o;const t=new Set;for(const s of n){const i=e.getShape(s);if(!i)continue;e.getShapeUtil(i).onDragShapesOut&&t.add(i);const a=e.getShape(i.parentId);a&&e.getShapeUtil(a).onDragShapesOut&&t.add(a)}const r=new Map;for(const s of t){const i=ej(e,s);i.length&&r.set(s,i)}for(const[s,i]of r){const a=e.getShapeUtil(s),l=me(i.map(c=>e.getShape(c)));(o=a.onDragShapesOut)==null||o.call(a,s,l)}}function ej(e,n){const t=e.getSortedChildIdsForParent(n.id);if(t.length===0)return[];const r=e.getShapePageBounds(n);if(!r)return[];let o,s,i;const a=[];for(const l of t){const c=e.getShapePageBounds(l);if(!c)continue;if(!r.includes(c)){a.push(l);continue}o??(o=e.getShapeGeometry(n)),s??(s=e.getShapePageTransform(n)),i??(i=s.applyToPoints(o.vertices));const d=e.getShapePageTransform(l).clone().invert().applyToPoints(i),{vertices:h,isClosed:p}=e.getShapeGeometry(l);if(!h.some(f=>tr(f,d))){if(p){if(I2(d,h))continue}else if(DW(d,h))continue;a.push(l)}}return a}function mf(e,n,t=!1){e.select(n),e.setEditingShape(n),e.setCurrentTool("select.editing_shape",{target:"shape",shape:n}),t&&e.emit("select-all-text",{shapeId:n.id}),tj(e)}const jY=16;function tj(e){const n=e.getSelectionPageBounds(),t=e.getViewportPageBounds();if(n&&!t.contains(n)){const r=n.clone().expandBy(jY/e.getZoomLevel()).expand(t),o=t.clone().translate({x:(r.center.x-t.center.x)*2,y:(r.center.y-t.center.y)*2});e.zoomToBounds(o,{animation:{duration:e.options.animationMediumMs},inset:0})}}const _i=20,AY=0,Be=200,hg=new w(Be/2,Be/2),nj=10,OY=[[["a1"],new w(Be*.5,Be*-.5-_i)],[["a2"],new w(Be*1.5+_i,Be*.5)],[["a3"],new w(Be*.5,Be*1.5+_i)],[["a4"],new w(Be*-.5-_i,Be*.5)]];function DY(e){if(e===1)return OY;const n=Be*e,t=_i*e;return[[["a1"],new w(n*.5,n*-.5-t)],[["a2"],new w(n*1.5+t,n*.5)],[["a3"],new w(n*.5,n*1.5+t)],[["a4"],new w(n*-.5-t,n*.5)]]}function rj(e,n,t,r,o){return Object.fromEntries(DY(o).map(([s,i],a)=>{const l=i.clone();return a===0&&r?l.y-=r:a===2&&t&&(l.y+=t),[s,l.rot(n).add(e)]}))}function oj(e,n,t,r){const o=new Set(e.getSelectedShapeIds()),s=(Be+_i+r)**2,i=new Map,a=[];for(const d of e.getCurrentPageShapes()){if(!e.isShapeOfType(d,"note")||t!==d.props.scale||o.has(d.id))continue;const h=e.getShapePageTransform(d.id);n===h.rotation()&&(i.set(d,e.getShapePageBounds(d).center),a.push(...Object.values(rj(h.point(),n,d.props.growY,r,t))))}const l=a.length;let c;for(const[d,h]of i)for(let p=0;ps||e.isPointInShape(d,c)&&(a[p]=void 0));return me(a)}function sj(e,n,t,r,o=!1){let s;const i=e.getCurrentPageShapesSorted(),a=(Be+_i**2)**n.props.scale;for(let l=i.length-1;l>=0;l--){const c=i[l];if(c.type==="note"&&c.id!==n.id){const d=e.getShapePageBounds(c);if(d&&w.Dist2(d.center,t){const{editor:t}=this;if(this.wasFocusedOnEnter=!t.getIsMenuOpen(),this.wasFocusedOnEnter){const r=$e();this.markId=`creating:${r}`,t.mark(this.markId);const o=this.editor.inputs.originPagePoint.clone(),s=JC(this.editor,o,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);s&&o.sub(s),this.shape=eI(this.editor,r,o)}});m(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){if(!this.wasFocusedOnEnter){const r=$e(),o=this.editor.inputs.originPagePoint.clone(),s=JC(this.editor,o,this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1);s&&o.sub(s),this.shape=eI(this.editor,r,o)}this.editor.setCurrentTool("select.translating",{...t,target:"shape",shape:this.shape,onInteractionEnd:"note",isCreating:!0,onCreate:()=>{this.editor.setEditingShape(this.shape.id),this.editor.setCurrentTool("select.editing_shape")}})}});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(By,"id","pointing"),By);function JC(e,n,t){let r=nj/e.getZoomLevel(),o;for(const s of oj(e,0,t,0)){const i=w.Sub(n,s),a=i.len();a[MY,RY]);function LY(e){const n=e.getShapeAtPoint(e.inputs.currentPagePoint,{hitInside:!1,hitLabels:!1,margin:e.options.hitTestMargin/e.getZoomLevel(),renderingOnly:!0});if(!n)return e.setHoveredShape(null);let t;const r=e.getOutermostSelectableShape(n);return r===n||r.id===e.getFocusedGroupId()||e.getSelectedShapeIds().includes(r.id)?t=n:t=r,e.setHoveredShape(t.id)}const Bo=fw(LY,32);var Uy;let $Y=(Uy=class extends se{constructor(){super(...arguments);m(this,"onPointerMove",t=>{switch(t.target){case"shape":case"canvas":Bo(this.editor)}});m(this,"onPointerDown",t=>{this.parent.transition("pointing",t)});m(this,"onEnter",()=>{this.editor.setCursor({type:"cross",rotation:0})});m(this,"onExit",()=>{Bo.cancel()});m(this,"onKeyDown",t=>{var r;if(t.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",{...t,target:"shape",shape:o}))}});m(this,"onCancel",()=>{this.editor.setCurrentTool("select")})}},m(Uy,"id","idle"),Uy);var Hy;let FY=(Hy=class extends se{constructor(){super(...arguments);m(this,"shape");m(this,"markId","");m(this,"onExit",()=>{this.editor.setHintingShapes([])});m(this,"onPointerMove",t=>{if(this.editor.inputs.isDragging){const{inputs:{originPagePoint:r}}=this.editor,o=$e();this.markId=`creating:${o}`,this.editor.mark(this.markId);const s=this.createTextShape(o,r,!1);if(!s){this.cancel();return}this.shape=this.editor.getShape(s),this.editor.select(o),this.editor.setCurrentTool("select.resizing",{...t,target:"selection",handle:"right",isCreating:!0,creationCursorOffset:{x:18,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 t=$e(),{currentPagePoint:r}=this.editor.inputs;this.createTextShape(t,r,!0)&&(this.editor.select(t),this.editor.setEditingShape(t),this.editor.setCurrentTool("select"),(s=this.editor.root.getCurrent())==null||s.transition("editing_shape"))}cancel(){this.parent.transition("idle"),this.editor.bailToMark(this.markId)}createTextShape(t,r,o){this.editor.createShape({id:t,type:"text",x:r.x,y:r.y,props:{text:"",autoSize:o,w:20,scale:this.editor.user.getIsDynamicResizeMode()?1/this.editor.getZoomLevel():1}});const s=this.editor.getShape(t);if(!s){this.cancel();return}const i=this.editor.getShapePageBounds(s),a=new w;if(o)switch(s.props.textAlign){case"start":{a.x=0;break}case"middle":{a.x=-i.width/2;break}case"end":{a.x=-i.width;break}}else a.x=0;if(a.y=-i.height/2,kn(s.parentId)){const l=this.editor.getShapeParentTransform(s);a.rot(-l.rotation())}return this.editor.updateShape({...s,x:s.x+a.x,y:s.y+a.y}),s}},m(Hy,"id","pointing"),Hy);class Wh extends se{constructor(){super(...arguments);m(this,"shapeType","text")}}m(Wh,"id","text"),m(Wh,"initial","idle"),m(Wh,"children",()=>[$Y,FY]);const NY=[Wh,zh,Bh,Kh,Hh,Cv,Nh,Uh];function _r(){return ss({isDarkMode:Wu()})}function vl(e){return{key:`${So.id}:${e}`,getElement:async()=>{const n=zY(e);if(!n)return null;const t=n.$$_url,r=n.$$_fontface;if(!t||!r)return null;const o=await(await yo(t)).blob(),s=await Oi.blobToDataUrl(o),i=r.replace(t,s);return u.jsx("style",{children:i})}}}function zY(e){const n=oM[e];for(const t of document.fonts)if(n.includes(t.family))return t;return null}function s0(e){return{key:`${So.id}:${e}`,getElement:async()=>e!=="pattern"?null:u.jsx(BY,{})}}function BY(){const e=_r(),n=8/12;return u.jsxs(u.Fragment,{children:[u.jsxs("mask",{id:"hash_pattern_mask",children:[u.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:"white"}),u.jsxs("g",{strokeLinecap:"round",stroke:"black",children:[u.jsx("line",{x1:n*1,y1:n*3,x2:n*3,y2:n*1}),u.jsx("line",{x1:n*5,y1:n*7,x2:n*7,y2:n*5}),u.jsx("line",{x1:n*9,y1:n*11,x2:n*11,y2:n*9})]})]}),u.jsx("pattern",{id:yf(1,e.id),width:"8",height:"8",patternUnits:"userSpaceOnUse",children:u.jsx("rect",{x:"0",y:"0",width:"8",height:"8",fill:e.solid,mask:"url(#hash_pattern_mask)"})})]})}function i0(){return{key:`${So.id}:pattern`,component:WY}}const Ic=8,tI=(e,n,t)=>new Promise((r,o)=>{const s=Ic*n*e,i=document.createElement("canvas");i.width=s,i.height=s;const a=i.getContext("2d");if(!a)return;a.fillStyle=t?tf.darkMode.solid:tf.lightMode.solid,a.fillRect(0,0,s,s),a.globalCompositeOperation="destination-out",a.lineCap="round",a.lineWidth=1.25*n*e;const l=8/12,c=d=>d*n*e;a.beginPath(),a.moveTo(c(l*1),c(l*3)),a.lineTo(c(l*3),c(l*1)),a.moveTo(c(l*5),c(l*7)),a.lineTo(c(l*7),c(l*5)),a.moveTo(c(l*9),c(l*11)),a.lineTo(c(l*11),c(l*9)),a.stroke(),i.toBlob(d=>{!d||wt.throwToBlob.get()?o():r(d)})}),nI=(e,n)=>{const t=document.createElement("canvas");t.width=e[0],t.height=e[1];const r=t.getContext("2d");return r?(n(r),t.toDataURL()):""};let cy=null;function UY(){return cy||(cy={white:nI([1,1],e=>{e.fillStyle="#f8f9fa",e.fillRect(0,0,1,1)}),black:nI([1,1],e=>{e.fillStyle="#212529",e.fillRect(0,0,1,1)})}),cy}function ij(e){return Math.ceil(Math.log2(Math.max(1,e)))}function yf(e,n){const t=ij(e);return`tldraw_hash_pattern_${n}_${t}`}function aj(e){const n=[],r=ij(e);for(let o=0;o<=r;o++)n.push(Math.pow(2,o));return n}function HY(e){const n=UY();return aj(e).flatMap(t=>[{zoom:t,url:n.white,theme:"light"},{zoom:t,url:n.black,theme:"dark"}])}function KY(){const e=B(),n=G("devicePixelRatio",()=>e.getInstanceState().devicePixelRatio,[e]),t=G("maxZoom",()=>Math.ceil(Nt(e.getCameraOptions().zoomSteps)),[e]),[r,o]=P.useState(!1),[s,i]=P.useState(()=>HY(t));return P.useEffect(()=>{const l=Promise.all(aj(t).flatMap(d=>[tI(n,d,!1).then(h=>({zoom:d,theme:"light",url:URL.createObjectURL(h)})),tI(n,d,!0).then(h=>({zoom:d,theme:"dark",url:URL.createObjectURL(h)}))]));let c=!1;return l.then(d=>{c||(i(d),o(!0))}),()=>{c=!0,o(!1),l.then(d=>{for(const{url:h}of d)URL.revokeObjectURL(h)})}},[n,t]),{defs:u.jsx(u.Fragment,{children:s.map(l=>{const c=yf(l.zoom,l.theme);return u.jsx("pattern",{id:c,width:Ic,height:Ic,patternUnits:"userSpaceOnUse",children:u.jsx("image",{href:l.url,width:Ic,height:Ic})},c)})}),isReady:r}}function WY(){const e=B(),n=P.useRef(null),{defs:t,isReady:r}=KY();return P.useEffect(()=>{if(r&&e.environment.isSafari){const o=lj(n.current);o&&e.timers.requestAnimationFrame(()=>{o.style.display="none",e.timers.requestAnimationFrame(()=>{o.style.display=""})})}},[e,r]),u.jsx("g",{ref:n,"data-testid":r?"ready-pattern-fill-defs":void 0,children:t})}function lj(e){return e.classList.contains("tl-html-layer")?e:e.parentElement?lj(e.parentElement):null}const en=xe.memo(function({theme:n,d:t,color:r,fill:o,scale:s}){switch(o){case"none":return null;case"solid":return u.jsx("path",{fill:n[r].semi,d:t});case"semi":return u.jsx("path",{fill:n.solid,d:t});case"fill":return u.jsx("path",{fill:n[r].fill,d:t});case"pattern":return u.jsx(GY,{theme:n,color:r,fill:o,d:t,scale:s})}});function GY({d:e,color:n,theme:t}){const r=B(),o=M2(),s=G("zoomLevel",()=>r.getZoomLevel(),[r]),i=r.getZoomLevel()<=.18;return u.jsxs(u.Fragment,{children:[u.jsx("path",{fill:t[n].pattern,d:e}),u.jsx("path",{fill:o?`url(#${yf(1,t.id)})`:i?t[n].semi:`url(#${yf(s,t.id)})`,d:e})]})}function VY(e){return e.replace(/\s/g," ")}function Iv(e,n,t){const{padding:r=0}=t;if(n.length===0)return null;const o=Z.From(n[0].box);for(const{box:c}of n)o.union(c);const s=r+(t.offsetX??0),i=(t.offsetY??0)+t.fontSize/2+(t.verticalTextAlign==="start"?r:t.verticalTextAlign==="end"?t.height-r-o.height:(Math.ceil(t.height)-o.height)/2);let a=null;const l=[];for(const{text:c,box:d}of n)a!==null&&d.y>a&&l.push(u.jsx("tspan",{alignmentBaseline:"mathematical",x:s,y:d.y+i,children:` `},l.length)),l.push(u.jsx("tspan",{alignmentBaseline:"mathematical",x:d.x+s,y:d.y+i,unicodeBidi:"plaintext",children:VY(c)},l.length)),a=d.y;return u.jsx("text",{fontSize:t.fontSize,fontFamily:t.fontFamily,fontStyle:t.fontFamily,fontWeight:t.fontWeight,dominantBaseline:"mathematical",alignmentBaseline:"mathematical",stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,children:l})}function YY(e,n,t,r){if((e==="start-legacy"||e==="end-legacy")&&t.length!==0){const o=Z.From(t[0].box);for(const{box:s}of t)o.union(s);if(e==="start-legacy")return(r-2*n-o.width)/2;if(e==="end-legacy")return-(r-2*n-o.width)/2}}function XY(e){return e==="start-legacy"||e==="middle-legacy"||e==="end-legacy"}function pg({fontSize:e,font:n,align:t,verticalAlign:r,text:o,labelColor:s,bounds:i,padding:a=16,stroke:l=!0}){const c=B(),d=_r(),h={fontSize:e,fontFamily:oM[n],textAlign:t,verticalTextAlign:r,width:Math.ceil(i.width),height:Math.ceil(i.height),padding:a,lineHeight:Wt.lineHeight,fontStyle:"normal",fontWeight:"normal",overflow:"wrap",offsetX:0,offsetY:0,fill:s,stroke:void 0,strokeWidth:void 0},p=c.textMeasure.measureTextSpans(o,h),f=YY(t,a,p,i.width);f&&(h.offsetX=f),h.offsetX+=i.x,h.offsetY+=i.y;const S=Iv(c,p,h);let g=null;return l&&(h.fill=d.background,h.stroke=d.background,h.strokeWidth=2,g=Iv(c,p,h)),u.jsxs(u.Fragment,{children:[g,S]})}const qY=P.forwardRef(function({isEditing:n,text:t,handleFocus:r,handleChange:o,handleKeyDown:s,handleBlur:i,handleInputPointerDown:a,handleDoubleClick:l},c){return u.jsx("textarea",{ref:c,className:"tl-text tl-text-input",name:"text",tabIndex:-1,readOnly:!n,autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",autoSave:"off",placeholder:"",spellCheck:"true",wrap:"off",dir:"auto",defaultValue:t,onFocus:r,onChange:o,onKeyDown:s,onBlur:i,onTouchEnd:Kt,onContextMenu:n?Kt:void 0,onPointerDown:a,onDoubleClick:l,onDragStart:Ee})});function ZY(e,n,t){const r=B(),o=P.useRef(null),s=G("isEditing",()=>r.getEditingShapeId()===e,[r]),i=G("isEditingAnything",()=>!!r.getEditingShapeId(),[r]);P.useEffect(()=>{function d({shapeId:h}){var p;h===e&&((p=o.current)==null||p.select())}return r.on("select-all-text",d),()=>{r.off("select-all-text",d)}},[r,e,s]),P.useEffect(()=>{var d,h,p,f;s&&(document.activeElement!==o.current&&((d=o.current)==null||d.focus()),r.getInstanceState().isCoarsePointer&&((h=o.current)==null||h.select()),r.environment.isSafari&&((p=o.current)==null||p.blur(),(f=o.current)==null||f.focus()))},[r,s]);const a=P.useCallback(d=>{if(r.getEditingShapeId()===e)switch(d.key){case"Enter":{(d.ctrlKey||d.metaKey)&&r.complete();break}}},[r,e]),l=P.useCallback(d=>{if(r.getEditingShapeId()!==e)return;let h=Sl.normalizeText(d.currentTarget.value);const p=h.replace(/\t/g,Va);if(p!==h){const f=d.currentTarget.selectionStart;d.currentTarget.value=p,d.currentTarget.selectionStart=f+(p.length-h.length),d.currentTarget.selectionEnd=f+(p.length-h.length),h=p}r.updateShape({id:e,type:n,props:{text:h}})},[r,e,n]),c=P.useCallback(d=>{r.dispatch({...On(d),type:"pointer",name:"pointer_down",target:"shape",shape:r.getShape(e)}),Kt(d)},[r,e]);return{rInput:o,handleFocus:Wp,handleBlur:Wp,handleKeyDown:a,handleChange:l,handleInputPointerDown:c,handleDoubleClick:Kt,isEmpty:t.trim().length===0,isEditing:s,isEditingAnything:i}}const fg=xe.memo(function({id:n,type:t,text:r,labelColor:o,font:s,fontSize:i,lineHeight:a,align:l,verticalAlign:c,wrap:d,isSelected:h,padding:p=0,onKeyDown:f,classNamePrefix:S,style:g,textWidth:x,textHeight:y}){const{rInput:v,isEmpty:b,isEditing:E,isEditingAnything:I,...C}=ZY(n,t,r),[k,T]=P.useState(r);P.useEffect(()=>{E||T(r)},[E,r]);const O=Sl.normalizeTextForDom(r),_=O.length>0,j=XY(l);if(!E&&!_)return null;const L=S||"tl-text";return u.jsx("div",{className:`${L}-label tl-text-wrapper`,"data-font":s,"data-align":l,"data-hastext":!b,"data-isediting":E,"data-iseditinganything":I,"data-textwrap":!!d,"data-isselected":h,style:{justifyContent:l==="middle"||j?"center":l,alignItems:c==="middle"?"center":c,padding:p,...g},children:u.jsxs("div",{className:`${L}-label__inner tl-text-content__wrapper`,style:{fontSize:i,lineHeight:Math.floor(i*a)+"px",minHeight:Math.floor(i*a)+"px",minWidth:Math.ceil(x||0),color:o,width:x?Math.ceil(x):void 0,height:y?Math.ceil(y):void 0},children:[u.jsx("div",{className:`${L} tl-text tl-text-content`,dir:"auto",children:O.split(` `).map((A,R)=>u.jsx("div",{dir:"auto",children:A},R))}),(I||h)&&u.jsx(qY,{ref:v,text:r,isEditing:E,...C,handleKeyDown:f??C.handleKeyDown},k)]})})});function ro(e,n,t={}){const{closed:r=!1,snap:o=1,start:s="outset",end:i="outset",lengthRatio:a=2,style:l="dashed"}=t;let c=0,d=0,h=1,p=0,f=0;switch(l){case"dashed":{h=1,c=Math.min(n*a,e/4);break}case"dotted":{h=100,c=n/h;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(s==="outset"?(e+=c/2,f+=c/2):s==="skip"&&(e-=c,f-=c),i==="outset"?e+=c/2:i==="skip"&&(e-=c)),d=Math.floor(e/c/(2*h)),d-=d%o,d<3&&l==="dashed"?e/n<4?(c=e,d=1,p=0):(c=e*(1/3),p=e*(1/3)):(c=e/d/(2*h),r?(f=c/2,p=(e-d*c)/d):p=(e-d*c)/Math.max(1,d-1)),{strokeDasharray:[c,p].join(" "),strokeDashoffset:f.toString()}}const rI=new WeakMap;function a0(e,n){const t=rI.get(n);if(t)return t;const r=co(e,n);let o=0,s=0;const i=r.isStraight?new zo({start:w.From(r.start.point),end:w.From(r.end.point)}):new Ha({center:w.Cast(r.handleArc.center),start:w.Cast(r.start.point),end:w.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});if(n.props.text.trim()){const l=i.bounds,c=Ev(n),{w:d,h}=e.textMeasure.measureText(n.props.text,{...Wt,fontFamily:mo[n.props.font],fontSize:c,maxWidth:null});if(o=d,s=h,l.width>l.height){o=Math.max(Math.min(d,64),Math.min(l.width-64,d));const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Wt,fontFamily:mo[n.props.font],fontSize:c,maxWidth:o});o=p,s=f}if(o>16*c){o=16*c;const{w:p,h:f}=e.textMeasure.measureText(n.props.text,{...Wt,fontFamily:mo[n.props.font],fontSize:c,maxWidth:o});o=p,s=f}}const a=new w(o,s).addScalar(WV*2*n.props.scale);return rI.set(n,a),a}function cj(e){const n=At[e.props.size];return(KV+(n-At.s)*2+(n===At.xl?20:0))*e.props.scale}function QY(e,n,t){const r=a0(e,n),o=cj(n),s=w.Nudge(t.start.point,t.end.point,o),i=w.Nudge(t.end.point,t.start.point,o),a=Gw(s,i,Z.FromCenter(t.middle,r).corners);if(!a||a.length!==2)return{start:.5,end:.5};let[l,c]=a;w.Dist2(l,s)>w.Dist2(c,s)&&([c,l]=a);const d=s.add(w.Sub(t.middle,l)),h=i.add(w.Sub(t.middle,c)),p=w.Dist(t.start.point,d)/t.length,f=w.Dist(t.start.point,h)/t.length;return{start:p,end:f}}function JY(e,n,t){const r=a0(e,n),o=cj(n),s=Math.sign(n.props.bend),i=o/t.handleArc.radius*s,a=w.Angle(t.bodyArc.center,t.start.point)-i,l=w.Angle(t.bodyArc.center,t.end.point)+i,c=Gi(t.bodyArc.center,t.bodyArc.radius,a),d=Gi(t.bodyArc.center,t.bodyArc.radius,l),h=[],p=oI(t.bodyArc.center,t.bodyArc.radius,a,l,s,Z.FromCenter(c,r).corners);h.push(new vt({points:Z.FromCenter(c,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));const f=oI(t.bodyArc.center,t.bodyArc.radius,a,l,s,Z.FromCenter(d,r).corners);h.push(new vt({points:Z.FromCenter(d,r).corners,debugColor:"lime",isFilled:!1,ignore:!0}));for(const k of[...p??[],...f??[],c,d])h.push(new t0({x:k.x-3,y:k.y-3,radius:3,isFilled:!1,debugColor:"magenta",ignore:!0}));const S=(p&&sI(t.start.point,p))??t.middle,g=(f&&sI(t.end.point,f))??t.middle,x=w.Angle(t.bodyArc.center,t.start.point),y=w.Angle(t.bodyArc.center,t.end.point),v=w.Angle(t.bodyArc.center,S),b=w.Angle(t.bodyArc.center,g);if(Is(x,v,s)>Is(x,b,s))return{start:.5,end:.5,dbg:h};const E=Is(x,y,s),I=Is(x,v,s)/E,C=Is(x,b,s)/E;return{start:I,end:C,dbg:h}}function Gh(e,n){let t;const r=[],o=co(e,n),s=!!o.bindings.start,i=!!o.bindings.end,a=o.start.arrowhead!=="none",l=o.end.arrowhead!=="none";if(o.isStraight){const d=QY(e,n,o);let h=_t(n.props.labelPosition,a||s?d.start:0,l||i?d.end:1);h=h>=.48&&h<=.52?.5:h,t=w.Lrp(o.start.point,o.end.point,h)}else{const d=JY(e,n,o);d.dbg&&r.push(...d.dbg);let h=_t(n.props.labelPosition,a||s?d.start:0,l||i?d.end:1);h=h>=.48&&h<=.52?.5:h;const p=eX(w.Angle(o.bodyArc.center,o.start.point),w.Angle(o.bodyArc.center,o.end.point),Math.sign(n.props.bend),h);t=Gi(o.bodyArc.center,o.bodyArc.radius,p)}const c=a0(e,n);return{box:Z.FromCenter(t,c),debugGeom:r}}function oI(e,n,t,r,o,s){const i=Sv(e,n,s),a=Is(t,r,o);return i==null?void 0:i.filter(l=>{const c=Is(t,w.Angle(e,l),o);return c>=0&&c<=a})}function sI(e,n){let t=null,r=-1/0;for(const o of n){const s=w.Dist2(e,o);s>r&&(t=o,r=s)}return t}function eX(e,n,t,r){const o=Is(e,n,t);return e+o*r*t*-1}function Ev(e){return HV[e.props.size]*e.props.scale}function tX(e,n,t){const r=n==="end"?e.end.point:e.start.point,o=n==="end"?e.start.point:e.end.point,s=e.isStraight?w.Dist(o,r):Math.abs(e.bodyArc.length),i=Math.max(Math.min(s/5,t*3),t);let a;if(e.isStraight)a=w.Nudge(r,o,i);else{const l=AW(r,i,e.handleArc.center,e.handleArc.radius);a=n==="end"?e.handleArc.sweepFlag?l[0]:l[1]:e.handleArc.sweepFlag?l[1]:l[0]}return w.IsNaN(a)&&(a=e.start.point),{point:r,int:a}}function nX({point:e,int:n}){const t=w.RotWith(n,e,_e/6),r=w.RotWith(n,e,-_e/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y}`}function rX({point:e,int:n}){const t=w.RotWith(n,e,_e/6),r=w.RotWith(n,e,-_e/6);return`M ${t.x} ${t.y} L ${e.x} ${e.y} L ${r.x} ${r.y} Z`}function oX({point:e,int:n}){const t=w.Sub(n,e).div(2),r=w.Add(e,w.Rot(t,Ve)),o=w.Sub(e,w.Rot(t,Ve));return`M ${r.x} ${r.y} L ${n.x} ${n.y} L ${o.x} ${o.y} Z`}function sX({point:e,int:n}){const t=w.Lrp(e,n,.45),r=w.Dist(t,e);return`M ${t.x-r},${t.y} a ${r},${r} 0 1,0 ${r*2},0 a ${r},${r} 0 1,0 -${r*2},0 `}function iX({point:e,int:n}){const t=w.Lrp(e,n,.75),r=w.RotWith(t,e,_e/4),o=w.RotWith(t,e,-_e/4),s=w.Lrp(r,o,.5);return s.add(w.Sub(s,e)),`M ${s.x} ${s.y} L ${r.x} ${r.y} ${e.x} ${e.y} L ${o.x} ${o.y} Z`}function aX({int:e,point:n}){const t=w.Lrp(n,e,.85),r=w.Sub(t,n).div(2),o=w.Add(n,w.Rot(r,Ve)),s=w.Sub(n,w.Rot(r,Ve)),i=w.Add(t,w.Rot(r,Ve)),a=w.Sub(t,w.Rot(r,Ve));return`M ${o.x} ${o.y} L ${i.x} ${i.y} L ${a.x} ${a.y} L ${s.x} ${s.y} Z`}function lX({int:e,point:n}){const t=w.Sub(e,n).div(2),r=w.Add(n,w.Rot(t,Ve)),o=w.Sub(n,w.Rot(t,Ve));return`M ${r.x} ${r.y} L ${o.x} ${o.y}`}function Sf(e,n,t){const r=n==="end"?e.end.arrowhead:e.start.arrowhead;if(r==="none")return;const o=tX(e,n,t);if(o){switch(r){case"bar":return lX(o);case"square":return aX(o);case"diamond":return iX(o);case"dot":return sX(o);case"inverted":return oX(o);case"arrow":return nX(o);case"triangle":return rX(o)}return""}}function cX(e){const{start:n,end:t,handleArc:{radius:r,largeArcFlag:o,sweepFlag:s}}=e;return`M${n.handle.x},${n.handle.y} A${r} ${r} 0 ${o} ${s} ${t.handle.x},${t.handle.y}`}function uj(e){const{start:n,end:t,bodyArc:{radius:r,largeArcFlag:o,sweepFlag:s}}=e;return`M${n.point.x},${n.point.y} A${r} ${r} 0 ${o} ${s} ${t.point.x},${t.point.y}`}function dj(e,n){return`M${e.x},${e.y}L${n.x},${n.y}`}function uX(e){return dj(e.start.handle,e.end.handle)}function hj(e){return dj(e.start.point,e.end.point)}let dX=0;class Vh extends Br{constructor(){super(...arguments);m(this,"canEdit",()=>!0);m(this,"canSnap",()=>!1);m(this,"hideResizeHandles",()=>!0);m(this,"hideRotateHandle",()=>!0);m(this,"hideSelectionBoundsBg",()=>!0);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"canBeLaidOut",t=>{const r=Mn(this.editor,t);return!r.start&&!r.end});m(this,"onHandleDrag",(t,{handle:r,isPrecise:o})=>{const s=r.id,i=Mn(this.editor,t);if(s==="middle"){const{start:C,end:k}=Ka(this.editor,t,i),T=w.Sub(k,C),O=w.Per(T),_=w.Med(k,C),j=w.Sub(_,O),L=w.Add(_,O),A=w.NearestPointOnLineSegment(j,L,r,!1);let R=w.Dist(A,_);return w.Clockwise(A,k,_)&&(R*=-1),{id:t.id,type:t.type,props:{bend:R}}}const a={id:t.id,type:"arrow",props:{}},l=i[s],d=i[s==="start"?"end":"start"];if(this.editor.inputs.ctrlKey)return $h(this.editor,t,s),a.props[s]={x:r.x,y:r.y},a;const h=this.editor.getShapePageTransform(t.id).applyToPoint(r),p=this.editor.getShapeAtPoint(h,{hitInside:!0,hitFrameInside:!0,margin:0,filter:C=>!C.isLocked&&this.editor.canBindShapes({fromShape:t,toShape:C,binding:"arrow"})});if(!p)return $h(this.editor,t,s),a.props[s]={x:r.x,y:r.y},a;const f=this.editor.getShapeGeometry(p),S=Z.ZeroFix(f.bounds),x=this.editor.getShapePageTransform(a.id).applyToPoint(r),y=this.editor.getPointInShapeSpace(p,x);let v=o;v||(!l||l&&p.id!==l.toId)&&(v=this.editor.inputs.pointerVelocity.len()<.5),o||(f.isClosed||(v=!0),d&&p.id===d.toId&&d.props.isPrecise&&(v=!0));const b={x:(y.x-S.minX)/S.width,y:(y.y-S.minY)/S.height};v&&w.Dist(y,S.center){const r=Mn(this.editor,t),o=Ka(this.editor,t,r),s=this.editor.getShapePageTransform(t.id),i=this.editor.getSelectedShapeIds();if(!(r.start&&(i.includes(r.start.toId)||this.editor.isAncestorSelected(r.start.toId))||r.end&&(i.includes(r.end.toId)||this.editor.isAncestorSelected(r.end.toId)))){aI.set(t,{pagePosition:s.applyToPoint(t),terminalBindings:Ru(o,(a,l)=>{const c=r[a];return c?{binding:c,shapePosition:l,pagePosition:s.applyToPoint(l)}:null})}),r.start&&(gf({editor:this.editor,arrow:t,terminal:"start",useHandle:!0}),t=this.editor.getShape(t.id)),r.end&&gf({editor:this.editor,arrow:t,terminal:"end",useHandle:!0});for(const a of["start","end"]){const l=r[a];l&&this.editor.updateBinding({...l,props:{...l.props,isPrecise:!0}})}}});m(this,"onTranslate",(t,r)=>{const o=aI.get(t);if(!o)return;const s=this.editor.getShapePageTransform(r.id),i=w.Sub(s.applyToPoint(r),o.pagePosition);for(const a of Object.values(o.terminalBindings)){if(!a)continue;const l=w.Add(a.pagePosition,w.Mul(i,.5)),c=this.editor.getShapeAtPoint(l,{hitInside:!0,hitFrameInside:!0,margin:0,filter:d=>!d.isLocked&&this.editor.canBindShapes({fromShape:r,toShape:d,binding:"arrow"})});if((c==null?void 0:c.id)===a.binding.toId){const d=Z.ZeroFix(this.editor.getShapeGeometry(c).bounds),h=this.editor.getPointInShapeSpace(c,l),p={x:(h.x-d.minX)/d.width,y:(h.y-d.minY)/d.height};cc(this.editor,r,c.id,{...a.binding.props,normalizedAnchor:p,isPrecise:!0})}else $h(this.editor,r,a.binding.props.terminal)}});m(this,"_resizeInitialBindings",new Zo);m(this,"onResize",(t,r)=>{const{scaleX:o,scaleY:s}=r,i=this._resizeInitialBindings.get(t,()=>Mn(this.editor,t)),a=Ka(this.editor,t,i),{start:l,end:c}=rt(t.props);let{bend:d}=t.props;i.start||(l.x=a.start.x*o,l.y=a.start.y*s),i.end||(c.x=a.end.x*o,c.y=a.end.y*s);const h=Math.abs(o),p=Math.abs(s),f=i!=null&&i.start?w.From(i.start.props.normalizedAnchor):null,S=i!=null&&i.end?w.From(i.end.props.normalizedAnchor):null;return o<0&&s>=0?(d!==0&&(d*=-1,d*=Math.max(h,p)),f&&(f.x=1-f.x),S&&(S.x=1-S.x)):o>=0&&s<0?(d!==0&&(d*=-1,d*=Math.max(h,p)),f&&(f.y=1-f.y),S&&(S.y=1-S.y)):o>=0&&s>=0?d!==0&&(d*=Math.max(h,p)):o<0&&s<0&&(d!==0&&(d*=Math.max(h,p)),f&&(f.x=1-f.x,f.y=1-f.y),S&&(S.x=1-S.x,S.y=1-S.y)),i.start&&f&&cc(this.editor,t,i.start.toId,{...i.start.props,normalizedAnchor:f.toJson()}),i.end&&S&&cc(this.editor,t,i.end.toId,{...i.end.props,normalizedAnchor:S.toJson()}),{props:{start:l,end:c,bend:d}}});m(this,"onDoubleClickHandle",(t,r)=>{switch(r.id){case"start":return{id:t.id,type:t.type,props:{...t.props,arrowheadStart:t.props.arrowheadStart==="none"?"arrow":"none"}};case"end":return{id:t.id,type:t.type,props:{...t.props,arrowheadEnd:t.props.arrowheadEnd==="none"?"arrow":"none"}}}});m(this,"onEditEnd",t=>{const{id:r,type:o,props:{text:s}}=t;s.trimEnd()!==t.props.text&&this.editor.updateShapes([{id:r,type:o,props:{text:s.trimEnd()}}])})}canBind({toShapeType:t}){return t!=="arrow"}getDefaultProps(){return{dash:"draw",size:"m",fill:"none",color:"black",labelColor:"black",bend:0,start:{x:0,y:0},end:{x:2,y:0},arrowheadStart:"none",arrowheadEnd:"arrow",text:"",labelPosition:.5,font:"draw",scale:1}}getGeometry(t){const r=co(this.editor,t),o=[],s=r.isStraight?new zo({start:w.From(r.start.point),end:w.From(r.end.point)}):new Ha({center:w.Cast(r.handleArc.center),start:w.Cast(r.start.point),end:w.Cast(r.end.point),sweepFlag:r.bodyArc.sweepFlag,largeArcFlag:r.bodyArc.largeArcFlag});let i;if(t.props.text.trim()){const a=Gh(this.editor,t);o.push(...a.debugGeom),i=new Jo({x:a.box.x,y:a.box.y,width:a.box.w,height:a.box.h,isFilled:!0,isLabel:!0})}return new Hr({children:[...i?[s,i]:[s],...o]})}getHandles(t){const r=co(this.editor,t);return[{id:"start",type:"vertex",index:"a0",x:r.start.handle.x,y:r.start.handle.y},{id:"middle",type:"virtual",index:"a2",x:r.middle.x,y:r.middle.y},{id:"end",type:"vertex",index:"a3",x:r.end.handle.x,y:r.end.handle.y}].filter(Boolean)}component(t){const r=_r(),o=this.editor.getOnlySelectedShape(),s=this.editor.isInAny("select.idle","select.pointing_handle","select.dragging_handle","select.translating","arrow.dragging")&&!this.editor.getInstanceState().isReadonly,i=co(this.editor,t);if(!(i!=null&&i.isValid))return null;const a=Gh(this.editor,t),l=t.id===this.editor.getOnlySelectedShapeId(),d=this.editor.getEditingShapeId()===t.id||t.props.text;return u.jsxs(u.Fragment,{children:[u.jsx(Ys,{id:t.id,style:{minWidth:50,minHeight:50},children:u.jsx(iI,{shape:t,shouldDisplayHandles:s&&(o==null?void 0:o.id)===t.id})}),d&&u.jsx(fg,{id:t.id,classNamePrefix:"tl-arrow",type:"arrow",font:t.props.font,fontSize:Ev(t),lineHeight:Wt.lineHeight,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:r[t.props.labelColor].solid,textWidth:a.box.w,isSelected:l,padding:0,style:{transform:`translate(${a.box.center.x}px, ${a.box.center.y}px)`}})]})}indicator(t){const r=ug(t.id),o=co(this.editor,t);if(!o)return null;const{start:s,end:i}=Ka(this.editor,t,o==null?void 0:o.bindings),a=this.editor.getShapeGeometry(t),l=a.bounds,c=t.props.text.trim()?a.children[1]:null;if(w.Equals(s,i))return null;const d=At[t.props.size]*t.props.scale,h=o.start.arrowhead&&Sf(o,"start",d),p=o.end.arrowhead&&Sf(o,"end",d),f=o.isStraight?hj(o):uj(o),S=h&&o.start.arrowhead!=="arrow"||p&&o.end.arrowhead!=="arrow"||!!c,g=(t.id+"_clip").replace(":","_");return r&&c?u.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5*t.props.scale,ry:3.5*t.props.scale}):u.jsxs("g",{children:[S&&u.jsx("defs",{children:u.jsxs("mask",{id:g,children:[u.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.w+200,height:l.h+200,fill:"white"}),c&&u.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,fill:"black",rx:3.5*t.props.scale,ry:3.5*t.props.scale}),h&&u.jsx("path",{d:h,fill:o.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),p&&u.jsx("path",{d:p,fill:o.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),u.jsxs("g",{...S?{mask:`url(#${g})`}:void 0,children:[S&&u.jsx("rect",{x:l.minX-100,y:l.minY-100,width:l.width+200,height:l.height+200,opacity:0}),u.jsx("path",{d:f})]}),h&&u.jsx("path",{d:h}),p&&u.jsx("path",{d:p}),c&&u.jsx("rect",{x:N(c.x),y:N(c.y),width:c.w,height:c.h,rx:3.5,ry:3.5})]})}toSvg(t,r){r.addExportDef(s0(t.props.fill)),t.props.text&&r.addExportDef(vl(t.props.font));const o=ss(r),s=1/t.props.scale;return u.jsxs("g",{transform:`scale(${s})`,children:[u.jsx(iI,{shape:t,shouldDisplayHandles:!1}),u.jsx(pg,{fontSize:Ev(t),font:t.props.font,align:"middle",verticalAlign:"middle",text:t.props.text,labelColor:o[t.props.labelColor].solid,bounds:Gh(this.editor,t).box,padding:4*t.props.scale})]})}getCanvasSvgDefs(){return[i0(),{key:"arrow:dot",component:pX},{key:"arrow:cross",component:fX}]}}m(Vh,"type","arrow"),m(Vh,"props",iM),m(Vh,"migrations",aM);function hX(e,n){const t=co(e,n);return t.isStraight?w.Dist(t.start.handle,t.end.handle):Math.abs(t.handleArc.length)}const iI=lr(function({shape:n,shouldDisplayHandles:t}){const r=B(),o=_r(),s=co(r,n),i=Z.ZeroFix(r.getShapeGeometry(n).bounds),a=Mn(r,n),l=xe.useMemo(()=>r.environment.isSafari?dX+=1:0,[n]);if(!(s!=null&&s.isValid))return null;const c=At[n.props.size]*n.props.scale,d=s.start.arrowhead&&Sf(s,"start",c),h=s.end.arrowhead&&Sf(s,"end",c),p=s.isStraight?hj(s):uj(s);let f=null;if(t){const E=2/r.getZoomLevel(),{strokeDasharray:I,strokeDashoffset:C}=ro(hX(r,n),E,{end:"skip",start:"skip",lengthRatio:2.5});f=a.start||a.end?u.jsx("path",{className:"tl-arrow-hint",d:s.isStraight?uX(s):cX(s),strokeDasharray:I,strokeDashoffset:C,strokeWidth:E,markerStart:a.start?a.start.props.isExact?"":a.start.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",markerEnd:a.end?a.end.props.isExact?"":a.end.props.isPrecise?"url(#arrowhead-cross)":"url(#arrowhead-dot)":"",opacity:.16}):null}const{strokeDasharray:S,strokeDashoffset:g}=ro(s.isStraight?s.length:Math.abs(s.bodyArc.length),c,{style:n.props.dash}),x=Gh(r,n),y=!(s.start.arrowhead==="none"||s.start.arrowhead==="arrow"),v=!(s.end.arrowhead==="none"||s.end.arrowhead==="arrow"),b=(n.id+"_clip_"+l).replace(":","_");return u.jsxs(u.Fragment,{children:[u.jsx("defs",{children:u.jsxs("mask",{id:b,children:[u.jsx("rect",{x:N(-100+i.minX),y:N(-100+i.minY),width:N(i.width+200),height:N(i.height+200),fill:"white"}),n.props.text.trim()&&u.jsx("rect",{x:x.box.x,y:x.box.y,width:x.box.w,height:x.box.h,fill:"black",rx:4,ry:4}),d&&y&&u.jsx("path",{d,fill:s.start.arrowhead==="arrow"?"none":"black",stroke:"none"}),h&&v&&u.jsx("path",{d:h,fill:s.end.arrowhead==="arrow"?"none":"black",stroke:"none"})]})}),u.jsxs("g",{fill:"none",stroke:o[n.props.color].solid,strokeWidth:c,strokeLinejoin:"round",strokeLinecap:"round",pointerEvents:"none",children:[f,u.jsxs("g",{mask:`url(#${b})`,children:[u.jsx("rect",{x:N(i.minX-100),y:N(i.minY-100),width:N(i.width+200),height:N(i.height+200),opacity:0}),u.jsx("path",{d:p,strokeDasharray:S,strokeDashoffset:g})]}),d&&y&&n.props.fill!=="none"&&u.jsx(en,{theme:o,d,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),h&&v&&n.props.fill!=="none"&&u.jsx(en,{theme:o,d:h,color:n.props.color,fill:n.props.fill,scale:n.props.scale}),d&&u.jsx("path",{d}),h&&u.jsx("path",{d:h})]})]})}),aI=new WeakMap;function pX(){return u.jsx("marker",{id:"arrowhead-dot",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"0",children:u.jsx("circle",{cx:"3",cy:"3",r:"2",strokeDasharray:"100%"})})}function fX(){return u.jsxs("marker",{id:"arrowhead-cross",className:"tl-arrow-hint",refX:"3.0",refY:"3.0",orient:"auto",children:[u.jsx("line",{x1:"1.5",y1:"1.5",x2:"4.5",y2:"4.5",strokeDasharray:"100%"}),u.jsx("line",{x1:"1.5",y1:"4.5",x2:"4.5",y2:"1.5",strokeDasharray:"100%"})]})}const lI="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 xl({url:e,zoomLevel:n}){return u.jsx("a",{className:ce("tl-hyperlink-button",{"tl-hyperlink-button__hidden":n<.32}),href:e,target:"_blank",rel:"noopener noreferrer",onPointerDown:Kt,onPointerUp:Kt,title:e,draggable:!1,children:u.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${lI}") center 100% / 100% no-repeat`,WebkitMask:`url("${lI}") center 100% / 100% no-repeat`}})})}const cI="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' fill='none'%3E%3Cpath stroke='%23000' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M13 5H7a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6M19 5h6m0 0v6m0-6L13 17'/%3E%3C/svg%3E",gX=[{offsetX:0,offsetY:2,blur:4,spread:0,color:"#00000029"},{offsetX:0,offsetY:3,blur:6,spread:0,color:"#0000001f"}];function l0(e){return gX.map(t=>{const{offsetX:r,offsetY:o,blur:s,spread:i,color:a}=t,l=new w(r,o),{x:c,y:d}=l.rot(-e);return`${c}px ${d}px ${s}px ${i}px ${a}`}).join(", ")}const mX=300,pj=320,yX=46,SX=101;class Yh extends $l{constructor(){super(...arguments);m(this,"canResize",()=>!1);m(this,"hideSelectionBoundsFg",()=>!0);m(this,"onBeforeCreate",t=>uI(this.editor,t));m(this,"onBeforeUpdate",(t,r)=>{if(t.props.url!==r.props.url)if(or.isValid(r.props.url))xX(this.editor,r);else return{...r,props:{...r.props,url:t.props.url}};if(t.props.assetId!==r.props.assetId)return uI(this.editor,r)})}getDefaultProps(){return{url:"",w:mX,h:pj,assetId:null}}component(t){const r=t.props.assetId?this.editor.getAsset(t.props.assetId):null,o=this.editor.getShapePageTransform(t).rotation(),s=vX(t);return u.jsx(Vi,{children:u.jsxs("div",{className:"tl-bookmark__container",style:{boxShadow:l0(o)},children:[(!r||r.props.image)&&u.jsxs("div",{className:"tl-bookmark__image_container",children:[r?u.jsx("img",{className:"tl-bookmark__image",draggable:!1,referrerPolicy:"strict-origin-when-cross-origin",src:r==null?void 0:r.props.image,alt:(r==null?void 0:r.props.title)||""}):u.jsx("div",{className:"tl-bookmark__placeholder"}),(r==null?void 0:r.props.image)&&u.jsx(xl,{url:t.props.url,zoomLevel:this.editor.getZoomLevel()})]}),u.jsxs("div",{className:"tl-bookmark__copy_container",children:[r!=null&&r.props.title?u.jsx("h2",{className:"tl-bookmark__heading",children:r.props.title}):null,r!=null&&r.props.description&&(r!=null&&r.props.image)?u.jsx("p",{className:"tl-bookmark__description",children:r.props.description}):null,u.jsxs("a",{className:"tl-bookmark__link",href:t.props.url||"",target:"_blank",rel:"noopener noreferrer",onPointerDown:Kt,onPointerUp:Kt,onClick:Kt,children:[r!=null&&r.props.favicon?u.jsx("img",{className:"tl-bookmark__favicon",src:r==null?void 0:r.props.favicon,referrerPolicy:"strict-origin-when-cross-origin",alt:`favicon of ${s}`}):u.jsx("div",{className:"tl-hyperlink__icon",style:{mask:`url("${cI}") center 100% / 100% no-repeat`,WebkitMask:`url("${cI}") center 100% / 100% no-repeat`}}),u.jsx("span",{children:s})]})]})]})})}indicator(t){return u.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:"6",ry:"6"})}}m(Yh,"type","bookmark"),m(Yh,"props",pM),m(Yh,"migrations",fM);function uI(e,n){const t=n.props.assetId?e.getAsset(n.props.assetId):null;let r=pj;return t&&(t.props.image||(t.props.title?r=SX:r=yX)),{...n,props:{...n.props,h:r}}}const vX=e=>{try{return new URL(e.props.url).hostname.replace(/^www\./,"")}catch{return e.props.url}};function xX(e,n){const{url:t}=n.props,r=ki.createId(ov(t));e.getAsset(r)?n.props.assetId!==r&&e.updateShapes([{id:n.id,type:n.type,props:{assetId:r}}]):(e.updateShapes([{id:n.id,type:n.type,props:{assetId:null}}]),wX(e,n))}const wX=CT(async(e,n)=>{if(e.isDisposed)return;const{url:t}=n.props,r=await e.getAssetForExternalContent({type:"url",url:t});r&&e.batch(()=>{e.createAssets([r]),e.updateShapes([{id:n.id,type:n.type,props:{assetId:r.id}}])})},500);function Yi(e,n=!1){const t=e.length;if(t<2)return"";let r=e[0].point,o=e[1].point;if(t===2)return`M${Ie(r)}L${Ie(o)}`;let s="";for(let i=2,a=t-1;i3?"T":""}${s}L${Ie(e[t-1].point)}`}function bX(e,n={}){const{start:t={},end:r={}}=n,{cap:o=!0}=t,{cap:s=!0}=r;st(!t.taper&&!r.taper,"cap taper not supported here"),st(!t.easing&&!r.easing,"cap easing not supported here"),st(o&&s,"cap must be true");const i=xo(e,n);dg(i,n);const a=PX(i);let l="";for(const c of a)l+=IX(c,n);return l}function PX(e){if(e.length<=2)return[e];const n=[];let t=[e[0]],r=w.Sub(e[1].point,e[0].point).uni(),o,s,i,a,l;for(let c=1,d=e.length;c.7)&&(w.Dist2(i.point,a.point)+w.Dist2(a.point,l.point))/((i.radius+a.radius+l.radius)/3)**2<1.5){t.push(a),n.push(uy(t)),t=[a];continue}}return t.push(e[e.length-1]),n.push(uy(t)),n}function uy(e){const n=e[0];let t;for(;e.length>2&&(t=e[1],w.Dist2(n.point,t.point)<((n.radius+t.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],w.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:w.Sub(e[0].point,e[1].point).uni()},e[e.length-1]={...e[e.length-1],vector:w.Sub(e[e.length-2].point,e[e.length-1].point).uni()}),e}function CX(e,n,t){return"M "+e+" "+n+" m -"+t+", 0 a "+t+","+t+" 0 1,1 "+t*2+",0 a "+t+","+t+" 0 1,1 -"+t*2+",0"}function IX(e,n={}){if(e.length===0)return"";if(e.length===1)return CX(e[0].point.x,e[0].point.y,e[0].radius);const{left:t,right:r}=W2(e,n);r.reverse();let o=`M${Ie(t[0])}T`;for(let s=1;se*.65+X9(e*_e/2)*.35,kX=e=>({size:e,thinning:.5,streamline:fl(e,[9,16],[.64,.74],!0),smoothing:.62,easing:jt.easeOutSine,simulatePressure:!0}),_X=e=>({size:1+e*1.2,thinning:.62,streamline:.62,smoothing:.62,simulatePressure:!1,easing:EX}),dI=e=>({size:e,thinning:0,streamline:fl(e,[9,16],[.68,.74],!0),smoothing:.62,simulatePressure:!1,easing:jt.linear}),TX=e=>({size:e,thinning:0,streamline:.62,smoothing:.62,simulatePressure:!1,easing:jt.linear});function c0({strokeWidth:e,showAsComplete:n}){return{size:1+e,thinning:0,streamline:.5,smoothing:.5,simulatePressure:!1,easing:jt.easeOutSine,last:n}}function kv(e,n,t,r){const o=e.isComplete||t;return r?e.isPen?{...TX(n),last:o}:{...dI(n),last:o}:e.dash==="draw"?e.isPen?{..._X(n),last:o}:{...kX(n),last:o}:{...dI(n),last:o}}function wl(e){const n=[];for(const t of e)if(t.type==="free"||t.points.length<2)n.push(...t.points.map(w.Cast));else{const r=Math.max(4,Math.floor(w.Dist(t.points[0],t.points[1])/16));n.push(...w.PointsBetween(t.points[0],t.points[1],r))}return n}function MX(e,n){return{draw:"none",solid:"none",dotted:`0.1 ${n*2}`,dashed:`${n*2} ${n*2}`}[e.props.dash]}class Xh extends Br{constructor(){super(...arguments);m(this,"hideResizeHandles",t=>dy(t));m(this,"hideRotateHandle",t=>dy(t));m(this,"hideSelectionBoundsFg",t=>dy(t));m(this,"onResize",(t,r)=>{const{scaleX:o,scaleY:s}=r,i=[];for(const a of t.props.segments)i.push({...a,points:a.points.map(({x:l,y:c,z:d})=>({x:$o(o*l),y:$o(s*c),z:d}))});return{props:{segments:i}}})}getDefaultProps(){return{segments:[],color:"black",fill:"none",dash:"draw",size:"m",isComplete:!1,isClosed:!1,isPen:!1,scale:1}}getGeometry(t){const r=wl(t.props.segments),o=(At[t.props.size]+1)*t.props.scale;if(t.props.segments.length===1){const i=Z.FromPoints(r);if(i.widthi.point);return t.props.isClosed?new vt({points:s,isFilled:t.props.fill!=="none"}):new Ll({points:s})}component(t){return u.jsx(Ys,{id:t.id,children:u.jsx(hI,{shape:t,zoomLevel:this.editor.getZoomLevel()})})}indicator(t){var h;const r=wl(t.props.segments);let o=(At[t.props.size]+1)*t.props.scale;const s=this.editor.getZoomLevel();!(s<.5&&s<1.5/o)&&!t.props.isPen&&t.props.dash==="draw"&&r.length===1&&(o+=Wr(t.id)()*(o/6));const a=t.props.isComplete||((h=Nt(t.props.segments))==null?void 0:h.type)==="straight",l=kv(t.props,o,a,!0),c=xo(r,l),d=c.length>1?Yi(c,t.props.isClosed):fj(r[0],o);return u.jsx("path",{d})}toSvg(t,r){r.addExportDef(s0(t.props.fill));const o=1/t.props.scale;return u.jsx("g",{transform:`scale(${o})`,children:u.jsx(hI,{shape:t,zoomLevel:1})})}getCanvasSvgDefs(){return[i0()]}expandSelectionOutlinePx(t){const r=t.props.dash==="draw"?1.6:1;return At[t.props.size]*r/2*t.props.scale}}m(Xh,"type","draw"),m(Xh,"props",mM),m(Xh,"migrations",yM);function fj(e,n){const t=(n+1)*.5;return`M ${e.x} ${e.y} m -${t}, 0 a ${t},${t} 0 1,0 ${t*2},0 a ${t},${t} 0 1,0 -${t*2},0`}function dy(e){return e.props.segments.length===1&&e.props.segments[0].points.length<2}function hI({shape:e,zoomLevel:n}){var h;const t=_r(),r=wl(e.props.segments),o=e.props.isComplete||((h=Nt(e.props.segments))==null?void 0:h.type)==="straight";let s=(At[e.props.size]+1)*e.props.scale;const i=n<.5&&n<1.5/s;!i&&!e.props.isPen&&e.props.dash==="draw"&&r.length===1&&(s+=Wr(e.id)()*(s/6));const a=kv(e.props,s,o,i);if(!i&&e.props.dash==="draw")return u.jsxs(u.Fragment,{children:[e.props.isClosed&&e.props.fill&&r.length>1?u.jsx(en,{d:Yi(xo(r,a),e.props.isClosed),theme:t,color:e.props.color,fill:e.props.isClosed?e.props.fill:"none",scale:e.props.scale}):null,u.jsx("path",{d:bX(r,a),strokeLinecap:"round",fill:t[e.props.color].solid})]});const l=xo(r,a),c=l.length<2,d=c?fj(r[0],0):Yi(l,e.props.isClosed);return u.jsxs(u.Fragment,{children:[u.jsx(en,{d,theme:t,color:e.props.color,fill:c||e.props.isClosed?e.props.fill:"none",scale:e.props.scale}),u.jsx("path",{d,strokeLinecap:"round",fill:c?t[e.props.color].solid:"none",stroke:t[e.props.color].solid,strokeWidth:s,strokeDasharray:c?"none":MX(e,s),strokeDashoffset:"0"})]})}function jX(e,n,t={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=n,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:d=1/0}=t;let h=e.props.w*s,p=e.props.h*i;const f=new w(0,0);if(h>0){if(h0){if(pObject.entries(e).filter(([n,t])=>t).map(([n])=>n).join(" ");class qh extends $l{constructor(){super(...arguments);m(this,"hideSelectionBoundsFg",t=>!this.canResize(t));m(this,"canEdit",()=>!0);m(this,"canResize",t=>{var r,o;return!!((o=(r=Ms(t.props.url))==null?void 0:r.definition)!=null&&o.doesResize)});m(this,"canEditInReadOnly",()=>!0);m(this,"isAspectRatioLocked",t=>{const r=Ms(t.props.url);return(r==null?void 0:r.definition.isAspectRatioLocked)??!1});m(this,"onResize",(t,r)=>{const o=this.isAspectRatioLocked(t),s=Ms(t.props.url);let i=(s==null?void 0:s.definition.minWidth)??200,a=(s==null?void 0:s.definition.minHeight)??200;if(o){const l=t.props.w/t.props.h;l>1?i*=l:a/=l}return jX(t,r,{minWidth:i,minHeight:a})})}getDefaultProps(){return{w:300,h:300,url:""}}component(t){const{w:r,h:o,url:s}=t.props,i=ug(t.id),a=P.useMemo(()=>q2(s),[s]),l=G("is hovering",()=>{const{editingShapeId:f,hoveredShapeId:S}=this.editor.getCurrentPageState();if(f&&S!==f){const g=this.editor.getShape(f);if(g&&this.editor.isShapeOfType(g,"embed"))return!0}return!1},[]),c=this.editor.getShapePageTransform(t).rotation(),d=i||l;if(typeof window<"u"&&(window!==window.top||window.self!==window.parent)&&(a==null?void 0:a.definition.type)==="tldraw")return null;if((a==null?void 0:a.definition.type)==="github_gist"){const f=a.url.split("/").pop();if(!f)throw Error("No gist id!");return u.jsx(Vi,{className:"tl-embed-container",id:t.id,children:u.jsx(OX,{id:f,width:N(r),height:N(o),isInteractive:d,pageRotation:c})})}const p=AX({...D9,...(a==null?void 0:a.definition.overridePermissions)??{}});return u.jsx(Vi,{className:"tl-embed-container",id:t.id,children:a!=null&&a.definition?u.jsx("iframe",{className:"tl-embed",sandbox:p,src:a.embedUrl,width:N(r),height:N(o),draggable:!1,frameBorder:"0",referrerPolicy:"no-referrer-when-downgrade",style:{border:0,pointerEvents:d?"auto":"none",zIndex:d?"":"-1",boxShadow:l0(c),borderRadius:(a==null?void 0:a.definition.overrideOutlineRadius)??8,background:a==null?void 0:a.definition.backgroundColor}}):null})}indicator(t){const r=P.useMemo(()=>Ms(t.props.url),[t.props.url]);return u.jsx("rect",{width:N(t.props.w),height:N(t.props.h),rx:(r==null?void 0:r.definition.overrideOutlineRadius)??8,ry:(r==null?void 0:r.definition.overrideOutlineRadius)??8})}}m(qh,"type","embed"),m(qh,"props",SM),m(qh,"migrations",vM);function OX({id:e,file:n,isInteractive:t,width:r,height:o,style:s,pageRotation:i}){return u.jsx("iframe",{className:"tl-embed",draggable:!1,width:N(r),height:N(o),frameBorder:"0",scrolling:"no",seamless:!0,referrerPolicy:"no-referrer-when-downgrade",style:{...s,pointerEvents:t?"all":"none",zIndex:t?"":"-1",boxShadow:l0(i)},srcDoc:`