@kitschpatrol/tldraw-cli 4.6.25 → 4.6.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -64,7 +64,7 @@ ${u}`}),"","You should configure your bundler to only import one version of each
64
64
  */let Vv=[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"&&(Vv=new Int32Array(Vv));const z9=(t,e)=>{let n=~~e^-1;for(let r=0;r<t.length;r++)n=Vv[(n^t[r])&255]^n>>>8;return n^-1},RC=4,LC=4;class Co{static isPng(e,n){return e.getUint8(n+0)===137&&e.getUint8(n+1)===80&&e.getUint8(n+2)===78&&e.getUint8(n+3)===71&&e.getUint8(n+4)===13&&e.getUint8(n+5)===10&&e.getUint8(n+6)===26&&e.getUint8(n+7)===10}static getChunkType(e,n){return[String.fromCharCode(e.getUint8(n)),String.fromCharCode(e.getUint8(n+1)),String.fromCharCode(e.getUint8(n+2)),String.fromCharCode(e.getUint8(n+3))].join("")}static readChunks(e,n=0){const r={};if(!Co.isPng(e,n))throw new Error("Not a PNG");for(n+=8;n<=e.buffer.byteLength;){const o=n,s=e.getInt32(n);n+=4;const i=Co.getChunkType(e,n);if(i==="IDAT"&&r[i]){n+=s+RC+LC;continue}if(i==="IEND")break;r[i]={start:o,dataOffset:n+4,size:s},n+=s+RC+LC}return r}static parsePhys(e,n){return{ppux:e.getUint32(n),ppuy:e.getUint32(n+4),unit:e.getUint8(n+4)}}static findChunk(e,n){return Co.readChunks(e)[n]}static setPhysChunk(e,n=1,r){let o=46,s=0;const i=Co.findChunk(e,"pHYs");i&&(o=i.start,s=i.size);const a=Co.findChunk(e,"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 u=2835.5;c.setInt32(8,u*n),c.setInt32(12,u*n),c.setInt8(16,1);const h=new Uint8Array(l.slice(4,17));c.setInt32(17,z9(h));const p=e.buffer.slice(0,o),f=e.buffer.slice(o+s);return new Blob([p,l,f],r)}}/*!
65
65
  * MIT License: https://github.com/sindresorhus/is-webp/blob/main/license
66
66
  * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
67
- */function B9(t){return!t||t.length<12?!1:t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80}function U9(t){const e=new Uint8Array(t);return!B9(e)||!e||e.length<21?!1:(e[20]>>1&1)===1}const LT=Object.freeze(["image/svg+xml"]),$T=Object.freeze(["image/jpeg","image/png","image/webp"]),FT=Object.freeze(["image/gif","image/apng","image/avif"]),xg=Object.freeze([...$T,...LT,...FT]),xw=Object.freeze(["video/mp4","video/webm","video/quicktime"]),H9=[...xg,...xw].join(",");class ar{static loadVideo(e){return new Promise((n,r)=>{const o=document.createElement("video");o.onloadeddata=()=>n(o),o.onerror=s=>{console.error(s),r(new Error("Could not load video"))},o.crossOrigin="anonymous",o.src=e})}static async getVideoFrameAsDataUrl(e,n=0){const r=yw();let o=!1;const s=()=>{if(!o)if(e.readyState>=e.HAVE_METADATA)o=!0,e.currentTime=n;else return;if(e.readyState>=e.HAVE_CURRENT_DATA){const a=document.createElement("canvas");a.width=e.videoWidth,a.height=e.videoHeight;const l=a.getContext("2d");if(!l)throw new Error("Could not get 2d context");l.drawImage(e,0,0),r.resolve(a.toDataURL())}},i=a=>{console.error(a),r.reject(new Error("Could not get video frame"))};e.addEventListener("loadedmetadata",s),e.addEventListener("loadeddata",s),e.addEventListener("canplay",s),e.addEventListener("seeked",s),e.addEventListener("error",i),e.addEventListener("stalled",i),s();try{return await r}finally{e.removeEventListener("loadedmetadata",s),e.removeEventListener("loadeddata",s),e.removeEventListener("canplay",s),e.removeEventListener("seeked",s),e.removeEventListener("error",i),e.removeEventListener("stalled",i)}}static loadImage(e){return new Promise((n,r)=>{const o=Lu();o.onload=()=>n(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=e})}static async getVideoSize(e){return ar.usingObjectURL(e,async n=>{const r=await ar.loadVideo(n);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(e){const n=await ar.usingObjectURL(e,ar.loadImage);try{if(e.type==="image/png"){const r=new DataView(await e.arrayBuffer());if(Co.isPng(r,0)){const o=Co.findChunk(r,"pHYs");if(o){const s=Co.parsePhys(r,o.dataOffset);if(s.unit===0&&s.ppux===s.ppuy){const i=Math.max(s.ppux/2834.5,1);return{w:Math.round(n.naturalWidth/i),h:Math.round(n.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:n.naturalWidth,h:n.naturalHeight}}return{w:n.naturalWidth,h:n.naturalHeight}}static async isAnimated(e){return e.type==="image/gif"?N9(await e.arrayBuffer()):e.type==="image/avif"?$9(await e.arrayBuffer()):e.type==="image/webp"?U9(await e.arrayBuffer()):e.type==="image/apng"?L9(await e.arrayBuffer()):!1}static isAnimatedImageType(e){return FT.includes(e||"")}static isStaticImageType(e){return $T.includes(e||"")}static isVectorImageType(e){return LT.includes(e||"")}static isImageType(e){return xg.includes(e)}static async usingObjectURL(e,n){const r=URL.createObjectURL(e);try{return await n(r)}finally{URL.revokeObjectURL(r)}}}function _e(t,e,n){return t+(e-t)*n}function co(t=""){let e=0,n=0,r=0,o=0;function s(){const i=e^e<<11;return e=n,n=r,r=o,o^=(o>>>19^i^i>>>8)>>>0,o/4294967296*2}for(let i=0;i<t.length+64;i++)e^=t.charCodeAt(i)|0,s();return s}function Ol(t,e,n,r=!1){const[o,s]=e,[i,a]=n,l=i+(t-o)/(s-o)*(a-i);return r?i<a?Math.max(Math.min(l,a),i):Math.max(Math.min(l,i),a):l}function no(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function hn(t,e){if(no(t,e))return t[e]}function $C(t){return Object.keys(t)}function ut(t){return Object.values(t)}function Xn(t){return Object.entries(t)}function ww(t){return Object.fromEntries(t)}function lu(t,e){const n={};let r=!1;for(const[o,s]of Xn(t))e(o,s)?n[o]=s:r=!0;return r?n:t}function od(t,e){const n={};for(const[r,o]of Xn(t)){const s=e(r,o);n[r]=s}return n}function NT(t,e){if(t===e)return!0;const n=new Set(Object.keys(t)),r=new Set(Object.keys(e));if(n.size!==r.size)return!1;for(const o of n)if(!r.has(o)||!Object.is(t[o],e[o]))return!1;return!0}function K9(t){const e=W9(t.chars),n=G9(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=V9(r,e.length);return{chars:t.chars,byChar:e.byChar,byCode:e.byCode,length:e.length,first:e.byCode[0],last:e.byCode[e.length-1],firstPositive:n.firstPositive,mostPositive:n.mostPositive,firstNegative:n.firstNegative,mostNegative:n.mostNegative,jitterRange:r,paddingDict:o}}function W9(t){const e={},n={},r=t.length;for(let o=0;o<r;o++){const s=t[o];e[o]=s,n[s]=o}return{byCode:e,byChar:n,length:r}}function G9(t,e,n,r){const o=e?t.byChar[e]:Math.ceil(t.length/2),s=n?t.byChar[n]:t.length-1,i=r?t.byChar[r]:0;if(o===void 0||s===void 0||i===void 0)throw new Error("invalid charSet");if(s-o<3)throw new Error("mostPositive must be at least 3 characters away from neutral");if(o-i<3)throw new Error("mostNegative must be at least 3 characters away from neutral");return{firstPositive:t.byCode[o],mostPositive:t.byCode[s],firstNegative:t.byCode[o-1],mostNegative:t.byCode[i]}}function V9(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var fy=null;function bw(){return fy||(fy=K9({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function Qs(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function Pw(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?Qs(n,e.firstPositive,e)+1+df(t.slice(1),"positive",e):n===e.mostNegative?Qs(n,e.firstNegative,e)+1+df(t.slice(1),"negative",e):n>=e.firstPositive?Qs(n,e.firstPositive,e)+2:Qs(n,e.firstNegative,e)+2}function df(t,e,n){const r=t[0];if(r>n.mostPositive||r<n.mostNegative)throw new Error("invalid firstChar on key");return r===n.mostPositive&&e==="positive"?Qs(r,n.mostNegative,n)+1+df(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?Qs(r,n.mostPositive,n)+1+df(t.slice(1),e,n):e==="positive"?Qs(r,n.mostNegative,n)+2:Qs(r,n.mostPositive,n)+2}function wg(t,e,n,r,o){const s=Math.max(t.length,e.length);return n==="start"?[t.padStart(s,r),e.padStart(s,r)]:[t.padEnd(s,r),e.padEnd(s,r)]}function Y9(t,e,n){let[r,o]=wg(t,e,"end",n.first),s=Yv(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=UT(Math.floor(s/2),n);return Cw(r,i,n)}function Yv(t,e,n){const[r,o]=wg(t,e,"end",n.first).sort(),s=zT(o,r,n);return X9(s,n)}function Cw(t,e,n){const r=n.length,[o,s]=wg(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){const c=n.byChar[o[l]],u=n.byChar[s[l]],h=c+u+a;a=Math.floor(h/r);const p=h%r;i.unshift(n.byCode[p])}return a>0&&i.unshift(n.byCode[a]),i.join("")}function zT(t,e,n){const r=n.length,[o,s]=wg(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){let c=n.byChar[o[l]];const u=n.byChar[s[l]]+a;c<u?(a=1,c+=r):a=0;const h=c-u;i.unshift(n.byCode[h])}if(a>0)throw new Error("Subtraction result is negative. Ensure a is greater than or equal to b.");for(;i.length>1&&i[0]===n.byCode[0];)i.shift();return i.join("")}function BT(t,e){return Cw(t,e.byCode[1],e)}function Xv(t,e){return zT(t,e.byCode[1],e)}function UT(t,e){if(t===0)return e.byCode[0];let n="";const r=e.length;for(;t>0;)n=e.byCode[t%r]+n,t=Math.floor(t/r);return n}function X9(t,e){let n=0;const r=t.length,o=e.length;for(let s=0;s<r;s++)n+=e.byChar[t[s]]*Math.pow(o,r-s-1);return n}function q9(t){return t.firstPositive+t.byCode[0]}function Z9(t,e){return Pw(t,e)===t.length}function FC(t,e){hf(t,e)}function hf(t,e){const n=WT(t,e),r=Pw(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function HT(t,e){if(!Z9(t,e))throw new Error("invalid integer length: "+t)}function KT(t,e){HT(t,e);const[n,r]=GT(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=BT(r,e);return n+i}const s=J9(n,e);return VT(s,"lower",e)}function Q9(t,e){HT(t,e);const[n,r]=GT(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=Xv(r,e);return n+i}const s=e7(n,e);return VT(s,"upper",e)}function WT(t,e){let n=0;if(t[0]===e.mostPositive)for(;t[n]===e.mostPositive;)n=n+1;if(t[0]===e.mostNegative)for(;t[n]===e.mostNegative;)n=n+1;return t.slice(0,n+1)}function GT(t,e){const n=WT(t,e),r=t.slice(n.length);return[n,r]}function J9(t,e){const n=t>=e.firstPositive,r=BT(t,e),o=t[t.length-1]===e.mostPositive,s=r[r.length-1]===e.mostPositive;return n&&s?r+e.mostNegative:!n&&o?t.slice(0,t.length-1):r}function e7(t,e){const n=t>=e.firstPositive,r=t[t.length-1]===e.mostNegative;if(n&&r){const o=t.slice(0,t.length-1);return Xv(o,e)}return!n&&r?t+e.mostPositive:Xv(t,e)}function VT(t,e,n){const r=Pw(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function YT(t,e){const n=UT(Math.floor(Math.random()*e.jitterRange),e);return Cw(t,n,e)}function t7(t,e,n){const r=t.padEnd(t.length+e,n.first);return YT(r,n)}function n7(t,e,n){const r=hf(t,n),o=KT(r,n);let s=0;if(e!==null){const a=Yv(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,NC(a,n)))}const i=Yv(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,NC(i,n))),s}function NC(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function r7(t,e,n=bw()){if(t!==null&&FC(t,n),e!==null&&FC(e,n),t===null&&e===null)return q9(n);if(t===null){const r=hf(e,n);return Q9(r,n)}if(e===null){const r=hf(t,n);return KT(r,n)}if(t>=e)throw new Error(t+" >= "+e);return Y9(t,e,n)}function XT(t,e,n=bw()){const r=r7(t,e,n),o=n7(r,e,n);return o?t7(r,o,n):YT(r,n)}function qT(t,e,n,r=bw()){return o7(t,e,n,r,XT,qT)}function o7(t,e,n,r,o,s){if(n===0)return[];if(n===1)return[o(t,e,r)];if(e==null){let l=o(t,e,r);const c=[l];for(let u=0;u<n-1;u++)l=o(l,e,r),c.push(l);return c}if(t==null){let l=o(t,e,r);const c=[l];for(let u=0;u<n-1;u++)l=o(t,l,r),c.push(l);return c.reverse(),c}const i=Math.floor(n/2),a=o(t,e,r);return[...s(t,a,i,r),a,...s(a,e,n-i-1,r)]}const Vl=qT,ZT="a0";function s7(t){try{XT(t,null)}catch{throw new Error("invalid index: "+t)}}function Dl(t,e,n){return Vl(t??null,e??null,n)}function gy(t,e){return Vl(t??null,null,e)}function $u(t,e){return Vl(t??null,e??null,1)[0]}function Io(t=null){return Vl(t,null,1)[0]}function i7(t=null){return Vl(null,t,1)[0]}function Fu(t,e="a1"){return[e,...Vl(e,null,t)]}function cn(t,e){return t.index<e.index?-1:t.index>e.index?1:0}function a7(t,e){return t.id>e.id?1:-1}function _w(t){try{return localStorage.getItem(t)}catch{return null}}function Iw(t,e){try{localStorage.setItem(t,e)}catch{}}function l7(){try{localStorage.clear()}catch{}}function QT(t){try{return sessionStorage.getItem(t)}catch{return null}}function Ew(t,e){try{sessionStorage.setItem(t,e)}catch{}}function JT(t){try{sessionStorage.removeItem(t)}catch{}}function c7(){try{sessionStorage.clear()}catch{}}const ol=[],u7=60,tp=Math.ceil(1e3/u7);let bc,my=0,qv=0;const d7=()=>{const t=ol.splice(0,ol.length);for(const e of t)e()};function eM(){if(bc)return;const t=Date.now(),e=t-qv;if(my+e<tp){bc=requestAnimationFrame(()=>{bc=void 0,eM()});return}bc=requestAnimationFrame(()=>{bc=void 0,qv=t,my=Math.min(my+e-tp,tp*10),d7()})}let zC=!1;function tM(t){return ol.includes(t)||(ol.push(t),zC||(zC=!0,qv=Date.now()-tp-1),eM()),()=>{const e=ol.indexOf(t);e>-1&&ol.splice(e,1)}}class h7{constructor(){I(this,"timeouts",new Map);I(this,"intervals",new Map);I(this,"rafs",new Map);this.setTimeout=this.setTimeout.bind(this),this.setInterval=this.setInterval.bind(this),this.requestAnimationFrame=this.requestAnimationFrame.bind(this),this.dispose=this.dispose.bind(this)}setTimeout(e,n,r,...o){const s=window.setTimeout(n,r,o),i=this.timeouts.get(e)??[];return this.timeouts.set(e,[...i,s]),s}setInterval(e,n,r,...o){const s=window.setInterval(n,r,o),i=this.intervals.get(e)??[];return this.intervals.set(e,[...i,s]),s}requestAnimationFrame(e,n){const r=window.requestAnimationFrame(n),o=this.rafs.get(e)??[];return this.rafs.set(e,[...o,r]),r}dispose(e){var n,r,o;(n=this.timeouts.get(e))==null||n.forEach(s=>clearTimeout(s)),(r=this.intervals.get(e))==null||r.forEach(s=>clearInterval(s)),(o=this.rafs.get(e))==null||o.forEach(s=>cancelAnimationFrame(s)),this.timeouts.delete(e),this.intervals.delete(e),this.rafs.delete(e)}disposeAll(){for(const e of this.timeouts.keys())this.dispose(e)}forContext(e){return{setTimeout:(n,r,...o)=>this.setTimeout(e,n,r,o),setInterval:(n,r,...o)=>this.setInterval(e,n,r,o),requestAnimationFrame:n=>this.requestAnimationFrame(e,n),dispose:()=>this.dispose(e)}}}const ge=(t,e)=>{try{return new URL(t,e)}catch{return}};function p7(t){return t!==void 0}function f7(){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]:[t=>t&&JSON.parse(JSON.stringify(t)),!1]}const nM=f7(),tt=nM[0];nM[1];const g7=Object.getPrototypeOf(tt({}));Ci("@tldraw/utils","3.7.0-canary.383dfd14bf86","esm");var Pc=function(t){return t&&t.Math===Math&&t},In=Pc(typeof globalThis=="object"&&globalThis)||Pc(typeof window=="object"&&window)||Pc(typeof self=="object"&&self)||Pc(typeof dn=="object"&&dn)||Pc(typeof dn=="object"&&dn)||function(){return this}()||Function("return this")(),kw={},En=function(t){try{return!!t()}catch{return!0}},m7=En,_i=!m7(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),y7=En,bg=!y7(function(){var t=(function(){}).bind();return typeof t!="function"||t.hasOwnProperty("prototype")}),S7=bg,nh=Function.prototype.call,Is=S7?nh.bind(nh):function(){return nh.apply(nh,arguments)},rM={},oM={}.propertyIsEnumerable,sM=Object.getOwnPropertyDescriptor,v7=sM&&!oM.call({1:2},1);rM.f=v7?function(e){var n=sM(this,e);return!!n&&n.enumerable}:oM;var iM=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}},aM=bg,lM=Function.prototype,Zv=lM.call,x7=aM&&lM.bind.bind(Zv,Zv),Lt=aM?x7:function(t){return function(){return Zv.apply(t,arguments)}},cM=Lt,w7=cM({}.toString),b7=cM("".slice),Yl=function(t){return b7(w7(t),8,-1)},P7=Lt,C7=En,_7=Yl,yy=Object,I7=P7("".split),E7=C7(function(){return!yy("z").propertyIsEnumerable(0)})?function(t){return _7(t)==="String"?I7(t,""):yy(t)}:yy,Pg=function(t){return t==null},k7=Pg,T7=TypeError,Xl=function(t){if(k7(t))throw new T7("Can't call method on "+t);return t},M7=E7,A7=Xl,Cg=function(t){return M7(A7(t))},Sy=typeof document=="object"&&document.all,kn=typeof Sy>"u"&&Sy!==void 0?function(t){return typeof t=="function"||t===Sy}:function(t){return typeof t=="function"},j7=kn,ba=function(t){return typeof t=="object"?t!==null:j7(t)},vy=In,O7=kn,D7=function(t){return O7(t)?t:void 0},_g=function(t,e){return arguments.length<2?D7(vy[t]):vy[t]&&vy[t][e]},R7=Lt,uM=R7({}.isPrototypeOf),L7=In,BC=L7.navigator,UC=BC&&BC.userAgent,$7=UC?String(UC):"",dM=In,xy=$7,HC=dM.process,KC=dM.Deno,WC=HC&&HC.versions||KC&&KC.version,GC=WC&&WC.v8,Xr,pf;GC&&(Xr=GC.split("."),pf=Xr[0]>0&&Xr[0]<4?1:+(Xr[0]+Xr[1]));!pf&&xy&&(Xr=xy.match(/Edge\/(\d+)/),(!Xr||Xr[1]>=74)&&(Xr=xy.match(/Chrome\/(\d+)/),Xr&&(pf=+Xr[1])));var F7=pf,VC=F7,N7=En,z7=In,B7=z7.String,hM=!!Object.getOwnPropertySymbols&&!N7(function(){var t=Symbol("symbol detection");return!B7(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&VC&&VC<41}),U7=hM,pM=U7&&!Symbol.sham&&typeof Symbol.iterator=="symbol",H7=_g,K7=kn,W7=uM,G7=pM,V7=Object,fM=G7?function(t){return typeof t=="symbol"}:function(t){var e=H7("Symbol");return K7(e)&&W7(e.prototype,V7(t))},Y7=String,X7=function(t){try{return Y7(t)}catch{return"Object"}},q7=kn,Z7=X7,Q7=TypeError,Tw=function(t){if(q7(t))return t;throw new Q7(Z7(t)+" is not a function")},J7=Tw,eB=Pg,Mw=function(t,e){var n=t[e];return eB(n)?void 0:J7(n)},wy=Is,by=kn,Py=ba,tB=TypeError,nB=function(t,e){var n,r;if(e==="string"&&by(n=t.toString)&&!Py(r=wy(n,t))||by(n=t.valueOf)&&!Py(r=wy(n,t))||e!=="string"&&by(n=t.toString)&&!Py(r=wy(n,t)))return r;throw new tB("Can't convert object to primitive value")},gM={exports:{}},YC=In,rB=Object.defineProperty,Aw=function(t,e){try{rB(YC,t,{value:e,configurable:!0,writable:!0})}catch{YC[t]=e}return e},oB=In,sB=Aw,XC="__core-js_shared__",qC=gM.exports=oB[XC]||sB(XC,{});(qC.versions||(qC.versions=[])).push({version:"3.39.0",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"});var jw=gM.exports,ZC=jw,Ow=function(t,e){return ZC[t]||(ZC[t]=e||{})},iB=Xl,aB=Object,sd=function(t){return aB(iB(t))},lB=Lt,cB=sd,uB=lB({}.hasOwnProperty),Ii=Object.hasOwn||function(e,n){return uB(cB(e),n)},dB=Lt,hB=0,pB=Math.random(),fB=dB(1 .toString),mM=function(t){return"Symbol("+(t===void 0?"":t)+")_"+fB(++hB+pB,36)},gB=In,mB=Ow,QC=Ii,yB=mM,SB=hM,vB=pM,sl=gB.Symbol,Cy=mB("wks"),xB=vB?sl.for||sl:sl&&sl.withoutSetter||yB,Es=function(t){return QC(Cy,t)||(Cy[t]=SB&&QC(sl,t)?sl[t]:xB("Symbol."+t)),Cy[t]},wB=Is,JC=ba,e_=fM,bB=Mw,PB=nB,CB=Es,_B=TypeError,IB=CB("toPrimitive"),EB=function(t,e){if(!JC(t)||e_(t))return t;var n=bB(t,IB),r;if(n){if(e===void 0&&(e="default"),r=wB(n,t,e),!JC(r)||e_(r))return r;throw new _B("Can't convert object to primitive value")}return e===void 0&&(e="number"),PB(t,e)},kB=EB,TB=fM,yM=function(t){var e=kB(t,"string");return TB(e)?e:e+""},MB=In,t_=ba,Qv=MB.document,AB=t_(Qv)&&t_(Qv.createElement),SM=function(t){return AB?Qv.createElement(t):{}},jB=_i,OB=En,DB=SM,vM=!jB&&!OB(function(){return Object.defineProperty(DB("div"),"a",{get:function(){return 7}}).a!==7}),RB=_i,LB=Is,$B=rM,FB=iM,NB=Cg,zB=yM,BB=Ii,UB=vM,n_=Object.getOwnPropertyDescriptor;kw.f=RB?n_:function(e,n){if(e=NB(e),n=zB(n),UB)try{return n_(e,n)}catch{}if(BB(e,n))return FB(!LB($B.f,e,n),e[n])};var ql={},HB=_i,KB=En,xM=HB&&KB(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),WB=ba,GB=String,VB=TypeError,Pa=function(t){if(WB(t))return t;throw new VB(GB(t)+" is not an object")},YB=_i,XB=vM,qB=xM,rh=Pa,r_=yM,ZB=TypeError,_y=Object.defineProperty,QB=Object.getOwnPropertyDescriptor,Iy="enumerable",Ey="configurable",ky="writable";ql.f=YB?qB?function(e,n,r){if(rh(e),n=r_(n),rh(r),typeof e=="function"&&n==="prototype"&&"value"in r&&ky in r&&!r[ky]){var o=QB(e,n);o&&o[ky]&&(e[n]=r.value,r={configurable:Ey in r?r[Ey]:o[Ey],enumerable:Iy in r?r[Iy]:o[Iy],writable:!1})}return _y(e,n,r)}:_y:function(e,n,r){if(rh(e),n=r_(n),rh(r),XB)try{return _y(e,n,r)}catch{}if("get"in r||"set"in r)throw new ZB("Accessors not supported");return"value"in r&&(e[n]=r.value),e};var JB=_i,eU=ql,tU=iM,Dw=JB?function(t,e,n){return eU.f(t,e,tU(1,n))}:function(t,e,n){return t[e]=n,t},wM={exports:{}},Jv=_i,nU=Ii,bM=Function.prototype,rU=Jv&&Object.getOwnPropertyDescriptor,Rw=nU(bM,"name"),oU=Rw&&(function(){}).name==="something",sU=Rw&&(!Jv||Jv&&rU(bM,"name").configurable),iU={EXISTS:Rw,PROPER:oU,CONFIGURABLE:sU},aU=Lt,lU=kn,ex=jw,cU=aU(Function.toString);lU(ex.inspectSource)||(ex.inspectSource=function(t){return cU(t)});var PM=ex.inspectSource,uU=In,dU=kn,o_=uU.WeakMap,hU=dU(o_)&&/native code/.test(String(o_)),pU=Ow,fU=mM,s_=pU("keys"),CM=function(t){return s_[t]||(s_[t]=fU(t))},Lw={},gU=hU,_M=In,mU=ba,yU=Dw,Ty=Ii,My=jw,SU=CM,vU=Lw,i_="Object already initialized",tx=_M.TypeError,xU=_M.WeakMap,ff,Nu,gf,wU=function(t){return gf(t)?Nu(t):ff(t,{})},bU=function(t){return function(e){var n;if(!mU(e)||(n=Nu(e)).type!==t)throw new tx("Incompatible receiver, "+t+" required");return n}};if(gU||My.state){var yo=My.state||(My.state=new xU);yo.get=yo.get,yo.has=yo.has,yo.set=yo.set,ff=function(t,e){if(yo.has(t))throw new tx(i_);return e.facade=t,yo.set(t,e),e},Nu=function(t){return yo.get(t)||{}},gf=function(t){return yo.has(t)}}else{var Ma=SU("state");vU[Ma]=!0,ff=function(t,e){if(Ty(t,Ma))throw new tx(i_);return e.facade=t,yU(t,Ma,e),e},Nu=function(t){return Ty(t,Ma)?t[Ma]:{}},gf=function(t){return Ty(t,Ma)}}var IM={set:ff,get:Nu,has:gf,enforce:wU,getterFor:bU},$w=Lt,PU=En,CU=kn,oh=Ii,nx=_i,_U=iU.CONFIGURABLE,IU=PM,EM=IM,EU=EM.enforce,kU=EM.get,a_=String,np=Object.defineProperty,TU=$w("".slice),MU=$w("".replace),AU=$w([].join),jU=nx&&!PU(function(){return np(function(){},"length",{value:8}).length!==8}),OU=String(String).split("String"),DU=wM.exports=function(t,e,n){TU(a_(e),0,7)==="Symbol("&&(e="["+MU(a_(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!oh(t,"name")||_U&&t.name!==e)&&(nx?np(t,"name",{value:e,configurable:!0}):t.name=e),jU&&n&&oh(n,"arity")&&t.length!==n.arity&&np(t,"length",{value:n.arity});try{n&&oh(n,"constructor")&&n.constructor?nx&&np(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch{}var r=EU(t);return oh(r,"source")||(r.source=AU(OU,typeof e=="string"?e:"")),t};Function.prototype.toString=DU(function(){return CU(this)&&kU(this).source||IU(this)},"toString");var RU=wM.exports,LU=kn,$U=ql,FU=RU,NU=Aw,kM=function(t,e,n,r){r||(r={});var o=r.enumerable,s=r.name!==void 0?r.name:e;if(LU(n)&&FU(n,s,r),r.global)o?t[e]=n:NU(e,n);else{try{r.unsafe?t[e]&&(o=!0):delete t[e]}catch{}o?t[e]=n:$U.f(t,e,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return t},TM={},zU=Math.ceil,BU=Math.floor,UU=Math.trunc||function(e){var n=+e;return(n>0?BU:zU)(n)},HU=UU,Ca=function(t){var e=+t;return e!==e||e===0?0:HU(e)},KU=Ca,WU=Math.max,GU=Math.min,VU=function(t,e){var n=KU(t);return n<0?WU(n+e,0):GU(n,e)},YU=Ca,XU=Math.min,MM=function(t){var e=YU(t);return e>0?XU(e,9007199254740991):0},qU=MM,id=function(t){return qU(t.length)},ZU=Cg,QU=VU,JU=id,l_=function(t){return function(e,n,r){var o=ZU(e),s=JU(o);if(s===0)return!t&&-1;var i=QU(r,s),a;if(t&&n!==n){for(;s>i;)if(a=o[i++],a!==a)return!0}else for(;s>i;i++)if((t||i in o)&&o[i]===n)return t||i||0;return!t&&-1}},eH={includes:l_(!0),indexOf:l_(!1)},tH=Lt,Ay=Ii,nH=Cg,rH=eH.indexOf,oH=Lw,c_=tH([].push),AM=function(t,e){var n=nH(t),r=0,o=[],s;for(s in n)!Ay(oH,s)&&Ay(n,s)&&c_(o,s);for(;e.length>r;)Ay(n,s=e[r++])&&(~rH(o,s)||c_(o,s));return o},Fw=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],sH=AM,iH=Fw,aH=iH.concat("length","prototype");TM.f=Object.getOwnPropertyNames||function(e){return sH(e,aH)};var jM={};jM.f=Object.getOwnPropertySymbols;var lH=_g,cH=Lt,uH=TM,dH=jM,hH=Pa,pH=cH([].concat),fH=lH("Reflect","ownKeys")||function(e){var n=uH.f(hH(e)),r=dH.f;return r?pH(n,r(e)):n},u_=Ii,gH=fH,mH=kw,yH=ql,SH=function(t,e,n){for(var r=gH(e),o=yH.f,s=mH.f,i=0;i<r.length;i++){var a=r[i];!u_(t,a)&&!(n&&u_(n,a))&&o(t,a,s(e,a))}},vH=En,xH=kn,wH=/#|\.prototype\./,ad=function(t,e){var n=PH[bH(t)];return n===_H?!0:n===CH?!1:xH(e)?vH(e):!!e},bH=ad.normalize=function(t){return String(t).replace(wH,".").toLowerCase()},PH=ad.data={},CH=ad.NATIVE="N",_H=ad.POLYFILL="P",IH=ad,sh=In,EH=kw.f,kH=Dw,TH=kM,MH=Aw,AH=SH,jH=IH,Zl=function(t,e){var n=t.target,r=t.global,o=t.stat,s,i,a,l,c,u;if(r?i=sh:o?i=sh[n]||MH(n,{}):i=sh[n]&&sh[n].prototype,i)for(a in e){if(c=e[a],t.dontCallGetSet?(u=EH(i,a),l=u&&u.value):l=i[a],s=jH(r?a:n+(o?".":"#")+a,t.forced),!s&&l!==void 0){if(typeof c==typeof l)continue;AH(c,l)}(t.sham||l&&l.sham)&&kH(c,"sham",!0),TH(i,a,c,t)}},OM={},OH=AM,DH=Fw,RH=Object.keys||function(e){return OH(e,DH)},LH=_i,$H=xM,FH=ql,NH=Pa,zH=Cg,BH=RH;OM.f=LH&&!$H?Object.defineProperties:function(e,n){NH(e);for(var r=zH(n),o=BH(n),s=o.length,i=0,a;s>i;)FH.f(e,a=o[i++],r[a]);return e};var UH=_g,HH=UH("document","documentElement"),KH=Pa,WH=OM,d_=Fw,GH=Lw,VH=HH,YH=SM,XH=CM,h_=">",p_="<",rx="prototype",ox="script",DM=XH("IE_PROTO"),jy=function(){},RM=function(t){return p_+ox+h_+t+p_+"/"+ox+h_},f_=function(t){t.write(RM("")),t.close();var e=t.parentWindow.Object;return t=null,e},qH=function(){var t=YH("iframe"),e="java"+ox+":",n;return t.style.display="none",VH.appendChild(t),t.src=String(e),n=t.contentWindow.document,n.open(),n.write(RM("document.F=Object")),n.close(),n.F},ih,rp=function(){try{ih=new ActiveXObject("htmlfile")}catch{}rp=typeof document<"u"?document.domain&&ih?f_(ih):qH():f_(ih);for(var t=d_.length;t--;)delete rp[rx][d_[t]];return rp()};GH[DM]=!0;var LM=Object.create||function(e,n){var r;return e!==null?(jy[rx]=KH(e),r=new jy,jy[rx]=null,r[DM]=e):r=rp(),n===void 0?r:WH.f(r,n)},ZH=Es,QH=LM,JH=ql.f,sx=ZH("unscopables"),ix=Array.prototype;ix[sx]===void 0&&JH(ix,sx,{configurable:!0,value:QH(null)});var Nw=function(t){ix[sx][t]=!0},eK=Zl,tK=sd,nK=id,rK=Ca,oK=Nw;eK({target:"Array",proto:!0},{at:function(e){var n=tK(this),r=nK(n),o=rK(e),s=o>=0?o:r+o;return s<0||s>=r?void 0:n[s]}});oK("at");var sK=In,iK=Lt,ld=function(t,e){return iK(sK[t].prototype[e])},aK=ld;aK("Array","at");var lK=Yl,$M=Array.isArray||function(e){return lK(e)==="Array"},cK=TypeError,uK=9007199254740991,dK=function(t){if(t>uK)throw cK("Maximum allowed index exceeded");return t},hK=Yl,pK=Lt,fK=function(t){if(hK(t)==="Function")return pK(t)},g_=fK,gK=Tw,mK=bg,yK=g_(g_.bind),SK=function(t,e){return gK(t),e===void 0?t:mK?yK(t,e):function(){return t.apply(e,arguments)}},vK=$M,xK=id,wK=dK,bK=SK,FM=function(t,e,n,r,o,s,i,a){for(var l=o,c=0,u=i?bK(i,a):!1,h,p;c<r;)c in n&&(h=u?u(n[c],c,e):n[c],s>0&&vK(h)?(p=xK(h),l=FM(t,e,h,p,l,s-1)-1):(wK(l+1),t[l]=h),l++),c++;return l},NM=FM,PK=Es,CK=PK("toStringTag"),zM={};zM[CK]="z";var _K=String(zM)==="[object z]",IK=_K,EK=kn,op=Yl,kK=Es,TK=kK("toStringTag"),MK=Object,AK=op(function(){return arguments}())==="Arguments",jK=function(t,e){try{return t[e]}catch{}},BM=IK?op:function(t){var e,n,r;return t===void 0?"Undefined":t===null?"Null":typeof(n=jK(e=MK(t),TK))=="string"?n:AK?op(e):(r=op(e))==="Object"&&EK(e.callee)?"Arguments":r},OK=Lt,DK=En,UM=kn,RK=BM,LK=_g,$K=PM,HM=function(){},KM=LK("Reflect","construct"),zw=/^\s*(?:class|function)\b/,FK=OK(zw.exec),NK=!zw.test(HM),Cc=function(e){if(!UM(e))return!1;try{return KM(HM,[],e),!0}catch{return!1}},WM=function(e){if(!UM(e))return!1;switch(RK(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NK||!!FK(zw,$K(e))}catch{return!0}};WM.sham=!0;var zK=!KM||DK(function(){var t;return Cc(Cc.call)||!Cc(Object)||!Cc(function(){t=!0})||t})?WM:Cc,m_=$M,BK=zK,UK=ba,HK=Es,KK=HK("species"),y_=Array,WK=function(t){var e;return m_(t)&&(e=t.constructor,BK(e)&&(e===y_||m_(e.prototype))?e=void 0:UK(e)&&(e=e[KK],e===null&&(e=void 0))),e===void 0?y_:e},GK=WK,GM=function(t,e){return new(GK(t))(e===0?0:e)},VK=Zl,YK=NM,XK=Tw,qK=sd,ZK=id,QK=GM;VK({target:"Array",proto:!0},{flatMap:function(e){var n=qK(this),r=ZK(n),o;return XK(e),o=QK(n,0),o.length=YK(o,n,n,r,0,1,e,arguments.length>1?arguments[1]:void 0),o}});var JK=Nw;JK("flatMap");var eW=ld;eW("Array","flatMap");var tW=Zl,nW=NM,rW=sd,oW=id,sW=Ca,iW=GM;tW({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,n=rW(this),r=oW(n),o=iW(n,0);return o.length=nW(o,n,n,r,0,e===void 0?1:sW(e)),o}});var aW=Nw;aW("flat");var lW=ld;lW("Array","flat");var cW=BM,uW=String,cd=function(t){if(cW(t)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return uW(t)},dW=Zl,hW=Lt,pW=Xl,fW=Ca,gW=cd,mW=En,yW=hW("".charAt),SW=mW(function(){return"𠮷".at(-2)!=="\uD842"});dW({target:"String",proto:!0,forced:SW},{at:function(e){var n=gW(pW(this)),r=n.length,o=fW(e),s=o>=0?o:r+o;return s<0||s>=r?void 0:yW(n,s)}});var vW=ld;vW("String","at");var xW=Pa,VM=function(){var t=xW(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e},Bw=En,wW=In,Uw=wW.RegExp,Hw=Bw(function(){var t=Uw("a","y");return t.lastIndex=2,t.exec("abcd")!==null}),bW=Hw||Bw(function(){return!Uw("a","y").sticky}),PW=Hw||Bw(function(){var t=Uw("^r","gy");return t.lastIndex=2,t.exec("str")!==null}),CW={BROKEN_CARET:PW,MISSED_STICKY:bW,UNSUPPORTED_Y:Hw},_W=En,IW=In,EW=IW.RegExp,kW=_W(function(){var t=EW(".","s");return!(t.dotAll&&t.test(`
67
+ */function B9(t){return!t||t.length<12?!1:t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80}function U9(t){const e=new Uint8Array(t);return!B9(e)||!e||e.length<21?!1:(e[20]>>1&1)===1}const LT=Object.freeze(["image/svg+xml"]),$T=Object.freeze(["image/jpeg","image/png","image/webp"]),FT=Object.freeze(["image/gif","image/apng","image/avif"]),xg=Object.freeze([...$T,...LT,...FT]),xw=Object.freeze(["video/mp4","video/webm","video/quicktime"]),H9=[...xg,...xw].join(",");class ar{static loadVideo(e){return new Promise((n,r)=>{const o=document.createElement("video");o.onloadeddata=()=>n(o),o.onerror=s=>{console.error(s),r(new Error("Could not load video"))},o.crossOrigin="anonymous",o.src=e})}static async getVideoFrameAsDataUrl(e,n=0){const r=yw();let o=!1;const s=()=>{if(!o)if(e.readyState>=e.HAVE_METADATA)o=!0,e.currentTime=n;else return;if(e.readyState>=e.HAVE_CURRENT_DATA){const a=document.createElement("canvas");a.width=e.videoWidth,a.height=e.videoHeight;const l=a.getContext("2d");if(!l)throw new Error("Could not get 2d context");l.drawImage(e,0,0),r.resolve(a.toDataURL())}},i=a=>{console.error(a),r.reject(new Error("Could not get video frame"))};e.addEventListener("loadedmetadata",s),e.addEventListener("loadeddata",s),e.addEventListener("canplay",s),e.addEventListener("seeked",s),e.addEventListener("error",i),e.addEventListener("stalled",i),s();try{return await r}finally{e.removeEventListener("loadedmetadata",s),e.removeEventListener("loadeddata",s),e.removeEventListener("canplay",s),e.removeEventListener("seeked",s),e.removeEventListener("error",i),e.removeEventListener("stalled",i)}}static loadImage(e){return new Promise((n,r)=>{const o=Lu();o.onload=()=>n(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=e})}static async getVideoSize(e){return ar.usingObjectURL(e,async n=>{const r=await ar.loadVideo(n);return{w:r.videoWidth,h:r.videoHeight}})}static async getImageSize(e){const n=await ar.usingObjectURL(e,ar.loadImage);try{if(e.type==="image/png"){const r=new DataView(await e.arrayBuffer());if(Co.isPng(r,0)){const o=Co.findChunk(r,"pHYs");if(o){const s=Co.parsePhys(r,o.dataOffset);if(s.unit===0&&s.ppux===s.ppuy){const i=Math.max(s.ppux/2834.5,1);return{w:Math.round(n.naturalWidth/i),h:Math.round(n.naturalHeight/i)}}}}}}catch(r){return console.error(r),{w:n.naturalWidth,h:n.naturalHeight}}return{w:n.naturalWidth,h:n.naturalHeight}}static async isAnimated(e){return e.type==="image/gif"?N9(await e.arrayBuffer()):e.type==="image/avif"?$9(await e.arrayBuffer()):e.type==="image/webp"?U9(await e.arrayBuffer()):e.type==="image/apng"?L9(await e.arrayBuffer()):!1}static isAnimatedImageType(e){return FT.includes(e||"")}static isStaticImageType(e){return $T.includes(e||"")}static isVectorImageType(e){return LT.includes(e||"")}static isImageType(e){return xg.includes(e)}static async usingObjectURL(e,n){const r=URL.createObjectURL(e);try{return await n(r)}finally{URL.revokeObjectURL(r)}}}function _e(t,e,n){return t+(e-t)*n}function co(t=""){let e=0,n=0,r=0,o=0;function s(){const i=e^e<<11;return e=n,n=r,r=o,o^=(o>>>19^i^i>>>8)>>>0,o/4294967296*2}for(let i=0;i<t.length+64;i++)e^=t.charCodeAt(i)|0,s();return s}function Ol(t,e,n,r=!1){const[o,s]=e,[i,a]=n,l=i+(t-o)/(s-o)*(a-i);return r?i<a?Math.max(Math.min(l,a),i):Math.max(Math.min(l,i),a):l}function no(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function hn(t,e){if(no(t,e))return t[e]}function $C(t){return Object.keys(t)}function ut(t){return Object.values(t)}function Xn(t){return Object.entries(t)}function ww(t){return Object.fromEntries(t)}function lu(t,e){const n={};let r=!1;for(const[o,s]of Xn(t))e(o,s)?n[o]=s:r=!0;return r?n:t}function od(t,e){const n={};for(const[r,o]of Xn(t)){const s=e(r,o);n[r]=s}return n}function NT(t,e){if(t===e)return!0;const n=new Set(Object.keys(t)),r=new Set(Object.keys(e));if(n.size!==r.size)return!1;for(const o of n)if(!r.has(o)||!Object.is(t[o],e[o]))return!1;return!0}function K9(t){const e=W9(t.chars),n=G9(e,t.firstPositive,t.mostPositive,t.mostNegative),r=t.jitterRange??Math.floor(Math.pow(e.length,3)/5),o=V9(r,e.length);return{chars:t.chars,byChar:e.byChar,byCode:e.byCode,length:e.length,first:e.byCode[0],last:e.byCode[e.length-1],firstPositive:n.firstPositive,mostPositive:n.mostPositive,firstNegative:n.firstNegative,mostNegative:n.mostNegative,jitterRange:r,paddingDict:o}}function W9(t){const e={},n={},r=t.length;for(let o=0;o<r;o++){const s=t[o];e[o]=s,n[s]=o}return{byCode:e,byChar:n,length:r}}function G9(t,e,n,r){const o=e?t.byChar[e]:Math.ceil(t.length/2),s=n?t.byChar[n]:t.length-1,i=r?t.byChar[r]:0;if(o===void 0||s===void 0||i===void 0)throw new Error("invalid charSet");if(s-o<3)throw new Error("mostPositive must be at least 3 characters away from neutral");if(o-i<3)throw new Error("mostNegative must be at least 3 characters away from neutral");return{firstPositive:t.byCode[o],mostPositive:t.byCode[s],firstNegative:t.byCode[o-1],mostNegative:t.byCode[i]}}function V9(t,e){const n={};for(let r=0;r<100&&(n[r]=Math.pow(e,r),!(n[r]>t));r++);return n}var fy=null;function bw(){return fy||(fy=K9({chars:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",firstPositive:"a",mostPositive:"z",mostNegative:"A"}))}function Qs(t,e,n){const r=n.byChar[t],o=n.byChar[e];return Math.abs(r-o)}function Pw(t,e){const n=t[0];if(n>e.mostPositive||n<e.mostNegative)throw new Error("invalid firstChar on key");return n===e.mostPositive?Qs(n,e.firstPositive,e)+1+df(t.slice(1),"positive",e):n===e.mostNegative?Qs(n,e.firstNegative,e)+1+df(t.slice(1),"negative",e):n>=e.firstPositive?Qs(n,e.firstPositive,e)+2:Qs(n,e.firstNegative,e)+2}function df(t,e,n){const r=t[0];if(r>n.mostPositive||r<n.mostNegative)throw new Error("invalid firstChar on key");return r===n.mostPositive&&e==="positive"?Qs(r,n.mostNegative,n)+1+df(t.slice(1),e,n):r===n.mostNegative&&e==="negative"?Qs(r,n.mostPositive,n)+1+df(t.slice(1),e,n):e==="positive"?Qs(r,n.mostNegative,n)+2:Qs(r,n.mostPositive,n)+2}function wg(t,e,n,r,o){const s=Math.max(t.length,e.length);return n==="start"?[t.padStart(s,r),e.padStart(s,r)]:[t.padEnd(s,r),e.padEnd(s,r)]}function Y9(t,e,n){let[r,o]=wg(t,e,"end",n.first),s=Yv(r,o,n);s===1&&(r=r.padEnd(r.length+1,n.first),s=n.length);const i=UT(Math.floor(s/2),n);return Cw(r,i,n)}function Yv(t,e,n){const[r,o]=wg(t,e,"end",n.first).sort(),s=zT(o,r,n);return X9(s,n)}function Cw(t,e,n){const r=n.length,[o,s]=wg(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){const c=n.byChar[o[l]],u=n.byChar[s[l]],h=c+u+a;a=Math.floor(h/r);const p=h%r;i.unshift(n.byCode[p])}return a>0&&i.unshift(n.byCode[a]),i.join("")}function zT(t,e,n){const r=n.length,[o,s]=wg(t,e,"start",n.first),i=[];let a=0;for(let l=o.length-1;l>=0;l--){let c=n.byChar[o[l]];const u=n.byChar[s[l]]+a;c<u?(a=1,c+=r):a=0;const h=c-u;i.unshift(n.byCode[h])}if(a>0)throw new Error("Subtraction result is negative. Ensure a is greater than or equal to b.");for(;i.length>1&&i[0]===n.byCode[0];)i.shift();return i.join("")}function BT(t,e){return Cw(t,e.byCode[1],e)}function Xv(t,e){return zT(t,e.byCode[1],e)}function UT(t,e){if(t===0)return e.byCode[0];let n="";const r=e.length;for(;t>0;)n=e.byCode[t%r]+n,t=Math.floor(t/r);return n}function X9(t,e){let n=0;const r=t.length,o=e.length;for(let s=0;s<r;s++)n+=e.byChar[t[s]]*Math.pow(o,r-s-1);return n}function q9(t){return t.firstPositive+t.byCode[0]}function Z9(t,e){return Pw(t,e)===t.length}function FC(t,e){hf(t,e)}function hf(t,e){const n=WT(t,e),r=Pw(n,e);if(r>t.length)throw new Error("invalid order key length: "+t);return t.slice(0,r)}function HT(t,e){if(!Z9(t,e))throw new Error("invalid integer length: "+t)}function KT(t,e){HT(t,e);const[n,r]=GT(t,e);if(r.split("").some(i=>i!==e.byCode[e.length-1])){const i=BT(r,e);return n+i}const s=J9(n,e);return VT(s,"lower",e)}function Q9(t,e){HT(t,e);const[n,r]=GT(t,e);if(r.split("").some(i=>i!==e.byCode[0])){const i=Xv(r,e);return n+i}const s=eB(n,e);return VT(s,"upper",e)}function WT(t,e){let n=0;if(t[0]===e.mostPositive)for(;t[n]===e.mostPositive;)n=n+1;if(t[0]===e.mostNegative)for(;t[n]===e.mostNegative;)n=n+1;return t.slice(0,n+1)}function GT(t,e){const n=WT(t,e),r=t.slice(n.length);return[n,r]}function J9(t,e){const n=t>=e.firstPositive,r=BT(t,e),o=t[t.length-1]===e.mostPositive,s=r[r.length-1]===e.mostPositive;return n&&s?r+e.mostNegative:!n&&o?t.slice(0,t.length-1):r}function eB(t,e){const n=t>=e.firstPositive,r=t[t.length-1]===e.mostNegative;if(n&&r){const o=t.slice(0,t.length-1);return Xv(o,e)}return!n&&r?t+e.mostPositive:Xv(t,e)}function VT(t,e,n){const r=Pw(t,n),o=e==="upper"?n.byCode[n.length-1]:n.byCode[0];return t+o.repeat(r-t.length)}function YT(t,e){const n=UT(Math.floor(Math.random()*e.jitterRange),e);return Cw(t,n,e)}function tB(t,e,n){const r=t.padEnd(t.length+e,n.first);return YT(r,n)}function nB(t,e,n){const r=hf(t,n),o=KT(r,n);let s=0;if(e!==null){const a=Yv(t,e,n);a<n.jitterRange+1&&(s=Math.max(s,NC(a,n)))}const i=Yv(t,o,n);return i<n.jitterRange+1&&(s=Math.max(s,NC(i,n))),s}function NC(t,e){const n=e.jitterRange-t,r=Object.entries(e.paddingDict).find(([o,s])=>s>n);return r?parseInt(r[0]):0}function rB(t,e,n=bw()){if(t!==null&&FC(t,n),e!==null&&FC(e,n),t===null&&e===null)return q9(n);if(t===null){const r=hf(e,n);return Q9(r,n)}if(e===null){const r=hf(t,n);return KT(r,n)}if(t>=e)throw new Error(t+" >= "+e);return Y9(t,e,n)}function XT(t,e,n=bw()){const r=rB(t,e,n),o=nB(r,e,n);return o?tB(r,o,n):YT(r,n)}function qT(t,e,n,r=bw()){return oB(t,e,n,r,XT,qT)}function oB(t,e,n,r,o,s){if(n===0)return[];if(n===1)return[o(t,e,r)];if(e==null){let l=o(t,e,r);const c=[l];for(let u=0;u<n-1;u++)l=o(l,e,r),c.push(l);return c}if(t==null){let l=o(t,e,r);const c=[l];for(let u=0;u<n-1;u++)l=o(t,l,r),c.push(l);return c.reverse(),c}const i=Math.floor(n/2),a=o(t,e,r);return[...s(t,a,i,r),a,...s(a,e,n-i-1,r)]}const Vl=qT,ZT="a0";function sB(t){try{XT(t,null)}catch{throw new Error("invalid index: "+t)}}function Dl(t,e,n){return Vl(t??null,e??null,n)}function gy(t,e){return Vl(t??null,null,e)}function $u(t,e){return Vl(t??null,e??null,1)[0]}function Io(t=null){return Vl(t,null,1)[0]}function iB(t=null){return Vl(null,t,1)[0]}function Fu(t,e="a1"){return[e,...Vl(e,null,t)]}function cn(t,e){return t.index<e.index?-1:t.index>e.index?1:0}function aB(t,e){return t.id>e.id?1:-1}function _w(t){try{return localStorage.getItem(t)}catch{return null}}function Iw(t,e){try{localStorage.setItem(t,e)}catch{}}function lB(){try{localStorage.clear()}catch{}}function QT(t){try{return sessionStorage.getItem(t)}catch{return null}}function Ew(t,e){try{sessionStorage.setItem(t,e)}catch{}}function JT(t){try{sessionStorage.removeItem(t)}catch{}}function cB(){try{sessionStorage.clear()}catch{}}const ol=[],uB=60,tp=Math.ceil(1e3/uB);let bc,my=0,qv=0;const dB=()=>{const t=ol.splice(0,ol.length);for(const e of t)e()};function eM(){if(bc)return;const t=Date.now(),e=t-qv;if(my+e<tp){bc=requestAnimationFrame(()=>{bc=void 0,eM()});return}bc=requestAnimationFrame(()=>{bc=void 0,qv=t,my=Math.min(my+e-tp,tp*10),dB()})}let zC=!1;function tM(t){return ol.includes(t)||(ol.push(t),zC||(zC=!0,qv=Date.now()-tp-1),eM()),()=>{const e=ol.indexOf(t);e>-1&&ol.splice(e,1)}}class hB{constructor(){I(this,"timeouts",new Map);I(this,"intervals",new Map);I(this,"rafs",new Map);this.setTimeout=this.setTimeout.bind(this),this.setInterval=this.setInterval.bind(this),this.requestAnimationFrame=this.requestAnimationFrame.bind(this),this.dispose=this.dispose.bind(this)}setTimeout(e,n,r,...o){const s=window.setTimeout(n,r,o),i=this.timeouts.get(e)??[];return this.timeouts.set(e,[...i,s]),s}setInterval(e,n,r,...o){const s=window.setInterval(n,r,o),i=this.intervals.get(e)??[];return this.intervals.set(e,[...i,s]),s}requestAnimationFrame(e,n){const r=window.requestAnimationFrame(n),o=this.rafs.get(e)??[];return this.rafs.set(e,[...o,r]),r}dispose(e){var n,r,o;(n=this.timeouts.get(e))==null||n.forEach(s=>clearTimeout(s)),(r=this.intervals.get(e))==null||r.forEach(s=>clearInterval(s)),(o=this.rafs.get(e))==null||o.forEach(s=>cancelAnimationFrame(s)),this.timeouts.delete(e),this.intervals.delete(e),this.rafs.delete(e)}disposeAll(){for(const e of this.timeouts.keys())this.dispose(e)}forContext(e){return{setTimeout:(n,r,...o)=>this.setTimeout(e,n,r,o),setInterval:(n,r,...o)=>this.setInterval(e,n,r,o),requestAnimationFrame:n=>this.requestAnimationFrame(e,n),dispose:()=>this.dispose(e)}}}const ge=(t,e)=>{try{return new URL(t,e)}catch{return}};function pB(t){return t!==void 0}function fB(){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]:[t=>t&&JSON.parse(JSON.stringify(t)),!1]}const nM=fB(),tt=nM[0];nM[1];const gB=Object.getPrototypeOf(tt({}));Ci("@tldraw/utils","3.7.0-canary.8e16c48b63b1","esm");var Pc=function(t){return t&&t.Math===Math&&t},In=Pc(typeof globalThis=="object"&&globalThis)||Pc(typeof window=="object"&&window)||Pc(typeof self=="object"&&self)||Pc(typeof dn=="object"&&dn)||Pc(typeof dn=="object"&&dn)||function(){return this}()||Function("return this")(),kw={},En=function(t){try{return!!t()}catch{return!0}},mB=En,_i=!mB(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),yB=En,bg=!yB(function(){var t=(function(){}).bind();return typeof t!="function"||t.hasOwnProperty("prototype")}),SB=bg,nh=Function.prototype.call,Is=SB?nh.bind(nh):function(){return nh.apply(nh,arguments)},rM={},oM={}.propertyIsEnumerable,sM=Object.getOwnPropertyDescriptor,vB=sM&&!oM.call({1:2},1);rM.f=vB?function(e){var n=sM(this,e);return!!n&&n.enumerable}:oM;var iM=function(t,e){return{enumerable:!(t&1),configurable:!(t&2),writable:!(t&4),value:e}},aM=bg,lM=Function.prototype,Zv=lM.call,xB=aM&&lM.bind.bind(Zv,Zv),Lt=aM?xB:function(t){return function(){return Zv.apply(t,arguments)}},cM=Lt,wB=cM({}.toString),bB=cM("".slice),Yl=function(t){return bB(wB(t),8,-1)},PB=Lt,CB=En,_B=Yl,yy=Object,IB=PB("".split),EB=CB(function(){return!yy("z").propertyIsEnumerable(0)})?function(t){return _B(t)==="String"?IB(t,""):yy(t)}:yy,Pg=function(t){return t==null},kB=Pg,TB=TypeError,Xl=function(t){if(kB(t))throw new TB("Can't call method on "+t);return t},MB=EB,AB=Xl,Cg=function(t){return MB(AB(t))},Sy=typeof document=="object"&&document.all,kn=typeof Sy>"u"&&Sy!==void 0?function(t){return typeof t=="function"||t===Sy}:function(t){return typeof t=="function"},jB=kn,ba=function(t){return typeof t=="object"?t!==null:jB(t)},vy=In,OB=kn,DB=function(t){return OB(t)?t:void 0},_g=function(t,e){return arguments.length<2?DB(vy[t]):vy[t]&&vy[t][e]},RB=Lt,uM=RB({}.isPrototypeOf),LB=In,BC=LB.navigator,UC=BC&&BC.userAgent,$B=UC?String(UC):"",dM=In,xy=$B,HC=dM.process,KC=dM.Deno,WC=HC&&HC.versions||KC&&KC.version,GC=WC&&WC.v8,Xr,pf;GC&&(Xr=GC.split("."),pf=Xr[0]>0&&Xr[0]<4?1:+(Xr[0]+Xr[1]));!pf&&xy&&(Xr=xy.match(/Edge\/(\d+)/),(!Xr||Xr[1]>=74)&&(Xr=xy.match(/Chrome\/(\d+)/),Xr&&(pf=+Xr[1])));var FB=pf,VC=FB,NB=En,zB=In,BB=zB.String,hM=!!Object.getOwnPropertySymbols&&!NB(function(){var t=Symbol("symbol detection");return!BB(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&VC&&VC<41}),UB=hM,pM=UB&&!Symbol.sham&&typeof Symbol.iterator=="symbol",HB=_g,KB=kn,WB=uM,GB=pM,VB=Object,fM=GB?function(t){return typeof t=="symbol"}:function(t){var e=HB("Symbol");return KB(e)&&WB(e.prototype,VB(t))},YB=String,XB=function(t){try{return YB(t)}catch{return"Object"}},qB=kn,ZB=XB,QB=TypeError,Tw=function(t){if(qB(t))return t;throw new QB(ZB(t)+" is not a function")},JB=Tw,e7=Pg,Mw=function(t,e){var n=t[e];return e7(n)?void 0:JB(n)},wy=Is,by=kn,Py=ba,t7=TypeError,n7=function(t,e){var n,r;if(e==="string"&&by(n=t.toString)&&!Py(r=wy(n,t))||by(n=t.valueOf)&&!Py(r=wy(n,t))||e!=="string"&&by(n=t.toString)&&!Py(r=wy(n,t)))return r;throw new t7("Can't convert object to primitive value")},gM={exports:{}},YC=In,r7=Object.defineProperty,Aw=function(t,e){try{r7(YC,t,{value:e,configurable:!0,writable:!0})}catch{YC[t]=e}return e},o7=In,s7=Aw,XC="__core-js_shared__",qC=gM.exports=o7[XC]||s7(XC,{});(qC.versions||(qC.versions=[])).push({version:"3.39.0",mode:"global",copyright:"© 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE",source:"https://github.com/zloirock/core-js"});var jw=gM.exports,ZC=jw,Ow=function(t,e){return ZC[t]||(ZC[t]=e||{})},i7=Xl,a7=Object,sd=function(t){return a7(i7(t))},l7=Lt,c7=sd,u7=l7({}.hasOwnProperty),Ii=Object.hasOwn||function(e,n){return u7(c7(e),n)},d7=Lt,h7=0,p7=Math.random(),f7=d7(1 .toString),mM=function(t){return"Symbol("+(t===void 0?"":t)+")_"+f7(++h7+p7,36)},g7=In,m7=Ow,QC=Ii,y7=mM,S7=hM,v7=pM,sl=g7.Symbol,Cy=m7("wks"),x7=v7?sl.for||sl:sl&&sl.withoutSetter||y7,Es=function(t){return QC(Cy,t)||(Cy[t]=S7&&QC(sl,t)?sl[t]:x7("Symbol."+t)),Cy[t]},w7=Is,JC=ba,e_=fM,b7=Mw,P7=n7,C7=Es,_7=TypeError,I7=C7("toPrimitive"),E7=function(t,e){if(!JC(t)||e_(t))return t;var n=b7(t,I7),r;if(n){if(e===void 0&&(e="default"),r=w7(n,t,e),!JC(r)||e_(r))return r;throw new _7("Can't convert object to primitive value")}return e===void 0&&(e="number"),P7(t,e)},k7=E7,T7=fM,yM=function(t){var e=k7(t,"string");return T7(e)?e:e+""},M7=In,t_=ba,Qv=M7.document,A7=t_(Qv)&&t_(Qv.createElement),SM=function(t){return A7?Qv.createElement(t):{}},j7=_i,O7=En,D7=SM,vM=!j7&&!O7(function(){return Object.defineProperty(D7("div"),"a",{get:function(){return 7}}).a!==7}),R7=_i,L7=Is,$7=rM,F7=iM,N7=Cg,z7=yM,B7=Ii,U7=vM,n_=Object.getOwnPropertyDescriptor;kw.f=R7?n_:function(e,n){if(e=N7(e),n=z7(n),U7)try{return n_(e,n)}catch{}if(B7(e,n))return F7(!L7($7.f,e,n),e[n])};var ql={},H7=_i,K7=En,xM=H7&&K7(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),W7=ba,G7=String,V7=TypeError,Pa=function(t){if(W7(t))return t;throw new V7(G7(t)+" is not an object")},Y7=_i,X7=vM,q7=xM,rh=Pa,r_=yM,Z7=TypeError,_y=Object.defineProperty,Q7=Object.getOwnPropertyDescriptor,Iy="enumerable",Ey="configurable",ky="writable";ql.f=Y7?q7?function(e,n,r){if(rh(e),n=r_(n),rh(r),typeof e=="function"&&n==="prototype"&&"value"in r&&ky in r&&!r[ky]){var o=Q7(e,n);o&&o[ky]&&(e[n]=r.value,r={configurable:Ey in r?r[Ey]:o[Ey],enumerable:Iy in r?r[Iy]:o[Iy],writable:!1})}return _y(e,n,r)}:_y:function(e,n,r){if(rh(e),n=r_(n),rh(r),X7)try{return _y(e,n,r)}catch{}if("get"in r||"set"in r)throw new Z7("Accessors not supported");return"value"in r&&(e[n]=r.value),e};var J7=_i,eU=ql,tU=iM,Dw=J7?function(t,e,n){return eU.f(t,e,tU(1,n))}:function(t,e,n){return t[e]=n,t},wM={exports:{}},Jv=_i,nU=Ii,bM=Function.prototype,rU=Jv&&Object.getOwnPropertyDescriptor,Rw=nU(bM,"name"),oU=Rw&&(function(){}).name==="something",sU=Rw&&(!Jv||Jv&&rU(bM,"name").configurable),iU={EXISTS:Rw,PROPER:oU,CONFIGURABLE:sU},aU=Lt,lU=kn,ex=jw,cU=aU(Function.toString);lU(ex.inspectSource)||(ex.inspectSource=function(t){return cU(t)});var PM=ex.inspectSource,uU=In,dU=kn,o_=uU.WeakMap,hU=dU(o_)&&/native code/.test(String(o_)),pU=Ow,fU=mM,s_=pU("keys"),CM=function(t){return s_[t]||(s_[t]=fU(t))},Lw={},gU=hU,_M=In,mU=ba,yU=Dw,Ty=Ii,My=jw,SU=CM,vU=Lw,i_="Object already initialized",tx=_M.TypeError,xU=_M.WeakMap,ff,Nu,gf,wU=function(t){return gf(t)?Nu(t):ff(t,{})},bU=function(t){return function(e){var n;if(!mU(e)||(n=Nu(e)).type!==t)throw new tx("Incompatible receiver, "+t+" required");return n}};if(gU||My.state){var yo=My.state||(My.state=new xU);yo.get=yo.get,yo.has=yo.has,yo.set=yo.set,ff=function(t,e){if(yo.has(t))throw new tx(i_);return e.facade=t,yo.set(t,e),e},Nu=function(t){return yo.get(t)||{}},gf=function(t){return yo.has(t)}}else{var Ma=SU("state");vU[Ma]=!0,ff=function(t,e){if(Ty(t,Ma))throw new tx(i_);return e.facade=t,yU(t,Ma,e),e},Nu=function(t){return Ty(t,Ma)?t[Ma]:{}},gf=function(t){return Ty(t,Ma)}}var IM={set:ff,get:Nu,has:gf,enforce:wU,getterFor:bU},$w=Lt,PU=En,CU=kn,oh=Ii,nx=_i,_U=iU.CONFIGURABLE,IU=PM,EM=IM,EU=EM.enforce,kU=EM.get,a_=String,np=Object.defineProperty,TU=$w("".slice),MU=$w("".replace),AU=$w([].join),jU=nx&&!PU(function(){return np(function(){},"length",{value:8}).length!==8}),OU=String(String).split("String"),DU=wM.exports=function(t,e,n){TU(a_(e),0,7)==="Symbol("&&(e="["+MU(a_(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),n&&n.getter&&(e="get "+e),n&&n.setter&&(e="set "+e),(!oh(t,"name")||_U&&t.name!==e)&&(nx?np(t,"name",{value:e,configurable:!0}):t.name=e),jU&&n&&oh(n,"arity")&&t.length!==n.arity&&np(t,"length",{value:n.arity});try{n&&oh(n,"constructor")&&n.constructor?nx&&np(t,"prototype",{writable:!1}):t.prototype&&(t.prototype=void 0)}catch{}var r=EU(t);return oh(r,"source")||(r.source=AU(OU,typeof e=="string"?e:"")),t};Function.prototype.toString=DU(function(){return CU(this)&&kU(this).source||IU(this)},"toString");var RU=wM.exports,LU=kn,$U=ql,FU=RU,NU=Aw,kM=function(t,e,n,r){r||(r={});var o=r.enumerable,s=r.name!==void 0?r.name:e;if(LU(n)&&FU(n,s,r),r.global)o?t[e]=n:NU(e,n);else{try{r.unsafe?t[e]&&(o=!0):delete t[e]}catch{}o?t[e]=n:$U.f(t,e,{value:n,enumerable:!1,configurable:!r.nonConfigurable,writable:!r.nonWritable})}return t},TM={},zU=Math.ceil,BU=Math.floor,UU=Math.trunc||function(e){var n=+e;return(n>0?BU:zU)(n)},HU=UU,Ca=function(t){var e=+t;return e!==e||e===0?0:HU(e)},KU=Ca,WU=Math.max,GU=Math.min,VU=function(t,e){var n=KU(t);return n<0?WU(n+e,0):GU(n,e)},YU=Ca,XU=Math.min,MM=function(t){var e=YU(t);return e>0?XU(e,9007199254740991):0},qU=MM,id=function(t){return qU(t.length)},ZU=Cg,QU=VU,JU=id,l_=function(t){return function(e,n,r){var o=ZU(e),s=JU(o);if(s===0)return!t&&-1;var i=QU(r,s),a;if(t&&n!==n){for(;s>i;)if(a=o[i++],a!==a)return!0}else for(;s>i;i++)if((t||i in o)&&o[i]===n)return t||i||0;return!t&&-1}},eH={includes:l_(!0),indexOf:l_(!1)},tH=Lt,Ay=Ii,nH=Cg,rH=eH.indexOf,oH=Lw,c_=tH([].push),AM=function(t,e){var n=nH(t),r=0,o=[],s;for(s in n)!Ay(oH,s)&&Ay(n,s)&&c_(o,s);for(;e.length>r;)Ay(n,s=e[r++])&&(~rH(o,s)||c_(o,s));return o},Fw=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],sH=AM,iH=Fw,aH=iH.concat("length","prototype");TM.f=Object.getOwnPropertyNames||function(e){return sH(e,aH)};var jM={};jM.f=Object.getOwnPropertySymbols;var lH=_g,cH=Lt,uH=TM,dH=jM,hH=Pa,pH=cH([].concat),fH=lH("Reflect","ownKeys")||function(e){var n=uH.f(hH(e)),r=dH.f;return r?pH(n,r(e)):n},u_=Ii,gH=fH,mH=kw,yH=ql,SH=function(t,e,n){for(var r=gH(e),o=yH.f,s=mH.f,i=0;i<r.length;i++){var a=r[i];!u_(t,a)&&!(n&&u_(n,a))&&o(t,a,s(e,a))}},vH=En,xH=kn,wH=/#|\.prototype\./,ad=function(t,e){var n=PH[bH(t)];return n===_H?!0:n===CH?!1:xH(e)?vH(e):!!e},bH=ad.normalize=function(t){return String(t).replace(wH,".").toLowerCase()},PH=ad.data={},CH=ad.NATIVE="N",_H=ad.POLYFILL="P",IH=ad,sh=In,EH=kw.f,kH=Dw,TH=kM,MH=Aw,AH=SH,jH=IH,Zl=function(t,e){var n=t.target,r=t.global,o=t.stat,s,i,a,l,c,u;if(r?i=sh:o?i=sh[n]||MH(n,{}):i=sh[n]&&sh[n].prototype,i)for(a in e){if(c=e[a],t.dontCallGetSet?(u=EH(i,a),l=u&&u.value):l=i[a],s=jH(r?a:n+(o?".":"#")+a,t.forced),!s&&l!==void 0){if(typeof c==typeof l)continue;AH(c,l)}(t.sham||l&&l.sham)&&kH(c,"sham",!0),TH(i,a,c,t)}},OM={},OH=AM,DH=Fw,RH=Object.keys||function(e){return OH(e,DH)},LH=_i,$H=xM,FH=ql,NH=Pa,zH=Cg,BH=RH;OM.f=LH&&!$H?Object.defineProperties:function(e,n){NH(e);for(var r=zH(n),o=BH(n),s=o.length,i=0,a;s>i;)FH.f(e,a=o[i++],r[a]);return e};var UH=_g,HH=UH("document","documentElement"),KH=Pa,WH=OM,d_=Fw,GH=Lw,VH=HH,YH=SM,XH=CM,h_=">",p_="<",rx="prototype",ox="script",DM=XH("IE_PROTO"),jy=function(){},RM=function(t){return p_+ox+h_+t+p_+"/"+ox+h_},f_=function(t){t.write(RM("")),t.close();var e=t.parentWindow.Object;return t=null,e},qH=function(){var t=YH("iframe"),e="java"+ox+":",n;return t.style.display="none",VH.appendChild(t),t.src=String(e),n=t.contentWindow.document,n.open(),n.write(RM("document.F=Object")),n.close(),n.F},ih,rp=function(){try{ih=new ActiveXObject("htmlfile")}catch{}rp=typeof document<"u"?document.domain&&ih?f_(ih):qH():f_(ih);for(var t=d_.length;t--;)delete rp[rx][d_[t]];return rp()};GH[DM]=!0;var LM=Object.create||function(e,n){var r;return e!==null?(jy[rx]=KH(e),r=new jy,jy[rx]=null,r[DM]=e):r=rp(),n===void 0?r:WH.f(r,n)},ZH=Es,QH=LM,JH=ql.f,sx=ZH("unscopables"),ix=Array.prototype;ix[sx]===void 0&&JH(ix,sx,{configurable:!0,value:QH(null)});var Nw=function(t){ix[sx][t]=!0},eK=Zl,tK=sd,nK=id,rK=Ca,oK=Nw;eK({target:"Array",proto:!0},{at:function(e){var n=tK(this),r=nK(n),o=rK(e),s=o>=0?o:r+o;return s<0||s>=r?void 0:n[s]}});oK("at");var sK=In,iK=Lt,ld=function(t,e){return iK(sK[t].prototype[e])},aK=ld;aK("Array","at");var lK=Yl,$M=Array.isArray||function(e){return lK(e)==="Array"},cK=TypeError,uK=9007199254740991,dK=function(t){if(t>uK)throw cK("Maximum allowed index exceeded");return t},hK=Yl,pK=Lt,fK=function(t){if(hK(t)==="Function")return pK(t)},g_=fK,gK=Tw,mK=bg,yK=g_(g_.bind),SK=function(t,e){return gK(t),e===void 0?t:mK?yK(t,e):function(){return t.apply(e,arguments)}},vK=$M,xK=id,wK=dK,bK=SK,FM=function(t,e,n,r,o,s,i,a){for(var l=o,c=0,u=i?bK(i,a):!1,h,p;c<r;)c in n&&(h=u?u(n[c],c,e):n[c],s>0&&vK(h)?(p=xK(h),l=FM(t,e,h,p,l,s-1)-1):(wK(l+1),t[l]=h),l++),c++;return l},NM=FM,PK=Es,CK=PK("toStringTag"),zM={};zM[CK]="z";var _K=String(zM)==="[object z]",IK=_K,EK=kn,op=Yl,kK=Es,TK=kK("toStringTag"),MK=Object,AK=op(function(){return arguments}())==="Arguments",jK=function(t,e){try{return t[e]}catch{}},BM=IK?op:function(t){var e,n,r;return t===void 0?"Undefined":t===null?"Null":typeof(n=jK(e=MK(t),TK))=="string"?n:AK?op(e):(r=op(e))==="Object"&&EK(e.callee)?"Arguments":r},OK=Lt,DK=En,UM=kn,RK=BM,LK=_g,$K=PM,HM=function(){},KM=LK("Reflect","construct"),zw=/^\s*(?:class|function)\b/,FK=OK(zw.exec),NK=!zw.test(HM),Cc=function(e){if(!UM(e))return!1;try{return KM(HM,[],e),!0}catch{return!1}},WM=function(e){if(!UM(e))return!1;switch(RK(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return NK||!!FK(zw,$K(e))}catch{return!0}};WM.sham=!0;var zK=!KM||DK(function(){var t;return Cc(Cc.call)||!Cc(Object)||!Cc(function(){t=!0})||t})?WM:Cc,m_=$M,BK=zK,UK=ba,HK=Es,KK=HK("species"),y_=Array,WK=function(t){var e;return m_(t)&&(e=t.constructor,BK(e)&&(e===y_||m_(e.prototype))?e=void 0:UK(e)&&(e=e[KK],e===null&&(e=void 0))),e===void 0?y_:e},GK=WK,GM=function(t,e){return new(GK(t))(e===0?0:e)},VK=Zl,YK=NM,XK=Tw,qK=sd,ZK=id,QK=GM;VK({target:"Array",proto:!0},{flatMap:function(e){var n=qK(this),r=ZK(n),o;return XK(e),o=QK(n,0),o.length=YK(o,n,n,r,0,1,e,arguments.length>1?arguments[1]:void 0),o}});var JK=Nw;JK("flatMap");var eW=ld;eW("Array","flatMap");var tW=Zl,nW=NM,rW=sd,oW=id,sW=Ca,iW=GM;tW({target:"Array",proto:!0},{flat:function(){var e=arguments.length?arguments[0]:void 0,n=rW(this),r=oW(n),o=iW(n,0);return o.length=nW(o,n,n,r,0,e===void 0?1:sW(e)),o}});var aW=Nw;aW("flat");var lW=ld;lW("Array","flat");var cW=BM,uW=String,cd=function(t){if(cW(t)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return uW(t)},dW=Zl,hW=Lt,pW=Xl,fW=Ca,gW=cd,mW=En,yW=hW("".charAt),SW=mW(function(){return"𠮷".at(-2)!=="\uD842"});dW({target:"String",proto:!0,forced:SW},{at:function(e){var n=gW(pW(this)),r=n.length,o=fW(e),s=o>=0?o:r+o;return s<0||s>=r?void 0:yW(n,s)}});var vW=ld;vW("String","at");var xW=Pa,VM=function(){var t=xW(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e},Bw=En,wW=In,Uw=wW.RegExp,Hw=Bw(function(){var t=Uw("a","y");return t.lastIndex=2,t.exec("abcd")!==null}),bW=Hw||Bw(function(){return!Uw("a","y").sticky}),PW=Hw||Bw(function(){var t=Uw("^r","gy");return t.lastIndex=2,t.exec("str")!==null}),CW={BROKEN_CARET:PW,MISSED_STICKY:bW,UNSUPPORTED_Y:Hw},_W=En,IW=In,EW=IW.RegExp,kW=_W(function(){var t=EW(".","s");return!(t.dotAll&&t.test(`
68
68
  `)&&t.flags==="s")}),TW=En,MW=In,AW=MW.RegExp,jW=TW(function(){var t=AW("(?<a>b)","g");return t.exec("b").groups.a!=="b"||"b".replace(t,"$<a>c")!=="bc"}),il=Is,Ig=Lt,OW=cd,DW=VM,RW=CW,LW=Ow,$W=LM,FW=IM.get,NW=kW,zW=jW,BW=LW("native-string-replace",String.prototype.replace),mf=RegExp.prototype.exec,ax=mf,UW=Ig("".charAt),HW=Ig("".indexOf),KW=Ig("".replace),Oy=Ig("".slice),lx=function(){var t=/a/,e=/b*/g;return il(mf,t,"a"),il(mf,e,"a"),t.lastIndex!==0||e.lastIndex!==0}(),YM=RW.BROKEN_CARET,cx=/()??/.exec("")[1]!==void 0,WW=lx||cx||YM||NW||zW;WW&&(ax=function(e){var n=this,r=FW(n),o=OW(e),s=r.raw,i,a,l,c,u,h,p;if(s)return s.lastIndex=n.lastIndex,i=il(ax,s,o),n.lastIndex=s.lastIndex,i;var f=r.groups,g=YM&&n.sticky,m=il(DW,n),v=n.source,y=0,S=o;if(g&&(m=KW(m,"y",""),HW(m,"g")===-1&&(m+="g"),S=Oy(o,n.lastIndex),n.lastIndex>0&&(!n.multiline||n.multiline&&UW(o,n.lastIndex-1)!==`
69
69
  `)&&(v="(?: "+v+")",S=" "+S,y++),a=new RegExp("^(?:"+v+")",m)),cx&&(a=new RegExp("^"+v+"$(?!\\s)",m)),lx&&(l=n.lastIndex),c=il(mf,g?a:n,S),g?c?(c.input=Oy(c.input,y),c[0]=Oy(c[0],y),c.index=n.lastIndex,n.lastIndex+=c[0].length):n.lastIndex=0:lx&&c&&(n.lastIndex=n.global?c.index+c[0].length:l),cx&&c&&c.length>1&&il(BW,c[0],a,function(){for(u=1;u<arguments.length-2;u++)arguments[u]===void 0&&(c[u]=void 0)}),c&&f)for(c.groups=h=$W(null),u=0;u<f.length;u++)p=f[u],h[p[0]]=c[p[1]];return c});var Kw=ax,GW=Zl,S_=Kw;GW({target:"RegExp",proto:!0,forced:/./.exec!==S_},{exec:S_});var VW=bg,XM=Function.prototype,v_=XM.apply,x_=XM.call,YW=typeof Reflect=="object"&&Reflect.apply||(VW?x_.bind(v_):function(){return x_.apply(v_,arguments)}),w_=Is,b_=kM,XW=Kw,P_=En,qM=Es,qW=Dw,ZW=qM("species"),Dy=RegExp.prototype,QW=function(t,e,n,r){var o=qM(t),s=!P_(function(){var c={};return c[o]=function(){return 7},""[t](c)!==7}),i=s&&!P_(function(){var c=!1,u=/a/;return t==="split"&&(u={},u.constructor={},u.constructor[ZW]=function(){return u},u.flags="",u[o]=/./[o]),u.exec=function(){return c=!0,null},u[o](""),!c});if(!s||!i||n){var a=/./[o],l=e(o,""[t],function(c,u,h,p,f){var g=u.exec;return g===XW||g===Dy.exec?s&&!f?{done:!0,value:w_(a,u,h,p)}:{done:!0,value:w_(c,h,u,p)}:{done:!1}});b_(String.prototype,t,l[0]),b_(Dy,o,l[1])}r&&qW(Dy[o],"sham",!0)},Ww=Lt,JW=Ca,eG=cd,tG=Xl,nG=Ww("".charAt),C_=Ww("".charCodeAt),rG=Ww("".slice),__=function(t){return function(e,n){var r=eG(tG(e)),o=JW(n),s=r.length,i,a;return o<0||o>=s?t?"":void 0:(i=C_(r,o),i<55296||i>56319||o+1===s||(a=C_(r,o+1))<56320||a>57343?t?nG(r,o):i:t?rG(r,o,o+2):(i-55296<<10)+(a-56320)+65536)}},oG={codeAt:__(!1),charAt:__(!0)},sG=oG.charAt,iG=function(t,e,n){return e+(n?sG(t,e).length:1)},Gw=Lt,aG=sd,lG=Math.floor,Ry=Gw("".charAt),cG=Gw("".replace),Ly=Gw("".slice),uG=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dG=/\$([$&'`]|\d{1,2})/g,ZM=function(t,e,n,r,o,s){var i=n+t.length,a=r.length,l=dG;return o!==void 0&&(o=aG(o),l=uG),cG(s,l,function(c,u){var h;switch(Ry(u,0)){case"$":return"$";case"&":return t;case"`":return Ly(e,0,n);case"'":return Ly(e,i);case"<":h=o[Ly(u,1,-1)];break;default:var p=+u;if(p===0)return c;if(p>a){var f=lG(p/10);return f===0?c:f<=a?r[f-1]===void 0?Ry(u,1):r[f-1]+Ry(u,1):c}h=r[p-1]}return h===void 0?"":h})},I_=Is,hG=Pa,pG=kn,fG=Yl,gG=Kw,mG=TypeError,yG=function(t,e){var n=t.exec;if(pG(n)){var r=I_(n,t,e);return r!==null&&hG(r),r}if(fG(t)==="RegExp")return I_(gG,t,e);throw new mG("RegExp#exec called on incompatible receiver")},SG=YW,E_=Is,Eg=Lt,vG=QW,xG=En,wG=Pa,bG=kn,PG=Pg,CG=Ca,_G=MM,Aa=cd,IG=Xl,EG=iG,kG=Mw,TG=ZM,MG=yG,AG=Es,ux=AG("replace"),jG=Math.max,OG=Math.min,DG=Eg([].concat),$y=Eg([].push),k_=Eg("".indexOf),T_=Eg("".slice),RG=function(t){return t===void 0?t:String(t)},LG=function(){return"a".replace(/./,"$0")==="$0"}(),M_=function(){return/./[ux]?/./[ux]("a","$0")==="":!1}(),$G=!xG(function(){var t=/./;return t.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(t,"$<a>")!=="7"});vG("replace",function(t,e,n){var r=M_?"$":"$0";return[function(s,i){var a=IG(this),l=PG(s)?void 0:kG(s,ux);return l?E_(l,s,a,i):E_(e,Aa(a),s,i)},function(o,s){var i=wG(this),a=Aa(o);if(typeof s=="string"&&k_(s,r)===-1&&k_(s,"$<")===-1){var l=n(e,i,a,s);if(l.done)return l.value}var c=bG(s);c||(s=Aa(s));var u=i.global,h;u&&(h=i.unicode,i.lastIndex=0);for(var p=[],f;f=MG(i,a),!(f===null||($y(p,f),!u));){var g=Aa(f[0]);g===""&&(i.lastIndex=EG(a,_G(i.lastIndex),h))}for(var m="",v=0,y=0;y<p.length;y++){f=p[y];for(var S=Aa(f[0]),b=jG(OG(CG(f.index),a.length),0),P=[],C,_=1;_<f.length;_++)$y(P,RG(f[_]));var E=f.groups;if(c){var k=DG([S],P,b,a);E!==void 0&&$y(k,E),C=Aa(SG(s,void 0,k))}else C=TG(S,a,b,P,E,s);b>=v&&(m+=T_(a,v,b)+C,v=b+S.length)}return m+T_(a,v)}]},!$G||!LG||M_);var FG=ba,NG=Yl,zG=Es,BG=zG("match"),UG=function(t){var e;return FG(t)&&((e=t[BG])!==void 0?!!e:NG(t)==="RegExp")},HG=Is,KG=Ii,WG=uM,GG=VM,A_=RegExp.prototype,VG=function(t){var e=t.flags;return e===void 0&&!("flags"in A_)&&!KG(t,"flags")&&WG(A_,t)?HG(GG,t):e},YG=Zl,XG=Is,Vw=Lt,j_=Xl,qG=kn,ZG=Pg,QG=UG,_c=cd,JG=Mw,eV=VG,tV=ZM,nV=Es,rV=nV("replace"),oV=TypeError,Fy=Vw("".indexOf);Vw("".replace);var O_=Vw("".slice),sV=Math.max;YG({target:"String",proto:!0},{replaceAll:function(e,n){var r=j_(this),o,s,i,a,l,c,u,h,p,f,g=0,m="";if(!ZG(e)){if(o=QG(e),o&&(s=_c(j_(eV(e))),!~Fy(s,"g")))throw new oV("`.replaceAll` does not allow non-global regexes");if(i=JG(e,rV),i)return XG(i,e,r,n)}for(a=_c(r),l=_c(e),c=qG(n),c||(n=_c(n)),u=l.length,h=sV(1,u),p=Fy(a,l);p!==-1;)f=c?_c(n(l,p,a)):tV(l,a,p,[],void 0,n),m+=O_(a,g,p)+f,g=p+u,p=p+h>a.length?-1:Fy(a,l,p+h);return g<a.length&&(m+=O_(a,g)),m}});var iV=ld;iV("String","replaceAll");function QM(t){return t&&typeof t=="object"&&"parents"in t}function JM(t){for(let e=0,n=t.parents.length;e<n;e++)if(t.parents[e].__unsafe__getWithoutCapture(!0),t.parents[e].lastChangedEpoch!==t.parentEpochs[e])return!0;return!1}function yf(t,e){if(t.children.remove(e)&&t.children.isEmpty&&QM(t))for(let n=0,r=t.parents.length;n<r;n++)yf(t.parents[n],t)}function Yw(t,e){if(t.children.add(e)&&QM(t))for(let n=0,r=t.parents.length;n<r;n++)Yw(t.parents[n],t)}function eA(t,e){return t===e||Object.is(t,e)||!!(t&&e&&typeof t.equals=="function"&&t.equals(e))}function Ei(t,e){const n=Symbol.for(`com.tldraw.state/${t}`),r=globalThis;return r[n]??(r[n]=e()),r[n]}const ps=Ei("empty_array",()=>Object.freeze([])),D_=8;class Sf{constructor(){I(this,"arraySize",0);I(this,"array",Array(D_));I(this,"set",null)}get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw new Error("no set or array")}add(e){if(this.array)return this.array.indexOf(e)!==-1?!1:this.arraySize<D_?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0);if(this.set)return this.set.has(e)?!1:(this.set.add(e),!0);throw new Error("no set or array")}remove(e){if(this.array){const n=this.array.indexOf(e);return n===-1?!1:(this.array[n]=void 0,this.arraySize--,n!==this.arraySize&&(this.array[n]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw new Error("no set or array")}visit(e){if(this.array){for(let n=0;n<this.arraySize;n++){const r=this.array[n];typeof r<"u"&&e(r)}return}if(this.set){this.set.forEach(e);return}throw new Error("no set or array")}has(e){return this.array?this.array.indexOf(e)!==-1:this.set.has(e)}clear(){this.set?this.set.clear():(this.arraySize=0,this.array=[])}size(){return this.set?this.set.size:this.arraySize}}const ur=Symbol.for("com.tldraw.state/RESET_VALUE");class tA{constructor(e){I(this,"index",0);I(this,"buffer");this.capacity=e,this.buffer=new Array(e)}pushEntry(e,n,r){if(r!==void 0){if(r===ur){this.clear();return}this.buffer[this.index]=[e,n,r],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){const{index:n,capacity:r,buffer:o}=this;for(let s=0;s<r;s++){const i=(n-1+r-s)%r,a=o[i];if(!a)return ur;const[l,c]=a;if(s===0&&e>=c)return[];if(l<=e&&e<c){const u=s+1,h=new Array(u);for(let p=0;p<u;p++)h[p]=o[(i+p)%r][2];return h}}return ur}}class aV{constructor(e,n){I(this,"offset",0);I(this,"maybeRemoved");this.below=e,this.child=n}}const st=Ei("capture",()=>({stack:null}));function ah(t){const e=st.stack;st.stack=null;try{return t()}finally{st.stack=e}}function nA(t){st.stack=new aV(st.stack,t),t.parentSet.clear()}function rA(){const t=st.stack;if(st.stack=t.below,t.offset<t.child.parents.length){for(let e=t.offset;e<t.child.parents.length;e++){const n=t.child.parents[e];t.child.parentSet.has(n)||yf(n,t.child)}t.child.parents.length=t.offset,t.child.parentEpochs.length=t.offset}if(t.maybeRemoved)for(let e=0;e<t.maybeRemoved.length;e++){const n=t.maybeRemoved[e];t.child.parentSet.has(n)||yf(n,t.child)}}function vf(t){if(st.stack){if(st.stack.child.parentSet.has(t))return;if(st.stack.child.parentSet.add(t),st.stack.child.isActivelyListening&&Yw(t,st.stack.child),st.stack.offset<st.stack.child.parents.length){const n=st.stack.child.parents[st.stack.offset];n!==t&&(st.stack.maybeRemoved?st.stack.maybeRemoved.push(n):st.stack.maybeRemoved=[n])}st.stack.child.parents[st.stack.offset]=t,st.stack.child.parentEpochs[st.stack.offset]=t.lastChangedEpoch,st.stack.offset++}}const Js=-1;class lV{constructor(e,n,r){I(this,"_isActivelyListening",!1);I(this,"lastTraversedEpoch",Js);I(this,"lastReactedEpoch",Js);I(this,"_scheduleCount",0);I(this,"parentSet",new Sf);I(this,"parentEpochs",[]);I(this,"parents",[]);I(this,"_scheduleEffect");I(this,"maybeExecute",()=>{this._isActivelyListening&&this.execute()});this.name=e,this.runEffect=n,this._scheduleEffect=r==null?void 0:r.scheduleEffect}get isActivelyListening(){return this._isActivelyListening}get scheduleCount(){return this._scheduleCount}maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==$n()){if(this.parents.length&&!JM(this)){this.lastReactedEpoch=$n();return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}attach(){this._isActivelyListening=!0;for(let e=0,n=this.parents.length;e<n;e++)Yw(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,n=this.parents.length;e<n;e++)yf(this.parents[e],this)}execute(){try{nA(this);const e=$n(),n=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=e,n}finally{rA()}}}const Ql=Ei("EffectScheduler",()=>lV);function jo(t,e,n){const r=new Ql(t,e,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}function cV(t,e,n){const r=new Ql(t,e,n);return{scheduler:r,start:o=>{const s=(o==null?void 0:o.force)??!1;r.attach(),s?r.scheduleEffect():r.maybeScheduleEffect()},stop:()=>{r.detach()}}}class uV{constructor(e){I(this,"initialAtomValues",new Map);this.parent=e}get isRoot(){return this.parent===null}commit(){if(Re.globalIsReacting)for(const e of this.initialAtomValues.keys())sA(e);else this.isRoot?oA(this.initialAtomValues.keys()):this.initialAtomValues.forEach((e,n)=>{this.parent.initialAtomValues.has(n)||this.parent.initialAtomValues.set(n,e)})}abort(){Re.globalEpoch++,this.initialAtomValues.forEach((e,n)=>{var r;n.set(e),(r=n.historyBuffer)==null||r.clear()}),this.commit()}}const Re=Ei("transactions",()=>({globalEpoch:Js+1,globalIsReacting:!1,currentTransaction:null,cleanupReactors:null,reactionEpoch:Js+1}));function dV(){return Re.reactionEpoch}function $n(){return Re.globalEpoch}function hV(){return Re.globalIsReacting}function Xw(t,e){e.lastTraversedEpoch!==Re.globalEpoch&&(e.lastTraversedEpoch=Re.globalEpoch,e instanceof Ql?t.add(e):e.children.visit(n=>Xw(t,n)))}function oA(t){var n;if(Re.globalIsReacting)throw new Error("flushChanges cannot be called during a reaction");const e=Re.currentTransaction;try{Re.currentTransaction=null,Re.globalIsReacting=!0,Re.reactionEpoch=Re.globalEpoch;const r=new Set;for(const s of t)s.children.visit(i=>Xw(r,i));for(const s of r)s.maybeScheduleEffect();let o=0;for(;(n=Re.cleanupReactors)!=null&&n.size;){if(o++>1e3)throw new Error("Reaction update depth limit exceeded");const s=Re.cleanupReactors;Re.cleanupReactors=null;for(const i of s)i.maybeScheduleEffect()}}finally{Re.cleanupReactors=null,Re.globalIsReacting=!1,Re.currentTransaction=e}}function pV(t,e){Re.currentTransaction?Re.currentTransaction.initialAtomValues.has(t)||Re.currentTransaction.initialAtomValues.set(t,e):Re.globalIsReacting?sA(t):oA([t])}function sA(t){const e=Re.cleanupReactors??(Re.cleanupReactors=new Set);t.children.visit(n=>Xw(e,n))}function fV(){Re.globalEpoch++}function gV(t){const e=new uV(Re.currentTransaction);Re.currentTransaction=e;try{let n,r=!1;try{n=t(()=>r=!0)}catch(o){throw e.abort(),o}return r?e.abort():e.commit(),n}finally{Re.currentTransaction=Re.currentTransaction.parent}}function Oo(t){return Re.currentTransaction?t():gV(t)}class mV{constructor(e,n,r){I(this,"isEqual");I(this,"computeDiff");I(this,"lastChangedEpoch",$n());I(this,"children",new Sf);I(this,"historyBuffer");this.name=e,this.current=n,this.isEqual=(r==null?void 0:r.isEqual)??null,r&&(r.historyLength&&(this.historyBuffer=new tA(r.historyLength)),this.computeDiff=r.computeDiff)}__unsafe__getWithoutCapture(e){return this.current}get(){return vf(this),this.current}set(e,n){var o,s;if(((o=this.isEqual)==null?void 0:o.call(this,this.current,e))??eA(this.current,e))return this.current;fV(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,$n(),n??((s=this.computeDiff)==null?void 0:s.call(this,this.current,e,this.lastChangedEpoch,$n()))??ur),this.lastChangedEpoch=$n();const r=this.current;return this.current=e,pV(this,r),e}update(e){return this.set(e(this.current))}getDiffSince(e){var n;return vf(this),e>=this.lastChangedEpoch?ps:((n=this.historyBuffer)==null?void 0:n.getChangesSince(e))??ur}}const yV=Ei("Atom",()=>mV);function Et(t,e,n){return new yV(t,e,n)}let R_=!1;function SV(){R_||(R_=!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.
70
70
 
@@ -79,13 +79,13 @@ get foo() {
79
79
  getFoo() {
80
80
  return 'foo'
81
81
  }
82
- `))}const Kc=Symbol.for("com.tldraw.state/UNINITIALIZED");function Zi(t){return t===Kc}const dx=Ei("WithDiff",()=>class{constructor(e,n){this.value=e,this.diff=n}});function Wc(t,e){return new dx(t,e)}class vV{constructor(e,n,r){I(this,"lastChangedEpoch",Js);I(this,"lastTraversedEpoch",Js);I(this,"lastCheckedEpoch",Js);I(this,"parentSet",new Sf);I(this,"parents",[]);I(this,"parentEpochs",[]);I(this,"children",new Sf);I(this,"historyBuffer");I(this,"state",Kc);I(this,"error",null);I(this,"computeDiff");I(this,"isEqual");this.name=e,this.derive=n,r!=null&&r.historyLength&&(this.historyBuffer=new tA(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??eA}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(e){var o;const n=this.lastChangedEpoch===Js,r=$n();if(!n&&(this.lastCheckedEpoch===r||this.isActivelyListening&&hV()&&this.lastTraversedEpoch<dV()||!JM(this)))if(this.lastCheckedEpoch=r,this.error){if(e)return this.state;throw this.error.thrownValue}else return this.state;try{nA(this);const s=this.derive(this.state,this.lastCheckedEpoch),i=s instanceof dx?s.value:s,a=this.state===Kc;if(a||!this.isEqual(i,this.state)){if(this.historyBuffer&&!a){const l=s instanceof dx?s.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,$n(),l??((o=this.computeDiff)==null?void 0:o.call(this,this.state,i,this.lastCheckedEpoch,$n()))??ur)}this.lastChangedEpoch=$n(),this.state=i}return this.error=null,this.lastCheckedEpoch=$n(),this.state}catch(s){if(this.state!==Kc&&(this.state=Kc,this.lastChangedEpoch=$n()),this.lastCheckedEpoch=$n(),this.historyBuffer&&this.historyBuffer.clear(),this.error={thrownValue:s},!e)throw s;return this.state}finally{rA()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{vf(this)}}getDiffSince(e){var n;return this.__unsafe__getWithoutCapture(!0),vf(this),e>=this.lastChangedEpoch?ps:((n=this.historyBuffer)==null?void 0:n.getChangesSince(e))??ur}}const kg=Ei("Computed",()=>vV);function xV(t={},e,n,r){const o=r.value,s=Symbol.for("__@tldraw/state__computed__"+n);return r.value=function(){let i=this[s];return i||(i=new kg(n,o.bind(this),t),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[iA]=!0,r}function wV(t={},e,n,r){const o=r.get,s=Symbol.for("__@tldraw/state__computed__"+n);return r.get=function(){let i=this[s];return i||(i=new kg(n,o.bind(this),t),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}function bV(t,e,n){Le(n.kind==="method","@computed can only be used on methods");const r=Symbol.for("__@tldraw/state__computed__"+String(n.name)),o=function(){let s=this[r];return s||(s=new kg(String(n.name),e.bind(this),t),Object.defineProperty(this,r,{enumerable:!1,configurable:!1,writable:!1,value:s})),s.get()};return o[iA]=!0,o}function L_(t={},e){if(e.length===2){const[n,r]=e;return bV(t,n,r)}else{const[n,r,o]=e;return o.get?(SV(),wV(t,n,r,o)):xV(t,n,r,o)}}const iA="@@__isComputedMethod__@@";function G(){if(arguments.length===1){const t=arguments[0];return(...e)=>L_(t,e)}else return typeof arguments[0]=="string"?new kg(arguments[0],arguments[1],arguments[2]):L_(void 0,arguments)}const aA=1,PV=Ei("apiVersion",()=>aA);if(PV!==aA)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");Ci("@tldraw/state","3.7.0-canary.383dfd14bf86","esm");function Tg(t,e,n=[]){const r=Te.useRef(e);r.current=e;const[o,s,i]=Te.useMemo(()=>{let a=null;const l=h=>(a=h,()=>{a=null}),c=new Ql(`useStateTracking(${t})`,()=>{var h;return(h=r.current)==null?void 0:h.call(r)},{scheduleEffect(){a==null||a()}});return[c,l,()=>c.scheduleCount]},[t,...n]);return Te.useSyncExternalStore(s,i,i),Te.useEffect(()=>(o.attach(),o.maybeScheduleEffect(),()=>{o.detach()}),[o]),o.execute()}const $_={apply(t,e,n){return Tg(t.displayName??t.name??"tracked(???)",()=>t.apply(e,n))}},CV=Symbol.for("react.memo"),_V=Symbol.for("react.forward_ref");function qt(t){let e=null;const n=t.$$typeof;return n===CV&&(t=t.type,e=t.compare),n===_V?w.memo(w.forwardRef(new Proxy(t.render,$_))):w.memo(new Proxy(t,$_),e)}function qw(t,e,n){return w.useState(()=>{const r=typeof e=="function"?e():e;return Et(`useAtom(${t})`,r,n)})[0]}function IV(){const t=arguments[0],e=arguments[1],n=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return w.useMemo(()=>G(`useComputed(${t})`,e,n),r)}function ci(t,e,n=ps){w.useEffect(()=>{const r=new Ql(t,e);return r.attach(),r.execute(),()=>{r.detach()}},n)}function U(){const t=arguments,e=t.length===3?t[2]:[t[0]],n=t.length===3?t[0]:`useValue(${t[0].name})`,r=w.useRef(!0);r.current=!0;const o=w.useMemo(()=>t.length===1?t[0]:G(n,()=>{if(r.current)return t[1]();try{return t[1]()}catch{return{}}}),e);try{const{subscribe:s,getSnapshot:i}=w.useMemo(()=>({subscribe:a=>jo(`useValue(${n})`,()=>{o.get(),a()}),getSnapshot:()=>o.get()}),[o]);return w.useSyncExternalStore(s,i,i)}finally{r.current=!1}}Ci("@tldraw/state-react","3.7.0-canary.383dfd14bf86","esm");const EV=(t,e)=>e.some(n=>t instanceof n);let F_,N_;function kV(){return F_||(F_=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function TV(){return N_||(N_=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const lA=new WeakMap,hx=new WeakMap,cA=new WeakMap,Ny=new WeakMap,Zw=new WeakMap;function MV(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(fs(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return e.then(n=>{n instanceof IDBCursor&&lA.set(n,t)}).catch(()=>{}),Zw.set(e,t),e}function AV(t){if(hx.has(t))return;const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{n(),o()},i=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});hx.set(t,e)}let px={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return hx.get(t);if(e==="objectStoreNames")return t.objectStoreNames||cA.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return fs(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function jV(t){px=t(px)}function OV(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const r=t.call(zy(this),e,...n);return cA.set(r,e.sort?e.sort():[e]),fs(r)}:TV().includes(t)?function(...e){return t.apply(zy(this),e),fs(lA.get(this))}:function(...e){return fs(t.apply(zy(this),e))}}function DV(t){return typeof t=="function"?OV(t):(t instanceof IDBTransaction&&AV(t),EV(t,kV())?new Proxy(t,px):t)}function fs(t){if(t instanceof IDBRequest)return MV(t);if(Ny.has(t))return Ny.get(t);const e=DV(t);return e!==t&&(Ny.set(t,e),Zw.set(e,t)),e}const zy=t=>Zw.get(t);function uA(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=fs(i);return r&&i.addEventListener("upgradeneeded",l=>{r(fs(i.result),l.oldVersion,l.newVersion,fs(i.transaction),l)}),n&&i.addEventListener("blocked",l=>n(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 dA(t,{blocked:e}={}){const n=indexedDB.deleteDatabase(t);return e&&n.addEventListener("blocked",r=>e(r.oldVersion,r)),fs(n).then(()=>{})}const RV=["get","getKey","getAll","getAllKeys","count"],LV=["put","add","delete","clear"],By=new Map;function z_(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(By.get(e))return By.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=LV.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||RV.includes(n)))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[n](...a),o&&l.done]))[0]};return By.set(e,s),s}jV(t=>({...t,get:(e,n,r)=>z_(e,n)||t.get(e,n,r),has:(e,n)=>!!z_(e,n)||t.has(e,n)}));const $V="TLDRAW_DOCUMENT_v2",FV="TLDRAW_ASSET_STORE_v1",hA="TLDRAW_DB_NAME_INDEX_v2",Ce={Records:"records",Schema:"schema",SessionState:"session_state",Assets:"assets"};async function pA(t){const e=$V+t;return zV(e),await uA(e,4,{upgrade(n){n.objectStoreNames.contains(Ce.Records)||n.createObjectStore(Ce.Records),n.objectStoreNames.contains(Ce.Schema)||n.createObjectStore(Ce.Schema),n.objectStoreNames.contains(Ce.SessionState)||n.createObjectStore(Ce.SessionState),n.objectStoreNames.contains(Ce.Assets)||n.createObjectStore(Ce.Assets)}})}async function NV(t){const e=window.indexedDB.databases?(await window.indexedDB.databases()).map(p=>p.name):Qw(),n=FV+t;if(!e.find(p=>p===n))return;const o=await uA(n,1,{upgrade(p){p.objectStoreNames.contains("assets")||p.createObjectStore("assets")}});if(!o.objectStoreNames.contains("assets"))return;const s=o.transaction(["assets"],"readonly"),i=s.objectStore("assets"),a=await i.getAllKeys(),l=await Promise.all(a.map(async p=>[p,await i.get(p)]));await s.done;const c=await pA(t),u=c.transaction([Ce.Assets],"readwrite"),h=u.objectStore(Ce.Assets);for(const[p,f]of l)h.put(f,p);await u.done,o.close(),c.close(),await dA(n)}const mu=class mu{constructor(e){I(this,"getDbPromise");I(this,"isClosed",!1);I(this,"pendingTransactionSet",new Set);mu.connectedInstances.add(this),this.getDbPromise=(async()=>(await NV(e),await pA(e)))()}getDb(){return this.getDbPromise}pending(){return Promise.allSettled([this.getDbPromise,...this.pendingTransactionSet]).then(Ru)}async close(){this.isClosed||(this.isClosed=!0,await this.pending(),(await this.getDb()).close(),mu.connectedInstances.delete(this))}tx(e,n,r){const o=(async()=>{Le(!this.isClosed,"db is closed");const i=(await this.getDb()).transaction(n,e),a=i.done.catch(l=>{if(!this.isClosed)throw l});try{return await r(i)}finally{this.isClosed?i.abort():await a}})();return this.pendingTransactionSet.add(o),o.finally(()=>this.pendingTransactionSet.delete(o)),o}async load({sessionId:e}={}){return await this.tx("readonly",[Ce.Records,Ce.Schema,Ce.SessionState],async n=>{var l,c;const r=n.objectStore(Ce.Records),o=n.objectStore(Ce.Schema),s=n.objectStore(Ce.SessionState);let i=e?(l=await s.get(e))==null?void 0:l.snapshot:null;return i||(i=(c=(await s.getAll()).sort((h,p)=>h.updatedAt-p.updatedAt).pop())==null?void 0:c.snapshot),{records:await r.getAll(),schema:await o.get(Ce.Schema),sessionStateSnapshot:i}})}async storeChanges({schema:e,changes:n,sessionId:r,sessionStateSnapshot:o}){await this.tx("readwrite",[Ce.Records,Ce.Schema,Ce.SessionState],async s=>{const i=s.objectStore(Ce.Records),a=s.objectStore(Ce.Schema),l=s.objectStore(Ce.SessionState);for(const[c,u]of Object.entries(n.added))await i.put(u,c);for(const[c,u]of Object.values(n.updated))await i.put(u,u.id);for(const c of Object.keys(n.removed))await i.delete(c);a.put(e.serialize(),Ce.Schema),o&&r?l.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async storeSnapshot({schema:e,snapshot:n,sessionId:r,sessionStateSnapshot:o}){await this.tx("readwrite",[Ce.Records,Ce.Schema,Ce.SessionState],async s=>{const i=s.objectStore(Ce.Records),a=s.objectStore(Ce.Schema),l=s.objectStore(Ce.SessionState);await i.clear();for(const[c,u]of Object.entries(n))await i.put(u,c);a.put(e.serialize(),Ce.Schema),o&&r?l.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async pruneSessions(){await this.tx("readwrite",[Ce.SessionState],async e=>{const n=e.objectStore(Ce.SessionState),r=(await n.getAll()).sort((s,i)=>s.updatedAt-i.updatedAt);if(r.length<10){await e.done;return}const o=r.slice(0,r.length-10);for(const{id:s}of o)await n.delete(s)})}async getAsset(e){return await this.tx("readonly",[Ce.Assets],async n=>await n.objectStore(Ce.Assets).get(e))}async storeAsset(e,n){await this.tx("readwrite",[Ce.Assets],async r=>{await r.objectStore(Ce.Assets).put(n,e)})}};I(mu,"connectedInstances",new Set);let xf=mu;function Qw(){const t=JSON.parse(_w(hA)||"[]")??[];return Array.isArray(t)?t:[]}function zV(t){const e=new Set(Qw());e.add(t),Iw(hA,JSON.stringify([...e]))}class sp{constructor(e){I(this,"nextValue");I(this,"diff");this.previousValue=e}get(){var r,o,s,i;const e=((o=(r=this.diff)==null?void 0:r.removed)==null?void 0:o.size)??0,n=((i=(s=this.diff)==null?void 0:s.added)==null?void 0:i.size)??0;if(!(e===0&&n===0))return{value:this.nextValue,diff:this.diff}}_add(e,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(e),this.diff??(this.diff={}),n?(r=this.diff.removed)==null||r.delete(e):((o=this.diff).added??(o.added=new Set),this.diff.added.add(e))}add(e){var o,s,i;const n=this.previousValue.has(e);if(n)return((s=(o=this.diff)==null?void 0:o.removed)==null?void 0:s.has(e))?this._add(e,n):void 0;(i=this.nextValue)!=null&&i.has(e)||this._add(e,n)}_remove(e,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(e),this.diff??(this.diff={}),n?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(e)):(o=this.diff.added)==null||o.delete(e)}remove(e){var o,s,i,a;const n=this.previousValue.has(e);if(!n)return((s=(o=this.diff)==null?void 0:o.added)==null?void 0:s.has(e))?this._remove(e,n):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(e)||this._remove(e,n)}}class Mg{constructor(e,n){I(this,"createDefaultProperties");I(this,"validator");I(this,"ephemeralKeys");I(this,"ephemeralKeySet");I(this,"scope");this.typeName=e,this.createDefaultProperties=n.createDefaultProperties,this.validator=n.validator??{validate:o=>o},this.scope=n.scope??"document",this.ephemeralKeys=n.ephemeralKeys;const r=new Set;if(n.ephemeralKeys)for(const[o,s]of Xn(n.ephemeralKeys))s&&r.add(o);this.ephemeralKeySet=r}create(e){const n={...this.createDefaultProperties(),id:this.createId()};for(const[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n.typeName=this.typeName,n}clone(e){return{...tt(e),id:this.createId()}}createId(e){return this.typeName+":"+(e??ze())}createCustomId(e){return this.typeName+":"+e}parseId(e){if(!this.isId(e))throw new Error(`ID "${e}" is not a valid ID for type "${this.typeName}"`);return e.slice(this.typeName.length+1)}isInstance(e){return(e==null?void 0:e.typeName)===this.typeName}isId(e){if(!e)return!1;for(let n=0;n<this.typeName.length;n++)if(e[n]!==this.typeName[n])return!1;return e[this.typeName.length]===":"}withDefaultProperties(e){return new Mg(this.typeName,{createDefaultProperties:e,validator:this.validator,scope:this.scope,ephemeralKeys:this.ephemeralKeys})}validate(e,n){return n&&this.validator.validateUsingKnownGoodVersion?this.validator.validateUsingKnownGoodVersion(n,e):this.validator.validate(e)}}function Ko(t,e){return new Mg(t,{createDefaultProperties:()=>({}),validator:e.validator,scope:e.scope,ephemeralKeys:e.ephemeralKeys})}function wf(){return{added:{},updated:{},removed:{}}}function fx(t){const e={added:t.removed,removed:t.added,updated:{}};for(const[n,r]of Object.values(t.updated))e.updated[n.id]=[r,n];return e}function fA(t){return Object.keys(t.added).length===0&&Object.keys(t.updated).length===0&&Object.keys(t.removed).length===0}function Jw(t){const e={added:{},removed:{},updated:{}};return cu(e,t),e}function cu(t,e){for(const n of e){for(const[r,o]of Xn(n.added))if(t.removed[r]){const s=t.removed[r];delete t.removed[r],s!==o&&(t.updated[r]=[s,o])}else t.added[r]=o;for(const[r,[o,s]]of Xn(n.updated)){if(t.added[r]){t.added[r]=s,delete t.updated[r],delete t.removed[r];continue}if(t.updated[r]){t.updated[r]=[t.updated[r][0],s],delete t.removed[r];continue}t.updated[r]=n.updated[r],delete t.removed[r]}for(const[r,o]of Xn(n.removed))t.added[r]?delete t.added[r]:t.updated[r]?(t.removed[r]=t.updated[r][0],delete t.updated[r]):t.removed[r]=o}}var bf={exports:{}};bf.exports;(function(t,e){var n=200,r="__lodash_hash_undefined__",o=1,s=2,i=9007199254740991,a="[object Arguments]",l="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",h="[object Date]",p="[object Error]",f="[object Function]",g="[object GeneratorFunction]",m="[object Map]",v="[object Number]",y="[object Null]",S="[object Object]",b="[object Promise]",P="[object Proxy]",C="[object RegExp]",_="[object Set]",E="[object String]",k="[object Symbol]",D="[object Undefined]",T="[object WeakMap]",j="[object ArrayBuffer]",$="[object DataView]",M="[object Float32Array]",O="[object Float64Array]",F="[object Int8Array]",B="[object Int16Array]",K="[object Int32Array]",R="[object Uint8Array]",H="[object Uint8ClampedArray]",Y="[object Uint16Array]",ee="[object Uint32Array]",he=/[\\^$.*+?()[\]{}|]/g,ue=/^\[object .+?Constructor\]$/,ke=/^(?:0|[1-9]\d*)$/,se={};se[M]=se[O]=se[F]=se[B]=se[K]=se[R]=se[H]=se[Y]=se[ee]=!0,se[a]=se[l]=se[j]=se[u]=se[$]=se[h]=se[p]=se[f]=se[m]=se[v]=se[S]=se[C]=se[_]=se[E]=se[T]=!1;var We=typeof dn=="object"&&dn&&dn.Object===Object&&dn,Fe=typeof self=="object"&&self&&self.Object===Object&&self,ot=We||Fe||Function("return this")(),$e=e&&!e.nodeType&&e,lt=$e&&!0&&t&&!t.nodeType&&t,Ue=lt&&lt.exports===$e,er=Ue&&We.process,$t=function(){try{return er&&er.binding&&er.binding("util")}catch{}}(),On=$t&&$t.isTypedArray;function vt(A,L){for(var V=-1,ne=A==null?0:A.length,Qe=0,Se=[];++V<ne;){var mt=A[V];L(mt,V,A)&&(Se[Qe++]=mt)}return Se}function Jt(A,L){for(var V=-1,ne=L.length,Qe=A.length;++V<ne;)A[Qe+V]=L[V];return A}function Xo(A,L){for(var V=-1,ne=A==null?0:A.length;++V<ne;)if(L(A[V],V,A))return!0;return!1}function cc(A,L){for(var V=-1,ne=Array(A);++V<A;)ne[V]=L(V);return ne}function js(A){return function(L){return A(L)}}function A4(A,L){return A.has(L)}function j4(A,L){return A==null?void 0:A[L]}function O4(A){var L=-1,V=Array(A.size);return A.forEach(function(ne,Qe){V[++L]=[Qe,ne]}),V}function D4(A,L){return function(V){return A(L(V))}}function R4(A){var L=-1,V=Array(A.size);return A.forEach(function(ne){V[++L]=ne}),V}var L4=Array.prototype,$4=Function.prototype,Ad=Object.prototype,Mm=ot["__core-js_shared__"],Jb=$4.toString,go=Ad.hasOwnProperty,eP=function(){var A=/[^.]+$/.exec(Mm&&Mm.keys&&Mm.keys.IE_PROTO||"");return A?"Symbol(src)_1."+A:""}(),tP=Ad.toString,F4=RegExp("^"+Jb.call(go).replace(he,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),nP=Ue?ot.Buffer:void 0,jd=ot.Symbol,rP=ot.Uint8Array,oP=Ad.propertyIsEnumerable,N4=L4.splice,Ri=jd?jd.toStringTag:void 0,sP=Object.getOwnPropertySymbols,z4=nP?nP.isBuffer:void 0,B4=D4(Object.keys,Object),Am=ka(ot,"DataView"),uc=ka(ot,"Map"),jm=ka(ot,"Promise"),Om=ka(ot,"Set"),Dm=ka(ot,"WeakMap"),dc=ka(Object,"create"),U4=Fi(Am),H4=Fi(uc),K4=Fi(jm),W4=Fi(Om),G4=Fi(Dm),iP=jd?jd.prototype:void 0,Rm=iP?iP.valueOf:void 0;function Li(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function V4(){this.__data__=dc?dc(null):{},this.size=0}function Y4(A){var L=this.has(A)&&delete this.__data__[A];return this.size-=L?1:0,L}function X4(A){var L=this.__data__;if(dc){var V=L[A];return V===r?void 0:V}return go.call(L,A)?L[A]:void 0}function q4(A){var L=this.__data__;return dc?L[A]!==void 0:go.call(L,A)}function Z4(A,L){var V=this.__data__;return this.size+=this.has(A)?0:1,V[A]=dc&&L===void 0?r:L,this}Li.prototype.clear=V4,Li.prototype.delete=Y4,Li.prototype.get=X4,Li.prototype.has=q4,Li.prototype.set=Z4;function qo(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function Q4(){this.__data__=[],this.size=0}function J4(A){var L=this.__data__,V=Dd(L,A);if(V<0)return!1;var ne=L.length-1;return V==ne?L.pop():N4.call(L,V,1),--this.size,!0}function eN(A){var L=this.__data__,V=Dd(L,A);return V<0?void 0:L[V][1]}function tN(A){return Dd(this.__data__,A)>-1}function nN(A,L){var V=this.__data__,ne=Dd(V,A);return ne<0?(++this.size,V.push([A,L])):V[ne][1]=L,this}qo.prototype.clear=Q4,qo.prototype.delete=J4,qo.prototype.get=eN,qo.prototype.has=tN,qo.prototype.set=nN;function $i(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function rN(){this.size=0,this.__data__={hash:new Li,map:new(uc||qo),string:new Li}}function oN(A){var L=Rd(this,A).delete(A);return this.size-=L?1:0,L}function sN(A){return Rd(this,A).get(A)}function iN(A){return Rd(this,A).has(A)}function aN(A,L){var V=Rd(this,A),ne=V.size;return V.set(A,L),this.size+=V.size==ne?0:1,this}$i.prototype.clear=rN,$i.prototype.delete=oN,$i.prototype.get=sN,$i.prototype.has=iN,$i.prototype.set=aN;function Od(A){var L=-1,V=A==null?0:A.length;for(this.__data__=new $i;++L<V;)this.add(A[L])}function lN(A){return this.__data__.set(A,r),this}function cN(A){return this.__data__.has(A)}Od.prototype.add=Od.prototype.push=lN,Od.prototype.has=cN;function Os(A){var L=this.__data__=new qo(A);this.size=L.size}function uN(){this.__data__=new qo,this.size=0}function dN(A){var L=this.__data__,V=L.delete(A);return this.size=L.size,V}function hN(A){return this.__data__.get(A)}function pN(A){return this.__data__.has(A)}function fN(A,L){var V=this.__data__;if(V instanceof qo){var ne=V.__data__;if(!uc||ne.length<n-1)return ne.push([A,L]),this.size=++V.size,this;V=this.__data__=new $i(ne)}return V.set(A,L),this.size=V.size,this}Os.prototype.clear=uN,Os.prototype.delete=dN,Os.prototype.get=hN,Os.prototype.has=pN,Os.prototype.set=fN;function gN(A,L){var V=Ld(A),ne=!V&&MN(A),Qe=!V&&!ne&&Lm(A),Se=!V&&!ne&&!Qe&&gP(A),mt=V||ne||Qe||Se,At=mt?cc(A.length,String):[],Ft=At.length;for(var ct in A)go.call(A,ct)&&!(mt&&(ct=="length"||Qe&&(ct=="offset"||ct=="parent")||Se&&(ct=="buffer"||ct=="byteLength"||ct=="byteOffset")||_N(ct,Ft)))&&At.push(ct);return At}function Dd(A,L){for(var V=A.length;V--;)if(dP(A[V][0],L))return V;return-1}function mN(A,L,V){var ne=L(A);return Ld(A)?ne:Jt(ne,V(A))}function hc(A){return A==null?A===void 0?D:y:Ri&&Ri in Object(A)?PN(A):TN(A)}function aP(A){return pc(A)&&hc(A)==a}function lP(A,L,V,ne,Qe){return A===L?!0:A==null||L==null||!pc(A)&&!pc(L)?A!==A&&L!==L:yN(A,L,V,ne,lP,Qe)}function yN(A,L,V,ne,Qe,Se){var mt=Ld(A),At=Ld(L),Ft=mt?l:Ds(A),ct=At?l:Ds(L);Ft=Ft==a?S:Ft,ct=ct==a?S:ct;var tr=Ft==S,Ur=ct==S,en=Ft==ct;if(en&&Lm(A)){if(!Lm(L))return!1;mt=!0,tr=!1}if(en&&!tr)return Se||(Se=new Os),mt||gP(A)?cP(A,L,V,ne,Qe,Se):wN(A,L,Ft,V,ne,Qe,Se);if(!(V&o)){var Pr=tr&&go.call(A,"__wrapped__"),Cr=Ur&&go.call(L,"__wrapped__");if(Pr||Cr){var Rs=Pr?A.value():A,Zo=Cr?L.value():L;return Se||(Se=new Os),Qe(Rs,Zo,V,ne,Se)}}return en?(Se||(Se=new Os),bN(A,L,V,ne,Qe,Se)):!1}function SN(A){if(!fP(A)||EN(A))return!1;var L=hP(A)?F4:ue;return L.test(Fi(A))}function vN(A){return pc(A)&&pP(A.length)&&!!se[hc(A)]}function xN(A){if(!kN(A))return B4(A);var L=[];for(var V in Object(A))go.call(A,V)&&V!="constructor"&&L.push(V);return L}function cP(A,L,V,ne,Qe,Se){var mt=V&o,At=A.length,Ft=L.length;if(At!=Ft&&!(mt&&Ft>At))return!1;var ct=Se.get(A);if(ct&&Se.get(L))return ct==L;var tr=-1,Ur=!0,en=V&s?new Od:void 0;for(Se.set(A,L),Se.set(L,A);++tr<At;){var Pr=A[tr],Cr=L[tr];if(ne)var Rs=mt?ne(Cr,Pr,tr,L,A,Se):ne(Pr,Cr,tr,A,L,Se);if(Rs!==void 0){if(Rs)continue;Ur=!1;break}if(en){if(!Xo(L,function(Zo,Ni){if(!A4(en,Ni)&&(Pr===Zo||Qe(Pr,Zo,V,ne,Se)))return en.push(Ni)})){Ur=!1;break}}else if(!(Pr===Cr||Qe(Pr,Cr,V,ne,Se))){Ur=!1;break}}return Se.delete(A),Se.delete(L),Ur}function wN(A,L,V,ne,Qe,Se,mt){switch(V){case $:if(A.byteLength!=L.byteLength||A.byteOffset!=L.byteOffset)return!1;A=A.buffer,L=L.buffer;case j:return!(A.byteLength!=L.byteLength||!Se(new rP(A),new rP(L)));case u:case h:case v:return dP(+A,+L);case p:return A.name==L.name&&A.message==L.message;case C:case E:return A==L+"";case m:var At=O4;case _:var Ft=ne&o;if(At||(At=R4),A.size!=L.size&&!Ft)return!1;var ct=mt.get(A);if(ct)return ct==L;ne|=s,mt.set(A,L);var tr=cP(At(A),At(L),ne,Qe,Se,mt);return mt.delete(A),tr;case k:if(Rm)return Rm.call(A)==Rm.call(L)}return!1}function bN(A,L,V,ne,Qe,Se){var mt=V&o,At=uP(A),Ft=At.length,ct=uP(L),tr=ct.length;if(Ft!=tr&&!mt)return!1;for(var Ur=Ft;Ur--;){var en=At[Ur];if(!(mt?en in L:go.call(L,en)))return!1}var Pr=Se.get(A);if(Pr&&Se.get(L))return Pr==L;var Cr=!0;Se.set(A,L),Se.set(L,A);for(var Rs=mt;++Ur<Ft;){en=At[Ur];var Zo=A[en],Ni=L[en];if(ne)var mP=mt?ne(Ni,Zo,en,L,A,Se):ne(Zo,Ni,en,A,L,Se);if(!(mP===void 0?Zo===Ni||Qe(Zo,Ni,V,ne,Se):mP)){Cr=!1;break}Rs||(Rs=en=="constructor")}if(Cr&&!Rs){var $d=A.constructor,Fd=L.constructor;$d!=Fd&&"constructor"in A&&"constructor"in L&&!(typeof $d=="function"&&$d instanceof $d&&typeof Fd=="function"&&Fd instanceof Fd)&&(Cr=!1)}return Se.delete(A),Se.delete(L),Cr}function uP(A){return mN(A,ON,CN)}function Rd(A,L){var V=A.__data__;return IN(L)?V[typeof L=="string"?"string":"hash"]:V.map}function ka(A,L){var V=j4(A,L);return SN(V)?V:void 0}function PN(A){var L=go.call(A,Ri),V=A[Ri];try{A[Ri]=void 0;var ne=!0}catch{}var Qe=tP.call(A);return ne&&(L?A[Ri]=V:delete A[Ri]),Qe}var CN=sP?function(A){return A==null?[]:(A=Object(A),vt(sP(A),function(L){return oP.call(A,L)}))}:DN,Ds=hc;(Am&&Ds(new Am(new ArrayBuffer(1)))!=$||uc&&Ds(new uc)!=m||jm&&Ds(jm.resolve())!=b||Om&&Ds(new Om)!=_||Dm&&Ds(new Dm)!=T)&&(Ds=function(A){var L=hc(A),V=L==S?A.constructor:void 0,ne=V?Fi(V):"";if(ne)switch(ne){case U4:return $;case H4:return m;case K4:return b;case W4:return _;case G4:return T}return L});function _N(A,L){return L=L??i,!!L&&(typeof A=="number"||ke.test(A))&&A>-1&&A%1==0&&A<L}function IN(A){var L=typeof A;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?A!=="__proto__":A===null}function EN(A){return!!eP&&eP in A}function kN(A){var L=A&&A.constructor,V=typeof L=="function"&&L.prototype||Ad;return A===V}function TN(A){return tP.call(A)}function Fi(A){if(A!=null){try{return Jb.call(A)}catch{}try{return A+""}catch{}}return""}function dP(A,L){return A===L||A!==A&&L!==L}var MN=aP(function(){return arguments}())?aP:function(A){return pc(A)&&go.call(A,"callee")&&!oP.call(A,"callee")},Ld=Array.isArray;function AN(A){return A!=null&&pP(A.length)&&!hP(A)}var Lm=z4||RN;function jN(A,L){return lP(A,L)}function hP(A){if(!fP(A))return!1;var L=hc(A);return L==f||L==g||L==c||L==P}function pP(A){return typeof A=="number"&&A>-1&&A%1==0&&A<=i}function fP(A){var L=typeof A;return A!=null&&(L=="object"||L=="function")}function pc(A){return A!=null&&typeof A=="object"}var gP=On?js(On):vN;function ON(A){return AN(A)?gN(A):xN(A)}function DN(){return[]}function RN(){return!1}t.exports=jN})(bf,bf.exports);var BV=bf.exports;const gA=xi(BV);function UV(t){if(t.length===0)return new Set;const e=t[0],n=t.slice(1),r=new Set;for(const o of e)n.every(s=>s.has(o))&&r.add(o);return r}function HV(t,e){const n={};for(const r of e)t.has(r)||(n.added??(n.added=new Set),n.added.add(r));for(const r of t)e.has(r)||(n.removed??(n.removed=new Set),n.removed.add(r));return n.added||n.removed?n:void 0}function B_(t,e){for(const[n,r]of Object.entries(t)){const o=r,s=e[n];if("eq"in o&&s!==o.eq||"neq"in o&&s===o.neq||"gt"in o&&(typeof s!="number"||s<=o.gt))return!1}return!0}function U_(t,e,n){const r=Object.fromEntries(Object.keys(n).map(o=>[o,new Set]));for(const[o,s]of Object.entries(n))if("eq"in s){const a=t.index(e,o).get().get(s.eq);if(a)for(const l of a)r[o].add(l)}else if("neq"in s){const i=t.index(e,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=t.index(e,o);for(const[a,l]of i.get())if(a>s.gt)for(const c of l)r[o].add(c)}return UV(Object.values(r))}class KV{constructor(e,n){I(this,"indexCache",new Map);I(this,"historyCache",new Map);this.atoms=e,this.history=n}filterHistory(e){if(this.historyCache.has(e))return this.historyCache.get(e);const n=G("filterHistory:"+e,(r,o)=>{if(Zi(r))return this.history.get();const s=this.history.getDiffSince(o);if(s===ur)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const u of s){for(const h of ut(u.added))if(h.typeName===e)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 ut(u.updated))p.typeName===e&&(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 ut(u.removed))h.typeName===e&&(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?Wc(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(e,n),n}index(e,n){const r=e+":"+n;if(this.indexCache.has(r))return this.indexCache.get(r);const o=this.__uncached_createIndex(e,n);return this.indexCache.set(r,o),o}__uncached_createIndex(e,n){const r=this.filterHistory(e),o=()=>{r.get();const s=new Map;for(const i of ut(this.atoms.get())){const a=i.get();if(a.typeName===e){const l=a[n];s.has(l)||s.set(l,new Set),s.get(l).add(a.id)}}return s};return G("index:"+e+":"+n,(s,i)=>{if(Zi(s))return o();const a=r.getDiffSince(i);if(a===ur)return o();const l=new Map,c=(f,g)=>{let m=l.get(f);m||(m=new sp(s.get(f)??new Set)),m.add(g),l.set(f,m)},u=(f,g)=>{let m=l.get(f);m||(m=new sp(s.get(f)??new Set)),m.remove(g),l.set(f,m)};for(const f of a){for(const g of ut(f.added))if(g.typeName===e){const m=g[n];c(m,g.id)}for(const[g,m]of ut(f.updated))if(m.typeName===e){const v=g[n],y=m[n];v!==y&&(u(v,m.id),c(y,m.id))}for(const g of ut(f.removed))if(g.typeName===e){const m=g[n];u(m,g.id)}}let h,p;for(const[f,g]of l){const m=g.get();m&&(h||(h=new Map(s)),p||(p=new Map),m.value.size===0?h.delete(f):h.set(f,m.value),p.set(f,m.diff))}return h&&p?Wc(h,p):s},{historyLength:100})}record(e,n=()=>({}),r="record:"+e+(n?":"+n.toString():"")){const o=this.ids(e,n,r);return G(r,()=>{var s;for(const i of o.get())return(s=this.atoms.get()[i])==null?void 0:s.get()})}records(e,n=()=>({}),r="records:"+e+(n?":"+n.toString():"")){const o=this.ids(e,n,"ids:"+r);return G(r,()=>{const s=this.atoms.get();return[...o.get()].map(i=>{const a=s[i];if(!a)throw new Error("no atom found for record id: "+i);return a.get()})},{isEqual:RT})}ids(e,n=()=>({}),r="ids:"+e+(n?":"+n.toString():"")){const o=this.filterHistory(e),s=()=>{o.get();const l=n();return Object.keys(l).length===0?new Set(ut(this.atoms.get()).flatMap(c=>{const u=c.get();return u.typeName===e?u.id:[]})):U_(this,e,l)},i=l=>{const c=s(),u=HV(l,c);return u?Wc(c,u):l},a=G("ids_query:"+r,n,{isEqual:gA});return G("query:"+r,(l,c)=>{const u=a.get();if(Zi(l))return s();if(c<a.lastChangedEpoch)return i(l);const h=o.getDiffSince(c);if(h===ur)return i(l);const p=new sp(l);for(const g of h){for(const m of ut(g.added))m.typeName===e&&B_(u,m)&&p.add(m.id);for(const[m,v]of ut(g.updated))v.typeName===e&&(B_(u,v)?p.add(v.id):p.remove(v.id));for(const m of ut(g.removed))m.typeName===e&&p.remove(m.id)}const f=p.get();return f?Wc(f.value,f.diff):l},{historyLength:50})}exec(e,n){const r=U_(this,e,n);if(r.size===0)return ps;const o=this.atoms.get();return[...r].map(s=>o[s].get())}}class WV{constructor(e){I(this,"_beforeCreateHandlers",{});I(this,"_afterCreateHandlers",{});I(this,"_beforeChangeHandlers",{});I(this,"_afterChangeHandlers",{});I(this,"_beforeDeleteHandlers",{});I(this,"_afterDeleteHandlers",{});I(this,"_operationCompleteHandlers",[]);I(this,"_isEnabled",!0);this.store=e}isEnabled(){return this._isEnabled}setIsEnabled(e){this._isEnabled=e}handleBeforeCreate(e,n){if(!this._isEnabled)return e;const r=this._beforeCreateHandlers[e.typeName];if(r){let o=e;for(const s of r)o=s(o,n);return o}return e}handleAfterCreate(e,n){if(!this._isEnabled)return;const r=this._afterCreateHandlers[e.typeName];if(r)for(const o of r)o(e,n)}handleBeforeChange(e,n,r){if(!this._isEnabled)return n;const o=this._beforeChangeHandlers[n.typeName];if(o){let s=n;for(const i of o)s=i(e,s,r);return s}return n}handleAfterChange(e,n,r){if(!this._isEnabled)return;const o=this._afterChangeHandlers[n.typeName];if(o)for(const s of o)s(e,n,r)}handleBeforeDelete(e,n){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[e.typeName];if(r){for(const o of r)if(o(e,n)===!1)return!1}return!0}handleAfterDelete(e,n){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[e.typeName];if(r)for(const o of r)o(e,n)}handleOperationComplete(e){if(this._isEnabled)for(const n of this._operationCompleteHandlers)n(e)}register(e){const n=[];for(const[r,o]of Object.entries(e))o!=null&&o.beforeCreate&&n.push(this.registerBeforeCreateHandler(r,o.beforeCreate)),o!=null&&o.afterCreate&&n.push(this.registerAfterCreateHandler(r,o.afterCreate)),o!=null&&o.beforeChange&&n.push(this.registerBeforeChangeHandler(r,o.beforeChange)),o!=null&&o.afterChange&&n.push(this.registerAfterChangeHandler(r,o.afterChange)),o!=null&&o.beforeDelete&&n.push(this.registerBeforeDeleteHandler(r,o.beforeDelete)),o!=null&&o.afterDelete&&n.push(this.registerAfterDeleteHandler(r,o.afterDelete));return()=>{for(const r of n)r()}}registerBeforeCreateHandler(e,n){return this._beforeCreateHandlers[e]||(this._beforeCreateHandlers[e]=[]),this._beforeCreateHandlers[e].push(n),()=>zi(this._beforeCreateHandlers[e],n)}registerAfterCreateHandler(e,n){return this._afterCreateHandlers[e]||(this._afterCreateHandlers[e]=[]),this._afterCreateHandlers[e].push(n),()=>zi(this._afterCreateHandlers[e],n)}registerBeforeChangeHandler(e,n){return this._beforeChangeHandlers[e]||(this._beforeChangeHandlers[e]=[]),this._beforeChangeHandlers[e].push(n),()=>zi(this._beforeChangeHandlers[e],n)}registerAfterChangeHandler(e,n){return this._afterChangeHandlers[e]||(this._afterChangeHandlers[e]=[]),this._afterChangeHandlers[e].push(n),()=>zi(this._afterChangeHandlers[e],n)}registerBeforeDeleteHandler(e,n){return this._beforeDeleteHandlers[e]||(this._beforeDeleteHandlers[e]=[]),this._beforeDeleteHandlers[e].push(n),()=>zi(this._beforeDeleteHandlers[e],n)}registerAfterDeleteHandler(e,n){return this._afterDeleteHandlers[e]||(this._afterDeleteHandlers[e]=[]),this._afterDeleteHandlers[e].push(n),()=>zi(this._afterDeleteHandlers[e],n)}registerOperationCompleteHandler(e){return this._operationCompleteHandlers.push(e),()=>zi(this._operationCompleteHandlers,e)}}function zi(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}class e1{constructor(e){I(this,"id");I(this,"atoms",Et("store_atoms",{}));I(this,"history",Et("history",0,{historyLength:1e3}));I(this,"query",new KV(this.atoms,this.history));I(this,"listeners",new Set);I(this,"historyAccumulator",new VV);I(this,"historyReactor");I(this,"schema");I(this,"props");I(this,"scopedTypes");I(this,"sideEffects",new WV(this));I(this,"isMergingRemoteChanges",!1);I(this,"_integrityChecker");I(this,"_isPossiblyCorrupted",!1);I(this,"pendingAfterEvents",null);I(this,"_isInAtomicOp",!1);const{initialData:n,schema:r,id:o}=e;this.id=o??ze(),this.schema=r,this.props=e.props,n&&this.atoms.set(ww(Xn(n).map(([s,i])=>[s,Et("atom:"+s,this.schema.validateRecord(this,i,"initialize",null))]))),this.historyReactor=cV("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:s=>this.cancelHistoryReactor=tM(s)}),this.scopedTypes={document:new Set(ut(this.schema.types).filter(s=>s.scope==="document").map(s=>s.typeName)),session:new Set(ut(this.schema.types).filter(s=>s.scope==="session").map(s=>s.typeName)),presence:new Set(ut(this.schema.types).filter(s=>s.scope==="presence").map(s=>s.typeName))}}cancelHistoryReactor(){}_flushHistory(){if(this.historyAccumulator.hasChanges()){const e=this.historyAccumulator.flush();for(const{changes:n,source:r}of e){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(n,"document")),!s)continue;a({changes:s,source:r})}else if(l.scope==="session"){if(o??(o=this.filterChangesByScope(n,"session")),!o)continue;a({changes:o,source:r})}else{if(i??(i=this.filterChangesByScope(n,"presence")),!i)continue;a({changes:i,source:r})}else a({changes:n,source:r})}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(e,n){const r={added:lu(e.added,(o,s)=>this.scopedTypes[n].has(s.typeName)),updated:lu(e.updated,(o,s)=>this.scopedTypes[n].has(s[1].typeName)),removed:lu(e.removed,(o,s)=>this.scopedTypes[n].has(s.typeName))};return Object.keys(r.added).length===0&&Object.keys(r.updated).length===0&&Object.keys(r.removed).length===0?null:r}updateHistory(e){this.historyAccumulator.add({changes:e,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,e)}validate(e){this.allRecords().forEach(n=>this.schema.validateRecord(this,n,e,null))}put(e,n){this.atomic(()=>{const r={},o={},s=this.atoms.__unsafe__getWithoutCapture();let i=null,a,l=!1;const c=this.isMergingRemoteChanges?"remote":"user";for(let u=0,h=e.length;u<h;u++){a=e[u];const p=(i??s)[a.id];if(p){const f=p.__unsafe__getWithoutCapture();if(a=this.sideEffects.handleBeforeChange(f,a,c),this.schema.validateRecord(this,a,n??"updateRecord",f)===f)continue;p.set(a),l=!0;const m=p.__unsafe__getWithoutCapture();r[a.id]=[f,m],this.addDiffForAfterEvent(f,m)}else a=this.sideEffects.handleBeforeCreate(a,c),l=!0,a=this.schema.validateRecord(this,a,n??"createRecord",null),o[a.id]=a,this.addDiffForAfterEvent(null,a),i||(i={...s}),i[a.id]=Et("atom:"+a.id,a)}i&&this.atoms.set(i),l&&this.updateHistory({added:o,updated:r,removed:{}})})}remove(e){this.atomic(()=>{const n=new Set,r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const s of e){const i=this.atoms.__unsafe__getWithoutCapture()[s];i&&this.sideEffects.handleBeforeDelete(i.get(),r)===!1&&n.add(s)}let o;this.atoms.update(s=>{let i;for(const a of e){if(n.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})})}get(e){var n;return(n=this.atoms.get()[e])==null?void 0:n.get()}unsafeGetWithoutCapture(e){var n;return(n=this.atoms.__unsafe__getWithoutCapture()[e])==null?void 0:n.__unsafe__getWithoutCapture()}serialize(e="document"){const n={};for(const[r,o]of Xn(this.atoms.get())){const s=o.get();(e==="all"||this.scopedTypes[e].has(s.typeName))&&(n[r]=s)}return n}getStoreSnapshot(e="document"){return{store:this.serialize(e),schema:this.schema.serialize()}}getSnapshot(e="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(e)}migrateSnapshot(e){const n=this.schema.migrateStoreSnapshot(e);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);return{store:n.value,schema:this.schema.serialize()}}loadStoreSnapshot(e){const n=this.schema.migrateStoreSnapshot(e);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);const r=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(n.value)),this.ensureStoreIsUsable()})}finally{this.sideEffects.setIsEnabled(r)}}loadSnapshot(e){console.warn("[tldraw] `Store.loadSnapshot` is deprecated and will be removed in a future release. Use `loadSnapshot` from the 'tldraw' package instead."),this.loadStoreSnapshot(e)}allRecords(){return ut(this.atoms.get()).map(e=>e.get())}clear(){this.remove($C(this.atoms.get()))}update(e,n){const r=this.atoms.get()[e];if(!r){console.error(`Record ${e} not found. This is probably an error`);return}this.put([n(r.__unsafe__getWithoutCapture())])}has(e){return!!this.atoms.get()[e]}listen(e,n){this._flushHistory();const r={onHistory:e,filters:{source:(n==null?void 0:n.source)??"all",scope:(n==null?void 0:n.scope)??"all"}};return this.historyReactor.scheduler.isActivelyListening||(this.historyReactor.start(),this.historyReactor.scheduler.execute()),this.listeners.add(r),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}}mergeRemoteChanges(e){if(this.isMergingRemoteChanges)return e();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.isMergingRemoteChanges=!0,Oo(e)}finally{this.isMergingRemoteChanges=!1,this.ensureStoreIsUsable()}}extractingChanges(e){const n=[],r=this.historyAccumulator.addInterceptor(o=>n.push(o.changes));try{return Oo(e),Jw(n)}finally{r()}}applyDiff(e,{runCallbacks:n=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const o=ut(e.added);for(const[i,a]of ut(e.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 u=null;for(const[h,p]of Object.entries(a))l.ephemeralKeySet.has(h)||Object.is(p,hn(c,h))||(u||(u={...c}),u[h]=p);u&&o.push(u)}else o.push(a)}const s=$C(e.removed);o.length&&this.put(o),s.length&&this.remove(s)},n)}createComputedCache(e,n,r){const o=new Ro;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=r?G(i.name+":equals",()=>i.get(),{isEqual:r}):i;return G(e+":"+s,()=>n(a.get()))}).get()}}}createSelectedComputedCache(e,n,r){const o=new Ro;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=G(e+":"+s+":selector",()=>n(i.get()));return G(e+":"+s,()=>r(a.get()))}).get()}}}ensureStoreIsUsable(){this.atomic(()=>{var e;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(e=this._integrityChecker)==null||e.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(e,n){if(Le(this.pendingAfterEvents,"must be in event operation"),e===n||(e&&n&&Le(e.id===n.id),!e&&!n))return;const r=(e||n).id,o=this.pendingAfterEvents.get(r);o?o.after=n:this.pendingAfterEvents.set(r,{before:e,after:n})}flushAtomicCallbacks(){let e=0;const n=this.isMergingRemoteChanges?"remote":"user";for(;this.pendingAfterEvents;){const r=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(e++,e>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,n):o&&!s?this.sideEffects.handleAfterDelete(o,n):!o&&s&&this.sideEffects.handleAfterCreate(s,n);this.pendingAfterEvents||this.sideEffects.handleOperationComplete(n)}}}atomic(e,n=!0){return Oo(()=>{if(this._isInAtomicOp)return this.pendingAfterEvents||(this.pendingAfterEvents=new Map),e();this.pendingAfterEvents=new Map;const r=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(n??r),this._isInAtomicOp=!0;try{const o=e();return this.flushAtomicCallbacks(),o}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(r),this._isInAtomicOp=!1}})}addHistoryInterceptor(e){return this.historyAccumulator.addInterceptor(n=>e(n,this.isMergingRemoteChanges?"remote":"user"))}}function GV(t){if(t.length===0)return[];const e=[];let n=[t[0]],r;for(let o=1,s=t.length;o<s;o++)r=t[o],n[0].source!==r.source&&(e.push(n),n=[]),n.push(r);return e.push(n),e.map(o=>({source:o[0].source,changes:Jw(o.map(s=>s.changes))}))}class VV{constructor(){I(this,"_history",[]);I(this,"_interceptors",new Set)}addInterceptor(e){return this._interceptors.add(e),()=>{this._interceptors.delete(e)}}add(e){this._history.push(e);for(const n of this._interceptors)n(e)}flush(){const e=GV(this._history);return this._history=[],e}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function YV(t,e,n){const r=new Ro;return{get(o,s){return r.get(o,()=>(o instanceof e1?o:o.store).createComputedCache(t,l=>e(o,l),n)).get(s)}}}function XV(t){const e=[];for(let n=t.length-1;n>=0;n--){const r=t[n];if("id"in r)e.unshift(r);else{const o=r.dependsOn,s=e[0];s&&(e[0]={...s,dependsOn:o.concat(s.dependsOn??[])})}}return e}function vl({sequence:t,sequenceId:e,retroactive:n=!0}){const r={sequenceId:e,retroactive:n,sequence:XV(t)};return mA(r),r}function Zn(t,e){return Object.fromEntries(Xn(e).map(([n,r])=>[n,`${t}/${r}`]))}function xr(t){const e=t.sequenceId;return vl({sequenceId:e,retroactive:t.retroactive??!0,sequence:t.sequence.map(n=>"id"in n?{...n,scope:"record",filter:r=>{var o,s;return r.typeName===t.recordType&&(((o=n.filter)==null?void 0:o.call(n,r))??!0)&&(((s=t.filter)==null?void 0:s.call(t,r))??!0)}}:n)})}function qV(t){const e=new Map(t.map(s=>[s.id,s])),n=new Set,r=[];function o(s){Le(!n.has(s.id),`Circular dependency in migrations: ${s.id}`),n.add(s.id);const{version:i,sequenceId:a}=Pf(s.id),l=e.get(`${a}/${i-1}`);if(l&&o(l),s.dependsOn)for(const c of s.dependsOn){const u=e.get(c);u&&o(u)}e.delete(s.id),r.push(s)}for(const s of e.values())o(s);return r}function Pf(t){const[e,n]=t.split("/");return{sequenceId:e,version:parseInt(n)}}function H_(t,e){e&&Le(t.startsWith(e+"/"),`Every migration in sequence '${e}' must have an id starting with '${e}/'. Got invalid id: '${t}'`),Le(t.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${t}'`)}function mA(t){if(Le(!t.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${t.sequenceId}`),Le(t.sequenceId.length,"sequenceId must be a non-empty string"),t.sequence.length===0)return;H_(t.sequence[0].id,t.sequenceId);let e=Pf(t.sequence[0].id).version;Le(e===1,`Expected the first migrationId to be '${t.sequenceId}/1' but got '${t.sequence[0].id}'`);for(let n=1;n<t.sequence.length;n++){const r=t.sequence[n].id;H_(r,t.sequenceId);const o=Pf(r).version;Le(o===e+1,`Migration id numbers must increase in increments of 1, expected ${t.sequenceId}/${e+1} but got '${t.sequence[n].id}'`),e=o}}var zs=(t=>(t.IncompatibleSubtype="incompatible-subtype",t.UnknownType="unknown-type",t.TargetVersionTooNew="target-version-too-new",t.TargetVersionTooOld="target-version-too-old",t.MigrationError="migration-error",t.UnrecognizedSubtype="unrecognized-subtype",t))(zs||{});function ZV(t){if(t.schemaVersion>2||t.schemaVersion<1)return wn.err("Bad schema version");if(t.schemaVersion===2)return wn.ok(t);const e={schemaVersion:2,sequences:{"com.tldraw.store":t.storeVersion}};for(const[n,r]of Object.entries(t.recordVersions))if(e.sequences[`com.tldraw.${n}`]=r.version,"subTypeKey"in r)for(const[o,s]of Object.entries(r.subTypeVersions))e.sequences[`com.tldraw.${n}.${o}`]=s;return wn.ok(e)}class t1{constructor(e,n){I(this,"migrations",{});I(this,"sortedMigrations");var o;this.types=e,this.options=n;for(const s of n.migrations??[])Le(!this.migrations[s.sequenceId],`Duplicate migration sequenceId ${s.sequenceId}`),mA(s),this.migrations[s.sequenceId]=s;const r=Object.values(this.migrations).flatMap(s=>s.sequence);this.sortedMigrations=qV(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);Le(a,`Migration '${s.id}' depends on missing migration '${i}'`)}}static create(e,n){return new t1(e,n??{})}validateRecord(e,n,r,o){try{const s=hn(this.types,n.typeName);if(!s)throw new Error(`Missing definition for record type ${n.typeName}`);return s.validate(n,o??void 0)}catch(s){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:e,record:n,phase:r,recordBefore:o,error:s});throw s}}getMigrationsSince(e){const n=ZV(e);if(!n.ok)return n;const r=n.value,o=new Set(Object.keys(r.sequences).filter(i=>this.migrations[i]));for(const i in this.migrations)r.sequences[i]===void 0&&this.migrations[i].retroactive&&o.add(i);if(o.size===0)return wn.ok([]);const s=new Set;for(const i of o){const a=r.sequences[i];if(typeof a!="number"&&this.migrations[i].retroactive||a===0){for(const u of this.migrations[i].sequence)s.add(u.id);continue}const l=`${i}/${a}`,c=this.migrations[i].sequence.findIndex(u=>u.id===l);if(c===-1)return wn.err("Incompatible schema?");for(const u of this.migrations[i].sequence.slice(c+1))s.add(u.id)}return wn.ok(this.sortedMigrations.filter(({id:i})=>s.has(i)))}migratePersistedRecord(e,n,r="up"){const o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:zs.MigrationError};let s=o.value;if(s.length===0)return{type:"success",value:e};if(s.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?zs.TargetVersionTooOld:zs.TargetVersionTooNew};if(r==="down"){if(!s.every(i=>i.down))return{type:"error",reason:zs.TargetVersionTooOld};s=s.slice().reverse()}e=tt(e);try{for(const i of s){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(e):!0))continue;const l=i[r](e);l&&(e=tt(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:zs.MigrationError}}return{type:"success",value:e}}migrateStoreSnapshot(e){let{store:n}=e;const r=this.getMigrationsSince(e.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:zs.MigrationError};const o=r.value;if(o.length===0)return{type:"success",value:n};n=tt(n);try{for(const s of o)if(s.scope==="record")for(const[i,a]of Object.entries(n)){if(!(s.filter?s.filter(a):!0))continue;const c=s.up(a);c&&(n[i]=tt(c))}else if(s.scope==="store"){const i=s.up(n);i&&(n=tt(i))}else Ot(s)}catch(s){return console.error("Error migrating store",s),{type:"error",reason:zs.MigrationError}}return{type:"success",value:n}}createIntegrityChecker(e){var n,r;return((r=(n=this.options).createIntegrityChecker)==null?void 0:r.call(n,e))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e,sequence:n})=>[e,n.length?Pf(n.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e})=>[e,0]))}}getType(e){const n=hn(this.types,e);return Le(n,"record type does not exists"),n}}Ci("@tldraw/store","3.7.0-canary.383dfd14bf86","esm");function QV(t){if(!t.length)return null;let e="";for(const n of t)typeof n=="number"?e+=`.${n}`:n.startsWith("(")?e.endsWith(")")?e=`${e.slice(0,-1)}, ${n.slice(1)}`:e+=n:e+=`.${n}`;return e=e.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),e.startsWith(".")?e.slice(1):e}class Me extends Error{constructor(n,r=[]){const o=QV(r),s=n.split(`
82
+ `))}const Kc=Symbol.for("com.tldraw.state/UNINITIALIZED");function Zi(t){return t===Kc}const dx=Ei("WithDiff",()=>class{constructor(e,n){this.value=e,this.diff=n}});function Wc(t,e){return new dx(t,e)}class vV{constructor(e,n,r){I(this,"lastChangedEpoch",Js);I(this,"lastTraversedEpoch",Js);I(this,"lastCheckedEpoch",Js);I(this,"parentSet",new Sf);I(this,"parents",[]);I(this,"parentEpochs",[]);I(this,"children",new Sf);I(this,"historyBuffer");I(this,"state",Kc);I(this,"error",null);I(this,"computeDiff");I(this,"isEqual");this.name=e,this.derive=n,r!=null&&r.historyLength&&(this.historyBuffer=new tA(r.historyLength)),this.computeDiff=r==null?void 0:r.computeDiff,this.isEqual=(r==null?void 0:r.isEqual)??eA}get isActivelyListening(){return!this.children.isEmpty}__unsafe__getWithoutCapture(e){var o;const n=this.lastChangedEpoch===Js,r=$n();if(!n&&(this.lastCheckedEpoch===r||this.isActivelyListening&&hV()&&this.lastTraversedEpoch<dV()||!JM(this)))if(this.lastCheckedEpoch=r,this.error){if(e)return this.state;throw this.error.thrownValue}else return this.state;try{nA(this);const s=this.derive(this.state,this.lastCheckedEpoch),i=s instanceof dx?s.value:s,a=this.state===Kc;if(a||!this.isEqual(i,this.state)){if(this.historyBuffer&&!a){const l=s instanceof dx?s.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,$n(),l??((o=this.computeDiff)==null?void 0:o.call(this,this.state,i,this.lastCheckedEpoch,$n()))??ur)}this.lastChangedEpoch=$n(),this.state=i}return this.error=null,this.lastCheckedEpoch=$n(),this.state}catch(s){if(this.state!==Kc&&(this.state=Kc,this.lastChangedEpoch=$n()),this.lastCheckedEpoch=$n(),this.historyBuffer&&this.historyBuffer.clear(),this.error={thrownValue:s},!e)throw s;return this.state}finally{rA()}}get(){try{return this.__unsafe__getWithoutCapture()}finally{vf(this)}}getDiffSince(e){var n;return this.__unsafe__getWithoutCapture(!0),vf(this),e>=this.lastChangedEpoch?ps:((n=this.historyBuffer)==null?void 0:n.getChangesSince(e))??ur}}const kg=Ei("Computed",()=>vV);function xV(t={},e,n,r){const o=r.value,s=Symbol.for("__@tldraw/state__computed__"+n);return r.value=function(){let i=this[s];return i||(i=new kg(n,o.bind(this),t),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r.value[iA]=!0,r}function wV(t={},e,n,r){const o=r.get,s=Symbol.for("__@tldraw/state__computed__"+n);return r.get=function(){let i=this[s];return i||(i=new kg(n,o.bind(this),t),Object.defineProperty(this,s,{enumerable:!1,configurable:!1,writable:!1,value:i})),i.get()},r}function bV(t,e,n){Le(n.kind==="method","@computed can only be used on methods");const r=Symbol.for("__@tldraw/state__computed__"+String(n.name)),o=function(){let s=this[r];return s||(s=new kg(String(n.name),e.bind(this),t),Object.defineProperty(this,r,{enumerable:!1,configurable:!1,writable:!1,value:s})),s.get()};return o[iA]=!0,o}function L_(t={},e){if(e.length===2){const[n,r]=e;return bV(t,n,r)}else{const[n,r,o]=e;return o.get?(SV(),wV(t,n,r,o)):xV(t,n,r,o)}}const iA="@@__isComputedMethod__@@";function G(){if(arguments.length===1){const t=arguments[0];return(...e)=>L_(t,e)}else return typeof arguments[0]=="string"?new kg(arguments[0],arguments[1],arguments[2]):L_(void 0,arguments)}const aA=1,PV=Ei("apiVersion",()=>aA);if(PV!==aA)throw new Error("You have multiple incompatible versions of @tldraw/state in your app. Please deduplicate the package.");Ci("@tldraw/state","3.7.0-canary.8e16c48b63b1","esm");function Tg(t,e,n=[]){const r=Te.useRef(e);r.current=e;const[o,s,i]=Te.useMemo(()=>{let a=null;const l=h=>(a=h,()=>{a=null}),c=new Ql(`useStateTracking(${t})`,()=>{var h;return(h=r.current)==null?void 0:h.call(r)},{scheduleEffect(){a==null||a()}});return[c,l,()=>c.scheduleCount]},[t,...n]);return Te.useSyncExternalStore(s,i,i),Te.useEffect(()=>(o.attach(),o.maybeScheduleEffect(),()=>{o.detach()}),[o]),o.execute()}const $_={apply(t,e,n){return Tg(t.displayName??t.name??"tracked(???)",()=>t.apply(e,n))}},CV=Symbol.for("react.memo"),_V=Symbol.for("react.forward_ref");function qt(t){let e=null;const n=t.$$typeof;return n===CV&&(t=t.type,e=t.compare),n===_V?w.memo(w.forwardRef(new Proxy(t.render,$_))):w.memo(new Proxy(t,$_),e)}function qw(t,e,n){return w.useState(()=>{const r=typeof e=="function"?e():e;return Et(`useAtom(${t})`,r,n)})[0]}function IV(){const t=arguments[0],e=arguments[1],n=arguments.length===3?void 0:arguments[2],r=arguments.length===3?arguments[2]:arguments[3];return w.useMemo(()=>G(`useComputed(${t})`,e,n),r)}function ci(t,e,n=ps){w.useEffect(()=>{const r=new Ql(t,e);return r.attach(),r.execute(),()=>{r.detach()}},n)}function U(){const t=arguments,e=t.length===3?t[2]:[t[0]],n=t.length===3?t[0]:`useValue(${t[0].name})`,r=w.useRef(!0);r.current=!0;const o=w.useMemo(()=>t.length===1?t[0]:G(n,()=>{if(r.current)return t[1]();try{return t[1]()}catch{return{}}}),e);try{const{subscribe:s,getSnapshot:i}=w.useMemo(()=>({subscribe:a=>jo(`useValue(${n})`,()=>{o.get(),a()}),getSnapshot:()=>o.get()}),[o]);return w.useSyncExternalStore(s,i,i)}finally{r.current=!1}}Ci("@tldraw/state-react","3.7.0-canary.8e16c48b63b1","esm");const EV=(t,e)=>e.some(n=>t instanceof n);let F_,N_;function kV(){return F_||(F_=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function TV(){return N_||(N_=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const lA=new WeakMap,hx=new WeakMap,cA=new WeakMap,Ny=new WeakMap,Zw=new WeakMap;function MV(t){const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{n(fs(t.result)),o()},i=()=>{r(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return e.then(n=>{n instanceof IDBCursor&&lA.set(n,t)}).catch(()=>{}),Zw.set(e,t),e}function AV(t){if(hx.has(t))return;const e=new Promise((n,r)=>{const o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{n(),o()},i=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});hx.set(t,e)}let px={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return hx.get(t);if(e==="objectStoreNames")return t.objectStoreNames||cA.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return fs(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function jV(t){px=t(px)}function OV(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){const r=t.call(zy(this),e,...n);return cA.set(r,e.sort?e.sort():[e]),fs(r)}:TV().includes(t)?function(...e){return t.apply(zy(this),e),fs(lA.get(this))}:function(...e){return fs(t.apply(zy(this),e))}}function DV(t){return typeof t=="function"?OV(t):(t instanceof IDBTransaction&&AV(t),EV(t,kV())?new Proxy(t,px):t)}function fs(t){if(t instanceof IDBRequest)return MV(t);if(Ny.has(t))return Ny.get(t);const e=DV(t);return e!==t&&(Ny.set(t,e),Zw.set(e,t)),e}const zy=t=>Zw.get(t);function uA(t,e,{blocked:n,upgrade:r,blocking:o,terminated:s}={}){const i=indexedDB.open(t,e),a=fs(i);return r&&i.addEventListener("upgradeneeded",l=>{r(fs(i.result),l.oldVersion,l.newVersion,fs(i.transaction),l)}),n&&i.addEventListener("blocked",l=>n(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 dA(t,{blocked:e}={}){const n=indexedDB.deleteDatabase(t);return e&&n.addEventListener("blocked",r=>e(r.oldVersion,r)),fs(n).then(()=>{})}const RV=["get","getKey","getAll","getAllKeys","count"],LV=["put","add","delete","clear"],By=new Map;function z_(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(By.get(e))return By.get(e);const n=e.replace(/FromIndex$/,""),r=e!==n,o=LV.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(o||RV.includes(n)))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[n](...a),o&&l.done]))[0]};return By.set(e,s),s}jV(t=>({...t,get:(e,n,r)=>z_(e,n)||t.get(e,n,r),has:(e,n)=>!!z_(e,n)||t.has(e,n)}));const $V="TLDRAW_DOCUMENT_v2",FV="TLDRAW_ASSET_STORE_v1",hA="TLDRAW_DB_NAME_INDEX_v2",Ce={Records:"records",Schema:"schema",SessionState:"session_state",Assets:"assets"};async function pA(t){const e=$V+t;return zV(e),await uA(e,4,{upgrade(n){n.objectStoreNames.contains(Ce.Records)||n.createObjectStore(Ce.Records),n.objectStoreNames.contains(Ce.Schema)||n.createObjectStore(Ce.Schema),n.objectStoreNames.contains(Ce.SessionState)||n.createObjectStore(Ce.SessionState),n.objectStoreNames.contains(Ce.Assets)||n.createObjectStore(Ce.Assets)}})}async function NV(t){const e=window.indexedDB.databases?(await window.indexedDB.databases()).map(p=>p.name):Qw(),n=FV+t;if(!e.find(p=>p===n))return;const o=await uA(n,1,{upgrade(p){p.objectStoreNames.contains("assets")||p.createObjectStore("assets")}});if(!o.objectStoreNames.contains("assets"))return;const s=o.transaction(["assets"],"readonly"),i=s.objectStore("assets"),a=await i.getAllKeys(),l=await Promise.all(a.map(async p=>[p,await i.get(p)]));await s.done;const c=await pA(t),u=c.transaction([Ce.Assets],"readwrite"),h=u.objectStore(Ce.Assets);for(const[p,f]of l)h.put(f,p);await u.done,o.close(),c.close(),await dA(n)}const mu=class mu{constructor(e){I(this,"getDbPromise");I(this,"isClosed",!1);I(this,"pendingTransactionSet",new Set);mu.connectedInstances.add(this),this.getDbPromise=(async()=>(await NV(e),await pA(e)))()}getDb(){return this.getDbPromise}pending(){return Promise.allSettled([this.getDbPromise,...this.pendingTransactionSet]).then(Ru)}async close(){this.isClosed||(this.isClosed=!0,await this.pending(),(await this.getDb()).close(),mu.connectedInstances.delete(this))}tx(e,n,r){const o=(async()=>{Le(!this.isClosed,"db is closed");const i=(await this.getDb()).transaction(n,e),a=i.done.catch(l=>{if(!this.isClosed)throw l});try{return await r(i)}finally{this.isClosed?i.abort():await a}})();return this.pendingTransactionSet.add(o),o.finally(()=>this.pendingTransactionSet.delete(o)),o}async load({sessionId:e}={}){return await this.tx("readonly",[Ce.Records,Ce.Schema,Ce.SessionState],async n=>{var l,c;const r=n.objectStore(Ce.Records),o=n.objectStore(Ce.Schema),s=n.objectStore(Ce.SessionState);let i=e?(l=await s.get(e))==null?void 0:l.snapshot:null;return i||(i=(c=(await s.getAll()).sort((h,p)=>h.updatedAt-p.updatedAt).pop())==null?void 0:c.snapshot),{records:await r.getAll(),schema:await o.get(Ce.Schema),sessionStateSnapshot:i}})}async storeChanges({schema:e,changes:n,sessionId:r,sessionStateSnapshot:o}){await this.tx("readwrite",[Ce.Records,Ce.Schema,Ce.SessionState],async s=>{const i=s.objectStore(Ce.Records),a=s.objectStore(Ce.Schema),l=s.objectStore(Ce.SessionState);for(const[c,u]of Object.entries(n.added))await i.put(u,c);for(const[c,u]of Object.values(n.updated))await i.put(u,u.id);for(const c of Object.keys(n.removed))await i.delete(c);a.put(e.serialize(),Ce.Schema),o&&r?l.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async storeSnapshot({schema:e,snapshot:n,sessionId:r,sessionStateSnapshot:o}){await this.tx("readwrite",[Ce.Records,Ce.Schema,Ce.SessionState],async s=>{const i=s.objectStore(Ce.Records),a=s.objectStore(Ce.Schema),l=s.objectStore(Ce.SessionState);await i.clear();for(const[c,u]of Object.entries(n))await i.put(u,c);a.put(e.serialize(),Ce.Schema),o&&r?l.put({snapshot:o,updatedAt:Date.now(),id:r},r):(o||r)&&console.error("sessionStateSnapshot and instanceId must be provided together")})}async pruneSessions(){await this.tx("readwrite",[Ce.SessionState],async e=>{const n=e.objectStore(Ce.SessionState),r=(await n.getAll()).sort((s,i)=>s.updatedAt-i.updatedAt);if(r.length<10){await e.done;return}const o=r.slice(0,r.length-10);for(const{id:s}of o)await n.delete(s)})}async getAsset(e){return await this.tx("readonly",[Ce.Assets],async n=>await n.objectStore(Ce.Assets).get(e))}async storeAsset(e,n){await this.tx("readwrite",[Ce.Assets],async r=>{await r.objectStore(Ce.Assets).put(n,e)})}};I(mu,"connectedInstances",new Set);let xf=mu;function Qw(){const t=JSON.parse(_w(hA)||"[]")??[];return Array.isArray(t)?t:[]}function zV(t){const e=new Set(Qw());e.add(t),Iw(hA,JSON.stringify([...e]))}class sp{constructor(e){I(this,"nextValue");I(this,"diff");this.previousValue=e}get(){var r,o,s,i;const e=((o=(r=this.diff)==null?void 0:r.removed)==null?void 0:o.size)??0,n=((i=(s=this.diff)==null?void 0:s.added)==null?void 0:i.size)??0;if(!(e===0&&n===0))return{value:this.nextValue,diff:this.diff}}_add(e,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.add(e),this.diff??(this.diff={}),n?(r=this.diff.removed)==null||r.delete(e):((o=this.diff).added??(o.added=new Set),this.diff.added.add(e))}add(e){var o,s,i;const n=this.previousValue.has(e);if(n)return((s=(o=this.diff)==null?void 0:o.removed)==null?void 0:s.has(e))?this._add(e,n):void 0;(i=this.nextValue)!=null&&i.has(e)||this._add(e,n)}_remove(e,n){var r,o;this.nextValue??(this.nextValue=new Set(this.previousValue)),this.nextValue.delete(e),this.diff??(this.diff={}),n?((r=this.diff).removed??(r.removed=new Set),this.diff.removed.add(e)):(o=this.diff.added)==null||o.delete(e)}remove(e){var o,s,i,a;const n=this.previousValue.has(e);if(!n)return((s=(o=this.diff)==null?void 0:o.added)==null?void 0:s.has(e))?this._remove(e,n):void 0;(a=(i=this.diff)==null?void 0:i.removed)!=null&&a.has(e)||this._remove(e,n)}}class Mg{constructor(e,n){I(this,"createDefaultProperties");I(this,"validator");I(this,"ephemeralKeys");I(this,"ephemeralKeySet");I(this,"scope");this.typeName=e,this.createDefaultProperties=n.createDefaultProperties,this.validator=n.validator??{validate:o=>o},this.scope=n.scope??"document",this.ephemeralKeys=n.ephemeralKeys;const r=new Set;if(n.ephemeralKeys)for(const[o,s]of Xn(n.ephemeralKeys))s&&r.add(o);this.ephemeralKeySet=r}create(e){const n={...this.createDefaultProperties(),id:this.createId()};for(const[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n.typeName=this.typeName,n}clone(e){return{...tt(e),id:this.createId()}}createId(e){return this.typeName+":"+(e??ze())}createCustomId(e){return this.typeName+":"+e}parseId(e){if(!this.isId(e))throw new Error(`ID "${e}" is not a valid ID for type "${this.typeName}"`);return e.slice(this.typeName.length+1)}isInstance(e){return(e==null?void 0:e.typeName)===this.typeName}isId(e){if(!e)return!1;for(let n=0;n<this.typeName.length;n++)if(e[n]!==this.typeName[n])return!1;return e[this.typeName.length]===":"}withDefaultProperties(e){return new Mg(this.typeName,{createDefaultProperties:e,validator:this.validator,scope:this.scope,ephemeralKeys:this.ephemeralKeys})}validate(e,n){return n&&this.validator.validateUsingKnownGoodVersion?this.validator.validateUsingKnownGoodVersion(n,e):this.validator.validate(e)}}function Ko(t,e){return new Mg(t,{createDefaultProperties:()=>({}),validator:e.validator,scope:e.scope,ephemeralKeys:e.ephemeralKeys})}function wf(){return{added:{},updated:{},removed:{}}}function fx(t){const e={added:t.removed,removed:t.added,updated:{}};for(const[n,r]of Object.values(t.updated))e.updated[n.id]=[r,n];return e}function fA(t){return Object.keys(t.added).length===0&&Object.keys(t.updated).length===0&&Object.keys(t.removed).length===0}function Jw(t){const e={added:{},removed:{},updated:{}};return cu(e,t),e}function cu(t,e){for(const n of e){for(const[r,o]of Xn(n.added))if(t.removed[r]){const s=t.removed[r];delete t.removed[r],s!==o&&(t.updated[r]=[s,o])}else t.added[r]=o;for(const[r,[o,s]]of Xn(n.updated)){if(t.added[r]){t.added[r]=s,delete t.updated[r],delete t.removed[r];continue}if(t.updated[r]){t.updated[r]=[t.updated[r][0],s],delete t.removed[r];continue}t.updated[r]=n.updated[r],delete t.removed[r]}for(const[r,o]of Xn(n.removed))t.added[r]?delete t.added[r]:t.updated[r]?(t.removed[r]=t.updated[r][0],delete t.updated[r]):t.removed[r]=o}}var bf={exports:{}};bf.exports;(function(t,e){var n=200,r="__lodash_hash_undefined__",o=1,s=2,i=9007199254740991,a="[object Arguments]",l="[object Array]",c="[object AsyncFunction]",u="[object Boolean]",h="[object Date]",p="[object Error]",f="[object Function]",g="[object GeneratorFunction]",m="[object Map]",v="[object Number]",y="[object Null]",S="[object Object]",b="[object Promise]",P="[object Proxy]",C="[object RegExp]",_="[object Set]",E="[object String]",k="[object Symbol]",D="[object Undefined]",T="[object WeakMap]",j="[object ArrayBuffer]",$="[object DataView]",M="[object Float32Array]",O="[object Float64Array]",F="[object Int8Array]",B="[object Int16Array]",K="[object Int32Array]",R="[object Uint8Array]",H="[object Uint8ClampedArray]",Y="[object Uint16Array]",ee="[object Uint32Array]",he=/[\\^$.*+?()[\]{}|]/g,ue=/^\[object .+?Constructor\]$/,ke=/^(?:0|[1-9]\d*)$/,se={};se[M]=se[O]=se[F]=se[B]=se[K]=se[R]=se[H]=se[Y]=se[ee]=!0,se[a]=se[l]=se[j]=se[u]=se[$]=se[h]=se[p]=se[f]=se[m]=se[v]=se[S]=se[C]=se[_]=se[E]=se[T]=!1;var We=typeof dn=="object"&&dn&&dn.Object===Object&&dn,Fe=typeof self=="object"&&self&&self.Object===Object&&self,ot=We||Fe||Function("return this")(),$e=e&&!e.nodeType&&e,lt=$e&&!0&&t&&!t.nodeType&&t,Ue=lt&&lt.exports===$e,er=Ue&&We.process,$t=function(){try{return er&&er.binding&&er.binding("util")}catch{}}(),On=$t&&$t.isTypedArray;function vt(A,L){for(var V=-1,ne=A==null?0:A.length,Qe=0,Se=[];++V<ne;){var mt=A[V];L(mt,V,A)&&(Se[Qe++]=mt)}return Se}function Jt(A,L){for(var V=-1,ne=L.length,Qe=A.length;++V<ne;)A[Qe+V]=L[V];return A}function Xo(A,L){for(var V=-1,ne=A==null?0:A.length;++V<ne;)if(L(A[V],V,A))return!0;return!1}function cc(A,L){for(var V=-1,ne=Array(A);++V<A;)ne[V]=L(V);return ne}function js(A){return function(L){return A(L)}}function A4(A,L){return A.has(L)}function j4(A,L){return A==null?void 0:A[L]}function O4(A){var L=-1,V=Array(A.size);return A.forEach(function(ne,Qe){V[++L]=[Qe,ne]}),V}function D4(A,L){return function(V){return A(L(V))}}function R4(A){var L=-1,V=Array(A.size);return A.forEach(function(ne){V[++L]=ne}),V}var L4=Array.prototype,$4=Function.prototype,Ad=Object.prototype,Mm=ot["__core-js_shared__"],Jb=$4.toString,go=Ad.hasOwnProperty,eP=function(){var A=/[^.]+$/.exec(Mm&&Mm.keys&&Mm.keys.IE_PROTO||"");return A?"Symbol(src)_1."+A:""}(),tP=Ad.toString,F4=RegExp("^"+Jb.call(go).replace(he,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),nP=Ue?ot.Buffer:void 0,jd=ot.Symbol,rP=ot.Uint8Array,oP=Ad.propertyIsEnumerable,N4=L4.splice,Ri=jd?jd.toStringTag:void 0,sP=Object.getOwnPropertySymbols,z4=nP?nP.isBuffer:void 0,B4=D4(Object.keys,Object),Am=ka(ot,"DataView"),uc=ka(ot,"Map"),jm=ka(ot,"Promise"),Om=ka(ot,"Set"),Dm=ka(ot,"WeakMap"),dc=ka(Object,"create"),U4=Fi(Am),H4=Fi(uc),K4=Fi(jm),W4=Fi(Om),G4=Fi(Dm),iP=jd?jd.prototype:void 0,Rm=iP?iP.valueOf:void 0;function Li(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function V4(){this.__data__=dc?dc(null):{},this.size=0}function Y4(A){var L=this.has(A)&&delete this.__data__[A];return this.size-=L?1:0,L}function X4(A){var L=this.__data__;if(dc){var V=L[A];return V===r?void 0:V}return go.call(L,A)?L[A]:void 0}function q4(A){var L=this.__data__;return dc?L[A]!==void 0:go.call(L,A)}function Z4(A,L){var V=this.__data__;return this.size+=this.has(A)?0:1,V[A]=dc&&L===void 0?r:L,this}Li.prototype.clear=V4,Li.prototype.delete=Y4,Li.prototype.get=X4,Li.prototype.has=q4,Li.prototype.set=Z4;function qo(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function Q4(){this.__data__=[],this.size=0}function J4(A){var L=this.__data__,V=Dd(L,A);if(V<0)return!1;var ne=L.length-1;return V==ne?L.pop():N4.call(L,V,1),--this.size,!0}function eN(A){var L=this.__data__,V=Dd(L,A);return V<0?void 0:L[V][1]}function tN(A){return Dd(this.__data__,A)>-1}function nN(A,L){var V=this.__data__,ne=Dd(V,A);return ne<0?(++this.size,V.push([A,L])):V[ne][1]=L,this}qo.prototype.clear=Q4,qo.prototype.delete=J4,qo.prototype.get=eN,qo.prototype.has=tN,qo.prototype.set=nN;function $i(A){var L=-1,V=A==null?0:A.length;for(this.clear();++L<V;){var ne=A[L];this.set(ne[0],ne[1])}}function rN(){this.size=0,this.__data__={hash:new Li,map:new(uc||qo),string:new Li}}function oN(A){var L=Rd(this,A).delete(A);return this.size-=L?1:0,L}function sN(A){return Rd(this,A).get(A)}function iN(A){return Rd(this,A).has(A)}function aN(A,L){var V=Rd(this,A),ne=V.size;return V.set(A,L),this.size+=V.size==ne?0:1,this}$i.prototype.clear=rN,$i.prototype.delete=oN,$i.prototype.get=sN,$i.prototype.has=iN,$i.prototype.set=aN;function Od(A){var L=-1,V=A==null?0:A.length;for(this.__data__=new $i;++L<V;)this.add(A[L])}function lN(A){return this.__data__.set(A,r),this}function cN(A){return this.__data__.has(A)}Od.prototype.add=Od.prototype.push=lN,Od.prototype.has=cN;function Os(A){var L=this.__data__=new qo(A);this.size=L.size}function uN(){this.__data__=new qo,this.size=0}function dN(A){var L=this.__data__,V=L.delete(A);return this.size=L.size,V}function hN(A){return this.__data__.get(A)}function pN(A){return this.__data__.has(A)}function fN(A,L){var V=this.__data__;if(V instanceof qo){var ne=V.__data__;if(!uc||ne.length<n-1)return ne.push([A,L]),this.size=++V.size,this;V=this.__data__=new $i(ne)}return V.set(A,L),this.size=V.size,this}Os.prototype.clear=uN,Os.prototype.delete=dN,Os.prototype.get=hN,Os.prototype.has=pN,Os.prototype.set=fN;function gN(A,L){var V=Ld(A),ne=!V&&MN(A),Qe=!V&&!ne&&Lm(A),Se=!V&&!ne&&!Qe&&gP(A),mt=V||ne||Qe||Se,At=mt?cc(A.length,String):[],Ft=At.length;for(var ct in A)go.call(A,ct)&&!(mt&&(ct=="length"||Qe&&(ct=="offset"||ct=="parent")||Se&&(ct=="buffer"||ct=="byteLength"||ct=="byteOffset")||_N(ct,Ft)))&&At.push(ct);return At}function Dd(A,L){for(var V=A.length;V--;)if(dP(A[V][0],L))return V;return-1}function mN(A,L,V){var ne=L(A);return Ld(A)?ne:Jt(ne,V(A))}function hc(A){return A==null?A===void 0?D:y:Ri&&Ri in Object(A)?PN(A):TN(A)}function aP(A){return pc(A)&&hc(A)==a}function lP(A,L,V,ne,Qe){return A===L?!0:A==null||L==null||!pc(A)&&!pc(L)?A!==A&&L!==L:yN(A,L,V,ne,lP,Qe)}function yN(A,L,V,ne,Qe,Se){var mt=Ld(A),At=Ld(L),Ft=mt?l:Ds(A),ct=At?l:Ds(L);Ft=Ft==a?S:Ft,ct=ct==a?S:ct;var tr=Ft==S,Ur=ct==S,en=Ft==ct;if(en&&Lm(A)){if(!Lm(L))return!1;mt=!0,tr=!1}if(en&&!tr)return Se||(Se=new Os),mt||gP(A)?cP(A,L,V,ne,Qe,Se):wN(A,L,Ft,V,ne,Qe,Se);if(!(V&o)){var Pr=tr&&go.call(A,"__wrapped__"),Cr=Ur&&go.call(L,"__wrapped__");if(Pr||Cr){var Rs=Pr?A.value():A,Zo=Cr?L.value():L;return Se||(Se=new Os),Qe(Rs,Zo,V,ne,Se)}}return en?(Se||(Se=new Os),bN(A,L,V,ne,Qe,Se)):!1}function SN(A){if(!fP(A)||EN(A))return!1;var L=hP(A)?F4:ue;return L.test(Fi(A))}function vN(A){return pc(A)&&pP(A.length)&&!!se[hc(A)]}function xN(A){if(!kN(A))return B4(A);var L=[];for(var V in Object(A))go.call(A,V)&&V!="constructor"&&L.push(V);return L}function cP(A,L,V,ne,Qe,Se){var mt=V&o,At=A.length,Ft=L.length;if(At!=Ft&&!(mt&&Ft>At))return!1;var ct=Se.get(A);if(ct&&Se.get(L))return ct==L;var tr=-1,Ur=!0,en=V&s?new Od:void 0;for(Se.set(A,L),Se.set(L,A);++tr<At;){var Pr=A[tr],Cr=L[tr];if(ne)var Rs=mt?ne(Cr,Pr,tr,L,A,Se):ne(Pr,Cr,tr,A,L,Se);if(Rs!==void 0){if(Rs)continue;Ur=!1;break}if(en){if(!Xo(L,function(Zo,Ni){if(!A4(en,Ni)&&(Pr===Zo||Qe(Pr,Zo,V,ne,Se)))return en.push(Ni)})){Ur=!1;break}}else if(!(Pr===Cr||Qe(Pr,Cr,V,ne,Se))){Ur=!1;break}}return Se.delete(A),Se.delete(L),Ur}function wN(A,L,V,ne,Qe,Se,mt){switch(V){case $:if(A.byteLength!=L.byteLength||A.byteOffset!=L.byteOffset)return!1;A=A.buffer,L=L.buffer;case j:return!(A.byteLength!=L.byteLength||!Se(new rP(A),new rP(L)));case u:case h:case v:return dP(+A,+L);case p:return A.name==L.name&&A.message==L.message;case C:case E:return A==L+"";case m:var At=O4;case _:var Ft=ne&o;if(At||(At=R4),A.size!=L.size&&!Ft)return!1;var ct=mt.get(A);if(ct)return ct==L;ne|=s,mt.set(A,L);var tr=cP(At(A),At(L),ne,Qe,Se,mt);return mt.delete(A),tr;case k:if(Rm)return Rm.call(A)==Rm.call(L)}return!1}function bN(A,L,V,ne,Qe,Se){var mt=V&o,At=uP(A),Ft=At.length,ct=uP(L),tr=ct.length;if(Ft!=tr&&!mt)return!1;for(var Ur=Ft;Ur--;){var en=At[Ur];if(!(mt?en in L:go.call(L,en)))return!1}var Pr=Se.get(A);if(Pr&&Se.get(L))return Pr==L;var Cr=!0;Se.set(A,L),Se.set(L,A);for(var Rs=mt;++Ur<Ft;){en=At[Ur];var Zo=A[en],Ni=L[en];if(ne)var mP=mt?ne(Ni,Zo,en,L,A,Se):ne(Zo,Ni,en,A,L,Se);if(!(mP===void 0?Zo===Ni||Qe(Zo,Ni,V,ne,Se):mP)){Cr=!1;break}Rs||(Rs=en=="constructor")}if(Cr&&!Rs){var $d=A.constructor,Fd=L.constructor;$d!=Fd&&"constructor"in A&&"constructor"in L&&!(typeof $d=="function"&&$d instanceof $d&&typeof Fd=="function"&&Fd instanceof Fd)&&(Cr=!1)}return Se.delete(A),Se.delete(L),Cr}function uP(A){return mN(A,ON,CN)}function Rd(A,L){var V=A.__data__;return IN(L)?V[typeof L=="string"?"string":"hash"]:V.map}function ka(A,L){var V=j4(A,L);return SN(V)?V:void 0}function PN(A){var L=go.call(A,Ri),V=A[Ri];try{A[Ri]=void 0;var ne=!0}catch{}var Qe=tP.call(A);return ne&&(L?A[Ri]=V:delete A[Ri]),Qe}var CN=sP?function(A){return A==null?[]:(A=Object(A),vt(sP(A),function(L){return oP.call(A,L)}))}:DN,Ds=hc;(Am&&Ds(new Am(new ArrayBuffer(1)))!=$||uc&&Ds(new uc)!=m||jm&&Ds(jm.resolve())!=b||Om&&Ds(new Om)!=_||Dm&&Ds(new Dm)!=T)&&(Ds=function(A){var L=hc(A),V=L==S?A.constructor:void 0,ne=V?Fi(V):"";if(ne)switch(ne){case U4:return $;case H4:return m;case K4:return b;case W4:return _;case G4:return T}return L});function _N(A,L){return L=L??i,!!L&&(typeof A=="number"||ke.test(A))&&A>-1&&A%1==0&&A<L}function IN(A){var L=typeof A;return L=="string"||L=="number"||L=="symbol"||L=="boolean"?A!=="__proto__":A===null}function EN(A){return!!eP&&eP in A}function kN(A){var L=A&&A.constructor,V=typeof L=="function"&&L.prototype||Ad;return A===V}function TN(A){return tP.call(A)}function Fi(A){if(A!=null){try{return Jb.call(A)}catch{}try{return A+""}catch{}}return""}function dP(A,L){return A===L||A!==A&&L!==L}var MN=aP(function(){return arguments}())?aP:function(A){return pc(A)&&go.call(A,"callee")&&!oP.call(A,"callee")},Ld=Array.isArray;function AN(A){return A!=null&&pP(A.length)&&!hP(A)}var Lm=z4||RN;function jN(A,L){return lP(A,L)}function hP(A){if(!fP(A))return!1;var L=hc(A);return L==f||L==g||L==c||L==P}function pP(A){return typeof A=="number"&&A>-1&&A%1==0&&A<=i}function fP(A){var L=typeof A;return A!=null&&(L=="object"||L=="function")}function pc(A){return A!=null&&typeof A=="object"}var gP=On?js(On):vN;function ON(A){return AN(A)?gN(A):xN(A)}function DN(){return[]}function RN(){return!1}t.exports=jN})(bf,bf.exports);var BV=bf.exports;const gA=xi(BV);function UV(t){if(t.length===0)return new Set;const e=t[0],n=t.slice(1),r=new Set;for(const o of e)n.every(s=>s.has(o))&&r.add(o);return r}function HV(t,e){const n={};for(const r of e)t.has(r)||(n.added??(n.added=new Set),n.added.add(r));for(const r of t)e.has(r)||(n.removed??(n.removed=new Set),n.removed.add(r));return n.added||n.removed?n:void 0}function B_(t,e){for(const[n,r]of Object.entries(t)){const o=r,s=e[n];if("eq"in o&&s!==o.eq||"neq"in o&&s===o.neq||"gt"in o&&(typeof s!="number"||s<=o.gt))return!1}return!0}function U_(t,e,n){const r=Object.fromEntries(Object.keys(n).map(o=>[o,new Set]));for(const[o,s]of Object.entries(n))if("eq"in s){const a=t.index(e,o).get().get(s.eq);if(a)for(const l of a)r[o].add(l)}else if("neq"in s){const i=t.index(e,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=t.index(e,o);for(const[a,l]of i.get())if(a>s.gt)for(const c of l)r[o].add(c)}return UV(Object.values(r))}class KV{constructor(e,n){I(this,"indexCache",new Map);I(this,"historyCache",new Map);this.atoms=e,this.history=n}filterHistory(e){if(this.historyCache.has(e))return this.historyCache.get(e);const n=G("filterHistory:"+e,(r,o)=>{if(Zi(r))return this.history.get();const s=this.history.getDiffSince(o);if(s===ur)return this.history.get();const i={added:{},removed:{},updated:{}};let a=0,l=0,c=0;for(const u of s){for(const h of ut(u.added))if(h.typeName===e)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 ut(u.updated))p.typeName===e&&(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 ut(u.removed))h.typeName===e&&(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?Wc(this.history.get(),i):r},{historyLength:100});return this.historyCache.set(e,n),n}index(e,n){const r=e+":"+n;if(this.indexCache.has(r))return this.indexCache.get(r);const o=this.__uncached_createIndex(e,n);return this.indexCache.set(r,o),o}__uncached_createIndex(e,n){const r=this.filterHistory(e),o=()=>{r.get();const s=new Map;for(const i of ut(this.atoms.get())){const a=i.get();if(a.typeName===e){const l=a[n];s.has(l)||s.set(l,new Set),s.get(l).add(a.id)}}return s};return G("index:"+e+":"+n,(s,i)=>{if(Zi(s))return o();const a=r.getDiffSince(i);if(a===ur)return o();const l=new Map,c=(f,g)=>{let m=l.get(f);m||(m=new sp(s.get(f)??new Set)),m.add(g),l.set(f,m)},u=(f,g)=>{let m=l.get(f);m||(m=new sp(s.get(f)??new Set)),m.remove(g),l.set(f,m)};for(const f of a){for(const g of ut(f.added))if(g.typeName===e){const m=g[n];c(m,g.id)}for(const[g,m]of ut(f.updated))if(m.typeName===e){const v=g[n],y=m[n];v!==y&&(u(v,m.id),c(y,m.id))}for(const g of ut(f.removed))if(g.typeName===e){const m=g[n];u(m,g.id)}}let h,p;for(const[f,g]of l){const m=g.get();m&&(h||(h=new Map(s)),p||(p=new Map),m.value.size===0?h.delete(f):h.set(f,m.value),p.set(f,m.diff))}return h&&p?Wc(h,p):s},{historyLength:100})}record(e,n=()=>({}),r="record:"+e+(n?":"+n.toString():"")){const o=this.ids(e,n,r);return G(r,()=>{var s;for(const i of o.get())return(s=this.atoms.get()[i])==null?void 0:s.get()})}records(e,n=()=>({}),r="records:"+e+(n?":"+n.toString():"")){const o=this.ids(e,n,"ids:"+r);return G(r,()=>{const s=this.atoms.get();return[...o.get()].map(i=>{const a=s[i];if(!a)throw new Error("no atom found for record id: "+i);return a.get()})},{isEqual:RT})}ids(e,n=()=>({}),r="ids:"+e+(n?":"+n.toString():"")){const o=this.filterHistory(e),s=()=>{o.get();const l=n();return Object.keys(l).length===0?new Set(ut(this.atoms.get()).flatMap(c=>{const u=c.get();return u.typeName===e?u.id:[]})):U_(this,e,l)},i=l=>{const c=s(),u=HV(l,c);return u?Wc(c,u):l},a=G("ids_query:"+r,n,{isEqual:gA});return G("query:"+r,(l,c)=>{const u=a.get();if(Zi(l))return s();if(c<a.lastChangedEpoch)return i(l);const h=o.getDiffSince(c);if(h===ur)return i(l);const p=new sp(l);for(const g of h){for(const m of ut(g.added))m.typeName===e&&B_(u,m)&&p.add(m.id);for(const[m,v]of ut(g.updated))v.typeName===e&&(B_(u,v)?p.add(v.id):p.remove(v.id));for(const m of ut(g.removed))m.typeName===e&&p.remove(m.id)}const f=p.get();return f?Wc(f.value,f.diff):l},{historyLength:50})}exec(e,n){const r=U_(this,e,n);if(r.size===0)return ps;const o=this.atoms.get();return[...r].map(s=>o[s].get())}}class WV{constructor(e){I(this,"_beforeCreateHandlers",{});I(this,"_afterCreateHandlers",{});I(this,"_beforeChangeHandlers",{});I(this,"_afterChangeHandlers",{});I(this,"_beforeDeleteHandlers",{});I(this,"_afterDeleteHandlers",{});I(this,"_operationCompleteHandlers",[]);I(this,"_isEnabled",!0);this.store=e}isEnabled(){return this._isEnabled}setIsEnabled(e){this._isEnabled=e}handleBeforeCreate(e,n){if(!this._isEnabled)return e;const r=this._beforeCreateHandlers[e.typeName];if(r){let o=e;for(const s of r)o=s(o,n);return o}return e}handleAfterCreate(e,n){if(!this._isEnabled)return;const r=this._afterCreateHandlers[e.typeName];if(r)for(const o of r)o(e,n)}handleBeforeChange(e,n,r){if(!this._isEnabled)return n;const o=this._beforeChangeHandlers[n.typeName];if(o){let s=n;for(const i of o)s=i(e,s,r);return s}return n}handleAfterChange(e,n,r){if(!this._isEnabled)return;const o=this._afterChangeHandlers[n.typeName];if(o)for(const s of o)s(e,n,r)}handleBeforeDelete(e,n){if(!this._isEnabled)return!0;const r=this._beforeDeleteHandlers[e.typeName];if(r){for(const o of r)if(o(e,n)===!1)return!1}return!0}handleAfterDelete(e,n){if(!this._isEnabled)return;const r=this._afterDeleteHandlers[e.typeName];if(r)for(const o of r)o(e,n)}handleOperationComplete(e){if(this._isEnabled)for(const n of this._operationCompleteHandlers)n(e)}register(e){const n=[];for(const[r,o]of Object.entries(e))o!=null&&o.beforeCreate&&n.push(this.registerBeforeCreateHandler(r,o.beforeCreate)),o!=null&&o.afterCreate&&n.push(this.registerAfterCreateHandler(r,o.afterCreate)),o!=null&&o.beforeChange&&n.push(this.registerBeforeChangeHandler(r,o.beforeChange)),o!=null&&o.afterChange&&n.push(this.registerAfterChangeHandler(r,o.afterChange)),o!=null&&o.beforeDelete&&n.push(this.registerBeforeDeleteHandler(r,o.beforeDelete)),o!=null&&o.afterDelete&&n.push(this.registerAfterDeleteHandler(r,o.afterDelete));return()=>{for(const r of n)r()}}registerBeforeCreateHandler(e,n){return this._beforeCreateHandlers[e]||(this._beforeCreateHandlers[e]=[]),this._beforeCreateHandlers[e].push(n),()=>zi(this._beforeCreateHandlers[e],n)}registerAfterCreateHandler(e,n){return this._afterCreateHandlers[e]||(this._afterCreateHandlers[e]=[]),this._afterCreateHandlers[e].push(n),()=>zi(this._afterCreateHandlers[e],n)}registerBeforeChangeHandler(e,n){return this._beforeChangeHandlers[e]||(this._beforeChangeHandlers[e]=[]),this._beforeChangeHandlers[e].push(n),()=>zi(this._beforeChangeHandlers[e],n)}registerAfterChangeHandler(e,n){return this._afterChangeHandlers[e]||(this._afterChangeHandlers[e]=[]),this._afterChangeHandlers[e].push(n),()=>zi(this._afterChangeHandlers[e],n)}registerBeforeDeleteHandler(e,n){return this._beforeDeleteHandlers[e]||(this._beforeDeleteHandlers[e]=[]),this._beforeDeleteHandlers[e].push(n),()=>zi(this._beforeDeleteHandlers[e],n)}registerAfterDeleteHandler(e,n){return this._afterDeleteHandlers[e]||(this._afterDeleteHandlers[e]=[]),this._afterDeleteHandlers[e].push(n),()=>zi(this._afterDeleteHandlers[e],n)}registerOperationCompleteHandler(e){return this._operationCompleteHandlers.push(e),()=>zi(this._operationCompleteHandlers,e)}}function zi(t,e){const n=t.indexOf(e);n>=0&&t.splice(n,1)}class e1{constructor(e){I(this,"id");I(this,"atoms",Et("store_atoms",{}));I(this,"history",Et("history",0,{historyLength:1e3}));I(this,"query",new KV(this.atoms,this.history));I(this,"listeners",new Set);I(this,"historyAccumulator",new VV);I(this,"historyReactor");I(this,"schema");I(this,"props");I(this,"scopedTypes");I(this,"sideEffects",new WV(this));I(this,"isMergingRemoteChanges",!1);I(this,"_integrityChecker");I(this,"_isPossiblyCorrupted",!1);I(this,"pendingAfterEvents",null);I(this,"_isInAtomicOp",!1);const{initialData:n,schema:r,id:o}=e;this.id=o??ze(),this.schema=r,this.props=e.props,n&&this.atoms.set(ww(Xn(n).map(([s,i])=>[s,Et("atom:"+s,this.schema.validateRecord(this,i,"initialize",null))]))),this.historyReactor=cV("Store.historyReactor",()=>{this.history.get(),this._flushHistory()},{scheduleEffect:s=>this.cancelHistoryReactor=tM(s)}),this.scopedTypes={document:new Set(ut(this.schema.types).filter(s=>s.scope==="document").map(s=>s.typeName)),session:new Set(ut(this.schema.types).filter(s=>s.scope==="session").map(s=>s.typeName)),presence:new Set(ut(this.schema.types).filter(s=>s.scope==="presence").map(s=>s.typeName))}}cancelHistoryReactor(){}_flushHistory(){if(this.historyAccumulator.hasChanges()){const e=this.historyAccumulator.flush();for(const{changes:n,source:r}of e){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(n,"document")),!s)continue;a({changes:s,source:r})}else if(l.scope==="session"){if(o??(o=this.filterChangesByScope(n,"session")),!o)continue;a({changes:o,source:r})}else{if(i??(i=this.filterChangesByScope(n,"presence")),!i)continue;a({changes:i,source:r})}else a({changes:n,source:r})}}}dispose(){this.cancelHistoryReactor()}filterChangesByScope(e,n){const r={added:lu(e.added,(o,s)=>this.scopedTypes[n].has(s.typeName)),updated:lu(e.updated,(o,s)=>this.scopedTypes[n].has(s[1].typeName)),removed:lu(e.removed,(o,s)=>this.scopedTypes[n].has(s.typeName))};return Object.keys(r.added).length===0&&Object.keys(r.updated).length===0&&Object.keys(r.removed).length===0?null:r}updateHistory(e){this.historyAccumulator.add({changes:e,source:this.isMergingRemoteChanges?"remote":"user"}),this.listeners.size===0&&this.historyAccumulator.clear(),this.history.set(this.history.get()+1,e)}validate(e){this.allRecords().forEach(n=>this.schema.validateRecord(this,n,e,null))}put(e,n){this.atomic(()=>{const r={},o={},s=this.atoms.__unsafe__getWithoutCapture();let i=null,a,l=!1;const c=this.isMergingRemoteChanges?"remote":"user";for(let u=0,h=e.length;u<h;u++){a=e[u];const p=(i??s)[a.id];if(p){const f=p.__unsafe__getWithoutCapture();if(a=this.sideEffects.handleBeforeChange(f,a,c),this.schema.validateRecord(this,a,n??"updateRecord",f)===f)continue;p.set(a),l=!0;const m=p.__unsafe__getWithoutCapture();r[a.id]=[f,m],this.addDiffForAfterEvent(f,m)}else a=this.sideEffects.handleBeforeCreate(a,c),l=!0,a=this.schema.validateRecord(this,a,n??"createRecord",null),o[a.id]=a,this.addDiffForAfterEvent(null,a),i||(i={...s}),i[a.id]=Et("atom:"+a.id,a)}i&&this.atoms.set(i),l&&this.updateHistory({added:o,updated:r,removed:{}})})}remove(e){this.atomic(()=>{const n=new Set,r=this.isMergingRemoteChanges?"remote":"user";if(this.sideEffects.isEnabled())for(const s of e){const i=this.atoms.__unsafe__getWithoutCapture()[s];i&&this.sideEffects.handleBeforeDelete(i.get(),r)===!1&&n.add(s)}let o;this.atoms.update(s=>{let i;for(const a of e){if(n.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})})}get(e){var n;return(n=this.atoms.get()[e])==null?void 0:n.get()}unsafeGetWithoutCapture(e){var n;return(n=this.atoms.__unsafe__getWithoutCapture()[e])==null?void 0:n.__unsafe__getWithoutCapture()}serialize(e="document"){const n={};for(const[r,o]of Xn(this.atoms.get())){const s=o.get();(e==="all"||this.scopedTypes[e].has(s.typeName))&&(n[r]=s)}return n}getStoreSnapshot(e="document"){return{store:this.serialize(e),schema:this.schema.serialize()}}getSnapshot(e="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(e)}migrateSnapshot(e){const n=this.schema.migrateStoreSnapshot(e);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);return{store:n.value,schema:this.schema.serialize()}}loadStoreSnapshot(e){const n=this.schema.migrateStoreSnapshot(e);if(n.type==="error")throw new Error(`Failed to migrate snapshot: ${n.reason}`);const r=this.sideEffects.isEnabled();try{this.sideEffects.setIsEnabled(!1),this.atomic(()=>{this.clear(),this.put(Object.values(n.value)),this.ensureStoreIsUsable()})}finally{this.sideEffects.setIsEnabled(r)}}loadSnapshot(e){console.warn("[tldraw] `Store.loadSnapshot` is deprecated and will be removed in a future release. Use `loadSnapshot` from the 'tldraw' package instead."),this.loadStoreSnapshot(e)}allRecords(){return ut(this.atoms.get()).map(e=>e.get())}clear(){this.remove($C(this.atoms.get()))}update(e,n){const r=this.atoms.get()[e];if(!r){console.error(`Record ${e} not found. This is probably an error`);return}this.put([n(r.__unsafe__getWithoutCapture())])}has(e){return!!this.atoms.get()[e]}listen(e,n){this._flushHistory();const r={onHistory:e,filters:{source:(n==null?void 0:n.source)??"all",scope:(n==null?void 0:n.scope)??"all"}};return this.historyReactor.scheduler.isActivelyListening||(this.historyReactor.start(),this.historyReactor.scheduler.execute()),this.listeners.add(r),()=>{this.listeners.delete(r),this.listeners.size===0&&this.historyReactor.stop()}}mergeRemoteChanges(e){if(this.isMergingRemoteChanges)return e();if(this._isInAtomicOp)throw new Error("Cannot merge remote changes while in atomic operation");try{this.isMergingRemoteChanges=!0,Oo(e)}finally{this.isMergingRemoteChanges=!1,this.ensureStoreIsUsable()}}extractingChanges(e){const n=[],r=this.historyAccumulator.addInterceptor(o=>n.push(o.changes));try{return Oo(e),Jw(n)}finally{r()}}applyDiff(e,{runCallbacks:n=!0,ignoreEphemeralKeys:r=!1}={}){this.atomic(()=>{const o=ut(e.added);for(const[i,a]of ut(e.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 u=null;for(const[h,p]of Object.entries(a))l.ephemeralKeySet.has(h)||Object.is(p,hn(c,h))||(u||(u={...c}),u[h]=p);u&&o.push(u)}else o.push(a)}const s=$C(e.removed);o.length&&this.put(o),s.length&&this.remove(s)},n)}createComputedCache(e,n,r){const o=new Ro;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=r?G(i.name+":equals",()=>i.get(),{isEqual:r}):i;return G(e+":"+s,()=>n(a.get()))}).get()}}}createSelectedComputedCache(e,n,r){const o=new Ro;return{get:s=>{const i=this.atoms.get()[s];if(i)return o.get(i,()=>{const a=G(e+":"+s+":selector",()=>n(i.get()));return G(e+":"+s,()=>r(a.get()))}).get()}}}ensureStoreIsUsable(){this.atomic(()=>{var e;this._integrityChecker??(this._integrityChecker=this.schema.createIntegrityChecker(this)),(e=this._integrityChecker)==null||e.call(this)})}markAsPossiblyCorrupted(){this._isPossiblyCorrupted=!0}isPossiblyCorrupted(){return this._isPossiblyCorrupted}addDiffForAfterEvent(e,n){if(Le(this.pendingAfterEvents,"must be in event operation"),e===n||(e&&n&&Le(e.id===n.id),!e&&!n))return;const r=(e||n).id,o=this.pendingAfterEvents.get(r);o?o.after=n:this.pendingAfterEvents.set(r,{before:e,after:n})}flushAtomicCallbacks(){let e=0;const n=this.isMergingRemoteChanges?"remote":"user";for(;this.pendingAfterEvents;){const r=this.pendingAfterEvents;if(this.pendingAfterEvents=null,!!this.sideEffects.isEnabled()){if(e++,e>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,n):o&&!s?this.sideEffects.handleAfterDelete(o,n):!o&&s&&this.sideEffects.handleAfterCreate(s,n);this.pendingAfterEvents||this.sideEffects.handleOperationComplete(n)}}}atomic(e,n=!0){return Oo(()=>{if(this._isInAtomicOp)return this.pendingAfterEvents||(this.pendingAfterEvents=new Map),e();this.pendingAfterEvents=new Map;const r=this.sideEffects.isEnabled();this.sideEffects.setIsEnabled(n??r),this._isInAtomicOp=!0;try{const o=e();return this.flushAtomicCallbacks(),o}finally{this.pendingAfterEvents=null,this.sideEffects.setIsEnabled(r),this._isInAtomicOp=!1}})}addHistoryInterceptor(e){return this.historyAccumulator.addInterceptor(n=>e(n,this.isMergingRemoteChanges?"remote":"user"))}}function GV(t){if(t.length===0)return[];const e=[];let n=[t[0]],r;for(let o=1,s=t.length;o<s;o++)r=t[o],n[0].source!==r.source&&(e.push(n),n=[]),n.push(r);return e.push(n),e.map(o=>({source:o[0].source,changes:Jw(o.map(s=>s.changes))}))}class VV{constructor(){I(this,"_history",[]);I(this,"_interceptors",new Set)}addInterceptor(e){return this._interceptors.add(e),()=>{this._interceptors.delete(e)}}add(e){this._history.push(e);for(const n of this._interceptors)n(e)}flush(){const e=GV(this._history);return this._history=[],e}clear(){this._history=[]}hasChanges(){return this._history.length>0}}function YV(t,e,n){const r=new Ro;return{get(o,s){return r.get(o,()=>(o instanceof e1?o:o.store).createComputedCache(t,l=>e(o,l),n)).get(s)}}}function XV(t){const e=[];for(let n=t.length-1;n>=0;n--){const r=t[n];if("id"in r)e.unshift(r);else{const o=r.dependsOn,s=e[0];s&&(e[0]={...s,dependsOn:o.concat(s.dependsOn??[])})}}return e}function vl({sequence:t,sequenceId:e,retroactive:n=!0}){const r={sequenceId:e,retroactive:n,sequence:XV(t)};return mA(r),r}function Zn(t,e){return Object.fromEntries(Xn(e).map(([n,r])=>[n,`${t}/${r}`]))}function xr(t){const e=t.sequenceId;return vl({sequenceId:e,retroactive:t.retroactive??!0,sequence:t.sequence.map(n=>"id"in n?{...n,scope:"record",filter:r=>{var o,s;return r.typeName===t.recordType&&(((o=n.filter)==null?void 0:o.call(n,r))??!0)&&(((s=t.filter)==null?void 0:s.call(t,r))??!0)}}:n)})}function qV(t){const e=new Map(t.map(s=>[s.id,s])),n=new Set,r=[];function o(s){Le(!n.has(s.id),`Circular dependency in migrations: ${s.id}`),n.add(s.id);const{version:i,sequenceId:a}=Pf(s.id),l=e.get(`${a}/${i-1}`);if(l&&o(l),s.dependsOn)for(const c of s.dependsOn){const u=e.get(c);u&&o(u)}e.delete(s.id),r.push(s)}for(const s of e.values())o(s);return r}function Pf(t){const[e,n]=t.split("/");return{sequenceId:e,version:parseInt(n)}}function H_(t,e){e&&Le(t.startsWith(e+"/"),`Every migration in sequence '${e}' must have an id starting with '${e}/'. Got invalid id: '${t}'`),Le(t.match(/^(.*?)\/(0|[1-9]\d*)$/),`Invalid migration id: '${t}'`)}function mA(t){if(Le(!t.sequenceId.includes("/"),`sequenceId cannot contain a '/', got ${t.sequenceId}`),Le(t.sequenceId.length,"sequenceId must be a non-empty string"),t.sequence.length===0)return;H_(t.sequence[0].id,t.sequenceId);let e=Pf(t.sequence[0].id).version;Le(e===1,`Expected the first migrationId to be '${t.sequenceId}/1' but got '${t.sequence[0].id}'`);for(let n=1;n<t.sequence.length;n++){const r=t.sequence[n].id;H_(r,t.sequenceId);const o=Pf(r).version;Le(o===e+1,`Migration id numbers must increase in increments of 1, expected ${t.sequenceId}/${e+1} but got '${t.sequence[n].id}'`),e=o}}var zs=(t=>(t.IncompatibleSubtype="incompatible-subtype",t.UnknownType="unknown-type",t.TargetVersionTooNew="target-version-too-new",t.TargetVersionTooOld="target-version-too-old",t.MigrationError="migration-error",t.UnrecognizedSubtype="unrecognized-subtype",t))(zs||{});function ZV(t){if(t.schemaVersion>2||t.schemaVersion<1)return wn.err("Bad schema version");if(t.schemaVersion===2)return wn.ok(t);const e={schemaVersion:2,sequences:{"com.tldraw.store":t.storeVersion}};for(const[n,r]of Object.entries(t.recordVersions))if(e.sequences[`com.tldraw.${n}`]=r.version,"subTypeKey"in r)for(const[o,s]of Object.entries(r.subTypeVersions))e.sequences[`com.tldraw.${n}.${o}`]=s;return wn.ok(e)}class t1{constructor(e,n){I(this,"migrations",{});I(this,"sortedMigrations");var o;this.types=e,this.options=n;for(const s of n.migrations??[])Le(!this.migrations[s.sequenceId],`Duplicate migration sequenceId ${s.sequenceId}`),mA(s),this.migrations[s.sequenceId]=s;const r=Object.values(this.migrations).flatMap(s=>s.sequence);this.sortedMigrations=qV(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);Le(a,`Migration '${s.id}' depends on missing migration '${i}'`)}}static create(e,n){return new t1(e,n??{})}validateRecord(e,n,r,o){try{const s=hn(this.types,n.typeName);if(!s)throw new Error(`Missing definition for record type ${n.typeName}`);return s.validate(n,o??void 0)}catch(s){if(this.options.onValidationFailure)return this.options.onValidationFailure({store:e,record:n,phase:r,recordBefore:o,error:s});throw s}}getMigrationsSince(e){const n=ZV(e);if(!n.ok)return n;const r=n.value,o=new Set(Object.keys(r.sequences).filter(i=>this.migrations[i]));for(const i in this.migrations)r.sequences[i]===void 0&&this.migrations[i].retroactive&&o.add(i);if(o.size===0)return wn.ok([]);const s=new Set;for(const i of o){const a=r.sequences[i];if(typeof a!="number"&&this.migrations[i].retroactive||a===0){for(const u of this.migrations[i].sequence)s.add(u.id);continue}const l=`${i}/${a}`,c=this.migrations[i].sequence.findIndex(u=>u.id===l);if(c===-1)return wn.err("Incompatible schema?");for(const u of this.migrations[i].sequence.slice(c+1))s.add(u.id)}return wn.ok(this.sortedMigrations.filter(({id:i})=>s.has(i)))}migratePersistedRecord(e,n,r="up"){const o=this.getMigrationsSince(n);if(!o.ok)return console.error("Error migrating record",o.error),{type:"error",reason:zs.MigrationError};let s=o.value;if(s.length===0)return{type:"success",value:e};if(s.some(i=>i.scope==="store"))return{type:"error",reason:r==="down"?zs.TargetVersionTooOld:zs.TargetVersionTooNew};if(r==="down"){if(!s.every(i=>i.down))return{type:"error",reason:zs.TargetVersionTooOld};s=s.slice().reverse()}e=tt(e);try{for(const i of s){if(i.scope==="store")throw new Error;if(!(i.filter?i.filter(e):!0))continue;const l=i[r](e);l&&(e=tt(l))}}catch(i){return console.error("Error migrating record",i),{type:"error",reason:zs.MigrationError}}return{type:"success",value:e}}migrateStoreSnapshot(e){let{store:n}=e;const r=this.getMigrationsSince(e.schema);if(!r.ok)return console.error("Error migrating store",r.error),{type:"error",reason:zs.MigrationError};const o=r.value;if(o.length===0)return{type:"success",value:n};n=tt(n);try{for(const s of o)if(s.scope==="record")for(const[i,a]of Object.entries(n)){if(!(s.filter?s.filter(a):!0))continue;const c=s.up(a);c&&(n[i]=tt(c))}else if(s.scope==="store"){const i=s.up(n);i&&(n=tt(i))}else Ot(s)}catch(s){return console.error("Error migrating store",s),{type:"error",reason:zs.MigrationError}}return{type:"success",value:n}}createIntegrityChecker(e){var n,r;return((r=(n=this.options).createIntegrityChecker)==null?void 0:r.call(n,e))??void 0}serialize(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e,sequence:n})=>[e,n.length?Pf(n.at(-1).id).version:0]))}}serializeEarliestVersion(){return{schemaVersion:2,sequences:Object.fromEntries(Object.values(this.migrations).map(({sequenceId:e})=>[e,0]))}}getType(e){const n=hn(this.types,e);return Le(n,"record type does not exists"),n}}Ci("@tldraw/store","3.7.0-canary.8e16c48b63b1","esm");function QV(t){if(!t.length)return null;let e="";for(const n of t)typeof n=="number"?e+=`.${n}`:n.startsWith("(")?e.endsWith(")")?e=`${e.slice(0,-1)}, ${n.slice(1)}`:e+=n:e+=`.${n}`;return e=e.replace(/id = [^,]+, /,"").replace(/id = [^)]+/,""),e.startsWith(".")?e.slice(1):e}class Me extends Error{constructor(n,r=[]){const o=QV(r),s=n.split(`
83
83
  `).map((i,a)=>a===0?i:` ${i}`).join(`
84
- `);super(r?`At ${o}: ${s}`:s);I(this,"name","ValidationError");this.rawMessage=n,this.path=r}}function qn(t,e){try{return e()}catch(n){throw n instanceof Me?new Me(n.rawMessage,[t,...n.path]):new Me(n.toString(),[t])}}function fi(t){if(t===null)return"null";if(Array.isArray(t))return"an array";const e=typeof t;switch(e){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${e}`;case"object":return`an ${e}`;case"undefined":return"undefined";default:Ot(e)}}class Tn{constructor(e,n){this.validationFn=e,this.validateUsingKnownGoodVersionFn=n}validate(e){return this.validationFn(e)}validateUsingKnownGoodVersion(e,n){return Object.is(e,n)?e:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(e,n):this.validate(n)}isValid(e){try{return this.validate(e),!0}catch{return!1}}nullable(){return oY(this)}optional(){return SA(this)}refine(e){return new Tn(n=>e(this.validate(n)),(n,r)=>{const o=this.validateUsingKnownGoodVersion(n,r);return Object.is(n,o)?n:e(o)})}check(e,n){return typeof e=="string"?this.refine(r=>(qn(`(check ${e})`,()=>n(r)),r)):this.refine(r=>(e(r),r))}}class JV extends Tn{constructor(e){super(n=>{const r=K_.validate(n);for(let o=0;o<r.length;o++)qn(o,()=>e.validate(r[o]));return r},(n,r)=>{if(!e.validateUsingKnownGoodVersion)return this.validate(r);const o=K_.validate(r);let s=n.length!==o.length;for(let i=0;i<o.length;i++){const a=o[i];if(i>=n.length){s=!0,qn(i,()=>e.validate(a));continue}if(Object.is(n[i],a))continue;const l=qn(i,()=>e.validateUsingKnownGoodVersion(n[i],a));Object.is(l,n[i])||(s=!0)}return s?r:n}),this.itemValidator=e}nonEmpty(){return this.check(e=>{if(e.length===0)throw new Me("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(e=>{if(e.length<=1)throw new Me("Expected an array with length greater than 1")})}}class Cf extends Tn{constructor(e,n=!1){super(r=>{if(typeof r!="object"||r===null)throw new Me(`Expected object, got ${fi(r)}`);for(const[o,s]of Object.entries(e))qn(o,()=>{s.validate(hn(r,o))});if(!n){for(const o of Object.keys(r))if(!no(e,o))throw new Me("Unexpected property",[o])}return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Me(`Expected object, got ${fi(o)}`);let s=!1;for(const[i,a]of Object.entries(e)){const l=hn(r,i),c=hn(o,i);if(Object.is(l,c))continue;const u=qn(i,()=>{const h=a;return h.validateUsingKnownGoodVersion?h.validateUsingKnownGoodVersion(l,c):h.validate(c)});Object.is(u,l)||(s=!0)}if(!n){for(const i of Object.keys(o))if(!no(e,i))throw new Me("Unexpected property",[i])}for(const i of Object.keys(r))if(!no(o,i)){s=!0;break}return s?o:r}),this.config=e,this.shouldAllowUnknownProperties=n}allowUnknownProperties(){return new Cf(this.config,!0)}extend(e){return new Cf({...this.config,...e})}}class Ag extends Tn{constructor(e,n,r,o){super(s=>{this.expectObject(s);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(s);return i===void 0?this.unknownValueValidation(s,a):qn(`(${e} = ${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):hn(s,e)!==hn(i,e)?qn(`(${e} = ${l})`,()=>a.validate(i)):qn(`(${e} = ${l})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(s,i):a.validate(i))}),this.key=e,this.config=n,this.unknownValueValidation=r,this.useNumberKeys=o}expectObject(e){if(typeof e!="object"||e===null)throw new Me(`Expected an object, got ${fi(e)}`,[])}getMatchingSchemaAndVariant(e){const n=hn(e,this.key);if(!this.useNumberKeys&&typeof n!="string")throw new Me(`Expected a string for key "${this.key}", got ${fi(n)}`);if(this.useNumberKeys&&!Number.isFinite(Number(n)))throw new Me(`Expected a number for key "${this.key}", got "${n}"`);return{matchingSchema:no(this.config,n)?this.config[n]:void 0,variant:n}}validateUnknownVariants(e){return new Ag(this.key,this.config,e,this.useNumberKeys)}}class eY extends Tn{constructor(e,n){super(r=>{if(typeof r!="object"||r===null)throw new Me(`Expected object, got ${fi(r)}`);for(const[o,s]of Object.entries(r))qn(o,()=>{e.validate(o),n.validate(s)});return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Me(`Expected object, got ${fi(o)}`);let s=!1;for(const[i,a]of Object.entries(o)){if(!no(r,i)){s=!0,qn(i,()=>{e.validate(i),n.validate(a)});continue}const l=hn(r,i),c=a;if(Object.is(l,c))continue;const u=qn(i,()=>n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(l,c):n.validate(c));Object.is(u,l)||(s=!0)}for(const i of Object.keys(r))if(!no(o,i)){s=!0;break}return s?o:r}),this.keyValidator=e,this.valueValidator=n}}function n1(t){return new Tn(e=>{if(typeof e!==t)throw new Me(`Expected ${t}, got ${fi(e)}`);return e})}const tY=new Tn(t=>t),ye=n1("string"),fe=n1("number").check(t=>{if(Number.isNaN(t))throw new Me("Expected a number, got NaN");if(!Number.isFinite(t))throw new Me(`Expected a finite number, got ${t}`)}),_f=fe.check(t=>{if(t<0)throw new Me(`Expected a positive number, got ${t}`)}),Ct=fe.check(t=>{if(t<=0)throw new Me(`Expected a non-zero positive number, got ${t}`)}),yA=fe.check(t=>{if(!Number.isInteger(t))throw new Me(`Expected an integer, got ${t}`)}),ip=yA.check(t=>{if(t<0)throw new Me(`Expected a positive integer, got ${t}`)}),nY=yA.check(t=>{if(t<=0)throw new Me(`Expected a non-zero positive integer, got ${t}`)}),we=n1("boolean");function mn(t){return new Tn(e=>{if(e!==t)throw new Me(`Expected ${t}, got ${JSON.stringify(e)}`);return t})}const K_=new Tn(t=>{if(!Array.isArray(t))throw new Me(`Expected an array, got ${fi(t)}`);return t});function Kt(t){return new JV(t)}function Pe(t){return new Cf(t)}function gx(t){return typeof t=="object"&&t!==null&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null||Object.getPrototypeOf(t)===g7)}function mx(t){return t===null||typeof t=="number"||typeof t=="string"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(mx):gx(t)?Object.values(t).every(mx):!1}const Wt=new Tn(t=>{if(mx(t))return t;throw new Me(`Expected json serializable value, got ${typeof t}`)},(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){let n=t.length!==e.length;for(let r=0;r<e.length;r++){if(r>=t.length){n=!0,Wt.validate(e[r]);continue}const o=t[r],s=e[r];if(Object.is(o,s))continue;const i=Wt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}return n?e:t}else if(gx(t)&&gx(e)){let n=!1;for(const r of Object.keys(e)){if(!no(t,r)){n=!0,Wt.validate(e[r]);continue}const o=t[r],s=e[r];if(Object.is(o,s))continue;const i=Wt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}for(const r of Object.keys(t))if(!no(e,r)){n=!0;break}return n?e:t}else return Wt.validate(e)});function If(t,e){return new eY(t,e)}function r1(t,e){return new Ag(t,e,(n,r)=>{throw new Me(`Expected one of ${Object.keys(e).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[t])},!1)}function rY(t,e){return new Ag(t,e,(n,r)=>{throw new Me(`Expected one of ${Object.keys(e).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[t])},!0)}function Wo(t,e){return new Tn(n=>qn(t,()=>e.validate(n)),(n,r)=>qn(t,()=>e.validateUsingKnownGoodVersion?e.validateUsingKnownGoodVersion(n,r):e.validate(r)))}function jg(t){return new Tn(e=>{if(!t.has(e)){const n=Array.from(t,r=>JSON.stringify(r)).join(" or ");throw new Me(`Expected ${n}, got ${e}`)}return e})}function SA(t){return new Tn(e=>{if(e!==void 0)return t.validate(e)},(e,n)=>{if(!(e===void 0&&n===void 0)&&n!==void 0)return t.validateUsingKnownGoodVersion&&e!==void 0?t.validateUsingKnownGoodVersion(e,n):t.validate(n)})}function oY(t){return new Tn(e=>e===null?null:t.validate(e),(e,n)=>n===null?null:t.validateUsingKnownGoodVersion&&e!==null?t.validateUsingKnownGoodVersion(e,n):t.validate(n))}function Og(...t){return jg(new Set(t))}function o1(t){try{return new URL(t)}catch{if(t.startsWith("/")||t.startsWith("./"))try{return new URL(t,"http://example.com")}catch{throw new Me(`Expected a valid url, got ${JSON.stringify(t)}`)}throw new Me(`Expected a valid url, got ${JSON.stringify(t)}`)}}const sY=new Set(["http:","https:","mailto:"]),gr=ye.check(t=>{if(t==="")return;const e=o1(t);if(!sY.has(e.protocol.toLowerCase()))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),iY=new Set(["http:","https:","data:","asset:"]),aa=ye.check(t=>{if(t==="")return;const e=o1(t);if(!iY.has(e.protocol.toLowerCase()))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)});ye.check(t=>{if(t==="")return;if(!o1(t).protocol.toLowerCase().match(/^https?:$/))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)});const s1=ye.refine(t=>{try{return s7(t),t}catch{throw new Me(`Expected an index key, got ${JSON.stringify(t)}`)}});Ci("@tldraw/validate","3.7.0-canary.383dfd14bf86","esm");function dr(t){return ye.refine(e=>{if(!e.startsWith(`${t}:`))throw new Error(`${t} ID must start with "${t}:"`);return e})}const Dg=dr("asset");function i1(t,e){return Pe({id:Dg,typeName:mn("asset"),type:mn(t),props:e,meta:Wt})}const la=Pe({x:fe,y:fe,z:fe.optional()}),uu=Pe({x:fe,y:fe,w:fe,h:fe}),vA=fe.check(t=>{if(t<0||t>1)throw new Me("Opacity must be between 0 and 1")}),aY=ye.refine(t=>{if(!t.startsWith("page:")&&!t.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return t}),Ir=dr("shape");function lY(t,e,n){return Pe({id:Ir,typeName:mn("shape"),x:fe,y:fe,rotation:fe,index:s1,parentId:aY,type:mn(t),isLocked:we,opacity:vA,props:e?Pe(e):Wt,meta:n?Pe(n):Wt})}const cY=dr("binding");function uY(t,e,n){return Pe({id:cY,typeName:mn("binding"),type:mn(t),fromId:Ir,toId:Ir,props:e?Pe(e):Wt,meta:n?Pe(n):Wt})}Zn("com.tldraw.binding",{});xr({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function Qi(t){return`binding:${ze()}`}function dY(t){return Ko("binding",{scope:"document",validator:Wo("binding",r1("type",od(t,(e,{props:n,meta:r})=>uY(e,n,r))))}).withDefaultProperties(()=>({meta:{}}))}class Zt{constructor(e,n,r){this.id=e,this.defaultValue=n,this.type=r}static define(e,n){const{defaultValue:r,type:o=tY}=n;return new Zt(e,r,o)}static defineEnum(e,n){const{defaultValue:r,values:o}=n;return new hY(e,r,o)}setDefaultValue(e){this.defaultValue=e}validate(e){return this.type.validate(e)}validateUsingKnownGoodVersion(e,n){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(e,n):this.validate(n)}}class hY extends Zt{constructor(e,n,r){super(e,n,Og(...r)),this.values=r}}const lh=Zn("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),pY=xr({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:lh.AddIsLocked,up:t=>{t.isLocked=!1},down:t=>{delete t.isLocked}},{id:lh.HoistOpacity,up:t=>{t.opacity=Number(t.props.opacity??"1"),delete t.props.opacity},down:t=>{const e=t.opacity;delete t.opacity,t.props.opacity=e<.175?"0.1":e<.375?"0.25":e<.625?"0.5":e<.875?"0.75":"1"}},{id:lh.AddMeta,up:t=>{t.meta={}}},{id:lh.AddWhite,up:t=>{},down:t=>{t.props.color==="white"&&(t.props.color="black")}}]});function al(t){return t?t.typeName==="shape":!1}function Fn(t){return t?t.startsWith("shape:"):!1}function Ke(t){return`shape:${t??ze()}`}function xA(t){const e=new Map;for(const[n,r]of Object.entries(t))if(r instanceof Zt){if(e.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);e.set(r,n)}return e}function uo(t,e){return od(e,(n,r)=>`com.tldraw.shape.${t}/${r}`)}function fY(t){return Ko("shape",{scope:"document",validator:Wo("shape",r1("type",od(t,(e,{props:n,meta:r})=>lY(e,n,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function W_(t,e){const n=[];for(const[r,{migrations:o}]of Object.entries(e)){const s=`com.tldraw.${t}.${r}`;o?"sequenceId"in o?(Le(s===o.sequenceId,`sequenceId mismatch for ${r} ${Mg} migrations. Expected '${s}', got '${o.sequenceId}'`),n.push(o)):"sequence"in o?n.push(vl({sequenceId:s,retroactive:!1,sequence:o.sequence.map(i=>"id"in i?wA(t,r,i):i)})):n.push(vl({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===t&&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}}))})):n.push(vl({sequenceId:s,retroactive:!1,sequence:[]}))}return n}function wA(t,e,n){return{id:n.id,dependsOn:n.dependsOn,scope:"record",filter:r=>r.typeName===t&&r.type===e,up:r=>{const o=n.up(r.props);o&&(r.props=o)},down:typeof n.down=="function"?r=>{const o=n.down(r.props);o&&(r.props=o)}:void 0}}const bA=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Ef={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 ks(t){return t.isDarkMode?Ef.darkMode:Ef.lightMode}const mr=Zt.defineEnum("tldraw:color",{defaultValue:"black",values:bA}),a1=Zt.defineEnum("tldraw:labelColor",{defaultValue:"black",values:bA}),ca=Zt.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),ua=Zt.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill"]}),$o=Zt.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),PA={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},Fo=Zt.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),CA=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],kf=Zt.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:CA}),Tf=Zt.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:CA}),_A={labelColor:a1,color:mr,fill:ua,dash:ca,size:Fo,arrowheadStart:kf,arrowheadEnd:Tf,font:$o,start:la,end:la,bend:fe,text:ye,labelPosition:fe,scale:Ct},Ua=uo("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5});function ch(t){return wA("shape","arrow",t)}const IA=vl({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[ch({id:Ua.AddLabelColor,up:t=>{t.labelColor="black"},down:"retired"}),ch({id:Ua.AddIsPrecise,up:({start:t,end:e})=>{t.type==="binding"&&(t.isPrecise=!(t.normalizedAnchor.x===.5&&t.normalizedAnchor.y===.5)),e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5))},down:({start:t,end:e})=>{t.type==="binding"&&(t.isPrecise||(t.normalizedAnchor={x:.5,y:.5}),delete t.isPrecise),e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise)}}),ch({id:Ua.AddLabelPosition,up:t=>{t.labelPosition=.5},down:t=>{delete t.labelPosition}}),{id:Ua.ExtractBindings,scope:"store",up:t=>{const e=Object.values(t).filter(n=>n.typeName==="shape"&&n.type==="arrow");for(const n of e){const{start:r,end:o}=n.props;if(r.type==="binding"){const s=Qi(),i={typeName:"binding",id:s,type:"arrow",fromId:n.id,toId:r.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:r.normalizedAnchor,isExact:r.isExact,isPrecise:r.isPrecise}};t[s]=i,n.props.start={x:0,y:0}}else delete n.props.start.type;if(o.type==="binding"){const s=Qi(),i={typeName:"binding",id:s,type:"arrow",fromId:n.id,toId:o.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:o.normalizedAnchor,isExact:o.isExact,isPrecise:o.isPrecise}};t[s]=i,n.props.end={x:0,y:0}}else delete n.props.end.type}}},ch({id:Ua.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}})]}),EA={terminal:Og("start","end"),normalizedAnchor:la,isExact:we,isPrecise:we},kA={sequence:[{dependsOn:[Ua.ExtractBindings]}]},gY=Wo("camera",Pe({typeName:mn("camera"),id:dr("camera"),x:fe,y:fe,z:fe,meta:Wt})),mY=Zn("com.tldraw.camera",{AddMeta:1}),yY=xr({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:mY.AddMeta,up:t=>{t.meta={}}}]}),Eo=Ko("camera",{validator:gY,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),SY=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"]),TA=jg(SY),vY=Pe({type:TA,rotation:fe}),xY=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),wY=jg(xY),bY=new Set(["starting","paused","active","stopping"]),MA=Pe({id:ye,points:Kt(la),size:_f,color:wY,opacity:fe,state:jg(bY),delay:fe,shrink:fe,taper:we}),zu=dr("page"),PY=Wo("page",Pe({typeName:mn("page"),id:zu,name:ye,index:s1,meta:Wt})),CY=Zn("com.tldraw.page",{AddMeta:1}),_Y=xr({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:CY.AddMeta,up:t=>{t.meta={}}}]}),yr=Ko("page",{validator:PY,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function Rn(t){return yr.isId(t)}const IY={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};function AA(t){return t?lu(t,e=>IY[e]):null}dr("instance");function EY(t){const e={};for(const[r,o]of t)e[r]=SA(o);const n=Wo("instance",Pe({typeName:mn("instance"),id:dr("instance"),currentPageId:zu,followingUserId:ye.nullable(),brush:uu.nullable(),opacityForNextShape:vA,stylesForNextShape:Pe(e),cursor:vY,scribbles:Kt(MA),isFocusMode:we,isDebugMode:we,isToolLocked:we,exportBackground:we,screenBounds:uu,insets:Kt(we),zoomBrush:uu.nullable(),isPenMode:we,isGridMode:we,chatMessage:ye,isChatting:we,highlightedUserIds:Kt(ye),isFocused:we,devicePixelRatio:fe,isCoarsePointer:we,isHoveringCanvas:we.nullable(),openMenus:Kt(ye),isChangingStyle:we,isReadonly:we,meta:Wt,duplicateProps:Pe({shapeIds:Kt(dr("shape")),offset:Pe({x:fe,y:fe})}).nullable()}));return Ko("instance",{validator:n,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 Je=Zn("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}),kY=xr({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:Je.AddTransparentExportBgs,up:t=>({...t,exportBackground:!0})},{id:Je.RemoveDialog,up:({dialog:t,...e})=>e},{id:Je.AddToolLockMode,up:t=>({...t,isToolLocked:!1})},{id:Je.RemoveExtraPropsForNextShape,up:({propsForNextShape:t,...e})=>({...e,propsForNextShape:Object.fromEntries(Object.entries(t).filter(([n])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(n)))})},{id:Je.AddLabelColor,up:({propsForNextShape:t,...e})=>({...e,propsForNextShape:{...t,labelColor:"black"}})},{id:Je.AddFollowingUserId,up:t=>({...t,followingUserId:null})},{id:Je.RemoveAlignJustify,up:t=>{let e=t.propsForNextShape.align;return e==="justify"&&(e="start"),{...t,propsForNextShape:{...t.propsForNextShape,align:e}}}},{id:Je.AddZoom,up:t=>({...t,zoomBrush:null})},{id:Je.AddVerticalAlign,up:t=>({...t,propsForNextShape:{...t.propsForNextShape,verticalAlign:"middle"}})},{id:Je.AddScribbleDelay,up:t=>t.scribble!==null?{...t,scribble:{...t.scribble,delay:0}}:{...t}},{id:Je.RemoveUserId,up:({userId:t,...e})=>e},{id:Je.AddIsPenModeAndIsGridMode,up:t=>({...t,isPenMode:!1,isGridMode:!1})},{id:Je.HoistOpacity,up:({propsForNextShape:{opacity:t,...e},...n})=>({...n,opacityForNextShape:Number(t??"1"),propsForNextShape:e})},{id:Je.AddChat,up:t=>({...t,chatMessage:"",isChatting:!1})},{id:Je.AddHighlightedUserIds,up:t=>({...t,highlightedUserIds:[]})},{id:Je.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:t,...e})=>({...e,stylesForNextShape:{}})},{id:Je.AddMeta,up:t=>({...t,meta:{}})},{id:Je.RemoveCursorColor,up:t=>{const{color:e,...n}=t.cursor;return{...t,cursor:n}}},{id:Je.AddLonelyProperties,up:t=>({...t,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:Je.ReadOnlyReadonly,up:({isReadOnly:t,...e})=>({...e,isReadonly:t})},{id:Je.AddHoveringCanvas,up:t=>({...t,isHoveringCanvas:null})},{id:Je.AddScribbles,up:({scribble:t,...e})=>({...e,scribbles:[]})},{id:Je.AddInset,up:t=>({...t,insets:[!1,!1,!1,!1]}),down:({insets:t,...e})=>({...e})},{id:Je.AddDuplicateProps,up:t=>({...t,duplicateProps:null}),down:({duplicateProps:t,...e})=>({...e})},{id:Je.RemoveCanMoveCamera,up:({canMoveCamera:t,...e})=>({...e}),down:t=>({...t,canMoveCamera:!0})}]}),bn="instance:instance",TY=Wo("instance_page_state",Pe({typeName:mn("instance_page_state"),id:dr("instance_page_state"),pageId:zu,selectedShapeIds:Kt(Ir),hintingShapeIds:Kt(Ir),erasingShapeIds:Kt(Ir),hoveredShapeId:Ir.nullable(),editingShapeId:Ir.nullable(),croppingShapeId:Ir.nullable(),focusedGroupId:Ir.nullable(),meta:Wt})),Ic=Zn("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),MY=xr({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:Ic.AddCroppingId,up(t){t.croppingShapeId=null}},{id:Ic.RemoveInstanceIdAndCameraId,up(t){delete t.instanceId,delete t.cameraId}},{id:Ic.AddMeta,up:t=>{t.meta={}}},{id:Ic.RenameProperties,up:t=>{},down:t=>{}},{id:Ic.RenamePropertiesAgain,up:t=>{t.selectedShapeIds=t.selectedIds,delete t.selectedIds,t.hintingShapeIds=t.hintingIds,delete t.hintingIds,t.erasingShapeIds=t.erasingIds,delete t.erasingIds,t.hoveredShapeId=t.hoveredId,delete t.hoveredId,t.editingShapeId=t.editingId,delete t.editingId,t.croppingShapeId=t.croppingShapeId??t.croppingId??null,delete t.croppingId,t.focusedGroupId=t.focusLayerId,delete t.focusLayerId},down:t=>{t.selectedIds=t.selectedShapeIds,delete t.selectedShapeIds,t.hintingIds=t.hintingShapeIds,delete t.hintingShapeIds,t.erasingIds=t.erasingShapeIds,delete t.erasingShapeIds,t.hoveredId=t.hoveredShapeId,delete t.hoveredShapeId,t.editingId=t.editingShapeId,delete t.editingShapeId,t.croppingId=t.croppingShapeId,delete t.croppingShapeId,t.focusLayerId=t.focusedGroupId,delete t.focusedGroupId}}]}),Qr=Ko("instance_page_state",{validator:TY,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:{}})),AY=Wo("pointer",Pe({typeName:mn("pointer"),id:dr("pointer"),x:fe,y:fe,lastActivityTimestamp:fe,meta:Wt})),jY=Zn("com.tldraw.pointer",{AddMeta:1}),OY=xr({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:jY.AddMeta,up:t=>{t.meta={}}}]}),l1=Ko("pointer",{validator:AY,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),Mf=l1.createId("pointer"),DY=Wo("instance_presence",Pe({typeName:mn("instance_presence"),id:dr("instance_presence"),userId:ye,userName:ye,lastActivityTimestamp:fe.nullable(),followingUserId:ye.nullable(),cursor:Pe({x:fe,y:fe,type:TA,rotation:fe}).nullable(),color:ye,camera:Pe({x:fe,y:fe,z:fe}).nullable(),screenBounds:uu.nullable(),selectedShapeIds:Kt(dr("shape")),currentPageId:dr("page"),brush:uu.nullable(),scribbles:Kt(MA),chatMessage:ye,meta:Wt})),ja=Zn("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),RY=xr({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:ja.AddScribbleDelay,up:t=>{t.scribble!==null&&(t.scribble.delay=0)}},{id:ja.RemoveInstanceId,up:t=>{delete t.instanceId}},{id:ja.AddChatMessage,up:t=>{t.chatMessage=""}},{id:ja.AddMeta,up:t=>{t.meta={}}},{id:ja.RenameSelectedShapeIds,up:t=>{}},{id:ja.NullableCameraCursor,up:t=>{},down:t=>{t.camera===null&&(t.camera={x:0,y:0,z:1}),t.lastActivityTimestamp===null&&(t.lastActivityTimestamp=0),t.cursor===null&&(t.cursor={type:"default",x:0,y:0,rotation:0}),t.screenBounds===null&&(t.screenBounds={x:0,y:0,w:1,h:1})}}]}),LY=Ko("instance_presence",{validator:DY,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}})),$Y=Wo("document",Pe({typeName:mn("document"),id:mn("document:document"),gridSize:fe,name:ye,meta:Wt})),G_=Zn("com.tldraw.document",{AddName:1,AddMeta:2}),FY=xr({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:G_.AddName,up:t=>{t.name=""},down:t=>{delete t.name}},{id:G_.AddMeta,up:t=>{t.meta={}}}]}),c1=Ko("document",{validator:$Y,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),yx=c1.createId("document");function NY(t,e){return t.index<e.index?-1:t.index>e.index?1:0}function V_(t){t.typeName==="asset"&&("src"in t&&(t.src="<redacted>"),"src"in t.props&&(t.props.src="<redacted>"))}function zY({error:t,phase:e,record:n,recordBefore:r}){throw vw(t,{tags:{origin:"store.validateRecord",storePhase:e,isExistingValidationIssue:e==="initialize"},extras:{recordBefore:r?V_(tt(r)):void 0,recordAfter:V_(tt(n))}}),t}function BY(){return[yr.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function UY(t){const e=t.query.ids("page"),n=t.query.records("instance_page_state"),r=()=>{if(!t.has(yx))return t.put([c1.create({id:yx,name:t.props.defaultName})]),r();if(!t.has(Mf))return t.put([l1.create({id:Mf})]),r();const o=e.get();if(o.size===0)return t.put(BY()),r();const s=()=>[...o].map(u=>t.get(u)).sort(NY)[0].id,i=t.get(bn);if(i){if(!o.has(i.currentPageId))return t.put([{...i,currentPageId:s()}]),r()}else return t.put([t.schema.types.instance.create({id:bn,currentPageId:s(),exportBackground:!0})]),r();const a=new Set,l=new Set;for(const u of o){const h=Qr.createId(u);t.get(h)||a.add(h);const f=Eo.createId(u);t.has(f)||l.add(f)}a.size>0&&t.put([...a].map(u=>Qr.create({id:u,pageId:Qr.parseId(u)}))),l.size>0&&t.put([...l].map(u=>Eo.create({id:u})));const c=n.get();for(const u of c){if(!o.has(u.pageId)){t.remove([u.id]);continue}if(u.croppingShapeId&&!t.has(u.croppingShapeId))return t.put([{...u,croppingShapeId:null}]),r();if(u.focusedGroupId&&!t.has(u.focusedGroupId))return t.put([{...u,focusedGroupId:null}]),r();if(u.hoveredShapeId&&!t.has(u.hoveredShapeId))return t.put([{...u,hoveredShapeId:null}]),r();const h=u.selectedShapeIds.filter(g=>t.has(g));if(h.length!==u.selectedShapeIds.length)return t.put([{...u,selectedShapeIds:h}]),r();const p=u.hintingShapeIds.filter(g=>t.has(g));if(p.length!==u.hintingShapeIds.length)return t.put([{...u,hintingShapeIds:p}]),r();const f=u.erasingShapeIds.filter(g=>t.has(g));if(f.length!==u.erasingShapeIds.length)return t.put([{...u,erasingShapeIds:f}]),r()}};return r}const HY=i1("bookmark",Pe({title:ye,description:ye,image:ye,favicon:ye,src:aa.nullable()})),Y_=Zn("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),KY=xr({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:t=>t.type==="bookmark",sequence:[{id:Y_.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:Y_.AddFavicon,up:t=>{aa.isValid(t.props.favicon)||(t.props.favicon="")},down:t=>{delete t.props.favicon}}]}),WY=i1("image",Pe({w:fe,h:fe,name:ye,isAnimated:we,mimeType:ye.nullable(),src:aa.nullable(),fileSize:Ct.optional()})),Ec=Zn("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),GY=xr({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:t=>t.type==="image",sequence:[{id:Ec.AddIsAnimated,up:t=>{t.props.isAnimated=!1},down:t=>{delete t.props.isAnimated}},{id:Ec.RenameWidthHeight,up:t=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:t=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:Ec.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:Ec.AddFileSize,up:t=>{t.props.fileSize=-1},down:t=>{delete t.props.fileSize}},{id:Ec.MakeFileSizeOptional,up:t=>{t.props.fileSize===-1&&(t.props.fileSize=void 0)},down:t=>{t.props.fileSize===void 0&&(t.props.fileSize=-1)}}]}),VY=i1("video",Pe({w:fe,h:fe,name:ye,isAnimated:we,mimeType:ye.nullable(),src:aa.nullable(),fileSize:fe.optional()})),kc=Zn("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),YY=xr({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:t=>t.type==="video",sequence:[{id:kc.AddIsAnimated,up:t=>{t.props.isAnimated=!1},down:t=>{delete t.props.isAnimated}},{id:kc.RenameWidthHeight,up:t=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:t=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:kc.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:kc.AddFileSize,up:t=>{t.props.fileSize=-1},down:t=>{delete t.props.fileSize}},{id:kc.MakeFileSizeOptional,up:t=>{t.props.fileSize===-1&&(t.props.fileSize=void 0)},down:t=>{t.props.fileSize===void 0&&(t.props.fileSize=-1)}}]}),XY=Wo("asset",r1("type",{image:WY,video:VY,bookmark:HY})),qY=Zn("com.tldraw.asset",{AddMeta:1}),ZY=xr({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:qY.AddMeta,up:t=>{t.meta={}}}]}),Vs=Ko("asset",{validator:XY,scope:"document"}).withDefaultProperties(()=>({meta:{}})),jA={w:Ct,h:Ct,assetId:Dg.nullable(),url:gr},X_=uo("bookmark",{NullAssetId:1,MakeUrlsValid:2}),OA={sequence:[{id:X_.NullAssetId,up:t=>{t.assetId===void 0&&(t.assetId=null)},down:"retired"},{id:X_.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}}]},DA=Pe({type:Og("free","straight"),points:Kt(la)}),RA={color:mr,fill:ua,dash:ca,size:Fo,segments:Kt(DA),isComplete:we,isClosed:we,isPen:we,scale:Ct},q_=uo("draw",{AddInPen:1,AddScale:2}),LA={sequence:[{id:q_.AddInPen,up:t=>{const{points:e}=t.segments[0];if(e.length===0){t.isPen=!1;return}let n=!(e[0].z===0||e[0].z===.5);e[1]&&(n=n&&!(e[1].z===0||e[1].z===.5)),t.isPen=n},down:"retired"},{id:q_.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},QY=/(^\/r\/[^/]+\/?$)/,JY=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(QY))return t}},{hostnames:["figma.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/?$/)){const n=e.searchParams.get("url");if(n)return n}}},{hostnames:["google.*"],fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom"),[o,s]=e.searchParams.get("center").split(",");return`https://www.google.com/maps/@${o},${s},${r}z`}}},{hostnames:["val.town"],fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(n)return`https://www.val.town/v/${n[1]}`}},{hostnames:["codesandbox.io"],fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://codesandbox.io/s/${n[1]}`}},{hostnames:["codepen.io"],fromEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/pen/${s}`}}},{hostnames:["scratch.mit.edu"],fromEmbedUrl:t=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/${o}`}}},{hostnames:["*.youtube.com","youtube.com","youtu.be"],fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{hostnames:["calendar.google.*"],fromEmbedUrl:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&n){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("cid",n),e.href}}},{hostnames:["docs.google.*"],fromEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}}},{hostnames:["gist.github.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0}},{hostnames:["replit.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{hostnames:["felt.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{hostnames:["open.spotify.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{hostnames:["vimeo.com","player.vimeo.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="player.vimeo.com"){const n=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(n)return"https://vimeo.com/"+n[1]}}},{hostnames:["excalidraw.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t}},{hostnames:["observablehq.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{hostnames:["desmos.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return t.replace("?embed","")}}],$A={w:Ct,h:Ct,url:ye},uh=uo("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),FA={sequence:[{id:uh.GenOriginalUrlInEmbed,up:t=>{try{const e=t.url,n=new URL(e).host.replace("www.","");let r;for(const o of JY)if(o.hostnames.includes(n))try{r=o.fromEmbedUrl(e)}catch(s){console.warn(s)}t.tmpOldUrl=t.url,t.url=r??""}catch{t.url="",t.tmpOldUrl=t.url}},down:"retired"},{id:uh.RemoveDoesResize,up:t=>{delete t.doesResize},down:"retired"},{id:uh.RemoveTmpOldUrl,up:t=>{delete t.tmpOldUrl},down:"retired"},{id:uh.RemovePermissionOverrides,up:t=>{delete t.overridePermissions},down:"retired"}]},NA={w:Ct,h:Ct,name:ye},zA={sequence:[]},Af=Zt.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),jf=Zt.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),Jr=Zt.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"]}),BA={geo:Jr,labelColor:a1,color:mr,fill:ua,dash:ca,size:Fo,font:$o,align:Af,verticalAlign:jf,url:gr,w:Ct,h:Ct,growY:_f,text:ye,scale:Ct},Jo=uo("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9}),UA={sequence:[{id:Jo.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:Jo.AddLabelColor,up:t=>{t.labelColor="black"},down:"retired"},{id:Jo.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:Jo.AddCheckBox,up:t=>{},down:"retired"},{id:Jo.AddVerticalAlign,up:t=>{t.verticalAlign="middle"},down:"retired"},{id:Jo.MigrateLegacyAlign,up:t=>{let e;switch(t.align){case"start":e="start-legacy";break;case"end":e="end-legacy";break;default:e="middle-legacy";break}t.align=e},down:"retired"},{id:Jo.AddCloud,up:t=>{},down:"retired"},{id:Jo.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:Jo.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},HA={},KA={sequence:[]},WA={color:mr,size:Fo,segments:Kt(DA),isComplete:we,isPen:we,scale:Ct},eX=uo("highlight",{AddScale:1}),GA={sequence:[{id:eX.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},tX=Pe({topLeft:la,bottomRight:la}),VA={w:Ct,h:Ct,playing:we,url:gr,assetId:Dg.nullable(),crop:tX.nullable(),flipX:we,flipY:we},dh=uo("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4}),YA={sequence:[{id:dh.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:dh.AddCropProp,up:t=>{t.crop=null},down:t=>{delete t.crop}},{id:dh.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:dh.AddFlipProps,up:t=>{t.flipX=!1,t.flipY=!1},down:t=>{delete t.flipX,delete t.flipY}}]},Of=Zt.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),nX=Pe({id:ye,index:s1,x:fe,y:fe}),XA={color:mr,dash:ca,size:Fo,spline:Of,points:If(ye,nX),scale:Ct},Tc=uo("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),qA={sequence:[{id:Tc.AddSnapHandles,up:t=>{for(const e of Object.values(t.handles))e.canSnap=!0},down:"retired"},{id:Tc.RemoveExtraHandleProps,up:t=>{t.handles=ww(Object.values(t.handles).map(e=>[e.index,{x:e.x,y:e.y}]))},down:t=>{const e=Object.entries(t.handles).map(([n,r])=>({index:n,...r})).sort(cn);t.handles=Object.fromEntries(e.map((n,r)=>{const o=r===0?"start":r===e.length-1?"end":`handle:${n.index}`;return[o,{id:o,type:"vertex",canBind:!1,canSnap:!0,index:n.index,x:n.x,y:n.y}]}))}},{id:Tc.HandlesToPoints,up:t=>{const e=Object.entries(t.handles).map(([n,{x:r,y:o}])=>({x:r,y:o,index:n})).sort(cn);t.points=e.map(({x:n,y:r})=>({x:n,y:r})),delete t.handles},down:t=>{const e=Fu(t.points.length);t.handles=Object.fromEntries(t.points.map((n,r)=>[e[r],{x:n.x,y:n.y}])),delete t.points}},{id:Tc.PointIndexIds,up:t=>{const e=Fu(t.points.length);t.points=Object.fromEntries(t.points.map((n,r)=>{const o=e[r];return[o,{id:o,index:o,x:n.x,y:n.y}]}))},down:t=>{const e=Object.values(t.points).sort(cn);t.points=e.map(({x:n,y:r})=>({x:n,y:r}))}},{id:Tc.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},ZA={color:mr,labelColor:a1,size:Fo,font:$o,fontSizeAdjustment:_f,align:Af,verticalAlign:jf,growY:_f,url:gr,text:ye,scale:Ct},$s=uo("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7,AddLabelColor:8}),QA={sequence:[{id:$s.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:$s.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:$s.MigrateLegacyAlign,up:t=>{switch(t.align){case"start":t.align="start-legacy";return;case"end":t.align="end-legacy";return;default:t.align="middle-legacy";return}},down:"retired"},{id:$s.AddVerticalAlign,up:t=>{t.verticalAlign="middle"},down:"retired"},{id:$s.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:$s.AddFontSizeAdjustment,up:t=>{t.fontSizeAdjustment=0},down:t=>{delete t.fontSizeAdjustment}},{id:$s.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}},{id:$s.AddLabelColor,up:t=>{t.labelColor="black"},down:t=>{delete t.labelColor}}]},Sx=Zt.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]}),JA={color:mr,size:Fo,font:$o,textAlign:Sx,w:Ct,text:ye,scale:Ct,autoSize:we},Z_=uo("text",{RemoveJustify:1,AddTextAlign:2}),ej={sequence:[{id:Z_.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:Z_.AddTextAlign,up:t=>{t.textAlign=t.align,delete t.align},down:t=>{t.align=t.textAlign,delete t.textAlign}}]},tj={w:Ct,h:Ct,time:fe,playing:we,url:gr,assetId:Dg.nullable()},Q_=uo("video",{AddUrlProp:1,MakeUrlsValid:2}),nj={sequence:[{id:Q_.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:Q_.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}}]},hh=Zn("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4}),rX=vl({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:hh.RemoveCodeAndIconShapeTypes,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName==="shape"&&(n.type==="icon"||n.type==="code")&&delete t[e]}},{id:hh.AddInstancePresenceType,scope:"store",up(t){}},{id:hh.RemoveTLUserAndPresenceAndAddPointer,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName.match(/^(user|user_presence)$/)&&delete t[e]}},{id:hh.RemoveUserDocument,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName.match("user_document")&&delete t[e]}}]}),oX={arrow:{migrations:IA,props:_A},bookmark:{migrations:OA,props:jA},draw:{migrations:LA,props:RA},embed:{migrations:FA,props:$A},frame:{migrations:zA,props:NA},geo:{migrations:UA,props:BA},group:{migrations:KA,props:HA},highlight:{migrations:GA,props:WA},image:{migrations:YA,props:VA},line:{migrations:qA,props:XA},note:{migrations:QA,props:ZA},text:{migrations:ej,props:JA},video:{migrations:nj,props:tj}},sX={arrow:{migrations:kA,props:EA}};function iX({shapes:t=oX,bindings:e=sX,migrations:n}={}){const r=new Map;for(const a of ut(t))for(const l of xA(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=fY(t),s=dY(e),i=EY(r);return t1.create({asset:Vs,binding:s,camera:Eo,document:c1,instance:i,instance_page_state:Qr,page:yr,instance_presence:LY,pointer:l1,shape:o},{migrations:[rX,ZY,yY,FY,kY,MY,_Y,RY,OY,pY,KY,GY,YY,...W_("shape",t),...W_("binding",e),...n??[]],onValidationFailure:zY,createIntegrityChecker:UY})}const Bu=[{locale:"id",label:"Bahasa Indonesia"},{locale:"ca",label:"Català"},{locale:"cs",label:"Čeština"},{locale:"da",label:"Danish"},{locale:"de",label:"Deutsch"},{locale:"en",label:"English"},{locale:"es",label:"Español"},{locale:"fr",label:"Français"},{locale:"gl",label:"Galego"},{locale:"hr",label:"Hrvatski"},{locale:"it",label:"Italiano"},{locale:"hu",label:"Magyar"},{locale:"no",label:"Norwegian"},{locale:"pl",label:"Polski"},{locale:"pt-br",label:"Português - Brasil"},{locale:"pt-pt",label:"Português - Europeu"},{locale:"ro",label:"Română"},{locale:"ru",label:"Russian"},{locale:"sl",label:"Slovenščina"},{locale:"so",label:"Somali"},{locale:"fi",label:"Suomi"},{locale:"sv",label:"Svenska"},{locale:"vi",label:"Tiếng Việt"},{locale:"tr",label:"Türkçe"},{locale:"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 aX(){const t=typeof window<"u"?window.navigator.languages??["en"]:["en"];return lX(t)}function lX(t){for(const e of t){const n=cX(e);if(n)return n}return"en"}const J_={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function cX(t){const e=Bu.find(o=>o.locale===t.toLowerCase());if(e)return e.locale;const[n,r]=t.split(/[-_]/).map(o=>o.toLowerCase());if(r){const o=Bu.find(s=>s.locale===n);if(o)return o.locale}return n in J_?J_[n]:null}Ci("@tldraw/tlschema","3.7.0-canary.383dfd14bf86","esm");var rj={exports:{}};/*!
84
+ `);super(r?`At ${o}: ${s}`:s);I(this,"name","ValidationError");this.rawMessage=n,this.path=r}}function qn(t,e){try{return e()}catch(n){throw n instanceof Me?new Me(n.rawMessage,[t,...n.path]):new Me(n.toString(),[t])}}function fi(t){if(t===null)return"null";if(Array.isArray(t))return"an array";const e=typeof t;switch(e){case"bigint":case"boolean":case"function":case"number":case"string":case"symbol":return`a ${e}`;case"object":return`an ${e}`;case"undefined":return"undefined";default:Ot(e)}}class Tn{constructor(e,n){this.validationFn=e,this.validateUsingKnownGoodVersionFn=n}validate(e){return this.validationFn(e)}validateUsingKnownGoodVersion(e,n){return Object.is(e,n)?e:this.validateUsingKnownGoodVersionFn?this.validateUsingKnownGoodVersionFn(e,n):this.validate(n)}isValid(e){try{return this.validate(e),!0}catch{return!1}}nullable(){return oY(this)}optional(){return SA(this)}refine(e){return new Tn(n=>e(this.validate(n)),(n,r)=>{const o=this.validateUsingKnownGoodVersion(n,r);return Object.is(n,o)?n:e(o)})}check(e,n){return typeof e=="string"?this.refine(r=>(qn(`(check ${e})`,()=>n(r)),r)):this.refine(r=>(e(r),r))}}class JV extends Tn{constructor(e){super(n=>{const r=K_.validate(n);for(let o=0;o<r.length;o++)qn(o,()=>e.validate(r[o]));return r},(n,r)=>{if(!e.validateUsingKnownGoodVersion)return this.validate(r);const o=K_.validate(r);let s=n.length!==o.length;for(let i=0;i<o.length;i++){const a=o[i];if(i>=n.length){s=!0,qn(i,()=>e.validate(a));continue}if(Object.is(n[i],a))continue;const l=qn(i,()=>e.validateUsingKnownGoodVersion(n[i],a));Object.is(l,n[i])||(s=!0)}return s?r:n}),this.itemValidator=e}nonEmpty(){return this.check(e=>{if(e.length===0)throw new Me("Expected a non-empty array")})}lengthGreaterThan1(){return this.check(e=>{if(e.length<=1)throw new Me("Expected an array with length greater than 1")})}}class Cf extends Tn{constructor(e,n=!1){super(r=>{if(typeof r!="object"||r===null)throw new Me(`Expected object, got ${fi(r)}`);for(const[o,s]of Object.entries(e))qn(o,()=>{s.validate(hn(r,o))});if(!n){for(const o of Object.keys(r))if(!no(e,o))throw new Me("Unexpected property",[o])}return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Me(`Expected object, got ${fi(o)}`);let s=!1;for(const[i,a]of Object.entries(e)){const l=hn(r,i),c=hn(o,i);if(Object.is(l,c))continue;const u=qn(i,()=>{const h=a;return h.validateUsingKnownGoodVersion?h.validateUsingKnownGoodVersion(l,c):h.validate(c)});Object.is(u,l)||(s=!0)}if(!n){for(const i of Object.keys(o))if(!no(e,i))throw new Me("Unexpected property",[i])}for(const i of Object.keys(r))if(!no(o,i)){s=!0;break}return s?o:r}),this.config=e,this.shouldAllowUnknownProperties=n}allowUnknownProperties(){return new Cf(this.config,!0)}extend(e){return new Cf({...this.config,...e})}}class Ag extends Tn{constructor(e,n,r,o){super(s=>{this.expectObject(s);const{matchingSchema:i,variant:a}=this.getMatchingSchemaAndVariant(s);return i===void 0?this.unknownValueValidation(s,a):qn(`(${e} = ${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):hn(s,e)!==hn(i,e)?qn(`(${e} = ${l})`,()=>a.validate(i)):qn(`(${e} = ${l})`,()=>a.validateUsingKnownGoodVersion?a.validateUsingKnownGoodVersion(s,i):a.validate(i))}),this.key=e,this.config=n,this.unknownValueValidation=r,this.useNumberKeys=o}expectObject(e){if(typeof e!="object"||e===null)throw new Me(`Expected an object, got ${fi(e)}`,[])}getMatchingSchemaAndVariant(e){const n=hn(e,this.key);if(!this.useNumberKeys&&typeof n!="string")throw new Me(`Expected a string for key "${this.key}", got ${fi(n)}`);if(this.useNumberKeys&&!Number.isFinite(Number(n)))throw new Me(`Expected a number for key "${this.key}", got "${n}"`);return{matchingSchema:no(this.config,n)?this.config[n]:void 0,variant:n}}validateUnknownVariants(e){return new Ag(this.key,this.config,e,this.useNumberKeys)}}class eY extends Tn{constructor(e,n){super(r=>{if(typeof r!="object"||r===null)throw new Me(`Expected object, got ${fi(r)}`);for(const[o,s]of Object.entries(r))qn(o,()=>{e.validate(o),n.validate(s)});return r},(r,o)=>{if(typeof o!="object"||o===null)throw new Me(`Expected object, got ${fi(o)}`);let s=!1;for(const[i,a]of Object.entries(o)){if(!no(r,i)){s=!0,qn(i,()=>{e.validate(i),n.validate(a)});continue}const l=hn(r,i),c=a;if(Object.is(l,c))continue;const u=qn(i,()=>n.validateUsingKnownGoodVersion?n.validateUsingKnownGoodVersion(l,c):n.validate(c));Object.is(u,l)||(s=!0)}for(const i of Object.keys(r))if(!no(o,i)){s=!0;break}return s?o:r}),this.keyValidator=e,this.valueValidator=n}}function n1(t){return new Tn(e=>{if(typeof e!==t)throw new Me(`Expected ${t}, got ${fi(e)}`);return e})}const tY=new Tn(t=>t),ye=n1("string"),fe=n1("number").check(t=>{if(Number.isNaN(t))throw new Me("Expected a number, got NaN");if(!Number.isFinite(t))throw new Me(`Expected a finite number, got ${t}`)}),_f=fe.check(t=>{if(t<0)throw new Me(`Expected a positive number, got ${t}`)}),Ct=fe.check(t=>{if(t<=0)throw new Me(`Expected a non-zero positive number, got ${t}`)}),yA=fe.check(t=>{if(!Number.isInteger(t))throw new Me(`Expected an integer, got ${t}`)}),ip=yA.check(t=>{if(t<0)throw new Me(`Expected a positive integer, got ${t}`)}),nY=yA.check(t=>{if(t<=0)throw new Me(`Expected a non-zero positive integer, got ${t}`)}),we=n1("boolean");function mn(t){return new Tn(e=>{if(e!==t)throw new Me(`Expected ${t}, got ${JSON.stringify(e)}`);return t})}const K_=new Tn(t=>{if(!Array.isArray(t))throw new Me(`Expected an array, got ${fi(t)}`);return t});function Kt(t){return new JV(t)}function Pe(t){return new Cf(t)}function gx(t){return typeof t=="object"&&t!==null&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null||Object.getPrototypeOf(t)===gB)}function mx(t){return t===null||typeof t=="number"||typeof t=="string"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(mx):gx(t)?Object.values(t).every(mx):!1}const Wt=new Tn(t=>{if(mx(t))return t;throw new Me(`Expected json serializable value, got ${typeof t}`)},(t,e)=>{if(Array.isArray(t)&&Array.isArray(e)){let n=t.length!==e.length;for(let r=0;r<e.length;r++){if(r>=t.length){n=!0,Wt.validate(e[r]);continue}const o=t[r],s=e[r];if(Object.is(o,s))continue;const i=Wt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}return n?e:t}else if(gx(t)&&gx(e)){let n=!1;for(const r of Object.keys(e)){if(!no(t,r)){n=!0,Wt.validate(e[r]);continue}const o=t[r],s=e[r];if(Object.is(o,s))continue;const i=Wt.validateUsingKnownGoodVersion(o,s);Object.is(i,o)||(n=!0)}for(const r of Object.keys(t))if(!no(e,r)){n=!0;break}return n?e:t}else return Wt.validate(e)});function If(t,e){return new eY(t,e)}function r1(t,e){return new Ag(t,e,(n,r)=>{throw new Me(`Expected one of ${Object.keys(e).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[t])},!1)}function rY(t,e){return new Ag(t,e,(n,r)=>{throw new Me(`Expected one of ${Object.keys(e).map(o=>JSON.stringify(o)).join(" or ")}, got ${JSON.stringify(r)}`,[t])},!0)}function Wo(t,e){return new Tn(n=>qn(t,()=>e.validate(n)),(n,r)=>qn(t,()=>e.validateUsingKnownGoodVersion?e.validateUsingKnownGoodVersion(n,r):e.validate(r)))}function jg(t){return new Tn(e=>{if(!t.has(e)){const n=Array.from(t,r=>JSON.stringify(r)).join(" or ");throw new Me(`Expected ${n}, got ${e}`)}return e})}function SA(t){return new Tn(e=>{if(e!==void 0)return t.validate(e)},(e,n)=>{if(!(e===void 0&&n===void 0)&&n!==void 0)return t.validateUsingKnownGoodVersion&&e!==void 0?t.validateUsingKnownGoodVersion(e,n):t.validate(n)})}function oY(t){return new Tn(e=>e===null?null:t.validate(e),(e,n)=>n===null?null:t.validateUsingKnownGoodVersion&&e!==null?t.validateUsingKnownGoodVersion(e,n):t.validate(n))}function Og(...t){return jg(new Set(t))}function o1(t){try{return new URL(t)}catch{if(t.startsWith("/")||t.startsWith("./"))try{return new URL(t,"http://example.com")}catch{throw new Me(`Expected a valid url, got ${JSON.stringify(t)}`)}throw new Me(`Expected a valid url, got ${JSON.stringify(t)}`)}}const sY=new Set(["http:","https:","mailto:"]),gr=ye.check(t=>{if(t==="")return;const e=o1(t);if(!sY.has(e.protocol.toLowerCase()))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)}),iY=new Set(["http:","https:","data:","asset:"]),aa=ye.check(t=>{if(t==="")return;const e=o1(t);if(!iY.has(e.protocol.toLowerCase()))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)});ye.check(t=>{if(t==="")return;if(!o1(t).protocol.toLowerCase().match(/^https?:$/))throw new Me(`Expected a valid url, got ${JSON.stringify(t)} (invalid protocol)`)});const s1=ye.refine(t=>{try{return sB(t),t}catch{throw new Me(`Expected an index key, got ${JSON.stringify(t)}`)}});Ci("@tldraw/validate","3.7.0-canary.8e16c48b63b1","esm");function dr(t){return ye.refine(e=>{if(!e.startsWith(`${t}:`))throw new Error(`${t} ID must start with "${t}:"`);return e})}const Dg=dr("asset");function i1(t,e){return Pe({id:Dg,typeName:mn("asset"),type:mn(t),props:e,meta:Wt})}const la=Pe({x:fe,y:fe,z:fe.optional()}),uu=Pe({x:fe,y:fe,w:fe,h:fe}),vA=fe.check(t=>{if(t<0||t>1)throw new Me("Opacity must be between 0 and 1")}),aY=ye.refine(t=>{if(!t.startsWith("page:")&&!t.startsWith("shape:"))throw new Error('Parent ID must start with "page:" or "shape:"');return t}),Ir=dr("shape");function lY(t,e,n){return Pe({id:Ir,typeName:mn("shape"),x:fe,y:fe,rotation:fe,index:s1,parentId:aY,type:mn(t),isLocked:we,opacity:vA,props:e?Pe(e):Wt,meta:n?Pe(n):Wt})}const cY=dr("binding");function uY(t,e,n){return Pe({id:cY,typeName:mn("binding"),type:mn(t),fromId:Ir,toId:Ir,props:e?Pe(e):Wt,meta:n?Pe(n):Wt})}Zn("com.tldraw.binding",{});xr({sequenceId:"com.tldraw.binding",recordType:"binding",sequence:[]});function Qi(t){return`binding:${ze()}`}function dY(t){return Ko("binding",{scope:"document",validator:Wo("binding",r1("type",od(t,(e,{props:n,meta:r})=>uY(e,n,r))))}).withDefaultProperties(()=>({meta:{}}))}class Zt{constructor(e,n,r){this.id=e,this.defaultValue=n,this.type=r}static define(e,n){const{defaultValue:r,type:o=tY}=n;return new Zt(e,r,o)}static defineEnum(e,n){const{defaultValue:r,values:o}=n;return new hY(e,r,o)}setDefaultValue(e){this.defaultValue=e}validate(e){return this.type.validate(e)}validateUsingKnownGoodVersion(e,n){return this.type.validateUsingKnownGoodVersion?this.type.validateUsingKnownGoodVersion(e,n):this.validate(n)}}class hY extends Zt{constructor(e,n,r){super(e,n,Og(...r)),this.values=r}}const lh=Zn("com.tldraw.shape",{AddIsLocked:1,HoistOpacity:2,AddMeta:3,AddWhite:4}),pY=xr({sequenceId:"com.tldraw.shape",recordType:"shape",sequence:[{id:lh.AddIsLocked,up:t=>{t.isLocked=!1},down:t=>{delete t.isLocked}},{id:lh.HoistOpacity,up:t=>{t.opacity=Number(t.props.opacity??"1"),delete t.props.opacity},down:t=>{const e=t.opacity;delete t.opacity,t.props.opacity=e<.175?"0.1":e<.375?"0.25":e<.625?"0.5":e<.875?"0.75":"1"}},{id:lh.AddMeta,up:t=>{t.meta={}}},{id:lh.AddWhite,up:t=>{},down:t=>{t.props.color==="white"&&(t.props.color="black")}}]});function al(t){return t?t.typeName==="shape":!1}function Fn(t){return t?t.startsWith("shape:"):!1}function Ke(t){return`shape:${t??ze()}`}function xA(t){const e=new Map;for(const[n,r]of Object.entries(t))if(r instanceof Zt){if(e.has(r))throw new Error(`Duplicate style prop ${r.id}. Each style prop can only be used once within a shape.`);e.set(r,n)}return e}function uo(t,e){return od(e,(n,r)=>`com.tldraw.shape.${t}/${r}`)}function fY(t){return Ko("shape",{scope:"document",validator:Wo("shape",r1("type",od(t,(e,{props:n,meta:r})=>lY(e,n,r))))}).withDefaultProperties(()=>({x:0,y:0,rotation:0,isLocked:!1,opacity:1,meta:{}}))}function W_(t,e){const n=[];for(const[r,{migrations:o}]of Object.entries(e)){const s=`com.tldraw.${t}.${r}`;o?"sequenceId"in o?(Le(s===o.sequenceId,`sequenceId mismatch for ${r} ${Mg} migrations. Expected '${s}', got '${o.sequenceId}'`),n.push(o)):"sequence"in o?n.push(vl({sequenceId:s,retroactive:!1,sequence:o.sequence.map(i=>"id"in i?wA(t,r,i):i)})):n.push(vl({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===t&&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}}))})):n.push(vl({sequenceId:s,retroactive:!1,sequence:[]}))}return n}function wA(t,e,n){return{id:n.id,dependsOn:n.dependsOn,scope:"record",filter:r=>r.typeName===t&&r.type===e,up:r=>{const o=n.up(r.props);o&&(r.props=o)},down:typeof n.down=="function"?r=>{const o=n.down(r.props);o&&(r.props=o)}:void 0}}const bA=["black","grey","light-violet","violet","blue","light-blue","yellow","orange","green","light-green","light-red","red","white"],Ef={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 ks(t){return t.isDarkMode?Ef.darkMode:Ef.lightMode}const mr=Zt.defineEnum("tldraw:color",{defaultValue:"black",values:bA}),a1=Zt.defineEnum("tldraw:labelColor",{defaultValue:"black",values:bA}),ca=Zt.defineEnum("tldraw:dash",{defaultValue:"draw",values:["draw","solid","dashed","dotted"]}),ua=Zt.defineEnum("tldraw:fill",{defaultValue:"none",values:["none","semi","solid","pattern","fill"]}),$o=Zt.defineEnum("tldraw:font",{defaultValue:"draw",values:["draw","sans","serif","mono"]}),PA={draw:"'tldraw_draw', sans-serif",sans:"'tldraw_sans', sans-serif",serif:"'tldraw_serif', serif",mono:"'tldraw_mono', monospace"},Fo=Zt.defineEnum("tldraw:size",{defaultValue:"m",values:["s","m","l","xl"]}),CA=["arrow","triangle","square","dot","pipe","diamond","inverted","bar","none"],kf=Zt.defineEnum("tldraw:arrowheadStart",{defaultValue:"none",values:CA}),Tf=Zt.defineEnum("tldraw:arrowheadEnd",{defaultValue:"arrow",values:CA}),_A={labelColor:a1,color:mr,fill:ua,dash:ca,size:Fo,arrowheadStart:kf,arrowheadEnd:Tf,font:$o,start:la,end:la,bend:fe,text:ye,labelPosition:fe,scale:Ct},Ua=uo("arrow",{AddLabelColor:1,AddIsPrecise:2,AddLabelPosition:3,ExtractBindings:4,AddScale:5});function ch(t){return wA("shape","arrow",t)}const IA=vl({sequenceId:"com.tldraw.shape.arrow",retroactive:!1,sequence:[ch({id:Ua.AddLabelColor,up:t=>{t.labelColor="black"},down:"retired"}),ch({id:Ua.AddIsPrecise,up:({start:t,end:e})=>{t.type==="binding"&&(t.isPrecise=!(t.normalizedAnchor.x===.5&&t.normalizedAnchor.y===.5)),e.type==="binding"&&(e.isPrecise=!(e.normalizedAnchor.x===.5&&e.normalizedAnchor.y===.5))},down:({start:t,end:e})=>{t.type==="binding"&&(t.isPrecise||(t.normalizedAnchor={x:.5,y:.5}),delete t.isPrecise),e.type==="binding"&&(e.isPrecise||(e.normalizedAnchor={x:.5,y:.5}),delete e.isPrecise)}}),ch({id:Ua.AddLabelPosition,up:t=>{t.labelPosition=.5},down:t=>{delete t.labelPosition}}),{id:Ua.ExtractBindings,scope:"store",up:t=>{const e=Object.values(t).filter(n=>n.typeName==="shape"&&n.type==="arrow");for(const n of e){const{start:r,end:o}=n.props;if(r.type==="binding"){const s=Qi(),i={typeName:"binding",id:s,type:"arrow",fromId:n.id,toId:r.boundShapeId,meta:{},props:{terminal:"start",normalizedAnchor:r.normalizedAnchor,isExact:r.isExact,isPrecise:r.isPrecise}};t[s]=i,n.props.start={x:0,y:0}}else delete n.props.start.type;if(o.type==="binding"){const s=Qi(),i={typeName:"binding",id:s,type:"arrow",fromId:n.id,toId:o.boundShapeId,meta:{},props:{terminal:"end",normalizedAnchor:o.normalizedAnchor,isExact:o.isExact,isPrecise:o.isPrecise}};t[s]=i,n.props.end={x:0,y:0}}else delete n.props.end.type}}},ch({id:Ua.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}})]}),EA={terminal:Og("start","end"),normalizedAnchor:la,isExact:we,isPrecise:we},kA={sequence:[{dependsOn:[Ua.ExtractBindings]}]},gY=Wo("camera",Pe({typeName:mn("camera"),id:dr("camera"),x:fe,y:fe,z:fe,meta:Wt})),mY=Zn("com.tldraw.camera",{AddMeta:1}),yY=xr({sequenceId:"com.tldraw.camera",recordType:"camera",sequence:[{id:mY.AddMeta,up:t=>{t.meta={}}}]}),Eo=Ko("camera",{validator:gY,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,z:1,meta:{}})),SY=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"]),TA=jg(SY),vY=Pe({type:TA,rotation:fe}),xY=new Set(["accent","white","black","selection-stroke","selection-fill","laser","muted-1"]),wY=jg(xY),bY=new Set(["starting","paused","active","stopping"]),MA=Pe({id:ye,points:Kt(la),size:_f,color:wY,opacity:fe,state:jg(bY),delay:fe,shrink:fe,taper:we}),zu=dr("page"),PY=Wo("page",Pe({typeName:mn("page"),id:zu,name:ye,index:s1,meta:Wt})),CY=Zn("com.tldraw.page",{AddMeta:1}),_Y=xr({sequenceId:"com.tldraw.page",recordType:"page",sequence:[{id:CY.AddMeta,up:t=>{t.meta={}}}]}),yr=Ko("page",{validator:PY,scope:"document"}).withDefaultProperties(()=>({meta:{}}));function Rn(t){return yr.isId(t)}const IY={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};function AA(t){return t?lu(t,e=>IY[e]):null}dr("instance");function EY(t){const e={};for(const[r,o]of t)e[r]=SA(o);const n=Wo("instance",Pe({typeName:mn("instance"),id:dr("instance"),currentPageId:zu,followingUserId:ye.nullable(),brush:uu.nullable(),opacityForNextShape:vA,stylesForNextShape:Pe(e),cursor:vY,scribbles:Kt(MA),isFocusMode:we,isDebugMode:we,isToolLocked:we,exportBackground:we,screenBounds:uu,insets:Kt(we),zoomBrush:uu.nullable(),isPenMode:we,isGridMode:we,chatMessage:ye,isChatting:we,highlightedUserIds:Kt(ye),isFocused:we,devicePixelRatio:fe,isCoarsePointer:we,isHoveringCanvas:we.nullable(),openMenus:Kt(ye),isChangingStyle:we,isReadonly:we,meta:Wt,duplicateProps:Pe({shapeIds:Kt(dr("shape")),offset:Pe({x:fe,y:fe})}).nullable()}));return Ko("instance",{validator:n,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 Je=Zn("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}),kY=xr({sequenceId:"com.tldraw.instance",recordType:"instance",sequence:[{id:Je.AddTransparentExportBgs,up:t=>({...t,exportBackground:!0})},{id:Je.RemoveDialog,up:({dialog:t,...e})=>e},{id:Je.AddToolLockMode,up:t=>({...t,isToolLocked:!1})},{id:Je.RemoveExtraPropsForNextShape,up:({propsForNextShape:t,...e})=>({...e,propsForNextShape:Object.fromEntries(Object.entries(t).filter(([n])=>["color","labelColor","dash","fill","size","font","align","verticalAlign","icon","geo","arrowheadStart","arrowheadEnd","spline"].includes(n)))})},{id:Je.AddLabelColor,up:({propsForNextShape:t,...e})=>({...e,propsForNextShape:{...t,labelColor:"black"}})},{id:Je.AddFollowingUserId,up:t=>({...t,followingUserId:null})},{id:Je.RemoveAlignJustify,up:t=>{let e=t.propsForNextShape.align;return e==="justify"&&(e="start"),{...t,propsForNextShape:{...t.propsForNextShape,align:e}}}},{id:Je.AddZoom,up:t=>({...t,zoomBrush:null})},{id:Je.AddVerticalAlign,up:t=>({...t,propsForNextShape:{...t.propsForNextShape,verticalAlign:"middle"}})},{id:Je.AddScribbleDelay,up:t=>t.scribble!==null?{...t,scribble:{...t.scribble,delay:0}}:{...t}},{id:Je.RemoveUserId,up:({userId:t,...e})=>e},{id:Je.AddIsPenModeAndIsGridMode,up:t=>({...t,isPenMode:!1,isGridMode:!1})},{id:Je.HoistOpacity,up:({propsForNextShape:{opacity:t,...e},...n})=>({...n,opacityForNextShape:Number(t??"1"),propsForNextShape:e})},{id:Je.AddChat,up:t=>({...t,chatMessage:"",isChatting:!1})},{id:Je.AddHighlightedUserIds,up:t=>({...t,highlightedUserIds:[]})},{id:Je.ReplacePropsForNextShapeWithStylesForNextShape,up:({propsForNextShape:t,...e})=>({...e,stylesForNextShape:{}})},{id:Je.AddMeta,up:t=>({...t,meta:{}})},{id:Je.RemoveCursorColor,up:t=>{const{color:e,...n}=t.cursor;return{...t,cursor:n}}},{id:Je.AddLonelyProperties,up:t=>({...t,canMoveCamera:!0,isFocused:!1,devicePixelRatio:1,isCoarsePointer:!1,openMenus:[],isChangingStyle:!1,isReadOnly:!1})},{id:Je.ReadOnlyReadonly,up:({isReadOnly:t,...e})=>({...e,isReadonly:t})},{id:Je.AddHoveringCanvas,up:t=>({...t,isHoveringCanvas:null})},{id:Je.AddScribbles,up:({scribble:t,...e})=>({...e,scribbles:[]})},{id:Je.AddInset,up:t=>({...t,insets:[!1,!1,!1,!1]}),down:({insets:t,...e})=>({...e})},{id:Je.AddDuplicateProps,up:t=>({...t,duplicateProps:null}),down:({duplicateProps:t,...e})=>({...e})},{id:Je.RemoveCanMoveCamera,up:({canMoveCamera:t,...e})=>({...e}),down:t=>({...t,canMoveCamera:!0})}]}),bn="instance:instance",TY=Wo("instance_page_state",Pe({typeName:mn("instance_page_state"),id:dr("instance_page_state"),pageId:zu,selectedShapeIds:Kt(Ir),hintingShapeIds:Kt(Ir),erasingShapeIds:Kt(Ir),hoveredShapeId:Ir.nullable(),editingShapeId:Ir.nullable(),croppingShapeId:Ir.nullable(),focusedGroupId:Ir.nullable(),meta:Wt})),Ic=Zn("com.tldraw.instance_page_state",{AddCroppingId:1,RemoveInstanceIdAndCameraId:2,AddMeta:3,RenameProperties:4,RenamePropertiesAgain:5}),MY=xr({sequenceId:"com.tldraw.instance_page_state",recordType:"instance_page_state",sequence:[{id:Ic.AddCroppingId,up(t){t.croppingShapeId=null}},{id:Ic.RemoveInstanceIdAndCameraId,up(t){delete t.instanceId,delete t.cameraId}},{id:Ic.AddMeta,up:t=>{t.meta={}}},{id:Ic.RenameProperties,up:t=>{},down:t=>{}},{id:Ic.RenamePropertiesAgain,up:t=>{t.selectedShapeIds=t.selectedIds,delete t.selectedIds,t.hintingShapeIds=t.hintingIds,delete t.hintingIds,t.erasingShapeIds=t.erasingIds,delete t.erasingIds,t.hoveredShapeId=t.hoveredId,delete t.hoveredId,t.editingShapeId=t.editingId,delete t.editingId,t.croppingShapeId=t.croppingShapeId??t.croppingId??null,delete t.croppingId,t.focusedGroupId=t.focusLayerId,delete t.focusLayerId},down:t=>{t.selectedIds=t.selectedShapeIds,delete t.selectedShapeIds,t.hintingIds=t.hintingShapeIds,delete t.hintingShapeIds,t.erasingIds=t.erasingShapeIds,delete t.erasingShapeIds,t.hoveredId=t.hoveredShapeId,delete t.hoveredShapeId,t.editingId=t.editingShapeId,delete t.editingShapeId,t.croppingId=t.croppingShapeId,delete t.croppingShapeId,t.focusLayerId=t.focusedGroupId,delete t.focusedGroupId}}]}),Qr=Ko("instance_page_state",{validator:TY,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:{}})),AY=Wo("pointer",Pe({typeName:mn("pointer"),id:dr("pointer"),x:fe,y:fe,lastActivityTimestamp:fe,meta:Wt})),jY=Zn("com.tldraw.pointer",{AddMeta:1}),OY=xr({sequenceId:"com.tldraw.pointer",recordType:"pointer",sequence:[{id:jY.AddMeta,up:t=>{t.meta={}}}]}),l1=Ko("pointer",{validator:AY,scope:"session"}).withDefaultProperties(()=>({x:0,y:0,lastActivityTimestamp:0,meta:{}})),Mf=l1.createId("pointer"),DY=Wo("instance_presence",Pe({typeName:mn("instance_presence"),id:dr("instance_presence"),userId:ye,userName:ye,lastActivityTimestamp:fe.nullable(),followingUserId:ye.nullable(),cursor:Pe({x:fe,y:fe,type:TA,rotation:fe}).nullable(),color:ye,camera:Pe({x:fe,y:fe,z:fe}).nullable(),screenBounds:uu.nullable(),selectedShapeIds:Kt(dr("shape")),currentPageId:dr("page"),brush:uu.nullable(),scribbles:Kt(MA),chatMessage:ye,meta:Wt})),ja=Zn("com.tldraw.instance_presence",{AddScribbleDelay:1,RemoveInstanceId:2,AddChatMessage:3,AddMeta:4,RenameSelectedShapeIds:5,NullableCameraCursor:6}),RY=xr({sequenceId:"com.tldraw.instance_presence",recordType:"instance_presence",sequence:[{id:ja.AddScribbleDelay,up:t=>{t.scribble!==null&&(t.scribble.delay=0)}},{id:ja.RemoveInstanceId,up:t=>{delete t.instanceId}},{id:ja.AddChatMessage,up:t=>{t.chatMessage=""}},{id:ja.AddMeta,up:t=>{t.meta={}}},{id:ja.RenameSelectedShapeIds,up:t=>{}},{id:ja.NullableCameraCursor,up:t=>{},down:t=>{t.camera===null&&(t.camera={x:0,y:0,z:1}),t.lastActivityTimestamp===null&&(t.lastActivityTimestamp=0),t.cursor===null&&(t.cursor={type:"default",x:0,y:0,rotation:0}),t.screenBounds===null&&(t.screenBounds={x:0,y:0,w:1,h:1})}}]}),LY=Ko("instance_presence",{validator:DY,scope:"presence"}).withDefaultProperties(()=>({lastActivityTimestamp:null,followingUserId:null,color:"#FF0000",camera:null,cursor:null,screenBounds:null,selectedShapeIds:[],brush:null,scribbles:[],chatMessage:"",meta:{}})),$Y=Wo("document",Pe({typeName:mn("document"),id:mn("document:document"),gridSize:fe,name:ye,meta:Wt})),G_=Zn("com.tldraw.document",{AddName:1,AddMeta:2}),FY=xr({sequenceId:"com.tldraw.document",recordType:"document",sequence:[{id:G_.AddName,up:t=>{t.name=""},down:t=>{delete t.name}},{id:G_.AddMeta,up:t=>{t.meta={}}}]}),c1=Ko("document",{validator:$Y,scope:"document"}).withDefaultProperties(()=>({gridSize:10,name:"",meta:{}})),yx=c1.createId("document");function NY(t,e){return t.index<e.index?-1:t.index>e.index?1:0}function V_(t){t.typeName==="asset"&&("src"in t&&(t.src="<redacted>"),"src"in t.props&&(t.props.src="<redacted>"))}function zY({error:t,phase:e,record:n,recordBefore:r}){throw vw(t,{tags:{origin:"store.validateRecord",storePhase:e,isExistingValidationIssue:e==="initialize"},extras:{recordBefore:r?V_(tt(r)):void 0,recordAfter:V_(tt(n))}}),t}function BY(){return[yr.create({id:"page:page",name:"Page 1",index:"a1",meta:{}})]}function UY(t){const e=t.query.ids("page"),n=t.query.records("instance_page_state"),r=()=>{if(!t.has(yx))return t.put([c1.create({id:yx,name:t.props.defaultName})]),r();if(!t.has(Mf))return t.put([l1.create({id:Mf})]),r();const o=e.get();if(o.size===0)return t.put(BY()),r();const s=()=>[...o].map(u=>t.get(u)).sort(NY)[0].id,i=t.get(bn);if(i){if(!o.has(i.currentPageId))return t.put([{...i,currentPageId:s()}]),r()}else return t.put([t.schema.types.instance.create({id:bn,currentPageId:s(),exportBackground:!0})]),r();const a=new Set,l=new Set;for(const u of o){const h=Qr.createId(u);t.get(h)||a.add(h);const f=Eo.createId(u);t.has(f)||l.add(f)}a.size>0&&t.put([...a].map(u=>Qr.create({id:u,pageId:Qr.parseId(u)}))),l.size>0&&t.put([...l].map(u=>Eo.create({id:u})));const c=n.get();for(const u of c){if(!o.has(u.pageId)){t.remove([u.id]);continue}if(u.croppingShapeId&&!t.has(u.croppingShapeId))return t.put([{...u,croppingShapeId:null}]),r();if(u.focusedGroupId&&!t.has(u.focusedGroupId))return t.put([{...u,focusedGroupId:null}]),r();if(u.hoveredShapeId&&!t.has(u.hoveredShapeId))return t.put([{...u,hoveredShapeId:null}]),r();const h=u.selectedShapeIds.filter(g=>t.has(g));if(h.length!==u.selectedShapeIds.length)return t.put([{...u,selectedShapeIds:h}]),r();const p=u.hintingShapeIds.filter(g=>t.has(g));if(p.length!==u.hintingShapeIds.length)return t.put([{...u,hintingShapeIds:p}]),r();const f=u.erasingShapeIds.filter(g=>t.has(g));if(f.length!==u.erasingShapeIds.length)return t.put([{...u,erasingShapeIds:f}]),r()}};return r}const HY=i1("bookmark",Pe({title:ye,description:ye,image:ye,favicon:ye,src:aa.nullable()})),Y_=Zn("com.tldraw.asset.bookmark",{MakeUrlsValid:1,AddFavicon:2}),KY=xr({sequenceId:"com.tldraw.asset.bookmark",recordType:"asset",filter:t=>t.type==="bookmark",sequence:[{id:Y_.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:Y_.AddFavicon,up:t=>{aa.isValid(t.props.favicon)||(t.props.favicon="")},down:t=>{delete t.props.favicon}}]}),WY=i1("image",Pe({w:fe,h:fe,name:ye,isAnimated:we,mimeType:ye.nullable(),src:aa.nullable(),fileSize:Ct.optional()})),Ec=Zn("com.tldraw.asset.image",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),GY=xr({sequenceId:"com.tldraw.asset.image",recordType:"asset",filter:t=>t.type==="image",sequence:[{id:Ec.AddIsAnimated,up:t=>{t.props.isAnimated=!1},down:t=>{delete t.props.isAnimated}},{id:Ec.RenameWidthHeight,up:t=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:t=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:Ec.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:Ec.AddFileSize,up:t=>{t.props.fileSize=-1},down:t=>{delete t.props.fileSize}},{id:Ec.MakeFileSizeOptional,up:t=>{t.props.fileSize===-1&&(t.props.fileSize=void 0)},down:t=>{t.props.fileSize===void 0&&(t.props.fileSize=-1)}}]}),VY=i1("video",Pe({w:fe,h:fe,name:ye,isAnimated:we,mimeType:ye.nullable(),src:aa.nullable(),fileSize:fe.optional()})),kc=Zn("com.tldraw.asset.video",{AddIsAnimated:1,RenameWidthHeight:2,MakeUrlsValid:3,AddFileSize:4,MakeFileSizeOptional:5}),YY=xr({sequenceId:"com.tldraw.asset.video",recordType:"asset",filter:t=>t.type==="video",sequence:[{id:kc.AddIsAnimated,up:t=>{t.props.isAnimated=!1},down:t=>{delete t.props.isAnimated}},{id:kc.RenameWidthHeight,up:t=>{t.props.w=t.props.width,t.props.h=t.props.height,delete t.props.width,delete t.props.height},down:t=>{t.props.width=t.props.w,t.props.height=t.props.h,delete t.props.w,delete t.props.h}},{id:kc.MakeUrlsValid,up:t=>{aa.isValid(t.props.src)||(t.props.src="")},down:t=>{}},{id:kc.AddFileSize,up:t=>{t.props.fileSize=-1},down:t=>{delete t.props.fileSize}},{id:kc.MakeFileSizeOptional,up:t=>{t.props.fileSize===-1&&(t.props.fileSize=void 0)},down:t=>{t.props.fileSize===void 0&&(t.props.fileSize=-1)}}]}),XY=Wo("asset",r1("type",{image:WY,video:VY,bookmark:HY})),qY=Zn("com.tldraw.asset",{AddMeta:1}),ZY=xr({sequenceId:"com.tldraw.asset",recordType:"asset",sequence:[{id:qY.AddMeta,up:t=>{t.meta={}}}]}),Vs=Ko("asset",{validator:XY,scope:"document"}).withDefaultProperties(()=>({meta:{}})),jA={w:Ct,h:Ct,assetId:Dg.nullable(),url:gr},X_=uo("bookmark",{NullAssetId:1,MakeUrlsValid:2}),OA={sequence:[{id:X_.NullAssetId,up:t=>{t.assetId===void 0&&(t.assetId=null)},down:"retired"},{id:X_.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}}]},DA=Pe({type:Og("free","straight"),points:Kt(la)}),RA={color:mr,fill:ua,dash:ca,size:Fo,segments:Kt(DA),isComplete:we,isClosed:we,isPen:we,scale:Ct},q_=uo("draw",{AddInPen:1,AddScale:2}),LA={sequence:[{id:q_.AddInPen,up:t=>{const{points:e}=t.segments[0];if(e.length===0){t.isPen=!1;return}let n=!(e[0].z===0||e[0].z===.5);e[1]&&(n=n&&!(e[1].z===0||e[1].z===.5)),t.isPen=n},down:"retired"},{id:q_.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},QY=/(^\/r\/[^/]+\/?$)/,JY=[{hostnames:["beta.tldraw.com","tldraw.com","localhost:3000"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(QY))return t}},{hostnames:["figma.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/?$/)){const n=e.searchParams.get("url");if(n)return n}}},{hostnames:["google.*"],fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom"),[o,s]=e.searchParams.get("center").split(",");return`https://www.google.com/maps/@${o},${s},${r}z`}}},{hostnames:["val.town"],fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(n)return`https://www.val.town/v/${n[1]}`}},{hostnames:["codesandbox.io"],fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://codesandbox.io/s/${n[1]}`}},{hostnames:["codepen.io"],fromEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/pen/${s}`}}},{hostnames:["scratch.mit.edu"],fromEmbedUrl:t=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/${o}`}}},{hostnames:["*.youtube.com","youtube.com","youtu.be"],fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{hostnames:["calendar.google.*"],fromEmbedUrl:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&n){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("cid",n),e.href}}},{hostnames:["docs.google.*"],fromEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}}},{hostnames:["gist.github.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0}},{hostnames:["replit.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{hostnames:["felt.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{hostnames:["open.spotify.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{hostnames:["vimeo.com","player.vimeo.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="player.vimeo.com"){const n=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(n)return"https://vimeo.com/"+n[1]}}},{hostnames:["excalidraw.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t}},{hostnames:["observablehq.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{hostnames:["desmos.com"],fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return t.replace("?embed","")}}],$A={w:Ct,h:Ct,url:ye},uh=uo("embed",{GenOriginalUrlInEmbed:1,RemoveDoesResize:2,RemoveTmpOldUrl:3,RemovePermissionOverrides:4}),FA={sequence:[{id:uh.GenOriginalUrlInEmbed,up:t=>{try{const e=t.url,n=new URL(e).host.replace("www.","");let r;for(const o of JY)if(o.hostnames.includes(n))try{r=o.fromEmbedUrl(e)}catch(s){console.warn(s)}t.tmpOldUrl=t.url,t.url=r??""}catch{t.url="",t.tmpOldUrl=t.url}},down:"retired"},{id:uh.RemoveDoesResize,up:t=>{delete t.doesResize},down:"retired"},{id:uh.RemoveTmpOldUrl,up:t=>{delete t.tmpOldUrl},down:"retired"},{id:uh.RemovePermissionOverrides,up:t=>{delete t.overridePermissions},down:"retired"}]},NA={w:Ct,h:Ct,name:ye},zA={sequence:[]},Af=Zt.defineEnum("tldraw:horizontalAlign",{defaultValue:"middle",values:["start","middle","end","start-legacy","end-legacy","middle-legacy"]}),jf=Zt.defineEnum("tldraw:verticalAlign",{defaultValue:"middle",values:["start","middle","end"]}),Jr=Zt.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"]}),BA={geo:Jr,labelColor:a1,color:mr,fill:ua,dash:ca,size:Fo,font:$o,align:Af,verticalAlign:jf,url:gr,w:Ct,h:Ct,growY:_f,text:ye,scale:Ct},Jo=uo("geo",{AddUrlProp:1,AddLabelColor:2,RemoveJustify:3,AddCheckBox:4,AddVerticalAlign:5,MigrateLegacyAlign:6,AddCloud:7,MakeUrlsValid:8,AddScale:9}),UA={sequence:[{id:Jo.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:Jo.AddLabelColor,up:t=>{t.labelColor="black"},down:"retired"},{id:Jo.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:Jo.AddCheckBox,up:t=>{},down:"retired"},{id:Jo.AddVerticalAlign,up:t=>{t.verticalAlign="middle"},down:"retired"},{id:Jo.MigrateLegacyAlign,up:t=>{let e;switch(t.align){case"start":e="start-legacy";break;case"end":e="end-legacy";break;default:e="middle-legacy";break}t.align=e},down:"retired"},{id:Jo.AddCloud,up:t=>{},down:"retired"},{id:Jo.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:Jo.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},HA={},KA={sequence:[]},WA={color:mr,size:Fo,segments:Kt(DA),isComplete:we,isPen:we,scale:Ct},eX=uo("highlight",{AddScale:1}),GA={sequence:[{id:eX.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},tX=Pe({topLeft:la,bottomRight:la}),VA={w:Ct,h:Ct,playing:we,url:gr,assetId:Dg.nullable(),crop:tX.nullable(),flipX:we,flipY:we},dh=uo("image",{AddUrlProp:1,AddCropProp:2,MakeUrlsValid:3,AddFlipProps:4}),YA={sequence:[{id:dh.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:dh.AddCropProp,up:t=>{t.crop=null},down:t=>{delete t.crop}},{id:dh.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:dh.AddFlipProps,up:t=>{t.flipX=!1,t.flipY=!1},down:t=>{delete t.flipX,delete t.flipY}}]},Of=Zt.defineEnum("tldraw:spline",{defaultValue:"line",values:["cubic","line"]}),nX=Pe({id:ye,index:s1,x:fe,y:fe}),XA={color:mr,dash:ca,size:Fo,spline:Of,points:If(ye,nX),scale:Ct},Tc=uo("line",{AddSnapHandles:1,RemoveExtraHandleProps:2,HandlesToPoints:3,PointIndexIds:4,AddScale:5}),qA={sequence:[{id:Tc.AddSnapHandles,up:t=>{for(const e of Object.values(t.handles))e.canSnap=!0},down:"retired"},{id:Tc.RemoveExtraHandleProps,up:t=>{t.handles=ww(Object.values(t.handles).map(e=>[e.index,{x:e.x,y:e.y}]))},down:t=>{const e=Object.entries(t.handles).map(([n,r])=>({index:n,...r})).sort(cn);t.handles=Object.fromEntries(e.map((n,r)=>{const o=r===0?"start":r===e.length-1?"end":`handle:${n.index}`;return[o,{id:o,type:"vertex",canBind:!1,canSnap:!0,index:n.index,x:n.x,y:n.y}]}))}},{id:Tc.HandlesToPoints,up:t=>{const e=Object.entries(t.handles).map(([n,{x:r,y:o}])=>({x:r,y:o,index:n})).sort(cn);t.points=e.map(({x:n,y:r})=>({x:n,y:r})),delete t.handles},down:t=>{const e=Fu(t.points.length);t.handles=Object.fromEntries(t.points.map((n,r)=>[e[r],{x:n.x,y:n.y}])),delete t.points}},{id:Tc.PointIndexIds,up:t=>{const e=Fu(t.points.length);t.points=Object.fromEntries(t.points.map((n,r)=>{const o=e[r];return[o,{id:o,index:o,x:n.x,y:n.y}]}))},down:t=>{const e=Object.values(t.points).sort(cn);t.points=e.map(({x:n,y:r})=>({x:n,y:r}))}},{id:Tc.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}}]},ZA={color:mr,labelColor:a1,size:Fo,font:$o,fontSizeAdjustment:_f,align:Af,verticalAlign:jf,growY:_f,url:gr,text:ye,scale:Ct},$s=uo("note",{AddUrlProp:1,RemoveJustify:2,MigrateLegacyAlign:3,AddVerticalAlign:4,MakeUrlsValid:5,AddFontSizeAdjustment:6,AddScale:7,AddLabelColor:8}),QA={sequence:[{id:$s.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:$s.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:$s.MigrateLegacyAlign,up:t=>{switch(t.align){case"start":t.align="start-legacy";return;case"end":t.align="end-legacy";return;default:t.align="middle-legacy";return}},down:"retired"},{id:$s.AddVerticalAlign,up:t=>{t.verticalAlign="middle"},down:"retired"},{id:$s.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}},{id:$s.AddFontSizeAdjustment,up:t=>{t.fontSizeAdjustment=0},down:t=>{delete t.fontSizeAdjustment}},{id:$s.AddScale,up:t=>{t.scale=1},down:t=>{delete t.scale}},{id:$s.AddLabelColor,up:t=>{t.labelColor="black"},down:t=>{delete t.labelColor}}]},Sx=Zt.defineEnum("tldraw:textAlign",{defaultValue:"start",values:["start","middle","end"]}),JA={color:mr,size:Fo,font:$o,textAlign:Sx,w:Ct,text:ye,scale:Ct,autoSize:we},Z_=uo("text",{RemoveJustify:1,AddTextAlign:2}),ej={sequence:[{id:Z_.RemoveJustify,up:t=>{t.align==="justify"&&(t.align="start")},down:"retired"},{id:Z_.AddTextAlign,up:t=>{t.textAlign=t.align,delete t.align},down:t=>{t.align=t.textAlign,delete t.textAlign}}]},tj={w:Ct,h:Ct,time:fe,playing:we,url:gr,assetId:Dg.nullable()},Q_=uo("video",{AddUrlProp:1,MakeUrlsValid:2}),nj={sequence:[{id:Q_.AddUrlProp,up:t=>{t.url=""},down:"retired"},{id:Q_.MakeUrlsValid,up:t=>{gr.isValid(t.url)||(t.url="")},down:t=>{}}]},hh=Zn("com.tldraw.store",{RemoveCodeAndIconShapeTypes:1,AddInstancePresenceType:2,RemoveTLUserAndPresenceAndAddPointer:3,RemoveUserDocument:4}),rX=vl({sequenceId:"com.tldraw.store",retroactive:!1,sequence:[{id:hh.RemoveCodeAndIconShapeTypes,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName==="shape"&&(n.type==="icon"||n.type==="code")&&delete t[e]}},{id:hh.AddInstancePresenceType,scope:"store",up(t){}},{id:hh.RemoveTLUserAndPresenceAndAddPointer,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName.match(/^(user|user_presence)$/)&&delete t[e]}},{id:hh.RemoveUserDocument,scope:"store",up:t=>{for(const[e,n]of Xn(t))n.typeName.match("user_document")&&delete t[e]}}]}),oX={arrow:{migrations:IA,props:_A},bookmark:{migrations:OA,props:jA},draw:{migrations:LA,props:RA},embed:{migrations:FA,props:$A},frame:{migrations:zA,props:NA},geo:{migrations:UA,props:BA},group:{migrations:KA,props:HA},highlight:{migrations:GA,props:WA},image:{migrations:YA,props:VA},line:{migrations:qA,props:XA},note:{migrations:QA,props:ZA},text:{migrations:ej,props:JA},video:{migrations:nj,props:tj}},sX={arrow:{migrations:kA,props:EA}};function iX({shapes:t=oX,bindings:e=sX,migrations:n}={}){const r=new Map;for(const a of ut(t))for(const l of xA(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=fY(t),s=dY(e),i=EY(r);return t1.create({asset:Vs,binding:s,camera:Eo,document:c1,instance:i,instance_page_state:Qr,page:yr,instance_presence:LY,pointer:l1,shape:o},{migrations:[rX,ZY,yY,FY,kY,MY,_Y,RY,OY,pY,KY,GY,YY,...W_("shape",t),...W_("binding",e),...n??[]],onValidationFailure:zY,createIntegrityChecker:UY})}const Bu=[{locale:"id",label:"Bahasa Indonesia"},{locale:"ca",label:"Català"},{locale:"cs",label:"Čeština"},{locale:"da",label:"Danish"},{locale:"de",label:"Deutsch"},{locale:"en",label:"English"},{locale:"es",label:"Español"},{locale:"fr",label:"Français"},{locale:"gl",label:"Galego"},{locale:"hr",label:"Hrvatski"},{locale:"it",label:"Italiano"},{locale:"hu",label:"Magyar"},{locale:"no",label:"Norwegian"},{locale:"pl",label:"Polski"},{locale:"pt-br",label:"Português - Brasil"},{locale:"pt-pt",label:"Português - Europeu"},{locale:"ro",label:"Română"},{locale:"ru",label:"Russian"},{locale:"sl",label:"Slovenščina"},{locale:"so",label:"Somali"},{locale:"fi",label:"Suomi"},{locale:"sv",label:"Svenska"},{locale:"vi",label:"Tiếng Việt"},{locale:"tr",label:"Türkçe"},{locale:"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 aX(){const t=typeof window<"u"?window.navigator.languages??["en"]:["en"];return lX(t)}function lX(t){for(const e of t){const n=cX(e);if(n)return n}return"en"}const J_={zh:"zh-cn",pt:"pt-br",ko:"ko-kr",hi:"hi-in"};function cX(t){const e=Bu.find(o=>o.locale===t.toLowerCase());if(e)return e.locale;const[n,r]=t.split(/[-_]/).map(o=>o.toLowerCase());if(r){const o=Bu.find(s=>s.locale===n);if(o)return o.locale}return n in J_?J_[n]:null}Ci("@tldraw/tlschema","3.7.0-canary.8e16c48b63b1","esm");var rj={exports:{}};/*!
85
85
  Copyright (c) 2018 Jed Watson.
86
86
  Licensed under the MIT License (MIT), see
87
87
  http://jedwatson.github.io/classnames
88
- */(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var s="",i=0;i<arguments.length;i++){var a=arguments[i];a&&(s=o(s,r(a)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var i="";for(var a in s)e.call(s,a)&&s[a]&&(i=o(i,a));return i}function o(s,i){return i?s?s+" "+i:s+i:s}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(rj);var uX=rj.exports;const le=xi(uX),oj="3.7.0-canary.383dfd14bf86",eI={major:"2024-09-13T14:36:29.063Z",minor:"2024-12-20T18:17:08.886Z",patch:"2024-12-20T18:17:08.886Z"},dX={error:null};class u1 extends w.Component{constructor(){super(...arguments);I(this,"state",dX)}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n){var r,o;(o=(r=this.props).onError)==null||o.call(r,n)}render(){const{error:n}=this.state;if(n!==null){const{fallback:r}=this.props;return d.jsx(r,{error:n})}return this.props.children}}function Uu({children:t,fallback:e,...n}){return e===null?t:d.jsx(u1,{fallback:e,...n,children:t})}function d1(t,e){return Rg(`${t}_${e}`)}function Jl(t){return Rg(`${w.useId()}${t??""}`)}function ro(t){const e=zn(w.useContext(sj));return Rg(`${e}_${t}`)}function Rg(t){return t.replace(/:/g,"_")}const sj=w.createContext(null);function hX({children:t}){const e=Jl();return d.jsx(sj.Provider,{value:e,children:t})}const h1=w.createContext(null);function z(){const t=Te.useContext(h1);if(!t)throw new Error("useEditor must be used inside of the <Tldraw /> or <TldrawEditor /> components");return t}function ki(){return Te.useContext(h1)}function p1({editor:t,children:e}){return d.jsx(h1.Provider,{value:t,children:d.jsx(hX,{children:e})})}function pX(){return d.jsx("div",{className:"tl-background"})}function ec(t,e,n,r,o,s){w.useLayoutEffect(()=>{const i=t.current;if(!i||e===void 0)return;let a=`translate(${e}px, ${n}px)`;r!==void 0&&(a+=` scale(${r})`),o!==void 0&&(a+=` rotate(${o}rad)`),s&&(a+=` translate(${s.x}px, ${s.y}px)`),i.style.transform=a})}const Dt={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),easeInOutQuad:t=>t<.5?2*t*t:-1+(4-2*t)*t,easeInCubic:t=>t*t*t,easeOutCubic:t=>--t*t*t+1,easeInOutCubic:t=>t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1,easeInQuart:t=>t*t*t*t,easeOutQuart:t=>1- --t*t*t*t,easeInOutQuart:t=>t<.5?8*t*t*t*t:1-8*--t*t*t*t,easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>1+--t*t*t*t*t,easeInOutQuint:t=>t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t,easeInSine:t=>1-Math.cos(t*Math.PI/2),easeOutSine:t=>Math.sin(t*Math.PI/2),easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,easeInExpo:t=>t<=0?0:Math.pow(2,10*t-10),easeOutExpo:t=>t>=1?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>t<=0?0:t>=1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2};class x{constructor(e=0,n=0,r=1){this.x=e,this.y=n,this.z=r}get pressure(){return this.z}set(e=this.x,n=this.y,r=this.z){return this.x=e,this.y=n,this.z=r,this}setTo({x:e=0,y:n=0,z:r=1}){return this.x=e,this.y=n,this.z=r,this}rot(e){if(e===0)return this;const{x:n,y:r}=this,o=Math.sin(e),s=Math.cos(e);return this.x=n*s-r*o,this.y=n*o+r*s,this}rotWith(e,n){if(n===0)return this;const r=this.x-e.x,o=this.y-e.y,s=Math.sin(n),i=Math.cos(n);return this.x=e.x+(r*i-o*s),this.y=e.y+(r*s+o*i),this}clone(){const{x:e,y:n,z:r}=this;return new x(e,n,r)}sub(e){return this.x-=e.x,this.y-=e.y,this}subXY(e,n){return this.x-=e,this.y-=n,this}subScalar(e){return this.x-=e,this.y-=e,this}add(e){return this.x+=e.x,this.y+=e.y,this}addXY(e,n){return this.x+=e,this.y+=n,this}addScalar(e){return this.x+=e,this.y+=e,this}clamp(e,n){return this.x=Math.max(this.x,e),this.y=Math.max(this.y,e),n!==void 0&&(this.x=Math.min(this.x,n),this.y=Math.min(this.y,n)),this}div(e){return this.x/=e,this.y/=e,this}divV(e){return this.x/=e.x,this.y/=e.y,this}mul(e){return this.x*=e,this.y*=e,this}mulV(e){return this.x*=e.x,this.y*=e.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(e,n){const r=x.Tan(e,this);return this.add(r.mul(n))}neg(){return this.x*=-1,this.y*=-1,this}cross(e){return this.x=this.y*e.z-this.z*e.y,this.y=this.z*e.x-this.x*e.z,this}dpr(e){return x.Dpr(this,e)}cpr(e){return x.Cpr(this,e)}len2(){return x.Len2(this)}len(){return x.Len(this)}pry(e){return x.Pry(this,e)}per(){const{x:e,y:n}=this;return this.x=n,this.y=-e,this}uni(){return x.Uni(this)}tan(e){return x.Tan(this,e)}dist(e){return x.Dist(this,e)}distanceToLineSegment(e,n){return x.DistanceToLineSegment(e,n,this)}slope(e){return x.Slope(this,e)}snapToGrid(e){return this.x=Math.round(this.x/e)*e,this.y=Math.round(this.y/e)*e,this}angle(e){return x.Angle(this,e)}toAngle(){return x.ToAngle(this)}lrp(e,n){return this.x=this.x+(e.x-this.x)*n,this.y=this.y+(e.y-this.y)*n,this}equals(e){return x.Equals(this,e)}equalsXY(e,n){return x.EqualsXY(this,e,n)}norm(){const e=this.len();return this.x=e===0?0:this.x/e,this.y=e===0?0:this.y/e,this}toFixed(){return x.ToFixed(this)}toString(){return x.ToString(x.ToFixed(this))}toJson(){return x.ToJson(this)}toArray(){return x.ToArray(this)}static Add(e,n){return new x(e.x+n.x,e.y+n.y)}static AddXY(e,n,r){return new x(e.x+n,e.y+r)}static Sub(e,n){return new x(e.x-n.x,e.y-n.y)}static SubXY(e,n,r){return new x(e.x-n,e.y-r)}static AddScalar(e,n){return new x(e.x+n,e.y+n)}static SubScalar(e,n){return new x(e.x-n,e.y-n)}static Div(e,n){return new x(e.x/n,e.y/n)}static Mul(e,n){return new x(e.x*n,e.y*n)}static DivV(e,n){return new x(e.x/n.x,e.y/n.y)}static MulV(e,n){return new x(e.x*n.x,e.y*n.y)}static Neg(e){return new x(-e.x,-e.y)}static Per(e){return new x(e.y,-e.x)}static Abs(e){return new x(Math.abs(e.x),Math.abs(e.y))}static Dist(e,n){return((e.y-n.y)**2+(e.x-n.x)**2)**.5}static DistMin(e,n,r){return(e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y)<r**2}static Dist2(e,n){return(e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y)}static Dpr(e,n){return e.x*n.x+e.y*n.y}static Cross(e,n){return new x(e.y*n.z-e.z*n.y,e.z*n.x-e.x*n.z)}static Cpr(e,n){return e.x*n.y-n.x*e.y}static Len2(e){return e.x*e.x+e.y*e.y}static Len(e){return(e.x*e.x+e.y*e.y)**.5}static Pry(e,n){return x.Dpr(e,n)/x.Len(n)}static Uni(e){return x.Div(e,x.Len(e))}static Tan(e,n){return x.Uni(x.Sub(e,n))}static Min(e,n){return new x(Math.min(e.x,n.x),Math.min(e.y,n.y))}static Max(e,n){return new x(Math.max(e.x,n.x),Math.max(e.y,n.y))}static From({x:e,y:n,z:r=1}){return new x(e,n,r)}static FromArray(e){return new x(e[0],e[1])}static Rot(e,n=0){const r=Math.sin(n),o=Math.cos(n);return new x(e.x*o-e.y*r,e.x*r+e.y*o)}static RotWith(e,n,r){const o=e.x-n.x,s=e.y-n.y,i=Math.sin(r),a=Math.cos(r);return new x(n.x+(o*a-s*i),n.y+(o*i+s*a))}static NearestPointOnLineThroughPoint(e,n,r){return x.Mul(n,x.Sub(r,e).pry(n)).add(e)}static NearestPointOnLineSegment(e,n,r,o=!0){if(x.Equals(e,r)||x.Equals(n,r))return x.From(r);const s=x.Tan(n,e),i=x.Add(e,x.Mul(s,x.Sub(r,e).pry(s)));if(o){if(i.x<Math.min(e.x,n.x))return x.Cast(e.x<n.x?e:n);if(i.x>Math.max(e.x,n.x))return x.Cast(e.x>n.x?e:n);if(i.y<Math.min(e.y,n.y))return x.Cast(e.y<n.y?e:n);if(i.y>Math.max(e.y,n.y))return x.Cast(e.y>n.y?e:n)}return i}static DistanceToLineThroughPoint(e,n,r){return x.Dist(r,x.NearestPointOnLineThroughPoint(e,n,r))}static DistanceToLineSegment(e,n,r,o=!0){return x.Dist(r,x.NearestPointOnLineSegment(e,n,r,o))}static Snap(e,n=1){return new x(Math.round(e.x/n)*n,Math.round(e.y/n)*n)}static Cast(e){return e instanceof x?e:x.From(e)}static Slope(e,n){return e.x===n.y?NaN:(e.y-n.y)/(e.x-n.x)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}static Angle(e,n){return Math.atan2(n.y-e.y,n.x-e.x)}static Lrp(e,n,r){return x.Sub(n,e).mul(r).add(e)}static Med(e,n){return new x((e.x+n.x)/2,(e.y+n.y)/2)}static Equals(e,n){return Math.abs(e.x-n.x)<1e-4&&Math.abs(e.y-n.y)<1e-4}static EqualsXY(e,n,r){return e.x===n&&e.y===r}static Clockwise(e,n,r){return(r.x-e.x)*(n.y-e.y)-(n.x-e.x)*(r.y-e.y)<0}static Rescale(e,n){const r=x.Len(e);return new x(n*e.x/r,n*e.y/r)}static ScaleWithOrigin(e,n,r){return x.Sub(e,r).mul(n).add(r)}static ToFixed(e){return new x(as(e.x),as(e.y))}static ToInt(e){return new x(parseInt(e.x.toFixed(0)),parseInt(e.y.toFixed(0)),parseInt((e.z??0).toFixed(0)))}static ToCss(e){return`${e.x},${e.y}`}static Nudge(e,n,r){return x.Add(e,x.Tan(n,e).mul(r))}static ToString(e){return`${e.x}, ${e.y}`}static ToAngle(e){let n=Math.atan2(e.y,e.x);return n<0&&(n+=Math.PI*2),n}static FromAngle(e,n=1){return new x(Math.cos(e)*n,Math.sin(e)*n)}static ToArray(e){return[e.x,e.y,e.z]}static ToJson(e){const{x:n,y:r,z:o}=e;return{x:n,y:r,z:o}}static Average(e){const n=e.length,r=new x(0,0);if(n===0)return r;for(let o=0;o<n;o++)r.add(e[o]);return r.div(n)}static Clamp(e,n,r){return r===void 0?new x(Math.min(Math.max(e.x,n)),Math.min(Math.max(e.y,n))):new x(Math.min(Math.max(e.x,n),r),Math.min(Math.max(e.y,n),r))}static PointsBetween(e,n,r=6){const o=[];for(let s=0;s<r;s++){const i=Dt.easeInQuad(s/(r-1)),a=x.Lrp(e,n,i);a.z=Math.min(1,.5+Math.abs(.5-fX(i))*.65),o.push(a)}return o}static SnapToGrid(e,n=8){return new x(Math.round(e.x/n)*n,Math.round(e.y/n)*n)}}const fX=t=>t<.5?2*t*t:-1+(4-2*t)*t;function je(t){return`${N(t.x)},${N(t.y)} `}function Bn(t,e){return`${N((t.x+e.x)/2)},${N((t.y+e.y)/2)} `}const De=Math.PI,qe=De/2,Ne=De*2,gX=Math.sin;function zt(t,e,n){return Math.max(e,typeof n<"u"?Math.min(t,n):t)}function ph(t,e=1e10){return t?Math.round(t*e)/e:0}function ui(t,e,n=1e-6){return Math.abs(t-e)<=n}function ij(t,e){const n=Math.pow(t-e,2)/Math.pow(t+e,2);return De*(t+e)*(1+3*n/(10+Math.sqrt(4-3*n)))}function Ji(t){return t=t%Ne,t<0?t=t+Ne:t===0&&(t=0),t}function ud(t,e){return t=Ji(t),e=Ji(e),t>e&&(e+=Ne),e-t}function aj(t,e){return Ne-ud(t,e)}function ap(t,e){const n=(e-t)%Ne;return 2*n%Ne-n}function vx(t){return(Ne+t)%Ne}function Df(t,e){const n=Ne/e;let r=Math.floor((vx(t)+n/2)/n)*n%Ne;return r<De&&(r+=Ne),r>De&&(r-=Ne),r}function lj(t,e){return t===e||ui(t%(Math.PI/2)-e%(Math.PI/2),0)}function mX(t){return t*De/180}function yX(t){return t*180/De}function da(t,e,n){return new x(t.x,t.y).add(x.FromAngle(n,e))}function Uy(t,e,n){const r=t/2,o=e/2,s=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let g=0;g<n;g++){const m=Ne/n,v=-qe+g*m,y=r+r*Math.cos(v),S=o+o*Math.sin(v);y<i&&(i=y),S<l&&(l=S),y>a&&(a=y),S>c&&(c=S),s.push(new x(y,S))}const u=a-i,h=c-l,p=t-u,f=e-h;if(p!==0||f!==0)for(let g=0;g<s.length;g++){const m=s[g];m.x=(m.x-i)/u*t,m.y=(m.y-l)/h*e}return s}function Mc(t,e,n,r){return t<r&&n<e}function Gr(t,e,n,r){const o=Math.max(t,n),s=Math.min(e,r);return o<=s?[o,s]:null}function tI(t,e,n){return(e.x-t.x)*(n.y-t.y)-(n.x-t.x)*(e.y-t.y)}function hr(t,e){let n=0,r,o;for(let s=0;s<e.length;s++){if(r=e[s],r.x===t.x&&r.y===t.y||(o=e[(s+1)%e.length],x.Dist(t,r)+x.Dist(t,o)===x.Dist(r,o)))return!0;r.y<=t.y?o.y>t.y&&tI(r,o,t)>0&&(n+=1):o.y<=t.y&&tI(r,o,t)<0&&(n-=1)}return n!==0}function N(t){return Math.round(t*1e4)/1e4}function as(t){return Math.round(t*100)/100}const nI=t=>Math.abs(t)<Number.MAX_SAFE_INTEGER;function Ys(t,e,n){return n<0?ud(t,e):aj(t,e)}function xx(t,e,n,r){let o;if(Math.abs(t)>De){o=ap(e,r);const s=ap(r,n);return Math.abs(o)<Math.abs(s)?o/t:(t-s)/t}else{o=ap(e,r);const s=o/t;return Math.sign(o)!==Math.sign(t)?Math.abs(s)>.5?1:0:s}}function SX(t,e,n,r){const o=2*((e-t)%Ne)%Ne-(e-t)%Ne;return r?(Ne-Math.abs(o))*(n?1:-1):o}function f1(t,e,n){const r=-2*(t.x*(e.y-n.y)-t.y*(e.x-n.x)+e.x*n.y-n.x*e.y),o=((t.x*t.x+t.y*t.y)*(n.y-e.y)+(e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y))/r,s=((t.x*t.x+t.y*t.y)*(e.x-n.x)+(e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x))/r;return!Number.isFinite(o)||!Number.isFinite(s)?null:new x(o,s)}function vX(t,e,n,r,o){if(n===null)return[x.From(t),x.From(e)];const s=[],i=x.Angle(n,t),a=x.Angle(n,e),l=ud(i,a);for(let c=0;c<o;c++){const u=c/(o-1),h=i+l*u,p=da(n,r,h);s.push(p)}return s}const Hy=({brush:t,color:e,opacity:n,className:r})=>{const o=w.useRef(null);ec(o,t.x,t.y);const s=N(Math.max(1,t.w)),i=N(Math.max(1,t.h));return d.jsx("svg",{className:"tl-overlays__item",ref:o,children:e?d.jsxs("g",{className:"tl-brush",opacity:n,children:[d.jsx("rect",{width:s,height:i,fill:e,opacity:.75}),d.jsx("rect",{width:s,height:i,fill:"none",stroke:e,opacity:.1})]}):d.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:s,height:i})})},Ge={isSafari:!1,isIos:!1,isChromeForIos:!1,isFirefox:!1,isAndroid:!1,isWebview:!1,isDarwin:!1};typeof window<"u"&&"navigator"in window&&(Ge.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),Ge.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),Ge.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),Ge.isFirefox=/firefox/i.test(navigator.userAgent),Ge.isAndroid=/android/i.test(navigator.userAgent),Ge.isDarwin=window.navigator.userAgent.toLowerCase().indexOf("mac")>-1);const rI={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.1,.25,.5,1,2,4,8]},Ky={duration:0,easing:Dt.easeInOutCubic},oI={CAMERA_MOVE:-10},xX=["top","right","bottom","left"],sI=0,g1=2,fh=1,iI=5,wX=128;var Wy={};const bX={},cj=Dn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),bt={logPreventDefaults:Dn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:Dn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:Dn("logElementRemoves",{defaults:{all:!1}}),debugSvg:Dn("debugSvg",{defaults:{all:!1}}),showFps:Dn("showFps",{defaults:{all:!1}}),measurePerformance:Dn("measurePerformance",{defaults:{all:!1}}),throwToBlob:Dn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:Dn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:Dn("debugCursors",{defaults:{all:!1}}),forceSrgb:Dn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:Dn("debugGeometry",{defaults:{all:!1}}),hideShapes:Dn("hideShapes",{defaults:{all:!1}}),editOnType:Dn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const t=Element.prototype.removeChild;jo("element removal logging",()=>{bt.logElementRemoves.get()?Element.prototype.removeChild=function(e){return console.warn("[tldraw] removing child:",e),t.call(this,e)}:Element.prototype.removeChild=t})}function Dn(t,{defaults:e,shouldStoreForSession:n=!0}){return PX({name:t,defaults:e,shouldStoreForSession:n})}function PX(t){const e=_X(t),n=t.shouldStoreForSession?CX(t.name):null,r=Et(`debug:${t.name}`,n??e);return typeof window<"u"&&(t.shouldStoreForSession&&jo(`debug:${t.name}`,()=>{const o=r.get();o===e?JT(`tldraw_debug:${t.name}`):Ew(`tldraw_debug:${t.name}`,JSON.stringify(o))}),Object.defineProperty(window,`tldraw${t.name.replace(/^[a-z]/,o=>o.toUpperCase())}`,{get(){return r.get()},set(o){r.set(o)},configurable:!0})),Object.assign(r,t)}function CX(t){try{return JSON.parse(QT(`tldraw_debug:${t}`)??"null")}catch{return null}}function Gy(t){try{return t()}catch{return null}}function _X(t){switch(Gy(()=>Wy.TLDRAW_ENV)??Gy(()=>Wy.VERCEL_PUBLIC_TLDRAW_ENV)??Gy(()=>Wy.NEXT_PUBLIC_TLDRAW_ENV)??"production"){case"production":return t.defaults.production??t.defaults.all;case"preview":case"staging":return t.defaults.staging??t.defaults.all;default:return t.defaults.development??t.defaults.all}}function Rf(t){if(t instanceof HTMLElement)return t;if(t.parentElement)return Rf(t.parentElement);throw Error("Could not find a parent element of an HTML type!")}function xe(t){t.preventDefault(),bt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",t)}function dd(t,e){if(t.setPointerCapture(e.pointerId),bt.logPointerCaptures.get()){const n=cj.get();n.set(t,(n.get(t)??0)+1),console.warn("setPointerCapture called on element:",t,e)}}function hd(t,e){if(t.hasPointerCapture(e.pointerId)&&(t.releasePointerCapture(e.pointerId),bt.logPointerCaptures.get())){const n=cj.get();n.get(t)===1?n.delete(t):n.has(t)?n.set(t,n.get(t)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",t,e)}}const _t=t=>t.stopPropagation(),rn=(t,e,n)=>{t&&t.style.setProperty(e,n)},un=t=>Ge.isDarwin?t.metaKey:t.ctrlKey||t.metaKey;function lr(t){return t.isKilled=!0,{point:{x:t.clientX,y:t.clientY,z:t.pressure},shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.metaKey||t.ctrlKey,metaKey:t.metaKey,accelKey:un(t),pointerId:t.pointerId,button:t.button,isPen:t.pointerType==="pen"}}function m1(){const t=z();return w.useMemo(function(){let r,o;function s(m){if(!m.isKilled){if(m.button===g1){t.dispatch({type:"pointer",target:"canvas",name:"right_click",...lr(m)});return}m.button!==0&&m.button!==1&&m.button!==5||(dd(m.currentTarget,m),t.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...lr(m)}))}}function i(m){m.isKilled||m.clientX===r&&m.clientY===o||(r=m.clientX,o=m.clientY,t.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...lr(m)}))}function a(m){m.isKilled||m.button!==0&&m.button!==1&&m.button!==2&&m.button!==5||(r=m.clientX,o=m.clientY,hd(m.currentTarget,m),t.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...lr(m)}))}function l(m){if(m.isKilled||t.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const v=m.pointerType==="mouse"||m.pointerType==="pen";t.updateInstanceState({isHoveringCanvas:v?!0:null})}function c(m){if(m.isKilled||t.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const v=m.pointerType==="mouse"||m.pointerType==="pen";t.updateInstanceState({isHoveringCanvas:v?!1:null})}function u(m){m.isKilled=!0,xe(m)}function h(m){m.isKilled=!0,m.target instanceof HTMLElement&&m.target.tagName!=="A"&&m.target.tagName!=="TEXTAREA"&&!(t.getEditingShape()&&m.target.className.includes("tl-text-content"))&&xe(m)}function p(m){xe(m)}async function f(m){var y,S;if(xe(m),_t(m),!((S=(y=m.dataTransfer)==null?void 0:y.files)!=null&&S.length))return;const v=Array.from(m.dataTransfer.files);await t.putExternalContent({type:"files",files:v,point:t.screenToPage({x:m.clientX,y:m.clientY}),ignoreParent:!1})}function g(m){_t(m)}return{onPointerDown:s,onPointerMove:i,onPointerUp:a,onPointerEnter:l,onPointerLeave:c,onDragOver:p,onDrop:f,onTouchStart:u,onTouchEnd:h,onClick:g}},[t])}function IX(){const t=z();w.useEffect(()=>{let e=t.getInstanceState().isCoarsePointer;const n=i=>{const a=i.pointerType!=="mouse";e!==a&&(e=a,t.updateInstanceState({isCoarsePointer:a}))};window.addEventListener("pointerdown",n,{capture:!0});const r=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),o=Ge.isFirefox&&!Ge.isAndroid&&!Ge.isIos,s=()=>{const i=o?!1:r.matches;e===i&&(e=i,t.updateInstanceState({isCoarsePointer:i}))};return r&&(r.addEventListener("change",s),s()),()=>{window.removeEventListener("pointerdown",n,{capture:!0}),r&&r.removeEventListener("change",s)}},[t])}const uj=w.createContext(null);function dj({container:t,children:e}){return d.jsx(uj.Provider,{value:t,children:e})}function Mt(){return zn(w.useContext(uj),"useContainer used outside of <Tldraw />")}function EX(){const t=z(),e=Mt(),n=U("isFocused",()=>t.getIsFocused(),[t]);w.useEffect(()=>{if(!e)return;function r(o){if(o.isSpecialRedispatchedEvent)return;xe(o),_t(o);const s=e.querySelector(".tl-canvas");if(!s)return;const i=new DragEvent(o.type,o);i.isSpecialRedispatchedEvent=!0,s.dispatchEvent(i)}return e.addEventListener("dragover",r),e.addEventListener("drop",r),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",r)}},[e]),w.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))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)},t.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return o(),()=>{r==null||r()}},[t]),w.useEffect(()=>{if(!n)return;const r=a=>{if(a.altKey&&(t.isIn("zoom")||!t.getPath().endsWith(".idle"))&&!gh(t)&&xe(a),a.isKilled)return;switch(a.isKilled=!0,a.key){case"=":case"-":case"0":{if(a.metaKey||a.ctrlKey){xe(a);return}break}case"Tab":{if(gh(t))return;break}case",":return;case"Escape":{if((t.getEditingShape()||t.getSelectedShapeIds().length>0)&&xe(a),t.menus.getOpenMenus().length>0)return;t.inputs.keys.has("Escape")||(t.inputs.keys.add("Escape"),t.cancel(),e.focus());return}default:if(gh(t))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,metaKey:a.metaKey,accelKey:un(a)};t.dispatch(l)},o=a=>{if(a.isKilled||(a.isKilled=!0,gh(t))||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,metaKey:a.metaKey,accelKey:un(a)};t.dispatch(l)};function s(a){var l,c;if(e.contains(a.target)){const u=a.touches[0].pageX,h=a.touches[0].radiusX||0;(u-h<10||u+h>t.getViewportScreenBounds().width-10)&&(((l=a.target)==null?void 0:l.tagName)==="BUTTON"&&((c=a.target)==null||c.click()),xe(a))}}const i=a=>{e.contains(a.target)&&(a.ctrlKey||a.metaKey)&&xe(a)};return e.addEventListener("touchstart",s,{passive:!1}),e.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",xe),document.addEventListener("gesturechange",xe),document.addEventListener("gestureend",xe),e.addEventListener("keydown",r),e.addEventListener("keyup",o),()=>{e.removeEventListener("touchstart",s),e.removeEventListener("wheel",i),document.removeEventListener("gesturestart",xe),document.removeEventListener("gesturechange",xe),document.removeEventListener("gestureend",xe),e.removeEventListener("keydown",r),e.removeEventListener("keyup",o)}},[t,e,n])}const kX=["input","select","button","textarea"];function gh(t){const{activeElement:e}=document;return t.menus.hasOpenMenus()||e&&(e.getAttribute("contenteditable")||kX.indexOf(e.tagName.toLowerCase())>-1)}const TX=["textarea","input"];function MX(t){const e=z();w.useEffect(()=>{const n=t.current;if(!n)return;const r=o=>{var s;if(o instanceof PointerEvent&&o.pointerType==="pen"){o.isKilled=!0;const{target:i}=o;if(TX.includes((s=i.tagName)==null?void 0:s.toLocaleLowerCase())||e.isIn("select.editing_shape"))return;xe(o)}};return n.addEventListener("touchstart",r),n.addEventListener("touchend",r),()=>{n.removeEventListener("touchstart",r),n.removeEventListener("touchend",r)}},[e,t])}function AX(t,e,n){return Math.max(e,Math.min(t,n))}const Gt={toVector(t,e){return t===void 0&&(t=e),Array.isArray(t)?t:[t,t]},add(t,e){return[t[0]+e[0],t[1]+e[1]]},sub(t,e){return[t[0]-e[0],t[1]-e[1]]},addTo(t,e){t[0]+=e[0],t[1]+=e[1]},subTo(t,e){t[0]-=e[0],t[1]-=e[1]}};function aI(t,e,n){return e===0||Math.abs(e)===1/0?Math.pow(t,n*5):t*e*n/(e+n*t)}function lI(t,e,n,r=.15){return r===0?AX(t,e,n):t<e?-aI(e-t,n-e,r)+e:t>n?+aI(t-n,n-e,r)+n:t}function jX(t,[e,n],[r,o]){const[[s,i],[a,l]]=t;return[lI(e,s,i,r),lI(n,a,l,o)]}function OX(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function DX(t){var e=OX(t,"string");return typeof e=="symbol"?e:String(e)}function sn(t,e,n){return e=DX(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function cI(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function ht(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cI(Object(n),!0).forEach(function(r){sn(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cI(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}const hj={pointer:{start:"down",change:"move",end:"up"},mouse:{start:"down",change:"move",end:"up"},touch:{start:"start",change:"move",end:"end"},gesture:{start:"start",change:"change",end:"end"}};function uI(t){return t?t[0].toUpperCase()+t.slice(1):""}const RX=["enter","leave"];function LX(t=!1,e){return t&&!RX.includes(e)}function $X(t,e="",n=!1){const r=hj[t],o=r&&r[e]||e;return"on"+uI(t)+uI(o)+(LX(n,o)?"Capture":"")}const FX=["gotpointercapture","lostpointercapture"];function NX(t){let e=t.substring(2).toLowerCase();const n=!!~e.indexOf("passive");n&&(e=e.replace("passive",""));const r=FX.includes(e)?"capturecapture":"capture",o=!!~e.indexOf(r);return o&&(e=e.replace("capture","")),{device:e,capture:o,passive:n}}function zX(t,e=""){const n=hj[t],r=n&&n[e]||e;return t+r}function pj(t){return"touches"in t}function BX(t){return pj(t)?"touch":"pointerType"in t?t.pointerType:"mouse"}function UX(t){return Array.from(t.touches).filter(e=>{var n,r;return e.target===t.currentTarget||((n=t.currentTarget)===null||n===void 0||(r=n.contains)===null||r===void 0?void 0:r.call(n,e.target))})}function wx(t,e){try{const n=e.clientX-t.clientX,r=e.clientY-t.clientY,o=(e.clientX+t.clientX)/2,s=(e.clientY+t.clientY)/2,i=Math.hypot(n,r);return{angle:-(Math.atan2(n,r)*180)/Math.PI,distance:i,origin:[o,s]}}catch{}return null}function HX(t){return UX(t).map(e=>e.identifier)}function dI(t,e){const[n,r]=Array.from(t.touches).filter(o=>e.includes(o.identifier));return wx(n,r)}const hI=40,pI=800;function fj(t){let{deltaX:e,deltaY:n,deltaMode:r}=t;return r===1?(e*=hI,n*=hI):r===2&&(e*=pI,n*=pI),[e,n]}function KX(t){const e={};if("buttons"in t&&(e.buttons=t.buttons),"shiftKey"in t){const{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s}=t;Object.assign(e,{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s})}return e}function Lf(t,...e){return typeof t=="function"?t(...e):t}function WX(){}function GX(...t){return t.length===0?WX:t.length===1?t[0]:function(){let e;for(const n of t)e=n.apply(this,arguments)||e;return e}}function fI(t,e){return Object.assign({},e,t||{})}const VX=32;class gj{constructor(e,n,r){this.ctrl=e,this.args=n,this.key=r,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(e){this.ctrl.state[this.key]=e}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:e,shared:n,ingKey:r,args:o}=this;n[r]=e._active=e.active=e._blocked=e._force=!1,e._step=[!1,!1],e.intentional=!1,e._movement=[0,0],e._distance=[0,0],e._direction=[0,0],e._delta=[0,0],e._bounds=[[-1/0,1/0],[-1/0,1/0]],e.args=o,e.axis=void 0,e.memo=void 0,e.elapsedTime=e.timeDelta=0,e.direction=[0,0],e.distance=[0,0],e.overflow=[0,0],e._movementBound=[!1,!1],e.velocity=[0,0],e.movement=[0,0],e.delta=[0,0],e.timeStamp=0}start(e){const n=this.state,r=this.config;n._active||(this.reset(),this.computeInitial(),n._active=!0,n.target=e.target,n.currentTarget=e.currentTarget,n.lastOffset=r.from?Lf(r.from,n):n.offset,n.offset=n.lastOffset,n.startTime=n.timeStamp=e.timeStamp)}computeValues(e){const n=this.state;n._values=e,n.values=this.config.transform(e)}computeInitial(){const e=this.state;e._initial=e._values,e.initial=e.values}compute(e){const{state:n,config:r,shared:o}=this;n.args=this.args;let s=0;if(e&&(n.event=e,r.preventDefault&&e.cancelable&&n.event.preventDefault(),n.type=e.type,o.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,o.locked=!!document.pointerLockElement,Object.assign(o,KX(e)),o.down=o.pressed=o.buttons%2===1||o.touches>0,s=e.timeStamp-n.timeStamp,n.timeStamp=e.timeStamp,n.elapsedTime=n.timeStamp-n.startTime),n._active){const _=n._delta.map(Math.abs);Gt.addTo(n._distance,_)}this.axisIntent&&this.axisIntent(e);const[i,a]=n._movement,[l,c]=r.threshold,{_step:u,values:h}=n;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=l&&h[0]),u[1]===!1&&(u[1]=Math.abs(a)>=c&&h[1])):(u[0]===!1&&(u[0]=Math.abs(i)>=l&&Math.sign(i)*l),u[1]===!1&&(u[1]=Math.abs(a)>=c&&Math.sign(a)*c)),n.intentional=u[0]!==!1||u[1]!==!1,!n.intentional)return;const p=[0,0];if(r.hasCustomTransform){const[_,E]=h;p[0]=u[0]!==!1?_-u[0]:0,p[1]=u[1]!==!1?E-u[1]:0}else p[0]=u[0]!==!1?i-u[0]:0,p[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!n._blocked&&this.restrictToAxis(p);const f=n.offset,g=n._active&&!n._blocked||n.active;g&&(n.first=n._active&&!n.active,n.last=!n._active&&n.active,n.active=o[this.ingKey]=n._active,e&&(n.first&&("bounds"in r&&(n._bounds=Lf(r.bounds,n)),this.setup&&this.setup()),n.movement=p,this.computeOffset()));const[m,v]=n.offset,[[y,S],[b,P]]=n._bounds;n.overflow=[m<y?-1:m>S?1:0,v<b?-1:v>P?1:0],n._movementBound[0]=n.overflow[0]?n._movementBound[0]===!1?n._movement[0]:n._movementBound[0]:!1,n._movementBound[1]=n.overflow[1]?n._movementBound[1]===!1?n._movement[1]:n._movementBound[1]:!1;const C=n._active?r.rubberband||[0,0]:[0,0];if(n.offset=jX(n._bounds,n.offset,C),n.delta=Gt.sub(n.offset,f),this.computeMovement(),g&&(!n.last||s>VX)){n.delta=Gt.sub(n.offset,f);const _=n.delta.map(Math.abs);Gt.addTo(n.distance,_),n.direction=n.delta.map(Math.sign),n._direction=n._delta.map(Math.sign),!n.first&&s>0&&(n.velocity=[_[0]/s,_[1]/s],n.timeDelta=s)}}emit(){const e=this.state,n=this.shared,r=this.config;if(e._active||this.clean(),(e._blocked||!e.intentional)&&!e._force&&!r.triggerAllEvents)return;const o=this.handler(ht(ht(ht({},n),e),{},{[this.aliasKey]:e.values}));o!==void 0&&(e.memo=o)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function YX([t,e],n){const r=Math.abs(t),o=Math.abs(e);if(r>o&&r>n)return"x";if(o>r&&o>n)return"y"}class XX extends gj{constructor(...e){super(...e),sn(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=Gt.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Gt.sub(this.state.offset,this.state.lastOffset)}axisIntent(e){const n=this.state,r=this.config;if(!n.axis&&e){const o=typeof r.axisThreshold=="object"?r.axisThreshold[BX(e)]:r.axisThreshold;n.axis=YX(n._movement,o)}n._blocked=(r.lockDirection||!!r.axis)&&!n.axis||!!r.axis&&r.axis!==n.axis}restrictToAxis(e){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":e[1]=0;break;case"y":e[0]=0;break}}}const qX=t=>t,gI=.15,mj={enabled(t=!0){return t},eventOptions(t,e,n){return ht(ht({},n.shared.eventOptions),t)},preventDefault(t=!1){return t},triggerAllEvents(t=!1){return t},rubberband(t=0){switch(t){case!0:return[gI,gI];case!1:return[0,0];default:return Gt.toVector(t)}},from(t){if(typeof t=="function")return t;if(t!=null)return Gt.toVector(t)},transform(t,e,n){const r=t||n.shared.transform;return this.hasCustomTransform=!!r,r||qX},threshold(t){return Gt.toVector(t,0)}},ZX=0,pd=ht(ht({},mj),{},{axis(t,e,{axis:n}){if(this.lockDirection=n==="lock",!this.lockDirection)return n},axisThreshold(t=ZX){return t},bounds(t={}){if(typeof t=="function")return s=>pd.bounds(t(s));if("current"in t)return()=>t.current;if(typeof HTMLElement=="function"&&t instanceof HTMLElement)return t;const{left:e=-1/0,right:n=1/0,top:r=-1/0,bottom:o=1/0}=t;return[[e,n],[r,o]]}}),fd=typeof window<"u"&&window.document&&window.document.createElement;function yj(){return fd&&"ontouchstart"in window}function QX(){return yj()||fd&&window.navigator.maxTouchPoints>1}function JX(){return fd&&"onpointerdown"in window}function eq(){return fd&&"exitPointerLock"in window.document}function tq(){try{return"constructor"in GestureEvent}catch{return!1}}const Mr={isBrowser:fd,gesture:tq(),touch:yj(),touchscreen:QX(),pointer:JX(),pointerLock:eq()},nq=250,rq=180,oq=.5,sq=50,iq=250,aq=10,mI={mouse:0,touch:0,pen:8};ht(ht({},pd),{},{device(t,e,{pointer:{touch:n=!1,lock:r=!1,mouse:o=!1}={}}){return this.pointerLock=r&&Mr.pointerLock,Mr.touch&&n?"touch":this.pointerLock?"mouse":Mr.pointer&&!o?"pointer":Mr.touch?"touch":"mouse"},preventScrollAxis(t,e,{preventScroll:n}){if(this.preventScrollDelay=typeof n=="number"?n:n||n===void 0&&t?nq:void 0,!(!Mr.touchscreen||n===!1))return t||(n!==void 0?"y":void 0)},pointerCapture(t,e,{pointer:{capture:n=!0,buttons:r=1,keys:o=!0}={}}){return this.pointerButtons=r,this.keys=o,!this.pointerLock&&this.device==="pointer"&&n},threshold(t,e,{filterTaps:n=!1,tapsThreshold:r=3,axis:o=void 0}){const s=Gt.toVector(t,n?r:o?1:0);return this.filterTaps=n,this.tapsThreshold=r,s},swipe({velocity:t=oq,distance:e=sq,duration:n=iq}={}){return{velocity:this.transform(Gt.toVector(t)),distance:this.transform(Gt.toVector(e)),duration:n}},delay(t=0){switch(t){case!0:return rq;case!1:return 0;default:return t}},axisThreshold(t){return t?ht(ht({},mI),t):mI},keyboardDisplacement(t=aq){return t}});function Sj(t){const[e,n]=t.overflow,[r,o]=t._delta,[s,i]=t._direction;(e<0&&r>0&&s<0||e>0&&r<0&&s>0)&&(t._movement[0]=t._movementBound[0]),(n<0&&o>0&&i<0||n>0&&o<0&&i>0)&&(t._movement[1]=t._movementBound[1])}const lq=30,cq=100;class uq extends gj{constructor(...e){super(...e),sn(this,"ingKey","pinching"),sn(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const e=this.state;e._touchIds=[],e.canceled=!1,e.cancel=this.cancel.bind(this),e.turns=0}computeOffset(){const{type:e,movement:n,lastOffset:r}=this.state;e==="wheel"?this.state.offset=Gt.add(n,r):this.state.offset=[(1+n[0])*r[0],n[1]+r[1]]}computeMovement(){const{offset:e,lastOffset:n}=this.state;this.state.movement=[e[0]/n[0],e[1]-n[1]]}axisIntent(){const e=this.state,[n,r]=e._movement;if(!e.axis){const o=Math.abs(n)*lq-Math.abs(r);o<0?e.axis="angle":o>0&&(e.axis="scale")}}restrictToAxis(e){this.config.lockDirection&&(this.state.axis==="scale"?e[1]=0:this.state.axis==="angle"&&(e[0]=0))}cancel(){const e=this.state;e.canceled||setTimeout(()=>{e.canceled=!0,e._active=!1,this.compute(),this.emit()},0)}touchStart(e){this.ctrl.setEventIds(e);const n=this.state,r=this.ctrl.touchIds;if(n._active&&n._touchIds.every(s=>r.has(s))||r.size<2)return;this.start(e),n._touchIds=Array.from(r).slice(0,2);const o=dI(e,n._touchIds);o&&this.pinchStart(e,o)}pointerStart(e){if(e.buttons!=null&&e.buttons%2!==1)return;this.ctrl.setEventIds(e),e.target.setPointerCapture(e.pointerId);const n=this.state,r=n._pointerEvents,o=this.ctrl.pointerIds;if(n._active&&Array.from(r.keys()).every(i=>o.has(i))||(r.size<2&&r.set(e.pointerId,e),n._pointerEvents.size<2))return;this.start(e);const s=wx(...Array.from(r.values()));s&&this.pinchStart(e,s)}pinchStart(e,n){const r=this.state;r.origin=n.origin,this.computeValues([n.distance,n.angle]),this.computeInitial(),this.compute(e),this.emit()}touchMove(e){if(!this.state._active)return;const n=dI(e,this.state._touchIds);n&&this.pinchMove(e,n)}pointerMove(e){const n=this.state._pointerEvents;if(n.has(e.pointerId)&&n.set(e.pointerId,e),!this.state._active)return;const r=wx(...Array.from(n.values()));r&&this.pinchMove(e,r)}pinchMove(e,n){const r=this.state,o=r._values[1],s=n.angle-o;let i=0;Math.abs(s)>270&&(i+=Math.sign(s)),this.computeValues([n.distance,n.angle-360*i]),r.origin=n.origin,r.turns=i,r._movement=[r._values[0]/r._initial[0]-1,r._values[1]-r._initial[1]],this.compute(e),this.emit()}touchEnd(e){this.ctrl.setEventIds(e),this.state._active&&this.state._touchIds.some(n=>!this.ctrl.touchIds.has(n))&&(this.state._active=!1,this.compute(e),this.emit())}pointerEnd(e){const n=this.state;this.ctrl.setEventIds(e);try{e.target.releasePointerCapture(e.pointerId)}catch{}n._pointerEvents.has(e.pointerId)&&n._pointerEvents.delete(e.pointerId),n._active&&n._pointerEvents.size<2&&(n._active=!1,this.compute(e),this.emit())}gestureStart(e){e.cancelable&&e.preventDefault();const n=this.state;n._active||(this.start(e),this.computeValues([e.scale,e.rotation]),n.origin=[e.clientX,e.clientY],this.compute(e),this.emit())}gestureMove(e){if(e.cancelable&&e.preventDefault(),!this.state._active)return;const n=this.state;this.computeValues([e.scale,e.rotation]),n.origin=[e.clientX,e.clientY];const r=n._movement;n._movement=[e.scale-1,e.rotation],n._delta=Gt.sub(n._movement,r),this.compute(e),this.emit()}gestureEnd(e){this.state._active&&(this.state._active=!1,this.compute(e),this.emit())}wheel(e){const n=this.config.modifierKey;n&&(Array.isArray(n)?!n.find(r=>e[r]):!e[n])||(this.state._active?this.wheelChange(e):this.wheelStart(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(e){this.start(e),this.wheelChange(e)}wheelChange(e){"uv"in e||e.cancelable&&e.preventDefault();const r=this.state;r._delta=[-fj(e)[1]/cq*r.offset[0],0],Gt.addTo(r._movement,r._delta),Sj(r),this.state.origin=[e.clientX,e.clientY],this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){const n=this.config.device;n&&(e(n,"start",this[n+"Start"].bind(this)),e(n,"change",this[n+"Move"].bind(this)),e(n,"end",this[n+"End"].bind(this)),e(n,"cancel",this[n+"End"].bind(this)),e("lostPointerCapture","",this[n+"End"].bind(this))),this.config.pinchOnWheel&&e("wheel","",this.wheel.bind(this),{passive:!1})}}const dq=ht(ht({},mj),{},{device(t,e,{shared:n,pointer:{touch:r=!1}={}}){if(n.target&&!Mr.touch&&Mr.gesture)return"gesture";if(Mr.touch&&r)return"touch";if(Mr.touchscreen){if(Mr.pointer)return"pointer";if(Mr.touch)return"touch"}},bounds(t,e,{scaleBounds:n={},angleBounds:r={}}){const o=i=>{const a=fI(Lf(n,i),{min:-1/0,max:1/0});return[a.min,a.max]},s=i=>{const a=fI(Lf(r,i),{min:-1/0,max:1/0});return[a.min,a.max]};return typeof n!="function"&&typeof r!="function"?[o(),s()]:i=>[o(i),s(i)]},threshold(t,e,n){return this.lockDirection=n.axis==="lock",Gt.toVector(t,this.lockDirection?[.1,3]:0)},modifierKey(t){return t===void 0?"ctrlKey":t},pinchOnWheel(t=!0){return t}});ht(ht({},pd),{},{mouseOnly:(t=!0)=>t});class hq extends XX{constructor(...e){super(...e),sn(this,"ingKey","wheeling")}wheel(e){this.state._active||this.start(e),this.wheelChange(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(e){const n=this.state;n._delta=fj(e),Gt.addTo(n._movement,n._delta),Sj(n),this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){e("wheel","",this.wheel.bind(this))}}const pq=pd;ht(ht({},pd),{},{mouseOnly:(t=!0)=>t});const y1=new Map,bx=new Map;function fq(t){y1.set(t.key,t.engine),bx.set(t.key,t.resolver)}const gq={key:"pinch",engine:uq,resolver:dq},mq={key:"wheel",engine:hq,resolver:pq};function yq(t,e){if(t==null)return{};var n={},r=Object.keys(t),o,s;for(s=0;s<r.length;s++)o=r[s],!(e.indexOf(o)>=0)&&(n[o]=t[o]);return n}function Sq(t,e){if(t==null)return{};var n=yq(t,e),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(o=0;o<s.length;o++)r=s[o],!(e.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}const vq={target(t){if(t)return()=>"current"in t?t.current:t},enabled(t=!0){return t},window(t=Mr.isBrowser?window:void 0){return t},eventOptions({passive:t=!0,capture:e=!1}={}){return{passive:t,capture:e}},transform(t){return t}},xq=["target","eventOptions","window","enabled","transform"];function lp(t={},e){const n={};for(const[r,o]of Object.entries(e))switch(typeof o){case"function":n[r]=o.call(n,t[r],r,t);break;case"object":n[r]=lp(t[r],o);break;case"boolean":o&&(n[r]=t[r]);break}return n}function wq(t,e,n={}){const r=t,{target:o,eventOptions:s,window:i,enabled:a,transform:l}=r,c=Sq(r,xq);if(n.shared=lp({target:o,eventOptions:s,window:i,enabled:a,transform:l},vq),e){const u=bx.get(e);n[e]=lp(ht({shared:n.shared},c),u)}else for(const u in c){const h=bx.get(u);h&&(n[u]=lp(ht({shared:n.shared},c[u]),h))}return n}class vj{constructor(e,n){sn(this,"_listeners",new Set),this._ctrl=e,this._gestureKey=n}add(e,n,r,o,s){const i=this._listeners,a=zX(n,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=ht(ht({},l),s);e.addEventListener(a,o,c);const u=()=>{e.removeEventListener(a,o,c),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(e=>e()),this._listeners.clear()}}class bq{constructor(){sn(this,"_timeouts",new Map)}add(e,n,r=140,...o){this.remove(e),this._timeouts.set(e,window.setTimeout(n,r,...o))}remove(e){const n=this._timeouts.get(e);n&&window.clearTimeout(n)}clean(){this._timeouts.forEach(e=>void window.clearTimeout(e)),this._timeouts.clear()}}class Pq{constructor(e){sn(this,"gestures",new Set),sn(this,"_targetEventStore",new vj(this)),sn(this,"gestureEventStores",{}),sn(this,"gestureTimeoutStores",{}),sn(this,"handlers",{}),sn(this,"config",{}),sn(this,"pointerIds",new Set),sn(this,"touchIds",new Set),sn(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),Cq(this,e)}setEventIds(e){if(pj(e))return this.touchIds=new Set(HX(e)),this.touchIds;if("pointerId"in e)return e.type==="pointerup"||e.type==="pointercancel"?this.pointerIds.delete(e.pointerId):e.type==="pointerdown"&&this.pointerIds.add(e.pointerId),this.pointerIds}applyHandlers(e,n){this.handlers=e,this.nativeHandlers=n}applyConfig(e,n){this.config=wq(e,n,this.config)}clean(){this._targetEventStore.clean();for(const e of this.gestures)this.gestureEventStores[e].clean(),this.gestureTimeoutStores[e].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...e){const n=this.config.shared,r={};let o;if(!(n.target&&(o=n.target(),!o))){if(n.enabled){for(const i of this.gestures){const a=this.config[i],l=yI(r,a.eventOptions,!!o);if(a.enabled){const c=y1.get(i);new c(this,e,i).bind(l)}}const s=yI(r,n.eventOptions,!!o);for(const i in this.nativeHandlers)s(i,"",a=>this.nativeHandlers[i](ht(ht({},this.state.shared),{},{event:a,args:e})),void 0,!0)}for(const s in r)r[s]=GX(...r[s]);if(!o)return r;for(const s in r){const{device:i,capture:a,passive:l}=NX(s);this._targetEventStore.add(o,i,"",r[s],{capture:a,passive:l})}}}}function Oa(t,e){t.gestures.add(e),t.gestureEventStores[e]=new vj(t,e),t.gestureTimeoutStores[e]=new bq}function Cq(t,e){e.drag&&Oa(t,"drag"),e.wheel&&Oa(t,"wheel"),e.scroll&&Oa(t,"scroll"),e.move&&Oa(t,"move"),e.pinch&&Oa(t,"pinch"),e.hover&&Oa(t,"hover")}const yI=(t,e,n)=>(r,o,s,i={},a=!1)=>{var l,c;const u=(l=i.capture)!==null&&l!==void 0?l:e.capture,h=(c=i.passive)!==null&&c!==void 0?c:e.passive;let p=a?r:$X(r,o,u);n&&h&&(p+="Passive"),t[p]=t[p]||[],t[p].push(s)},_q=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function Iq(t){const e={},n={},r=new Set;for(let o in t)_q.test(o)?(r.add(RegExp.lastMatch),n[o]=t[o]):e[o]=t[o];return[n,e,r]}function Da(t,e,n,r,o,s){if(!t.has(n)||!y1.has(r))return;const i=n+"Start",a=n+"End",l=c=>{let u;return c.first&&i in e&&e[i](c),n in e&&(u=e[n](c)),c.last&&a in e&&e[a](c),u};o[r]=l,s[r]=s[r]||{}}function Eq(t,e){const[n,r,o]=Iq(t),s={};return Da(o,n,"onDrag","drag",s,e),Da(o,n,"onWheel","wheel",s,e),Da(o,n,"onScroll","scroll",s,e),Da(o,n,"onPinch","pinch",s,e),Da(o,n,"onMove","move",s,e),Da(o,n,"onHover","hover",s,e),{handlers:s,config:e,nativeHandlers:r}}function kq(t,e={},n,r){const o=Te.useMemo(()=>new Pq(t),[]);if(o.applyHandlers(t,r),o.applyConfig(e,n),Te.useEffect(o.effect.bind(o)),Te.useEffect(()=>o.clean.bind(o),[]),e.target===void 0)return o.bind.bind(o)}function Tq(t){return t.forEach(fq),function(n,r){const{handlers:o,nativeHandlers:s,config:i}=Eq(n,r||{});return kq(o,i,void 0,s)}}const SI=10,Mq=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function xj(t){let{deltaY:e,deltaX:n}=t,r=0;return t.ctrlKey||t.altKey||t.metaKey?r=(Math.abs(e)>SI?SI*Math.sign(e):e)/100:t.shiftKey&&!Mq&&(n=e,e=0),{x:-n,y:-e,z:-r}}const Aq=Tq([mq,gq]);let Ra;const jq=t=>Ra===void 0?(Ra=t,!1):t-Ra>120&&t-Ra<160?(Ra=t,!0):(Ra=t,!1);function Oq(t){const e=z(),n=w.useMemo(()=>{let r="not sure";const o=({event:m})=>{if(!e.getInstanceState().isFocused||(r="not sure",jq(Date.now())))return;const v=e.getEditingShapeId();if(v){const b=e.getShape(v);if(b&&e.getShapeUtil(b).canScroll(b)){const C=e.getShapePageBounds(v);if(C!=null&&C.containsPoint(e.inputs.currentPagePoint))return}}xe(m),_t(m);const y=xj(m);if(y.x===0&&y.y===0)return;const S={type:"wheel",name:"wheel",delta:y,point:new x(m.clientX,m.clientY),shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey,metaKey:m.metaKey,accelKey:un(m)};e.dispatch(S)};let s=1,i=1,a=1,l=0;const c=new x,u=new x,h=m=>{const v=t.current;r="not sure";const{event:y,origin:S,da:b}=m;y instanceof WheelEvent||(y.target===v||v!=null&&v.contains(y.target))&&(u.x=S[0],u.y=S[1],c.x=S[0],c.y=S[1],s=b[0],i=e.getZoomLevel(),e.dispatch({type:"pinch",name:"pinch_start",point:{x:S[0],y:S[1],z:e.getZoomLevel()},delta:{x:0,y:0},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)}))},p=m=>{if(m&&(r="zooming"),r==="zooming")return;const v=Math.abs(l-s),y=x.Dist(c,u);switch(r){case"not sure":{v>24?r="zooming":y>16&&(r="panning");break}case"panning":{v>64&&(r="zooming");break}}};return{onWheel:o,onPinchStart:h,onPinchEnd:m=>{const v=t.current,{event:y,origin:S,offset:b}=m;if(y instanceof WheelEvent||!(y.target===v||v!=null&&v.contains(y.target)))return;const P=b[0];r="not sure",e.timers.requestAnimationFrame(()=>{e.dispatch({type:"pinch",name:"pinch_end",point:{x:S[0],y:S[1],z:P},delta:{x:S[0],y:S[1]},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)})})},onPinch:m=>{const v=t.current,{event:y,origin:S,offset:b,da:P}=m;if(y instanceof WheelEvent||!(y.target===v||v!=null&&v.contains(y.target)))return;const C=m.type==="gesturechange"||m.type==="gestureend";l=P[0];const _=S[0]-u.x,E=S[1]-u.y;switch(u.x=S[0],u.y=S[1],p(C),r){case"zooming":{a=b[0],e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:a},delta:{x:_,y:E},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)});break}case"panning":{e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:i},delta:{x:_,y:E},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)});break}}}}},[e,t]);Aq(n,{target:t,eventOptions:{passive:!1},pinch:{from:()=>[e.getZoomLevel(),0],scaleBounds:()=>{const r=e.getBaseZoom(),o=e.getCameraOptions().zoomSteps,s=o[0]*r,i=o[o.length-1]*r;return{from:e.getZoomLevel(),max:i,min:s}}}})}function Vy(t,e,n){const r=t.getShape(e),o=t.getShapeHandles(r);return{shape:r,handle:o.find(s=>s.id===n)}}function Dq(t,e){const n=z();return w.useMemo(()=>{const r=l=>{if(l.isKilled)return;const c=Rf(l.currentTarget);dd(c,l);const{shape:u,handle:h}=Vy(n,t,e);h&&n.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_down",...lr(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:u}=Vy(n,t,e);u&&n.dispatch({type:"pointer",target:"handle",handle:u,shape:c,name:"pointer_move",...lr(l)})},onPointerUp:l=>{if(l.isKilled)return;const c=Rf(l.currentTarget);hd(c,l);const{shape:u,handle:h}=Vy(n,t,e);h&&n.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_up",...lr(l)})}}},[n,t,e])}function Rq(t){const e=z();w.useLayoutEffect(()=>{const n=kT(()=>{t.current&&e.updateViewportScreenBounds(t.current)},200,{trailing:!0}),r=e.timers.setInterval(n,1e3);window.addEventListener("resize",n);const o=new ResizeObserver(a=>{a[0].contentRect&&n()}),s=t.current;let i=null;return s&&(o.observe(s),i=Lq(s),i.addEventListener("scroll",n)),()=>{clearInterval(r),window.removeEventListener("resize",n),o.disconnect(),i==null||i.removeEventListener("scroll",n),n.cancel()}},[e,t])}/*!
88
+ */(function(t){(function(){var e={}.hasOwnProperty;function n(){for(var s="",i=0;i<arguments.length;i++){var a=arguments[i];a&&(s=o(s,r(a)))}return s}function r(s){if(typeof s=="string"||typeof s=="number")return s;if(typeof s!="object")return"";if(Array.isArray(s))return n.apply(null,s);if(s.toString!==Object.prototype.toString&&!s.toString.toString().includes("[native code]"))return s.toString();var i="";for(var a in s)e.call(s,a)&&s[a]&&(i=o(i,a));return i}function o(s,i){return i?s?s+" "+i:s+i:s}t.exports?(n.default=n,t.exports=n):window.classNames=n})()})(rj);var uX=rj.exports;const le=xi(uX),oj="3.7.0-canary.8e16c48b63b1",eI={major:"2024-09-13T14:36:29.063Z",minor:"2024-12-28T18:42:41.901Z",patch:"2024-12-28T18:42:41.901Z"},dX={error:null};class u1 extends w.Component{constructor(){super(...arguments);I(this,"state",dX)}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n){var r,o;(o=(r=this.props).onError)==null||o.call(r,n)}render(){const{error:n}=this.state;if(n!==null){const{fallback:r}=this.props;return d.jsx(r,{error:n})}return this.props.children}}function Uu({children:t,fallback:e,...n}){return e===null?t:d.jsx(u1,{fallback:e,...n,children:t})}function d1(t,e){return Rg(`${t}_${e}`)}function Jl(t){return Rg(`${w.useId()}${t??""}`)}function ro(t){const e=zn(w.useContext(sj));return Rg(`${e}_${t}`)}function Rg(t){return t.replace(/:/g,"_")}const sj=w.createContext(null);function hX({children:t}){const e=Jl();return d.jsx(sj.Provider,{value:e,children:t})}const h1=w.createContext(null);function z(){const t=Te.useContext(h1);if(!t)throw new Error("useEditor must be used inside of the <Tldraw /> or <TldrawEditor /> components");return t}function ki(){return Te.useContext(h1)}function p1({editor:t,children:e}){return d.jsx(h1.Provider,{value:t,children:d.jsx(hX,{children:e})})}function pX(){return d.jsx("div",{className:"tl-background"})}function ec(t,e,n,r,o,s){w.useLayoutEffect(()=>{const i=t.current;if(!i||e===void 0)return;let a=`translate(${e}px, ${n}px)`;r!==void 0&&(a+=` scale(${r})`),o!==void 0&&(a+=` rotate(${o}rad)`),s&&(a+=` translate(${s.x}px, ${s.y}px)`),i.style.transform=a})}const Dt={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),easeInOutQuad:t=>t<.5?2*t*t:-1+(4-2*t)*t,easeInCubic:t=>t*t*t,easeOutCubic:t=>--t*t*t+1,easeInOutCubic:t=>t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1,easeInQuart:t=>t*t*t*t,easeOutQuart:t=>1- --t*t*t*t,easeInOutQuart:t=>t<.5?8*t*t*t*t:1-8*--t*t*t*t,easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>1+--t*t*t*t*t,easeInOutQuint:t=>t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t,easeInSine:t=>1-Math.cos(t*Math.PI/2),easeOutSine:t=>Math.sin(t*Math.PI/2),easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,easeInExpo:t=>t<=0?0:Math.pow(2,10*t-10),easeOutExpo:t=>t>=1?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>t<=0?0:t>=1?1:t<.5?Math.pow(2,20*t-10)/2:(2-Math.pow(2,-20*t+10))/2};class x{constructor(e=0,n=0,r=1){this.x=e,this.y=n,this.z=r}get pressure(){return this.z}set(e=this.x,n=this.y,r=this.z){return this.x=e,this.y=n,this.z=r,this}setTo({x:e=0,y:n=0,z:r=1}){return this.x=e,this.y=n,this.z=r,this}rot(e){if(e===0)return this;const{x:n,y:r}=this,o=Math.sin(e),s=Math.cos(e);return this.x=n*s-r*o,this.y=n*o+r*s,this}rotWith(e,n){if(n===0)return this;const r=this.x-e.x,o=this.y-e.y,s=Math.sin(n),i=Math.cos(n);return this.x=e.x+(r*i-o*s),this.y=e.y+(r*s+o*i),this}clone(){const{x:e,y:n,z:r}=this;return new x(e,n,r)}sub(e){return this.x-=e.x,this.y-=e.y,this}subXY(e,n){return this.x-=e,this.y-=n,this}subScalar(e){return this.x-=e,this.y-=e,this}add(e){return this.x+=e.x,this.y+=e.y,this}addXY(e,n){return this.x+=e,this.y+=n,this}addScalar(e){return this.x+=e,this.y+=e,this}clamp(e,n){return this.x=Math.max(this.x,e),this.y=Math.max(this.y,e),n!==void 0&&(this.x=Math.min(this.x,n),this.y=Math.min(this.y,n)),this}div(e){return this.x/=e,this.y/=e,this}divV(e){return this.x/=e.x,this.y/=e.y,this}mul(e){return this.x*=e,this.y*=e,this}mulV(e){return this.x*=e.x,this.y*=e.y,this}abs(){return this.x=Math.abs(this.x),this.y=Math.abs(this.y),this}nudge(e,n){const r=x.Tan(e,this);return this.add(r.mul(n))}neg(){return this.x*=-1,this.y*=-1,this}cross(e){return this.x=this.y*e.z-this.z*e.y,this.y=this.z*e.x-this.x*e.z,this}dpr(e){return x.Dpr(this,e)}cpr(e){return x.Cpr(this,e)}len2(){return x.Len2(this)}len(){return x.Len(this)}pry(e){return x.Pry(this,e)}per(){const{x:e,y:n}=this;return this.x=n,this.y=-e,this}uni(){return x.Uni(this)}tan(e){return x.Tan(this,e)}dist(e){return x.Dist(this,e)}distanceToLineSegment(e,n){return x.DistanceToLineSegment(e,n,this)}slope(e){return x.Slope(this,e)}snapToGrid(e){return this.x=Math.round(this.x/e)*e,this.y=Math.round(this.y/e)*e,this}angle(e){return x.Angle(this,e)}toAngle(){return x.ToAngle(this)}lrp(e,n){return this.x=this.x+(e.x-this.x)*n,this.y=this.y+(e.y-this.y)*n,this}equals(e){return x.Equals(this,e)}equalsXY(e,n){return x.EqualsXY(this,e,n)}norm(){const e=this.len();return this.x=e===0?0:this.x/e,this.y=e===0?0:this.y/e,this}toFixed(){return x.ToFixed(this)}toString(){return x.ToString(x.ToFixed(this))}toJson(){return x.ToJson(this)}toArray(){return x.ToArray(this)}static Add(e,n){return new x(e.x+n.x,e.y+n.y)}static AddXY(e,n,r){return new x(e.x+n,e.y+r)}static Sub(e,n){return new x(e.x-n.x,e.y-n.y)}static SubXY(e,n,r){return new x(e.x-n,e.y-r)}static AddScalar(e,n){return new x(e.x+n,e.y+n)}static SubScalar(e,n){return new x(e.x-n,e.y-n)}static Div(e,n){return new x(e.x/n,e.y/n)}static Mul(e,n){return new x(e.x*n,e.y*n)}static DivV(e,n){return new x(e.x/n.x,e.y/n.y)}static MulV(e,n){return new x(e.x*n.x,e.y*n.y)}static Neg(e){return new x(-e.x,-e.y)}static Per(e){return new x(e.y,-e.x)}static Abs(e){return new x(Math.abs(e.x),Math.abs(e.y))}static Dist(e,n){return((e.y-n.y)**2+(e.x-n.x)**2)**.5}static DistMin(e,n,r){return(e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y)<r**2}static Dist2(e,n){return(e.x-n.x)*(e.x-n.x)+(e.y-n.y)*(e.y-n.y)}static Dpr(e,n){return e.x*n.x+e.y*n.y}static Cross(e,n){return new x(e.y*n.z-e.z*n.y,e.z*n.x-e.x*n.z)}static Cpr(e,n){return e.x*n.y-n.x*e.y}static Len2(e){return e.x*e.x+e.y*e.y}static Len(e){return(e.x*e.x+e.y*e.y)**.5}static Pry(e,n){return x.Dpr(e,n)/x.Len(n)}static Uni(e){return x.Div(e,x.Len(e))}static Tan(e,n){return x.Uni(x.Sub(e,n))}static Min(e,n){return new x(Math.min(e.x,n.x),Math.min(e.y,n.y))}static Max(e,n){return new x(Math.max(e.x,n.x),Math.max(e.y,n.y))}static From({x:e,y:n,z:r=1}){return new x(e,n,r)}static FromArray(e){return new x(e[0],e[1])}static Rot(e,n=0){const r=Math.sin(n),o=Math.cos(n);return new x(e.x*o-e.y*r,e.x*r+e.y*o)}static RotWith(e,n,r){const o=e.x-n.x,s=e.y-n.y,i=Math.sin(r),a=Math.cos(r);return new x(n.x+(o*a-s*i),n.y+(o*i+s*a))}static NearestPointOnLineThroughPoint(e,n,r){return x.Mul(n,x.Sub(r,e).pry(n)).add(e)}static NearestPointOnLineSegment(e,n,r,o=!0){if(x.Equals(e,r)||x.Equals(n,r))return x.From(r);const s=x.Tan(n,e),i=x.Add(e,x.Mul(s,x.Sub(r,e).pry(s)));if(o){if(i.x<Math.min(e.x,n.x))return x.Cast(e.x<n.x?e:n);if(i.x>Math.max(e.x,n.x))return x.Cast(e.x>n.x?e:n);if(i.y<Math.min(e.y,n.y))return x.Cast(e.y<n.y?e:n);if(i.y>Math.max(e.y,n.y))return x.Cast(e.y>n.y?e:n)}return i}static DistanceToLineThroughPoint(e,n,r){return x.Dist(r,x.NearestPointOnLineThroughPoint(e,n,r))}static DistanceToLineSegment(e,n,r,o=!0){return x.Dist(r,x.NearestPointOnLineSegment(e,n,r,o))}static Snap(e,n=1){return new x(Math.round(e.x/n)*n,Math.round(e.y/n)*n)}static Cast(e){return e instanceof x?e:x.From(e)}static Slope(e,n){return e.x===n.y?NaN:(e.y-n.y)/(e.x-n.x)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}static Angle(e,n){return Math.atan2(n.y-e.y,n.x-e.x)}static Lrp(e,n,r){return x.Sub(n,e).mul(r).add(e)}static Med(e,n){return new x((e.x+n.x)/2,(e.y+n.y)/2)}static Equals(e,n){return Math.abs(e.x-n.x)<1e-4&&Math.abs(e.y-n.y)<1e-4}static EqualsXY(e,n,r){return e.x===n&&e.y===r}static Clockwise(e,n,r){return(r.x-e.x)*(n.y-e.y)-(n.x-e.x)*(r.y-e.y)<0}static Rescale(e,n){const r=x.Len(e);return new x(n*e.x/r,n*e.y/r)}static ScaleWithOrigin(e,n,r){return x.Sub(e,r).mul(n).add(r)}static ToFixed(e){return new x(as(e.x),as(e.y))}static ToInt(e){return new x(parseInt(e.x.toFixed(0)),parseInt(e.y.toFixed(0)),parseInt((e.z??0).toFixed(0)))}static ToCss(e){return`${e.x},${e.y}`}static Nudge(e,n,r){return x.Add(e,x.Tan(n,e).mul(r))}static ToString(e){return`${e.x}, ${e.y}`}static ToAngle(e){let n=Math.atan2(e.y,e.x);return n<0&&(n+=Math.PI*2),n}static FromAngle(e,n=1){return new x(Math.cos(e)*n,Math.sin(e)*n)}static ToArray(e){return[e.x,e.y,e.z]}static ToJson(e){const{x:n,y:r,z:o}=e;return{x:n,y:r,z:o}}static Average(e){const n=e.length,r=new x(0,0);if(n===0)return r;for(let o=0;o<n;o++)r.add(e[o]);return r.div(n)}static Clamp(e,n,r){return r===void 0?new x(Math.min(Math.max(e.x,n)),Math.min(Math.max(e.y,n))):new x(Math.min(Math.max(e.x,n),r),Math.min(Math.max(e.y,n),r))}static PointsBetween(e,n,r=6){const o=[];for(let s=0;s<r;s++){const i=Dt.easeInQuad(s/(r-1)),a=x.Lrp(e,n,i);a.z=Math.min(1,.5+Math.abs(.5-fX(i))*.65),o.push(a)}return o}static SnapToGrid(e,n=8){return new x(Math.round(e.x/n)*n,Math.round(e.y/n)*n)}}const fX=t=>t<.5?2*t*t:-1+(4-2*t)*t;function je(t){return`${N(t.x)},${N(t.y)} `}function Bn(t,e){return`${N((t.x+e.x)/2)},${N((t.y+e.y)/2)} `}const De=Math.PI,qe=De/2,Ne=De*2,gX=Math.sin;function zt(t,e,n){return Math.max(e,typeof n<"u"?Math.min(t,n):t)}function ph(t,e=1e10){return t?Math.round(t*e)/e:0}function ui(t,e,n=1e-6){return Math.abs(t-e)<=n}function ij(t,e){const n=Math.pow(t-e,2)/Math.pow(t+e,2);return De*(t+e)*(1+3*n/(10+Math.sqrt(4-3*n)))}function Ji(t){return t=t%Ne,t<0?t=t+Ne:t===0&&(t=0),t}function ud(t,e){return t=Ji(t),e=Ji(e),t>e&&(e+=Ne),e-t}function aj(t,e){return Ne-ud(t,e)}function ap(t,e){const n=(e-t)%Ne;return 2*n%Ne-n}function vx(t){return(Ne+t)%Ne}function Df(t,e){const n=Ne/e;let r=Math.floor((vx(t)+n/2)/n)*n%Ne;return r<De&&(r+=Ne),r>De&&(r-=Ne),r}function lj(t,e){return t===e||ui(t%(Math.PI/2)-e%(Math.PI/2),0)}function mX(t){return t*De/180}function yX(t){return t*180/De}function da(t,e,n){return new x(t.x,t.y).add(x.FromAngle(n,e))}function Uy(t,e,n){const r=t/2,o=e/2,s=[];let i=1/0,a=-1/0,l=1/0,c=-1/0;for(let g=0;g<n;g++){const m=Ne/n,v=-qe+g*m,y=r+r*Math.cos(v),S=o+o*Math.sin(v);y<i&&(i=y),S<l&&(l=S),y>a&&(a=y),S>c&&(c=S),s.push(new x(y,S))}const u=a-i,h=c-l,p=t-u,f=e-h;if(p!==0||f!==0)for(let g=0;g<s.length;g++){const m=s[g];m.x=(m.x-i)/u*t,m.y=(m.y-l)/h*e}return s}function Mc(t,e,n,r){return t<r&&n<e}function Gr(t,e,n,r){const o=Math.max(t,n),s=Math.min(e,r);return o<=s?[o,s]:null}function tI(t,e,n){return(e.x-t.x)*(n.y-t.y)-(n.x-t.x)*(e.y-t.y)}function hr(t,e){let n=0,r,o;for(let s=0;s<e.length;s++){if(r=e[s],r.x===t.x&&r.y===t.y||(o=e[(s+1)%e.length],x.Dist(t,r)+x.Dist(t,o)===x.Dist(r,o)))return!0;r.y<=t.y?o.y>t.y&&tI(r,o,t)>0&&(n+=1):o.y<=t.y&&tI(r,o,t)<0&&(n-=1)}return n!==0}function N(t){return Math.round(t*1e4)/1e4}function as(t){return Math.round(t*100)/100}const nI=t=>Math.abs(t)<Number.MAX_SAFE_INTEGER;function Ys(t,e,n){return n<0?ud(t,e):aj(t,e)}function xx(t,e,n,r){let o;if(Math.abs(t)>De){o=ap(e,r);const s=ap(r,n);return Math.abs(o)<Math.abs(s)?o/t:(t-s)/t}else{o=ap(e,r);const s=o/t;return Math.sign(o)!==Math.sign(t)?Math.abs(s)>.5?1:0:s}}function SX(t,e,n,r){const o=2*((e-t)%Ne)%Ne-(e-t)%Ne;return r?(Ne-Math.abs(o))*(n?1:-1):o}function f1(t,e,n){const r=-2*(t.x*(e.y-n.y)-t.y*(e.x-n.x)+e.x*n.y-n.x*e.y),o=((t.x*t.x+t.y*t.y)*(n.y-e.y)+(e.x*e.x+e.y*e.y)*(t.y-n.y)+(n.x*n.x+n.y*n.y)*(e.y-t.y))/r,s=((t.x*t.x+t.y*t.y)*(e.x-n.x)+(e.x*e.x+e.y*e.y)*(n.x-t.x)+(n.x*n.x+n.y*n.y)*(t.x-e.x))/r;return!Number.isFinite(o)||!Number.isFinite(s)?null:new x(o,s)}function vX(t,e,n,r,o){if(n===null)return[x.From(t),x.From(e)];const s=[],i=x.Angle(n,t),a=x.Angle(n,e),l=ud(i,a);for(let c=0;c<o;c++){const u=c/(o-1),h=i+l*u,p=da(n,r,h);s.push(p)}return s}const Hy=({brush:t,color:e,opacity:n,className:r})=>{const o=w.useRef(null);ec(o,t.x,t.y);const s=N(Math.max(1,t.w)),i=N(Math.max(1,t.h));return d.jsx("svg",{className:"tl-overlays__item",ref:o,children:e?d.jsxs("g",{className:"tl-brush",opacity:n,children:[d.jsx("rect",{width:s,height:i,fill:e,opacity:.75}),d.jsx("rect",{width:s,height:i,fill:"none",stroke:e,opacity:.1})]}):d.jsx("rect",{className:`tl-brush tl-brush__default ${r}`,width:s,height:i})})},Ge={isSafari:!1,isIos:!1,isChromeForIos:!1,isFirefox:!1,isAndroid:!1,isWebview:!1,isDarwin:!1};typeof window<"u"&&"navigator"in window&&(Ge.isSafari=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),Ge.isIos=!!navigator.userAgent.match(/iPad/i)||!!navigator.userAgent.match(/iPhone/i),Ge.isChromeForIos=/crios.*safari/i.test(navigator.userAgent),Ge.isFirefox=/firefox/i.test(navigator.userAgent),Ge.isAndroid=/android/i.test(navigator.userAgent),Ge.isDarwin=window.navigator.userAgent.toLowerCase().indexOf("mac")>-1);const rI={isLocked:!1,wheelBehavior:"pan",panSpeed:1,zoomSpeed:1,zoomSteps:[.1,.25,.5,1,2,4,8]},Ky={duration:0,easing:Dt.easeInOutCubic},oI={CAMERA_MOVE:-10},xX=["top","right","bottom","left"],sI=0,g1=2,fh=1,iI=5,wX=128;var Wy={};const bX={},cj=Dn("pointerCaptureTrackingObject",{defaults:{all:new Map},shouldStoreForSession:!1}),bt={logPreventDefaults:Dn("logPreventDefaults",{defaults:{all:!1}}),logPointerCaptures:Dn("logPointerCaptures",{defaults:{all:!1}}),logElementRemoves:Dn("logElementRemoves",{defaults:{all:!1}}),debugSvg:Dn("debugSvg",{defaults:{all:!1}}),showFps:Dn("showFps",{defaults:{all:!1}}),measurePerformance:Dn("measurePerformance",{defaults:{all:!1}}),throwToBlob:Dn("throwToBlob",{defaults:{all:!1}}),reconnectOnPing:Dn("reconnectOnPing",{defaults:{all:!1}}),debugCursors:Dn("debugCursors",{defaults:{all:!1}}),forceSrgb:Dn("forceSrgbColors",{defaults:{all:!1}}),debugGeometry:Dn("debugGeometry",{defaults:{all:!1}}),hideShapes:Dn("hideShapes",{defaults:{all:!1}}),editOnType:Dn("editOnType",{defaults:{all:!1}})};if(typeof Element<"u"){const t=Element.prototype.removeChild;jo("element removal logging",()=>{bt.logElementRemoves.get()?Element.prototype.removeChild=function(e){return console.warn("[tldraw] removing child:",e),t.call(this,e)}:Element.prototype.removeChild=t})}function Dn(t,{defaults:e,shouldStoreForSession:n=!0}){return PX({name:t,defaults:e,shouldStoreForSession:n})}function PX(t){const e=_X(t),n=t.shouldStoreForSession?CX(t.name):null,r=Et(`debug:${t.name}`,n??e);return typeof window<"u"&&(t.shouldStoreForSession&&jo(`debug:${t.name}`,()=>{const o=r.get();o===e?JT(`tldraw_debug:${t.name}`):Ew(`tldraw_debug:${t.name}`,JSON.stringify(o))}),Object.defineProperty(window,`tldraw${t.name.replace(/^[a-z]/,o=>o.toUpperCase())}`,{get(){return r.get()},set(o){r.set(o)},configurable:!0})),Object.assign(r,t)}function CX(t){try{return JSON.parse(QT(`tldraw_debug:${t}`)??"null")}catch{return null}}function Gy(t){try{return t()}catch{return null}}function _X(t){switch(Gy(()=>Wy.TLDRAW_ENV)??Gy(()=>Wy.VERCEL_PUBLIC_TLDRAW_ENV)??Gy(()=>Wy.NEXT_PUBLIC_TLDRAW_ENV)??"production"){case"production":return t.defaults.production??t.defaults.all;case"preview":case"staging":return t.defaults.staging??t.defaults.all;default:return t.defaults.development??t.defaults.all}}function Rf(t){if(t instanceof HTMLElement)return t;if(t.parentElement)return Rf(t.parentElement);throw Error("Could not find a parent element of an HTML type!")}function xe(t){t.preventDefault(),bt.logPreventDefaults.get()&&console.warn("preventDefault called on event:",t)}function dd(t,e){if(t.setPointerCapture(e.pointerId),bt.logPointerCaptures.get()){const n=cj.get();n.set(t,(n.get(t)??0)+1),console.warn("setPointerCapture called on element:",t,e)}}function hd(t,e){if(t.hasPointerCapture(e.pointerId)&&(t.releasePointerCapture(e.pointerId),bt.logPointerCaptures.get())){const n=cj.get();n.get(t)===1?n.delete(t):n.has(t)?n.set(t,n.get(t)-1):console.warn("Release without capture"),console.warn("releasePointerCapture called on element:",t,e)}}const _t=t=>t.stopPropagation(),rn=(t,e,n)=>{t&&t.style.setProperty(e,n)},un=t=>Ge.isDarwin?t.metaKey:t.ctrlKey||t.metaKey;function lr(t){return t.isKilled=!0,{point:{x:t.clientX,y:t.clientY,z:t.pressure},shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.metaKey||t.ctrlKey,metaKey:t.metaKey,accelKey:un(t),pointerId:t.pointerId,button:t.button,isPen:t.pointerType==="pen"}}function m1(){const t=z();return w.useMemo(function(){let r,o;function s(m){if(!m.isKilled){if(m.button===g1){t.dispatch({type:"pointer",target:"canvas",name:"right_click",...lr(m)});return}m.button!==0&&m.button!==1&&m.button!==5||(dd(m.currentTarget,m),t.dispatch({type:"pointer",target:"canvas",name:"pointer_down",...lr(m)}))}}function i(m){m.isKilled||m.clientX===r&&m.clientY===o||(r=m.clientX,o=m.clientY,t.dispatch({type:"pointer",target:"canvas",name:"pointer_move",...lr(m)}))}function a(m){m.isKilled||m.button!==0&&m.button!==1&&m.button!==2&&m.button!==5||(r=m.clientX,o=m.clientY,hd(m.currentTarget,m),t.dispatch({type:"pointer",target:"canvas",name:"pointer_up",...lr(m)}))}function l(m){if(m.isKilled||t.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const v=m.pointerType==="mouse"||m.pointerType==="pen";t.updateInstanceState({isHoveringCanvas:v?!0:null})}function c(m){if(m.isKilled||t.getInstanceState().isPenMode&&m.pointerType!=="pen")return;const v=m.pointerType==="mouse"||m.pointerType==="pen";t.updateInstanceState({isHoveringCanvas:v?!1:null})}function u(m){m.isKilled=!0,xe(m)}function h(m){m.isKilled=!0,m.target instanceof HTMLElement&&m.target.tagName!=="A"&&m.target.tagName!=="TEXTAREA"&&!(t.getEditingShape()&&m.target.className.includes("tl-text-content"))&&xe(m)}function p(m){xe(m)}async function f(m){var y,S;if(xe(m),_t(m),!((S=(y=m.dataTransfer)==null?void 0:y.files)!=null&&S.length))return;const v=Array.from(m.dataTransfer.files);await t.putExternalContent({type:"files",files:v,point:t.screenToPage({x:m.clientX,y:m.clientY}),ignoreParent:!1})}function g(m){_t(m)}return{onPointerDown:s,onPointerMove:i,onPointerUp:a,onPointerEnter:l,onPointerLeave:c,onDragOver:p,onDrop:f,onTouchStart:u,onTouchEnd:h,onClick:g}},[t])}function IX(){const t=z();w.useEffect(()=>{let e=t.getInstanceState().isCoarsePointer;const n=i=>{const a=i.pointerType!=="mouse";e!==a&&(e=a,t.updateInstanceState({isCoarsePointer:a}))};window.addEventListener("pointerdown",n,{capture:!0});const r=window.matchMedia&&window.matchMedia("(any-pointer: coarse)"),o=Ge.isFirefox&&!Ge.isAndroid&&!Ge.isIos,s=()=>{const i=o?!1:r.matches;e===i&&(e=i,t.updateInstanceState({isCoarsePointer:i}))};return r&&(r.addEventListener("change",s),s()),()=>{window.removeEventListener("pointerdown",n,{capture:!0}),r&&r.removeEventListener("change",s)}},[t])}const uj=w.createContext(null);function dj({container:t,children:e}){return d.jsx(uj.Provider,{value:t,children:e})}function Mt(){return zn(w.useContext(uj),"useContainer used outside of <Tldraw />")}function EX(){const t=z(),e=Mt(),n=U("isFocused",()=>t.getIsFocused(),[t]);w.useEffect(()=>{if(!e)return;function r(o){if(o.isSpecialRedispatchedEvent)return;xe(o),_t(o);const s=e.querySelector(".tl-canvas");if(!s)return;const i=new DragEvent(o.type,o);i.isSpecialRedispatchedEvent=!0,s.dispatchEvent(i)}return e.addEventListener("dragover",r),e.addEventListener("drop",r),()=>{e.removeEventListener("dragover",r),e.removeEventListener("drop",r)}},[e]),w.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))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)},t.updateInstanceState({devicePixelRatio:window.devicePixelRatio})};return o(),()=>{r==null||r()}},[t]),w.useEffect(()=>{if(!n)return;const r=a=>{if(a.altKey&&(t.isIn("zoom")||!t.getPath().endsWith(".idle"))&&!gh(t)&&xe(a),a.isKilled)return;switch(a.isKilled=!0,a.key){case"=":case"-":case"0":{if(a.metaKey||a.ctrlKey){xe(a);return}break}case"Tab":{if(gh(t))return;break}case",":return;case"Escape":{if((t.getEditingShape()||t.getSelectedShapeIds().length>0)&&xe(a),t.menus.getOpenMenus().length>0)return;t.inputs.keys.has("Escape")||(t.inputs.keys.add("Escape"),t.cancel(),e.focus());return}default:if(gh(t))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,metaKey:a.metaKey,accelKey:un(a)};t.dispatch(l)},o=a=>{if(a.isKilled||(a.isKilled=!0,gh(t))||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,metaKey:a.metaKey,accelKey:un(a)};t.dispatch(l)};function s(a){var l,c;if(e.contains(a.target)){const u=a.touches[0].pageX,h=a.touches[0].radiusX||0;(u-h<10||u+h>t.getViewportScreenBounds().width-10)&&(((l=a.target)==null?void 0:l.tagName)==="BUTTON"&&((c=a.target)==null||c.click()),xe(a))}}const i=a=>{e.contains(a.target)&&(a.ctrlKey||a.metaKey)&&xe(a)};return e.addEventListener("touchstart",s,{passive:!1}),e.addEventListener("wheel",i,{passive:!1}),document.addEventListener("gesturestart",xe),document.addEventListener("gesturechange",xe),document.addEventListener("gestureend",xe),e.addEventListener("keydown",r),e.addEventListener("keyup",o),()=>{e.removeEventListener("touchstart",s),e.removeEventListener("wheel",i),document.removeEventListener("gesturestart",xe),document.removeEventListener("gesturechange",xe),document.removeEventListener("gestureend",xe),e.removeEventListener("keydown",r),e.removeEventListener("keyup",o)}},[t,e,n])}const kX=["input","select","button","textarea"];function gh(t){const{activeElement:e}=document;return t.menus.hasOpenMenus()||e&&(e.getAttribute("contenteditable")||kX.indexOf(e.tagName.toLowerCase())>-1)}const TX=["textarea","input"];function MX(t){const e=z();w.useEffect(()=>{const n=t.current;if(!n)return;const r=o=>{var s;if(o instanceof PointerEvent&&o.pointerType==="pen"){o.isKilled=!0;const{target:i}=o;if(TX.includes((s=i.tagName)==null?void 0:s.toLocaleLowerCase())||e.isIn("select.editing_shape"))return;xe(o)}};return n.addEventListener("touchstart",r),n.addEventListener("touchend",r),()=>{n.removeEventListener("touchstart",r),n.removeEventListener("touchend",r)}},[e,t])}function AX(t,e,n){return Math.max(e,Math.min(t,n))}const Gt={toVector(t,e){return t===void 0&&(t=e),Array.isArray(t)?t:[t,t]},add(t,e){return[t[0]+e[0],t[1]+e[1]]},sub(t,e){return[t[0]-e[0],t[1]-e[1]]},addTo(t,e){t[0]+=e[0],t[1]+=e[1]},subTo(t,e){t[0]-=e[0],t[1]-=e[1]}};function aI(t,e,n){return e===0||Math.abs(e)===1/0?Math.pow(t,n*5):t*e*n/(e+n*t)}function lI(t,e,n,r=.15){return r===0?AX(t,e,n):t<e?-aI(e-t,n-e,r)+e:t>n?+aI(t-n,n-e,r)+n:t}function jX(t,[e,n],[r,o]){const[[s,i],[a,l]]=t;return[lI(e,s,i,r),lI(n,a,l,o)]}function OX(t,e){if(typeof t!="object"||t===null)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e||"default");if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function DX(t){var e=OX(t,"string");return typeof e=="symbol"?e:String(e)}function sn(t,e,n){return e=DX(e),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function cI(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,r)}return n}function ht(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?cI(Object(n),!0).forEach(function(r){sn(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):cI(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}const hj={pointer:{start:"down",change:"move",end:"up"},mouse:{start:"down",change:"move",end:"up"},touch:{start:"start",change:"move",end:"end"},gesture:{start:"start",change:"change",end:"end"}};function uI(t){return t?t[0].toUpperCase()+t.slice(1):""}const RX=["enter","leave"];function LX(t=!1,e){return t&&!RX.includes(e)}function $X(t,e="",n=!1){const r=hj[t],o=r&&r[e]||e;return"on"+uI(t)+uI(o)+(LX(n,o)?"Capture":"")}const FX=["gotpointercapture","lostpointercapture"];function NX(t){let e=t.substring(2).toLowerCase();const n=!!~e.indexOf("passive");n&&(e=e.replace("passive",""));const r=FX.includes(e)?"capturecapture":"capture",o=!!~e.indexOf(r);return o&&(e=e.replace("capture","")),{device:e,capture:o,passive:n}}function zX(t,e=""){const n=hj[t],r=n&&n[e]||e;return t+r}function pj(t){return"touches"in t}function BX(t){return pj(t)?"touch":"pointerType"in t?t.pointerType:"mouse"}function UX(t){return Array.from(t.touches).filter(e=>{var n,r;return e.target===t.currentTarget||((n=t.currentTarget)===null||n===void 0||(r=n.contains)===null||r===void 0?void 0:r.call(n,e.target))})}function wx(t,e){try{const n=e.clientX-t.clientX,r=e.clientY-t.clientY,o=(e.clientX+t.clientX)/2,s=(e.clientY+t.clientY)/2,i=Math.hypot(n,r);return{angle:-(Math.atan2(n,r)*180)/Math.PI,distance:i,origin:[o,s]}}catch{}return null}function HX(t){return UX(t).map(e=>e.identifier)}function dI(t,e){const[n,r]=Array.from(t.touches).filter(o=>e.includes(o.identifier));return wx(n,r)}const hI=40,pI=800;function fj(t){let{deltaX:e,deltaY:n,deltaMode:r}=t;return r===1?(e*=hI,n*=hI):r===2&&(e*=pI,n*=pI),[e,n]}function KX(t){const e={};if("buttons"in t&&(e.buttons=t.buttons),"shiftKey"in t){const{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s}=t;Object.assign(e,{shiftKey:n,altKey:r,metaKey:o,ctrlKey:s})}return e}function Lf(t,...e){return typeof t=="function"?t(...e):t}function WX(){}function GX(...t){return t.length===0?WX:t.length===1?t[0]:function(){let e;for(const n of t)e=n.apply(this,arguments)||e;return e}}function fI(t,e){return Object.assign({},e,t||{})}const VX=32;class gj{constructor(e,n,r){this.ctrl=e,this.args=n,this.key=r,this.state||(this.state={},this.computeValues([0,0]),this.computeInitial(),this.init&&this.init(),this.reset())}get state(){return this.ctrl.state[this.key]}set state(e){this.ctrl.state[this.key]=e}get shared(){return this.ctrl.state.shared}get eventStore(){return this.ctrl.gestureEventStores[this.key]}get timeoutStore(){return this.ctrl.gestureTimeoutStores[this.key]}get config(){return this.ctrl.config[this.key]}get sharedConfig(){return this.ctrl.config.shared}get handler(){return this.ctrl.handlers[this.key]}reset(){const{state:e,shared:n,ingKey:r,args:o}=this;n[r]=e._active=e.active=e._blocked=e._force=!1,e._step=[!1,!1],e.intentional=!1,e._movement=[0,0],e._distance=[0,0],e._direction=[0,0],e._delta=[0,0],e._bounds=[[-1/0,1/0],[-1/0,1/0]],e.args=o,e.axis=void 0,e.memo=void 0,e.elapsedTime=e.timeDelta=0,e.direction=[0,0],e.distance=[0,0],e.overflow=[0,0],e._movementBound=[!1,!1],e.velocity=[0,0],e.movement=[0,0],e.delta=[0,0],e.timeStamp=0}start(e){const n=this.state,r=this.config;n._active||(this.reset(),this.computeInitial(),n._active=!0,n.target=e.target,n.currentTarget=e.currentTarget,n.lastOffset=r.from?Lf(r.from,n):n.offset,n.offset=n.lastOffset,n.startTime=n.timeStamp=e.timeStamp)}computeValues(e){const n=this.state;n._values=e,n.values=this.config.transform(e)}computeInitial(){const e=this.state;e._initial=e._values,e.initial=e.values}compute(e){const{state:n,config:r,shared:o}=this;n.args=this.args;let s=0;if(e&&(n.event=e,r.preventDefault&&e.cancelable&&n.event.preventDefault(),n.type=e.type,o.touches=this.ctrl.pointerIds.size||this.ctrl.touchIds.size,o.locked=!!document.pointerLockElement,Object.assign(o,KX(e)),o.down=o.pressed=o.buttons%2===1||o.touches>0,s=e.timeStamp-n.timeStamp,n.timeStamp=e.timeStamp,n.elapsedTime=n.timeStamp-n.startTime),n._active){const _=n._delta.map(Math.abs);Gt.addTo(n._distance,_)}this.axisIntent&&this.axisIntent(e);const[i,a]=n._movement,[l,c]=r.threshold,{_step:u,values:h}=n;if(r.hasCustomTransform?(u[0]===!1&&(u[0]=Math.abs(i)>=l&&h[0]),u[1]===!1&&(u[1]=Math.abs(a)>=c&&h[1])):(u[0]===!1&&(u[0]=Math.abs(i)>=l&&Math.sign(i)*l),u[1]===!1&&(u[1]=Math.abs(a)>=c&&Math.sign(a)*c)),n.intentional=u[0]!==!1||u[1]!==!1,!n.intentional)return;const p=[0,0];if(r.hasCustomTransform){const[_,E]=h;p[0]=u[0]!==!1?_-u[0]:0,p[1]=u[1]!==!1?E-u[1]:0}else p[0]=u[0]!==!1?i-u[0]:0,p[1]=u[1]!==!1?a-u[1]:0;this.restrictToAxis&&!n._blocked&&this.restrictToAxis(p);const f=n.offset,g=n._active&&!n._blocked||n.active;g&&(n.first=n._active&&!n.active,n.last=!n._active&&n.active,n.active=o[this.ingKey]=n._active,e&&(n.first&&("bounds"in r&&(n._bounds=Lf(r.bounds,n)),this.setup&&this.setup()),n.movement=p,this.computeOffset()));const[m,v]=n.offset,[[y,S],[b,P]]=n._bounds;n.overflow=[m<y?-1:m>S?1:0,v<b?-1:v>P?1:0],n._movementBound[0]=n.overflow[0]?n._movementBound[0]===!1?n._movement[0]:n._movementBound[0]:!1,n._movementBound[1]=n.overflow[1]?n._movementBound[1]===!1?n._movement[1]:n._movementBound[1]:!1;const C=n._active?r.rubberband||[0,0]:[0,0];if(n.offset=jX(n._bounds,n.offset,C),n.delta=Gt.sub(n.offset,f),this.computeMovement(),g&&(!n.last||s>VX)){n.delta=Gt.sub(n.offset,f);const _=n.delta.map(Math.abs);Gt.addTo(n.distance,_),n.direction=n.delta.map(Math.sign),n._direction=n._delta.map(Math.sign),!n.first&&s>0&&(n.velocity=[_[0]/s,_[1]/s],n.timeDelta=s)}}emit(){const e=this.state,n=this.shared,r=this.config;if(e._active||this.clean(),(e._blocked||!e.intentional)&&!e._force&&!r.triggerAllEvents)return;const o=this.handler(ht(ht(ht({},n),e),{},{[this.aliasKey]:e.values}));o!==void 0&&(e.memo=o)}clean(){this.eventStore.clean(),this.timeoutStore.clean()}}function YX([t,e],n){const r=Math.abs(t),o=Math.abs(e);if(r>o&&r>n)return"x";if(o>r&&o>n)return"y"}class XX extends gj{constructor(...e){super(...e),sn(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=Gt.add(this.state.lastOffset,this.state.movement)}computeMovement(){this.state.movement=Gt.sub(this.state.offset,this.state.lastOffset)}axisIntent(e){const n=this.state,r=this.config;if(!n.axis&&e){const o=typeof r.axisThreshold=="object"?r.axisThreshold[BX(e)]:r.axisThreshold;n.axis=YX(n._movement,o)}n._blocked=(r.lockDirection||!!r.axis)&&!n.axis||!!r.axis&&r.axis!==n.axis}restrictToAxis(e){if(this.config.axis||this.config.lockDirection)switch(this.state.axis){case"x":e[1]=0;break;case"y":e[0]=0;break}}}const qX=t=>t,gI=.15,mj={enabled(t=!0){return t},eventOptions(t,e,n){return ht(ht({},n.shared.eventOptions),t)},preventDefault(t=!1){return t},triggerAllEvents(t=!1){return t},rubberband(t=0){switch(t){case!0:return[gI,gI];case!1:return[0,0];default:return Gt.toVector(t)}},from(t){if(typeof t=="function")return t;if(t!=null)return Gt.toVector(t)},transform(t,e,n){const r=t||n.shared.transform;return this.hasCustomTransform=!!r,r||qX},threshold(t){return Gt.toVector(t,0)}},ZX=0,pd=ht(ht({},mj),{},{axis(t,e,{axis:n}){if(this.lockDirection=n==="lock",!this.lockDirection)return n},axisThreshold(t=ZX){return t},bounds(t={}){if(typeof t=="function")return s=>pd.bounds(t(s));if("current"in t)return()=>t.current;if(typeof HTMLElement=="function"&&t instanceof HTMLElement)return t;const{left:e=-1/0,right:n=1/0,top:r=-1/0,bottom:o=1/0}=t;return[[e,n],[r,o]]}}),fd=typeof window<"u"&&window.document&&window.document.createElement;function yj(){return fd&&"ontouchstart"in window}function QX(){return yj()||fd&&window.navigator.maxTouchPoints>1}function JX(){return fd&&"onpointerdown"in window}function eq(){return fd&&"exitPointerLock"in window.document}function tq(){try{return"constructor"in GestureEvent}catch{return!1}}const Mr={isBrowser:fd,gesture:tq(),touch:yj(),touchscreen:QX(),pointer:JX(),pointerLock:eq()},nq=250,rq=180,oq=.5,sq=50,iq=250,aq=10,mI={mouse:0,touch:0,pen:8};ht(ht({},pd),{},{device(t,e,{pointer:{touch:n=!1,lock:r=!1,mouse:o=!1}={}}){return this.pointerLock=r&&Mr.pointerLock,Mr.touch&&n?"touch":this.pointerLock?"mouse":Mr.pointer&&!o?"pointer":Mr.touch?"touch":"mouse"},preventScrollAxis(t,e,{preventScroll:n}){if(this.preventScrollDelay=typeof n=="number"?n:n||n===void 0&&t?nq:void 0,!(!Mr.touchscreen||n===!1))return t||(n!==void 0?"y":void 0)},pointerCapture(t,e,{pointer:{capture:n=!0,buttons:r=1,keys:o=!0}={}}){return this.pointerButtons=r,this.keys=o,!this.pointerLock&&this.device==="pointer"&&n},threshold(t,e,{filterTaps:n=!1,tapsThreshold:r=3,axis:o=void 0}){const s=Gt.toVector(t,n?r:o?1:0);return this.filterTaps=n,this.tapsThreshold=r,s},swipe({velocity:t=oq,distance:e=sq,duration:n=iq}={}){return{velocity:this.transform(Gt.toVector(t)),distance:this.transform(Gt.toVector(e)),duration:n}},delay(t=0){switch(t){case!0:return rq;case!1:return 0;default:return t}},axisThreshold(t){return t?ht(ht({},mI),t):mI},keyboardDisplacement(t=aq){return t}});function Sj(t){const[e,n]=t.overflow,[r,o]=t._delta,[s,i]=t._direction;(e<0&&r>0&&s<0||e>0&&r<0&&s>0)&&(t._movement[0]=t._movementBound[0]),(n<0&&o>0&&i<0||n>0&&o<0&&i>0)&&(t._movement[1]=t._movementBound[1])}const lq=30,cq=100;class uq extends gj{constructor(...e){super(...e),sn(this,"ingKey","pinching"),sn(this,"aliasKey","da")}init(){this.state.offset=[1,0],this.state.lastOffset=[1,0],this.state._pointerEvents=new Map}reset(){super.reset();const e=this.state;e._touchIds=[],e.canceled=!1,e.cancel=this.cancel.bind(this),e.turns=0}computeOffset(){const{type:e,movement:n,lastOffset:r}=this.state;e==="wheel"?this.state.offset=Gt.add(n,r):this.state.offset=[(1+n[0])*r[0],n[1]+r[1]]}computeMovement(){const{offset:e,lastOffset:n}=this.state;this.state.movement=[e[0]/n[0],e[1]-n[1]]}axisIntent(){const e=this.state,[n,r]=e._movement;if(!e.axis){const o=Math.abs(n)*lq-Math.abs(r);o<0?e.axis="angle":o>0&&(e.axis="scale")}}restrictToAxis(e){this.config.lockDirection&&(this.state.axis==="scale"?e[1]=0:this.state.axis==="angle"&&(e[0]=0))}cancel(){const e=this.state;e.canceled||setTimeout(()=>{e.canceled=!0,e._active=!1,this.compute(),this.emit()},0)}touchStart(e){this.ctrl.setEventIds(e);const n=this.state,r=this.ctrl.touchIds;if(n._active&&n._touchIds.every(s=>r.has(s))||r.size<2)return;this.start(e),n._touchIds=Array.from(r).slice(0,2);const o=dI(e,n._touchIds);o&&this.pinchStart(e,o)}pointerStart(e){if(e.buttons!=null&&e.buttons%2!==1)return;this.ctrl.setEventIds(e),e.target.setPointerCapture(e.pointerId);const n=this.state,r=n._pointerEvents,o=this.ctrl.pointerIds;if(n._active&&Array.from(r.keys()).every(i=>o.has(i))||(r.size<2&&r.set(e.pointerId,e),n._pointerEvents.size<2))return;this.start(e);const s=wx(...Array.from(r.values()));s&&this.pinchStart(e,s)}pinchStart(e,n){const r=this.state;r.origin=n.origin,this.computeValues([n.distance,n.angle]),this.computeInitial(),this.compute(e),this.emit()}touchMove(e){if(!this.state._active)return;const n=dI(e,this.state._touchIds);n&&this.pinchMove(e,n)}pointerMove(e){const n=this.state._pointerEvents;if(n.has(e.pointerId)&&n.set(e.pointerId,e),!this.state._active)return;const r=wx(...Array.from(n.values()));r&&this.pinchMove(e,r)}pinchMove(e,n){const r=this.state,o=r._values[1],s=n.angle-o;let i=0;Math.abs(s)>270&&(i+=Math.sign(s)),this.computeValues([n.distance,n.angle-360*i]),r.origin=n.origin,r.turns=i,r._movement=[r._values[0]/r._initial[0]-1,r._values[1]-r._initial[1]],this.compute(e),this.emit()}touchEnd(e){this.ctrl.setEventIds(e),this.state._active&&this.state._touchIds.some(n=>!this.ctrl.touchIds.has(n))&&(this.state._active=!1,this.compute(e),this.emit())}pointerEnd(e){const n=this.state;this.ctrl.setEventIds(e);try{e.target.releasePointerCapture(e.pointerId)}catch{}n._pointerEvents.has(e.pointerId)&&n._pointerEvents.delete(e.pointerId),n._active&&n._pointerEvents.size<2&&(n._active=!1,this.compute(e),this.emit())}gestureStart(e){e.cancelable&&e.preventDefault();const n=this.state;n._active||(this.start(e),this.computeValues([e.scale,e.rotation]),n.origin=[e.clientX,e.clientY],this.compute(e),this.emit())}gestureMove(e){if(e.cancelable&&e.preventDefault(),!this.state._active)return;const n=this.state;this.computeValues([e.scale,e.rotation]),n.origin=[e.clientX,e.clientY];const r=n._movement;n._movement=[e.scale-1,e.rotation],n._delta=Gt.sub(n._movement,r),this.compute(e),this.emit()}gestureEnd(e){this.state._active&&(this.state._active=!1,this.compute(e),this.emit())}wheel(e){const n=this.config.modifierKey;n&&(Array.isArray(n)?!n.find(r=>e[r]):!e[n])||(this.state._active?this.wheelChange(e):this.wheelStart(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this)))}wheelStart(e){this.start(e),this.wheelChange(e)}wheelChange(e){"uv"in e||e.cancelable&&e.preventDefault();const r=this.state;r._delta=[-fj(e)[1]/cq*r.offset[0],0],Gt.addTo(r._movement,r._delta),Sj(r),this.state.origin=[e.clientX,e.clientY],this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){const n=this.config.device;n&&(e(n,"start",this[n+"Start"].bind(this)),e(n,"change",this[n+"Move"].bind(this)),e(n,"end",this[n+"End"].bind(this)),e(n,"cancel",this[n+"End"].bind(this)),e("lostPointerCapture","",this[n+"End"].bind(this))),this.config.pinchOnWheel&&e("wheel","",this.wheel.bind(this),{passive:!1})}}const dq=ht(ht({},mj),{},{device(t,e,{shared:n,pointer:{touch:r=!1}={}}){if(n.target&&!Mr.touch&&Mr.gesture)return"gesture";if(Mr.touch&&r)return"touch";if(Mr.touchscreen){if(Mr.pointer)return"pointer";if(Mr.touch)return"touch"}},bounds(t,e,{scaleBounds:n={},angleBounds:r={}}){const o=i=>{const a=fI(Lf(n,i),{min:-1/0,max:1/0});return[a.min,a.max]},s=i=>{const a=fI(Lf(r,i),{min:-1/0,max:1/0});return[a.min,a.max]};return typeof n!="function"&&typeof r!="function"?[o(),s()]:i=>[o(i),s(i)]},threshold(t,e,n){return this.lockDirection=n.axis==="lock",Gt.toVector(t,this.lockDirection?[.1,3]:0)},modifierKey(t){return t===void 0?"ctrlKey":t},pinchOnWheel(t=!0){return t}});ht(ht({},pd),{},{mouseOnly:(t=!0)=>t});class hq extends XX{constructor(...e){super(...e),sn(this,"ingKey","wheeling")}wheel(e){this.state._active||this.start(e),this.wheelChange(e),this.timeoutStore.add("wheelEnd",this.wheelEnd.bind(this))}wheelChange(e){const n=this.state;n._delta=fj(e),Gt.addTo(n._movement,n._delta),Sj(n),this.compute(e),this.emit()}wheelEnd(){this.state._active&&(this.state._active=!1,this.compute(),this.emit())}bind(e){e("wheel","",this.wheel.bind(this))}}const pq=pd;ht(ht({},pd),{},{mouseOnly:(t=!0)=>t});const y1=new Map,bx=new Map;function fq(t){y1.set(t.key,t.engine),bx.set(t.key,t.resolver)}const gq={key:"pinch",engine:uq,resolver:dq},mq={key:"wheel",engine:hq,resolver:pq};function yq(t,e){if(t==null)return{};var n={},r=Object.keys(t),o,s;for(s=0;s<r.length;s++)o=r[s],!(e.indexOf(o)>=0)&&(n[o]=t[o]);return n}function Sq(t,e){if(t==null)return{};var n=yq(t,e),r,o;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(o=0;o<s.length;o++)r=s[o],!(e.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(t,r)&&(n[r]=t[r])}return n}const vq={target(t){if(t)return()=>"current"in t?t.current:t},enabled(t=!0){return t},window(t=Mr.isBrowser?window:void 0){return t},eventOptions({passive:t=!0,capture:e=!1}={}){return{passive:t,capture:e}},transform(t){return t}},xq=["target","eventOptions","window","enabled","transform"];function lp(t={},e){const n={};for(const[r,o]of Object.entries(e))switch(typeof o){case"function":n[r]=o.call(n,t[r],r,t);break;case"object":n[r]=lp(t[r],o);break;case"boolean":o&&(n[r]=t[r]);break}return n}function wq(t,e,n={}){const r=t,{target:o,eventOptions:s,window:i,enabled:a,transform:l}=r,c=Sq(r,xq);if(n.shared=lp({target:o,eventOptions:s,window:i,enabled:a,transform:l},vq),e){const u=bx.get(e);n[e]=lp(ht({shared:n.shared},c),u)}else for(const u in c){const h=bx.get(u);h&&(n[u]=lp(ht({shared:n.shared},c[u]),h))}return n}class vj{constructor(e,n){sn(this,"_listeners",new Set),this._ctrl=e,this._gestureKey=n}add(e,n,r,o,s){const i=this._listeners,a=zX(n,r),l=this._gestureKey?this._ctrl.config[this._gestureKey].eventOptions:{},c=ht(ht({},l),s);e.addEventListener(a,o,c);const u=()=>{e.removeEventListener(a,o,c),i.delete(u)};return i.add(u),u}clean(){this._listeners.forEach(e=>e()),this._listeners.clear()}}class bq{constructor(){sn(this,"_timeouts",new Map)}add(e,n,r=140,...o){this.remove(e),this._timeouts.set(e,window.setTimeout(n,r,...o))}remove(e){const n=this._timeouts.get(e);n&&window.clearTimeout(n)}clean(){this._timeouts.forEach(e=>void window.clearTimeout(e)),this._timeouts.clear()}}class Pq{constructor(e){sn(this,"gestures",new Set),sn(this,"_targetEventStore",new vj(this)),sn(this,"gestureEventStores",{}),sn(this,"gestureTimeoutStores",{}),sn(this,"handlers",{}),sn(this,"config",{}),sn(this,"pointerIds",new Set),sn(this,"touchIds",new Set),sn(this,"state",{shared:{shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1}}),Cq(this,e)}setEventIds(e){if(pj(e))return this.touchIds=new Set(HX(e)),this.touchIds;if("pointerId"in e)return e.type==="pointerup"||e.type==="pointercancel"?this.pointerIds.delete(e.pointerId):e.type==="pointerdown"&&this.pointerIds.add(e.pointerId),this.pointerIds}applyHandlers(e,n){this.handlers=e,this.nativeHandlers=n}applyConfig(e,n){this.config=wq(e,n,this.config)}clean(){this._targetEventStore.clean();for(const e of this.gestures)this.gestureEventStores[e].clean(),this.gestureTimeoutStores[e].clean()}effect(){return this.config.shared.target&&this.bind(),()=>this._targetEventStore.clean()}bind(...e){const n=this.config.shared,r={};let o;if(!(n.target&&(o=n.target(),!o))){if(n.enabled){for(const i of this.gestures){const a=this.config[i],l=yI(r,a.eventOptions,!!o);if(a.enabled){const c=y1.get(i);new c(this,e,i).bind(l)}}const s=yI(r,n.eventOptions,!!o);for(const i in this.nativeHandlers)s(i,"",a=>this.nativeHandlers[i](ht(ht({},this.state.shared),{},{event:a,args:e})),void 0,!0)}for(const s in r)r[s]=GX(...r[s]);if(!o)return r;for(const s in r){const{device:i,capture:a,passive:l}=NX(s);this._targetEventStore.add(o,i,"",r[s],{capture:a,passive:l})}}}}function Oa(t,e){t.gestures.add(e),t.gestureEventStores[e]=new vj(t,e),t.gestureTimeoutStores[e]=new bq}function Cq(t,e){e.drag&&Oa(t,"drag"),e.wheel&&Oa(t,"wheel"),e.scroll&&Oa(t,"scroll"),e.move&&Oa(t,"move"),e.pinch&&Oa(t,"pinch"),e.hover&&Oa(t,"hover")}const yI=(t,e,n)=>(r,o,s,i={},a=!1)=>{var l,c;const u=(l=i.capture)!==null&&l!==void 0?l:e.capture,h=(c=i.passive)!==null&&c!==void 0?c:e.passive;let p=a?r:$X(r,o,u);n&&h&&(p+="Passive"),t[p]=t[p]||[],t[p].push(s)},_q=/^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;function Iq(t){const e={},n={},r=new Set;for(let o in t)_q.test(o)?(r.add(RegExp.lastMatch),n[o]=t[o]):e[o]=t[o];return[n,e,r]}function Da(t,e,n,r,o,s){if(!t.has(n)||!y1.has(r))return;const i=n+"Start",a=n+"End",l=c=>{let u;return c.first&&i in e&&e[i](c),n in e&&(u=e[n](c)),c.last&&a in e&&e[a](c),u};o[r]=l,s[r]=s[r]||{}}function Eq(t,e){const[n,r,o]=Iq(t),s={};return Da(o,n,"onDrag","drag",s,e),Da(o,n,"onWheel","wheel",s,e),Da(o,n,"onScroll","scroll",s,e),Da(o,n,"onPinch","pinch",s,e),Da(o,n,"onMove","move",s,e),Da(o,n,"onHover","hover",s,e),{handlers:s,config:e,nativeHandlers:r}}function kq(t,e={},n,r){const o=Te.useMemo(()=>new Pq(t),[]);if(o.applyHandlers(t,r),o.applyConfig(e,n),Te.useEffect(o.effect.bind(o)),Te.useEffect(()=>o.clean.bind(o),[]),e.target===void 0)return o.bind.bind(o)}function Tq(t){return t.forEach(fq),function(n,r){const{handlers:o,nativeHandlers:s,config:i}=Eq(n,r||{});return kq(o,i,void 0,s)}}const SI=10,Mq=/Mac|iPod|iPhone|iPad/.test(typeof window>"u"?"node":window.navigator.platform);function xj(t){let{deltaY:e,deltaX:n}=t,r=0;return t.ctrlKey||t.altKey||t.metaKey?r=(Math.abs(e)>SI?SI*Math.sign(e):e)/100:t.shiftKey&&!Mq&&(n=e,e=0),{x:-n,y:-e,z:-r}}const Aq=Tq([mq,gq]);let Ra;const jq=t=>Ra===void 0?(Ra=t,!1):t-Ra>120&&t-Ra<160?(Ra=t,!0):(Ra=t,!1);function Oq(t){const e=z(),n=w.useMemo(()=>{let r="not sure";const o=({event:m})=>{if(!e.getInstanceState().isFocused||(r="not sure",jq(Date.now())))return;const v=e.getEditingShapeId();if(v){const b=e.getShape(v);if(b&&e.getShapeUtil(b).canScroll(b)){const C=e.getShapePageBounds(v);if(C!=null&&C.containsPoint(e.inputs.currentPagePoint))return}}xe(m),_t(m);const y=xj(m);if(y.x===0&&y.y===0)return;const S={type:"wheel",name:"wheel",delta:y,point:new x(m.clientX,m.clientY),shiftKey:m.shiftKey,altKey:m.altKey,ctrlKey:m.metaKey||m.ctrlKey,metaKey:m.metaKey,accelKey:un(m)};e.dispatch(S)};let s=1,i=1,a=1,l=0;const c=new x,u=new x,h=m=>{const v=t.current;r="not sure";const{event:y,origin:S,da:b}=m;y instanceof WheelEvent||(y.target===v||v!=null&&v.contains(y.target))&&(u.x=S[0],u.y=S[1],c.x=S[0],c.y=S[1],s=b[0],i=e.getZoomLevel(),e.dispatch({type:"pinch",name:"pinch_start",point:{x:S[0],y:S[1],z:e.getZoomLevel()},delta:{x:0,y:0},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)}))},p=m=>{if(m&&(r="zooming"),r==="zooming")return;const v=Math.abs(l-s),y=x.Dist(c,u);switch(r){case"not sure":{v>24?r="zooming":y>16&&(r="panning");break}case"panning":{v>64&&(r="zooming");break}}};return{onWheel:o,onPinchStart:h,onPinchEnd:m=>{const v=t.current,{event:y,origin:S,offset:b}=m;if(y instanceof WheelEvent||!(y.target===v||v!=null&&v.contains(y.target)))return;const P=b[0];r="not sure",e.timers.requestAnimationFrame(()=>{e.dispatch({type:"pinch",name:"pinch_end",point:{x:S[0],y:S[1],z:P},delta:{x:S[0],y:S[1]},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)})})},onPinch:m=>{const v=t.current,{event:y,origin:S,offset:b,da:P}=m;if(y instanceof WheelEvent||!(y.target===v||v!=null&&v.contains(y.target)))return;const C=m.type==="gesturechange"||m.type==="gestureend";l=P[0];const _=S[0]-u.x,E=S[1]-u.y;switch(u.x=S[0],u.y=S[1],p(C),r){case"zooming":{a=b[0],e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:a},delta:{x:_,y:E},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)});break}case"panning":{e.dispatch({type:"pinch",name:"pinch",point:{x:S[0],y:S[1],z:i},delta:{x:_,y:E},shiftKey:y.shiftKey,altKey:y.altKey,ctrlKey:y.metaKey||y.ctrlKey,metaKey:y.metaKey,accelKey:un(y)});break}}}}},[e,t]);Aq(n,{target:t,eventOptions:{passive:!1},pinch:{from:()=>[e.getZoomLevel(),0],scaleBounds:()=>{const r=e.getBaseZoom(),o=e.getCameraOptions().zoomSteps,s=o[0]*r,i=o[o.length-1]*r;return{from:e.getZoomLevel(),max:i,min:s}}}})}function Vy(t,e,n){const r=t.getShape(e),o=t.getShapeHandles(r);return{shape:r,handle:o.find(s=>s.id===n)}}function Dq(t,e){const n=z();return w.useMemo(()=>{const r=l=>{if(l.isKilled)return;const c=Rf(l.currentTarget);dd(c,l);const{shape:u,handle:h}=Vy(n,t,e);h&&n.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_down",...lr(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:u}=Vy(n,t,e);u&&n.dispatch({type:"pointer",target:"handle",handle:u,shape:c,name:"pointer_move",...lr(l)})},onPointerUp:l=>{if(l.isKilled)return;const c=Rf(l.currentTarget);hd(c,l);const{shape:u,handle:h}=Vy(n,t,e);h&&n.dispatch({type:"pointer",target:"handle",handle:h,shape:u,name:"pointer_up",...lr(l)})}}},[n,t,e])}function Rq(t){const e=z();w.useLayoutEffect(()=>{const n=kT(()=>{t.current&&e.updateViewportScreenBounds(t.current)},200,{trailing:!0}),r=e.timers.setInterval(n,1e3);window.addEventListener("resize",n);const o=new ResizeObserver(a=>{a[0].contentRect&&n()}),s=t.current;let i=null;return s&&(o.observe(s),i=Lq(s),i.addEventListener("scroll",n)),()=>{clearInterval(r),window.removeEventListener("resize",n),o.disconnect(),i==null||i.removeEventListener("scroll",n),n.cancel()}},[e,t])}/*!
89
89
  * Author: excalidraw
90
90
  * MIT License: https://github.com/excalidraw/excalidraw/blob/master/LICENSE
91
91
  * https://github.com/excalidraw/excalidraw/blob/48c3465b19f10ec755b3eb84e21a01a468e96e43/packages/excalidraw/utils.ts#L600
@@ -98,11 +98,11 @@ ${h??u}
98
98
  My browser: ${navigator.userAgent}`),d.jsxs("div",{ref:n,className:le("tl-container tl-error-boundary",f===null?"":f?"tl-theme__dark":"tl-theme__light"),children:[d.jsx("div",{className:"tl-error-boundary__overlay"}),e&&d.jsx(u1,{onError:Ru,fallback:()=>null,children:d.jsx(p1,{editor:e,children:d.jsx("div",{className:"tl-overlay tl-error-boundary__canvas",children:c?d.jsx(c,{}):null})})}),d.jsx("div",{className:le("tl-modal","tl-error-boundary__content",{"tl-error-boundary__content__expanded":r&&!a}),children:a?d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Are you sure?"}),d.jsx("p",{children:"Resetting your data will delete your drawing and cannot be undone."}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>l(!1),children:"Cancel"}),d.jsx("button",{className:"tl-error-boundary__reset",onClick:y,children:"Reset data"})]})]}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{children:"Something went wrong"}),d.jsx("p",{children:"Please refresh the page to continue."}),d.jsxs("p",{children:["If you keep seeing this screen, you can create a"," ",d.jsx("a",{href:S.toString(),children:"GitHub issue"})," or ask for help on"," ",d.jsx("a",{href:"https://discord.gg/Cq6cPsTfNy",children:"Discord"}),". If you are still stuck, you can reset the tldraw data on your machine. This may erase the project you were working on, so try to get help first."]}),r&&d.jsxs(d.Fragment,{children:["Message:",d.jsx("h4",{children:d.jsx("code",{children:u})}),"Stack trace:",d.jsxs("div",{className:"tl-error-boundary__content__error",children:[d.jsx("pre",{children:d.jsx("code",{children:h??u})}),d.jsx("button",{onClick:m,children:s?"Copied!":"Copy"})]})]}),d.jsxs("div",{className:"tl-error-boundary__content__actions",children:[d.jsx("button",{onClick:()=>o(!r),children:r?"Hide details":"Show details"}),d.jsxs("div",{className:"tl-error-boundary__content__actions__group",children:[d.jsx("button",{className:"tl-error-boundary__reset",onClick:()=>l(!0),children:"Reset data"}),d.jsx("button",{className:"tl-error-boundary__refresh",onClick:v,children:"Refresh Page"})]})]})]})})]})},Oj="TLDRAW_USER_DATA_v3",Dj=Pe({id:ye,name:ye.nullable().optional(),color:ye.nullable().optional(),locale:ye.nullable().optional(),animationSpeed:fe.nullable().optional(),edgeScrollSpeed:fe.nullable().optional(),colorScheme:Og("light","dark","system").optional(),isSnapMode:we.nullable().optional(),isWrapMode:we.nullable().optional(),isDynamicSizeMode:we.nullable().optional(),isPasteAtCursorMode:we.nullable().optional()}),ts={AddAnimationSpeed:1,AddIsSnapMode:2,MakeFieldsNullable:3,AddEdgeScrollSpeed:4,AddExcalidrawSelectMode:5,AddDynamicSizeMode:6,AllowSystemColorScheme:7,AddPasteAtCursor:8},x1=Math.max(...Object.values(ts));function OZ(t){t.version<ts.AddAnimationSpeed&&(t.user.animationSpeed=1),t.version<ts.AddIsSnapMode&&(t.user.isSnapMode=!1),t.version<ts.MakeFieldsNullable,t.version<ts.AddEdgeScrollSpeed&&(t.user.edgeScrollSpeed=1),t.version<ts.AddExcalidrawSelectMode&&(t.user.isWrapMode=!1),t.version<ts.AllowSystemColorScheme&&(t.user.isDarkMode===!0?t.user.colorScheme="dark":t.user.isDarkMode===!1&&(t.user.colorScheme="light"),delete t.user.isDarkMode),t.version<ts.AddDynamicSizeMode&&(t.user.isDynamicSizeMode=!1),t.version<ts.AddPasteAtCursor&&(t.user.isPasteAtCursorMode=!1),t.version=x1}const Px=["#FF802B","#EC5E41","#F2555A","#F04F88","#E34BA9","#BD54C6","#9D5BD2","#7B66DC","#02B1CC","#11B3A3","#39B178","#55B467"];function Rj(){return Px[Math.floor(Math.random()*Px.length)]}function DZ(){var t,e;return typeof window<"u"&&"matchMedia"in window?((e=(t=window.matchMedia)==null?void 0:t.call(window,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1:!1}const xo=Object.freeze({name:"New User",locale:aX(),color:Rj(),edgeScrollSpeed:1,animationSpeed:DZ()?0:1,isSnapMode:!1,isWrapMode:!1,isDynamicSizeMode:!1,isPasteAtCursorMode:!1,colorScheme:"light"});function Yy(){return{id:ze(),color:Rj()}}function Lj(t){if(t===null||typeof t!="object"||!("version"in t)||!("user"in t)||typeof t.version!="number")return Yy();const e=tt(t);OZ(e);try{return Dj.validate(e.user)}catch{return Yy()}}function RZ(){const t=JSON.parse(_w(Oj)||"null")??null;return Lj(t)}const Fg=Et("globalUserData",null);function LZ(){Iw(Oj,JSON.stringify({version:x1,user:Fg.get()}))}function $j(t){Dj.validate(t),Fg.set(t),LZ(),FZ()}const $Z=typeof process<"u"&&!1,xl=typeof BroadcastChannel<"u"&&!$Z?new BroadcastChannel("tldraw-user-sync"):null;xl==null||xl.addEventListener("message",t=>{const e=t.data;(e==null?void 0:e.type)===Nj&&(e==null?void 0:e.origin)!==Fj()&&Fg.set(Lj(e.data))});let Xy=null;function Fj(){return Xy===null&&(Xy=ze()),Xy}const Nj="tldraw-user-preferences-change";function FZ(){xl==null||xl.postMessage({type:Nj,origin:Fj(),data:{user:zj(),version:x1}})}function zj(){let t=Fg.get();return t||(t=RZ(),$j(t)),t}const NZ=G("defaultLocalStorageUserPrefs",()=>zj());function Bj(t={}){return{userPreferences:t.userPreferences??NZ,setUserPreferences:t.setUserPreferences??$j}}var Uj={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function o(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function s(l,c,u,h,p){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new o(u,h||l,p),g=n?n+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function i(l,c){--l._eventsCount===0?l._events=new r:delete l._events[c]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},a.prototype.listeners=function(c){var u=n?n+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,g=new Array(f);p<f;p++)g[p]=h[p].fn;return g},a.prototype.listenerCount=function(c){var u=n?n+c:c,h=this._events[u];return h?h.fn?1:h.length:0},a.prototype.emit=function(c,u,h,p,f,g){var m=n?n+c:c;if(!this._events[m])return!1;var v=this._events[m],y=arguments.length,S,b;if(v.fn){switch(v.once&&this.removeListener(c,v.fn,void 0,!0),y){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,u),!0;case 3:return v.fn.call(v.context,u,h),!0;case 4:return v.fn.call(v.context,u,h,p),!0;case 5:return v.fn.call(v.context,u,h,p,f),!0;case 6:return v.fn.call(v.context,u,h,p,f,g),!0}for(b=1,S=new Array(y-1);b<y;b++)S[b-1]=arguments[b];v.fn.apply(v.context,S)}else{var P=v.length,C;for(b=0;b<P;b++)switch(v[b].once&&this.removeListener(c,v[b].fn,void 0,!0),y){case 1:v[b].fn.call(v[b].context);break;case 2:v[b].fn.call(v[b].context,u);break;case 3:v[b].fn.call(v[b].context,u,h);break;case 4:v[b].fn.call(v[b].context,u,h,p);break;default:if(!S)for(C=1,S=new Array(y-1);C<y;C++)S[C-1]=arguments[C];v[b].fn.apply(v[b].context,S)}}return!0},a.prototype.on=function(c,u,h){return s(this,c,u,h,!1)},a.prototype.once=function(c,u,h){return s(this,c,u,h,!0)},a.prototype.removeListener=function(c,u,h,p){var f=n?n+c:c;if(!this._events[f])return this;if(!u)return i(this,f),this;var g=this._events[f];if(g.fn)g.fn===u&&(!p||g.once)&&(!h||g.context===h)&&i(this,f);else{for(var m=0,v=[],y=g.length;m<y;m++)(g[m].fn!==u||p&&!g[m].once||h&&g[m].context!==h)&&v.push(g[m]);v.length?this._events[f]=v.length===1?v[0]:v:i(this,f)}return this},a.prototype.removeAllListeners=function(c){var u;return c?(u=n?n+c:c,this._events[u]&&i(this,u)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a})(Uj);var zZ=Uj.exports;const BZ=xi(zZ),wl="TLDRAW_TAB_ID_v2",gs=globalThis.window;function UZ(){return gs?["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(gs.navigator.platform)||Ge.isDarwin&&"ontouchend"in document:!1}const $f=gs?gs[wl]??QT(wl)??"TLDRAW_INSTANCE_STATE_V1_"+ze():"<error>";gs&&(gs[wl]=$f,UZ()?Ew(wl,$f):JT(wl));gs==null||gs.addEventListener("beforeunload",()=>{Ew(wl,$f)});const Hj={Initial:0},Ng=Math.max(...Object.values(Hj));function HZ(t){t.version<Hj.Initial,t.version=Ng}const Kj=Pe({version:fe,currentPageId:zu.optional(),isFocusMode:we.optional(),exportBackground:we.optional(),isDebugMode:we.optional(),isToolLocked:we.optional(),isGridMode:we.optional(),pageStates:Kt(Pe({pageId:zu,camera:Pe({x:fe,y:fe,z:fe}).optional(),selectedShapeIds:Kt(Ir).optional(),focusedGroupId:Ir.nullable().optional()})).optional()});function KZ(t){if(!t||typeof t!="object")return console.warn("Invalid instance state"),null;if(!("version"in t)||typeof t.version!="number")return console.warn("No version in instance state"),null;t.version!==Ng&&(t=tt(t),HZ(t));try{return Kj.validate(t)}catch(e){return console.warn(e),null}}function w1(t){const e=t.query.ids("page");return G("sessionStateSnapshot",()=>{const n=t.get(bn);if(!n)return null;const r=[...e.get()];return{version:Ng,currentPageId:n.currentPageId,exportBackground:n.exportBackground,isFocusMode:n.isFocusMode,isDebugMode:n.isDebugMode,isToolLocked:n.isToolLocked,isGridMode:n.isGridMode,pageStates:r.map(o=>{const s=t.get(Qr.createId(o)),i=t.get(Eo.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}})}},{isEqual:gA})}function Cx(t,e,n){const r=KZ(e);if(!r)return;const o=AA(t.get(bn)),s=n!=null&&n.forceOverwrite?r:o,i=n!=null&&n.forceOverwrite?o:r,a=t.schema.types.instance.create({id:bn,...o,currentPageId:r.currentPageId,isDebugMode:(s==null?void 0:s.isDebugMode)??(i==null?void 0:i.isDebugMode),isFocusMode:(s==null?void 0:s.isFocusMode)??(i==null?void 0:i.isFocusMode),isToolLocked:(s==null?void 0:s.isToolLocked)??(i==null?void 0:i.isToolLocked),isGridMode:(s==null?void 0:s.isGridMode)??(i==null?void 0:i.isGridMode),exportBackground:(s==null?void 0:s.exportBackground)??(i==null?void 0:i.exportBackground)});t.atomic(()=>{var l,c,u;for(const h of r.pageStates??[]){if(!t.has(h.pageId))continue;const p=Eo.createId(h.pageId),f=Qr.createId(h.pageId),g=t.get(p),m=t.get(f);t.put([Eo.create({id:p,x:((l=h.camera)==null?void 0:l.x)??(g==null?void 0:g.x),y:((c=h.camera)==null?void 0:c.y)??(g==null?void 0:g.y),z:((u=h.camera)==null?void 0:u.z)??(g==null?void 0:g.z)}),Qr.create({id:f,pageId:h.pageId,selectedShapeIds:h.selectedShapeIds??(m==null?void 0:m.selectedShapeIds),focusedGroupId:h.focusedGroupId??(m==null?void 0:m.focusedGroupId)})])}t.put([a]),t.ensureStoreIsUsable()})}function WZ(t){var o;const e=[];for(const s of Object.values(t))(o=s.typeName)!=null&&o.match(/^(instance.*|pointer|camera)$/)&&e.push(s);const n=e.filter(s=>s.typeName==="instance"&&s.id!==bn)[0];if(!n)return null;const r={version:Ng,currentPageId:n.currentPageId,exportBackground:!!n.exportBackground,isFocusMode:!!n.isFocusMode,isDebugMode:!!n.isDebugMode,isToolLocked:!!n.isToolLocked,isGridMode:!1,pageStates:e.filter(s=>s.typeName==="instance_page_state"&&s.instanceId===n.id).map(s=>{const i=t[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 Kj.validate(r),r}catch{return null}}function Wj(t,e,n){let r={};if("store"in e){const i=t.schema.migrateStoreSnapshot(e);if(i.type!=="success")throw new Error("Failed to migrate store snapshot: "+i.reason);r.document={schema:t.schema.serialize(),store:lu(i.value,(a,{typeName:l})=>t.scopedTypes.document.has(l))}}else r=e;const o=AA(t.get(bn)),s=Gj.get(t,w1).get();t.atomic(()=>{r.document&&t.loadStoreSnapshot(r.document),o&&t.update(bn,i=>({...i,...o})),s&&Cx(t,s),r.session&&Cx(t,r.session,{forceOverwrite:n==null?void 0:n.forceOverwriteSessionState})})}const Gj=new Ro;function GZ(t){const n=Gj.get(t,w1).get();if(!n)throw new Error("Session state is not ready yet");return{document:t.getStoreSnapshot(),session:n}}function Vj(t){const e=[],n=new Set;for(const r of t){if(n.has(r.type))throw new Error(`Binding type "${r.type}" is defined more than once`);e.push(r),n.add(r.type)}return e}function gi({children:t,className:e="",...n}){return d.jsx("svg",{...n,className:le("tl-svg-container",e),children:t})}function b1(t,e,n,r){const o=t.x-n.x,s=t.y-n.y,i=r.x-n.x,a=r.y-n.y,l=e.x-t.x,c=e.y-t.y,u=i*s-a*o,h=l*s-c*o,p=a*l-i*c;if(u===0||h===0||p===0)return null;if(p!==0){const f=u/p,g=h/p;if(0<=f&&f<=1&&0<=g&&g<=1)return x.AddXY(t,f*l,f*c)}return null}function gd(t,e,n,r){const o=(e.x-t.x)*(e.x-t.x)+(e.y-t.y)*(e.y-t.y),s=2*((e.x-t.x)*(t.x-n.x)+(e.y-t.y)*(t.y-n.y)),i=n.x*n.x+n.y*n.y+t.x*t.x+t.y*t.y-2*(n.x*t.x+n.y*t.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),u=(-s-l)/(2*o);if((c<0||c>1)&&(u<0||u>1))return null;const h=[];return 0<=c&&c<=1&&h.push(x.Lrp(t,e,c)),0<=u&&u<=1&&h.push(x.Lrp(t,e,u)),h.length===0?null:h}function VZ(t,e,n){const r=[];let o;for(let s=0,i=n.length-1;s<i;s++)o=b1(t,e,n[s],n[s+1]),o&&r.push(o);return r.length===0?null:r}function P1(t,e,n){const r=[];let o;for(let s=1,i=n.length;s<i+1;s++)o=b1(t,e,n[s-1],n[s%n.length]),o&&r.push(o);return r.length===0?null:r}function YZ(t,e,n,r){let o=n.x-t.x,s=n.y-t.y;const i=Math.sqrt(o*o+s*s),a=(i*i-r*r+e*e)/(2*i),l=Math.sqrt(e*e-a*a);return o/=i,s/=i,[new x(t.x+o*a-s*l,t.y+s*a+o*l),new x(t.x+o*a+s*l,t.y+s*a-o*l)]}function _x(t,e,n){const r=[];let o,s,i;for(let a=0,l=n.length;a<l;a++)o=n[a],s=n[(a+1)%n.length],i=gd(o,s,t,e),i&&r.push(...i);return r.length===0?null:r}function PI(t,e,n){const r=[];let o,s,i;for(let a=1,l=n.length;a<l;a++)o=n[a-1],s=n[a],i=gd(o,s,t,e),i&&r.push(...i);return r.length===0?null:r}function mh(t,e,n){return(n.y-t.y)*(e.x-t.x)>(e.y-t.y)*(n.x-t.x)}function C1(t,e,n,r){return mh(t,n,r)!==mh(e,n,r)&&mh(t,e,n)!==mh(t,e,r)}function CI(t,e){const n=new Map;let r,o,s,i;for(let a=0,l=t.length;a<l;a++)if(r=t[a],hr(r,e)){const c=qy(r);n.has(c)||n.set(c,r)}for(let a=0,l=e.length;a<l;a++)if(r=e[a],hr(r,t)){const c=qy(r);n.has(c)||n.set(c,r)}for(let a=0,l=t.length;a<l;a++){r=t[a],o=t[(a+1)%t.length];for(let c=0,u=e.length;c<u;c++){s=e[c],i=e[(c+1)%e.length];const h=b1(r,o,s,i);if(h!==null){const p=qy(h);n.has(p)||n.set(p,h)}}}return n.size===0?null:XZ([...n.values()])}function qy(t){return`${t.x},${t.y}`}function XZ(t){const e=x.Average(t);return t.sort((n,r)=>x.Angle(e,n)-x.Angle(e,r))}function _1(t,e){let n,r,o,s;for(let i=0,a=t.length;i<a;i++){n=t[i],r=t[(i+1)%a];for(let l=0,c=e.length;l<c;l++)if(o=e[l],s=e[(l+1)%c],C1(n,r,o,s))return!0}return!1}function qZ(t,e){let n,r,o,s;for(let i=0,a=t.length;i<a;i++){n=t[i],r=t[(i+1)%a];for(let l=1,c=e.length;l<c;l++)if(o=e[l-1],s=e[l],C1(n,r,o,s))return!0}return!1}class us extends Ti{constructor(n){super({...n,isClosed:!1,isFilled:!1});I(this,"start");I(this,"end");I(this,"d");I(this,"u");I(this,"ul");const{start:r,end:o}=n;this.start=r,this.end=o,this.d=r.clone().sub(o),this.u=this.d.clone().uni(),this.ul=this.u.len()}getLength(){return this.d.len()}midPoint(){return this.start.lrp(this.end,.5)}getVertices(){return[this.start,this.end]}nearestPoint(n){const{start:r,end:o,d:s,u:i,ul:a}=this;if(s.len()===0||a===0)return r;const l=x.Sub(n,r).dpr(i)/a,c=r.x+i.x*l;if(c<Math.min(r.x,o.x))return r.x<o.x?r:o;if(c>Math.max(r.x,o.x))return r.x>o.x?r:o;const u=r.y+i.y*l;return u<Math.min(r.y,o.y)?r.y<o.y?r:o:u>Math.max(r.y,o.y)?r.y>o.y?r:o:new x(c,u)}hitTestLineSegment(n,r,o=0){return C1(n,r,this.start,this.end)||this.distanceToLineSegment(n,r)<=o}getSvgPathData(n=!0){const{start:r,end:o}=this;return`${n?`M${r.toFixed()}`:""} L${o.toFixed()}`}}class nc extends Ti{constructor(n){super({isClosed:!1,isFilled:!1,...n});I(this,"points");I(this,"_segments");const{points:r}=n;this.points=r}get segments(){if(!this._segments){this._segments=[];const{vertices:n}=this;for(let r=0,o=n.length-1;r<o;r++){const s=n[r],i=n[r+1];this._segments.push(new us({start:s,end:i}))}this.isClosed&&this._segments.push(new us({start:n[n.length-1],end:n[0]}))}return this._segments}getLength(){return this.segments.reduce((n,r)=>n+r.length,0)}getVertices(){return this.points}nearestPoint(n){const{segments:r}=this;let o=this.points[0],s=1/0,i,a;for(let l=0;l<r.length;l++)i=r[l].nearestPoint(n),a=x.Dist2(i,n),a<s&&(o=i,s=a);if(!o)throw Error("nearest point not found");return o}hitTestLineSegment(n,r,o=0){const{segments:s}=this;for(let i=0,a=s.length;i<a;i++)if(s[i].hitTestLineSegment(n,r,o))return!0;return!1}getSvgPathData(){const{vertices:n}=this;return n.length<2?"":n.reduce((r,o,s)=>s===0?`M ${o.x} ${o.y}`:`${r} L ${o.x} ${o.y}`,"")}}class xt extends nc{constructor(e){super({...e}),this.isClosed=!0}}class No extends xt{constructor(n){const{x:r=0,y:o=0,width:s,height:i}=n;super({...n,points:[new x(r,o),new x(r+s,o),new x(r+s,o+i),new x(r,o+i)]});I(this,"x");I(this,"y");I(this,"w");I(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:n,y:r,w:o,h:s}=this;return`M${n},${r} h${o} v${s} h-${o}z`}}class oo{constructor(e){this.editor=e}canSnap(e){return!0}canScroll(e){return!1}canBind(e){return!0}canEdit(e){return!1}canResize(e){return!0}canEditInReadOnly(e){return!1}canCrop(e){return!1}canBeLaidOut(e){return!0}providesBackgroundForChildren(e){return!1}hideResizeHandles(e){return!1}hideRotateHandle(e){return!1}hideSelectionBoundsBg(e){return!1}hideSelectionBoundsFg(e){return!1}isAspectRatioLocked(e){return!1}canReceiveNewChildrenOfType(e,n){return!1}canDropShapes(e,n){return!1}expandSelectionOutlinePx(e){return 0}getCanvasSvgDefs(){return[]}getBoundsSnapGeometry(e){return{}}getHandleSnapGeometry(e){return{}}getText(e){}}I(oo,"props"),I(oo,"migrations"),I(oo,"type");function qr(t,e,n={}){const{closed:r=!1,snap:o=1,start:s="outset",end:i="outset",lengthRatio:a=2,style:l="dashed",forceSolid:c=!1}=n;let u=0,h=0,p=1,f=0,g=0;if(c)return{strokeDasharray:"none",strokeDashoffset:"none"};switch(l){case"dashed":{p=1,u=Math.min(e*a,t/4);break}case"dotted":{p=100,u=e/p;break}default:return{strokeDasharray:"none",strokeDashoffset:"none"}}return r||(s==="outset"?(t+=u/2,g+=u/2):s==="skip"&&(t-=u,g-=u),i==="outset"?t+=u/2:i==="skip"&&(t-=u)),h=Math.floor(t/u/(2*p)),h-=h%o,h<3&&l==="dashed"?t/e<4?(u=t,h=1,f=0):(u=t*(1/3),f=t*(1/3)):(u=t/h/(2*p),r?(g=u/2,f=(t-h*u)/h):f=(t-h*u)/Math.max(1,h-1)),{strokeDasharray:[u,f].join(" "),strokeDashoffset:g.toString()}}function _I({bounds:t,className:e}){const n=z(),r=U("zoom level",()=>n.getZoomLevel(),[n]);return d.jsx("g",{className:e,pointerEvents:"none",strokeLinecap:"round",strokeLinejoin:"round",children:t.sides.map((o,s)=>{const{strokeDasharray:i,strokeDashoffset:a}=qr(o[0].dist(o[1]),1/r,{style:"dashed",lengthRatio:4});return d.jsx("line",{x1:o[0].x,y1:o[0].y,x2:o[1].x,y2:o[1].y,strokeDasharray:i,strokeDashoffset:a},s)})})}class cp extends oo{hideSelectionBoundsFg(){return!0}canBind(){return!1}getDefaultProps(){return{}}getGeometry(e){const n=this.editor.getSortedChildIdsForParent(e.id);return n.length===0?new No({width:1,height:1,isFilled:!1}):new $r({children:n.map(r=>{const o=this.editor.getShape(r),s=this.editor.getShapeGeometry(r),i=this.editor.getShapeLocalTransform(o).applyToPoints(s.vertices);return s.isClosed?new xt({points:i,isFilled:!0}):new nc({points:i})})})}component(e){const n=this.editor.getErasingShapeIds().includes(e.id),{hintingShapeIds:r}=this.editor.getCurrentPageState(),o=r.length>0&&r.some(a=>a!==e.id&&this.editor.isShapeOfType(this.editor.getShape(a),"group")),s=this.editor.getCurrentPageState().focusedGroupId!==e.id;if(!n&&(s||o))return null;const i=this.editor.getShapeGeometry(e).bounds;return d.jsx(gi,{children:d.jsx(_I,{className:"tl-group",bounds:i})})}indicator(e){const n=this.editor.getShapeGeometry(e).bounds;return d.jsx(_I,{className:"",bounds:n})}onChildrenChange(e){const n=this.editor.getSortedChildIdsForParent(e.id);if(n.length===0){this.editor.getCurrentPageState().focusedGroupId===e.id&&this.editor.popFocusedGroupId(),this.editor.deleteShapes([e.id]);return}else if(n.length===1){this.editor.getCurrentPageState().focusedGroupId===e.id&&this.editor.popFocusedGroupId(),this.editor.reparentShapes(n,e.parentId),this.editor.deleteShapes([e.id]);return}}}I(cp,"type","group"),I(cp,"props",HA),I(cp,"migrations",KA);const Yj=[cp],ZZ=new Set(Yj.map(t=>t.type));function Xj(t){const e=[...Yj],n=new Set;for(const r of t){if(ZZ.has(r.type))throw new Error(`Shape type "${r.type}" is a core shapes type and cannot be overridden`);if(n.has(r.type))throw new Error(`Shape type "${r.type}" is defined more than once`);e.push(r),n.add(r.type)}return e}function qj(t,e){const n=new Map;return async function(o){const s=n.get(o);if(s)return s;const i=(async()=>{try{const a=await Lo(o,e);return Le(a.ok),await t(a)}catch(a){return console.error(a),null}})();return n.set(o,i),i}}const zg=qj(async t=>await Zr.blobToDataUrl(await t.blob())),QZ=/@import\s+(?:"([^"]+)"|'([^']+)'|url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\))([^;]+);/gi,JZ=/@font-face\s*{([^}]+)}/gi,Zj=/url\s*\(\s*(?:"([^"]+)"|'([^']+)'|([^'")]+))\s*\)/gi,eQ=/(?:^|;)\s*font-family\s*:\s*(?:([^'"][^;\n]+)|"([^"]+)"|'([^']+)')\s*(?:;|$)/gi;function tQ(t){return Array.from(t.matchAll(QZ),e=>({url:e[1]||e[2]||e[3]||e[4]||e[5],extras:e[6]}))}function Qj(t,e){return Array.from(t.matchAll(JZ),n=>{const r=n[1],o=Array.from(r.matchAll(Zj),i=>{var l;const a=i[1]||i[2]||i[3];return{original:a,resolved:((l=ge(a,e))==null?void 0:l.href)??null}}),s=new Set(Array.from(r.matchAll(eQ),i=>(i[1]||i[2]||i[3]).toLowerCase()));return{fontFace:r,urls:o,fontFamilies:s}})}function nQ(t){const e=/\s*(?:([^'"][^;\n\s,]+)|"([^"]+)"|'([^']+)')\s*/gi,n=/\s*,\s*/gi,r=new Set;for(;;){const o=e.exec(t);if(!o)break;const s=o[1]||o[2]||o[3];if(r.add(s.toLowerCase()),n.lastIndex=e.lastIndex,!n.exec(t))break;e.lastIndex=n.lastIndex}return r}function Jj(t){return!(t.startsWith("-")||t.startsWith("animation")||t.startsWith("transition")||t==="cursor"||t==="pointer-events"||t==="user-select"||t==="touch-action")}function rQ(t,e){return{imports:tQ(t),fontFaces:Qj(t,e)}}function oQ(t){return Array.from(t.matchAll(Zj),e=>({original:e[0],url:e[1]||e[2]||e[3]}))}const sQ=new Set(["border-collapse","border-spacing","caption-side","color","cursor","direction","empty-cells","font-family","font-size","font-style","font-variant","font-weight","font-size-adjust","font-stretch","font","letter-spacing","line-height","list-style-image","list-style-position","list-style-type","list-style","orphans","quotes","tab-size","text-align","text-align-last","text-decoration-color","text-indent","text-justify","text-shadow","text-transform","visibility","white-space","widows","word-break","word-spacing","word-wrap"]);function eO(t){return sQ.has(t)}var iQ=Object.create,tO=Object.defineProperty,aQ=Object.getOwnPropertyDescriptor,lQ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),nO=t=>{throw TypeError(t)},rO=(t,e,n)=>e in t?tO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cQ=t=>[,,,iQ(null)],oO=["class","method","getter","setter","accessor","field","value","get","set"],sO=t=>t!==void 0&&typeof t!="function"?nO("Function expected"):t,uQ=(t,e,n,r,o)=>({kind:oO[t],name:e,metadata:r,addInitializer:s=>n._?nO("Already initialized"):o.push(sO(s||null))}),dQ=(t,e)=>rO(e,lQ("metadata"),t[3]),hQ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},pQ=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=oO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,aQ(o,n)),y=r.length-1;y>=0;y--)l=uQ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,sO(i)&&(v[g]=i);return v&&tO(o,n,v),o},yh=(t,e,n)=>rO(t,typeof e!="symbol"?e+"":e,n),iO,Bg;iO=[Kn];class I1{constructor(){hQ(Bg,5,this),yh(this,"fontFacesPromise",null),yh(this,"foundFontNames",new Set),yh(this,"fontFacesToEmbed",new Set),yh(this,"pendingPromises",[])}startFindingCurrentDocumentFontFaces(){Le(!this.fontFacesPromise,"FontEmbedder already started"),this.fontFacesPromise=fQ()}onFontFamilyValue(e){Le(this.fontFacesPromise,"FontEmbedder not started");const n=nQ(e);for(const r of n){if(this.foundFontNames.has(r))return;this.foundFontNames.add(r),this.pendingPromises.push(this.fontFacesPromise.then(o=>{const s=o.filter(i=>i.fontFamilies.has(r));for(const i of s)if(!this.fontFacesToEmbed.has(i)){this.fontFacesToEmbed.add(i);for(const a of i.urls)!a.resolved||a.embedded||(a.embedded=zg(a.resolved))}}))}}async createCss(){await Promise.all(this.pendingPromises);let e="";for(const n of this.fontFacesToEmbed){let r=`@font-face {${n.fontFace}}`;for(const o of n.urls){if(!o.embedded)continue;const s=await o.embedded;s&&(r=r.replace(o.original,s))}e+=r}return e}}Bg=cQ();pQ(Bg,1,"onFontFamilyValue",iO,I1);dQ(Bg,I1);async function fQ(){const t=[];for(const e of document.styleSheets){let n;try{n=e.cssRules}catch{}if(n)for(const r of e.cssRules)r instanceof CSSFontFaceRule?t.push(Qj(r.cssText,e.href??document.baseURI)):r instanceof CSSImportRule&&t.push(Ix(r.href));else e.href&&t.push(Ix(e.href))}return me(await Promise.all(t)).flat()}const Ix=qj(async t=>{const e=rQ(await t.text(),t.url),n=await Promise.all(e.imports.map(({url:r})=>Ix(new URL(r,t.url).href)));return[...e.fontFaces,...me(n).flat()]});function aO(t){if(t.shadowRoot)return t.shadowRoot.childNodes;if(SQ(t)){const e=t.assignedNodes();if(e!=null&&e.length)return e}return t.childNodes}function*Ex(t){for(const e of aO(t))gQ(e)&&(yield e)}function Ug(t){var e;return((e=t.ownerDocument)==null?void 0:e.defaultView)??globalThis}function gQ(t){return t instanceof Ug(t).Element}function mQ(t){return t instanceof Ug(t).ShadowRoot}function yQ(t){return"getRootNode"in t&&mQ(t.getRootNode())}function SQ(t){return yQ(t)&&t instanceof Ug(t).HTMLSlotElement}function vQ(t){return t.style}function E1(t,e){return Ug(t).getComputedStyle(t,e)}const ea={};class xQ{constructor(e){I(this,"styles",new Map);I(this,"fonts",new I1);this.root=e}readRootElementStyles(e){this.readElementStyles(e,{shouldRespectDefaults:!1,shouldSkipInheritedParentStyles:!1});const n=Array.from(Ex(e));for(;n.length;){const r=n.pop();n.push(...Ex(r)),this.readElementStyles(r,{shouldRespectDefaults:!0,shouldSkipInheritedParentStyles:!0})}}readElementStyles(e,{shouldRespectDefaults:n=!0,shouldSkipInheritedParentStyles:r=!0}){var a;const o=n?CQ(e.tagName.toLowerCase()):ea,s=r?((a=this.styles.get(e.parentElement))==null?void 0:a.self)??ea:ea,i={self:wQ(e,{defaultStyles:o,parentStyles:s}),before:II(e,"::before"),after:II(e,"::after")};this.styles.set(e,i)}fetchResources(){const e=[];for(const n of this.styles.values())for(const r of ut(n))if(r)for(const[o,s]of Object.entries(r)){if(!s)continue;o==="font-family"&&this.fonts.onFontFamilyValue(s);const i=oQ(s);i.length!==0&&e.push(...i.map(async({url:a,original:l})=>{const c=await zg(a)??"data:";r[o]=s.replace(l,`url("${c}")`)}))}return Promise.all(e)}unwrapCustomElements(){const e=new Set,n=(r,o)=>{if(e.has(r))return;e.add(r);const s=r.shadowRoot;if(s){const i=document.createElement("div");this.styles.set(i,this.styles.get(r)),i.setAttribute("data-tl-custom-element",r.tagName),(o??r.parentElement).appendChild(i);for(const a of s.childNodes)a instanceof Element?n(a,i):i.appendChild(a.cloneNode(!0));r.remove()}else if(o){if(r.tagName.toLowerCase()==="style")return;const i=r.cloneNode(!1);this.styles.set(i,this.styles.get(r)),o.appendChild(i);for(const a of aO(r))a instanceof Element?n(a,i):i.appendChild(a.cloneNode(!0))}};for(const r of this.styles.keys())n(r,null)}embedStyles(){let e="";for(const[n,r]of this.styles){if(r.after||r.before){const s=`pseudo-${ze()}`;n.classList.add(s),r.before&&(e+=`.${s}::before {${EI(r.before)}}
99
99
  `),r.after&&(e+=`.${s}::after {${EI(r.after)}}
100
100
  `)}const o=vQ(n);for(const[s,i]of Object.entries(r.self))i&&o.setProperty(s,i);o.fontKerning==="auto"&&(o.fontKerning="normal")}return e}async getFontFaceCss(){return await this.fonts.createCss()}dispose(){PQ()}}function wQ(t,{defaultStyles:e,parentStyles:n}){return t.computedStyleMap?lO(t.computedStyleMap(),{defaultStyles:e,parentStyles:n}):k1(E1(t),{defaultStyles:e,parentStyles:n})}function II(t,e){const n=E1(t,e),r=n.getPropertyValue("content");if(!(r===""||r==="none"))return k1(n,{defaultStyles:ea,parentStyles:ea})}function lO(t,{defaultStyles:e,parentStyles:n}){const r={};for(const o of t.keys()){if(!Jj(o))continue;const s=t.get(o).toString();e[o]!==s&&(n[o]===s&&eO(o)||(r[o]=s))}return r}function k1(t,{defaultStyles:e,parentStyles:n}){const r={};for(const o of t){if(!Jj(o))continue;const s=t.getPropertyValue(o);e[o]!==s&&(n[o]===s&&eO(o)||(r[o]=s))}return r}function EI(t){let e="";for(const[n,r]of Object.entries(t))e+=`${n}: ${r};`;return e}let bl;const kI={};function bQ(){if(!bl){const t=document.createElement("iframe");t.style.display="none",document.body.appendChild(t);const e=zn(t.contentDocument,"frame must have a document"),n=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","foreignObject");n.appendChild(r),e.body.appendChild(n),bl={iframe:t,foreignObject:r,document:e}}return bl}function PQ(){bl&&(document.body.removeChild(bl.iframe),bl=void 0)}const TI={defaultStyles:ea,parentStyles:ea};function CQ(t){let e=kI[t];if(!e){const{foreignObject:n,document:r}=bQ(),o=r.createElement(t);n.appendChild(o),e=o.computedStyleMap?lO(o.computedStyleMap(),TI):k1(E1(o),TI),n.removeChild(o),kI[t]=e}return e}function _Q(t,e){Array.from(t.attributes).forEach(r=>{e.setAttribute(r.name,r.value)})}function MI(t,e){return t.replaceWith(e),e}async function du(t,e){const n=document.createElement("img");e&&_Q(e,n),n.setAttribute("src",t??"data:"),n.setAttribute("decoding","sync"),n.setAttribute("loading","eager");try{await n.decode()}catch{}return n}async function IQ(t){try{const e=t.toDataURL();return await du(e,t)}catch{return await du(null,t)}}async function EQ(t){try{const e=await ar.getVideoFrameAsDataUrl(t);return du(e,t)}catch(e){console.error("Could not get video frame",e)}if(t.poster){const e=await zg(t.poster);return du(e,t)}return du(null,t)}async function cO(t){if(t instanceof HTMLCanvasElement)return MI(t,await IQ(t));if(t instanceof HTMLVideoElement)return MI(t,await EQ(t));if(t instanceof HTMLImageElement){const e=t.currentSrc||t.src,n=await zg(e);t.setAttribute("src",n??"data:"),t.setAttribute("decoding","sync"),t.setAttribute("loading","eager");try{await t.decode()}catch{}return t}else t instanceof HTMLInputElement?t.setAttribute("value",t.value):t instanceof HTMLTextAreaElement&&(t.textContent=t.value);await Promise.all(Array.from(Ex(t),e=>cO(e)))}function Hg(t){const e=w.useRef();return w.useLayoutEffect(()=>{e.current=t}),w.useDebugValue(t),w.useCallback((...n)=>{const r=e.current;return Le(r,"fn does not exist"),r(...n)},[])}const T1=w.createContext(null);function kQ({context:t,editor:e,children:n}){const r=e.options.exportProvider;return d.jsx(p1,{editor:e,children:d.jsx(dj,{container:e.getContainer(),children:d.jsx(T1.Provider,{value:t,children:d.jsx(r,{children:n})})})})}function md(){return w.useContext(T1)}function TQ(){const t=w.useContext(T1),[e]=w.useState(yw);return w.useEffect(()=>(t==null||t.waitUntil(e),()=>{e.resolve()}),[e,t]),Hg(()=>{e.resolve()})}var MQ=Object.create,uO=Object.defineProperty,AQ=Object.getOwnPropertyDescriptor,jQ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),dO=t=>{throw TypeError(t)},hO=(t,e,n)=>e in t?uO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OQ=t=>[,,,MQ(null)],pO=["class","method","getter","setter","accessor","field","value","get","set"],fO=t=>t!==void 0&&typeof t!="function"?dO("Function expected"):t,DQ=(t,e,n,r,o)=>({kind:pO[t],name:e,metadata:r,addInitializer:s=>n._?dO("Already initialized"):o.push(fO(s||null))}),RQ=(t,e)=>hO(e,jQ("metadata"),t[3]),LQ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},$Q=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=pO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,AQ(o,n)),y=r.length-1;y>=0;y--)l=DQ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,fO(i)&&(v[g]=i);return v&&uO(o,n,v),o},AI=(t,e,n)=>hO(t,typeof e!="symbol"?e+"":e,n),gO,Kg;gO=[Kn];class M1{constructor(e){this.maxDelayTimeMs=e,LQ(Kg,5,this),AI(this,"isResolved",!1),AI(this,"promisesToWaitFor",[])}waitUntil(e){if(this.isResolved)throw new Error("Cannot `waitUntil` - the export has already been resolved. Make sure to call `waitUntil` as soon as possible during an export - ie within the first react effect after rendering.");this.promisesToWaitFor.push(e.catch(n=>console.error("Error whilst waiting for export:",n)))}async resolvePromises(){let e=null;for(;this.promisesToWaitFor.length!==e;)e=this.promisesToWaitFor.length,await Promise.allSettled(this.promisesToWaitFor),await Wv(0)}async resolve(){const e=Wv(this.maxDelayTimeMs).then(()=>"timeout"),n=this.resolvePromises().then(()=>"resolved");await Promise.race([e,n])==="timeout"&&console.warn("[tldraw] Export delay timed out after ${this.maxDelayTimeMs}ms"),this.isResolved=!0}}Kg=OQ();$Q(Kg,1,"waitUntil",gO,M1);RQ(Kg,M1);function FQ(t,e,n={}){var y,S;if(!window.document)throw Error("No document");const{scale:r=1,background:o=!1,padding:s=t.options.defaultSvgPadding,preserveAspectRatio:i}=n,a=n.darkMode??t.user.getIsDarkMode(),l=t.getShapeAndDescendantIds(e),c=t.getUnorderedRenderingShapes(!1).filter(({id:b})=>l.has(b));let u=null;if(n.bounds)u=n.bounds;else for(const{id:b}of c){const P=t.getShapeMaskedPageBounds(b);P&&(u?u.union(P):u=P.clone())}if(!u)return;const h=e.length===1&&t.isShapeOfType(t.getShape(e[0]),"frame")?e[0]:null;h||u.expandBy(s);const p=u.width*r,f=u.height*r;try{(S=(y=document.body).focus)==null||S.call(y)}catch{}const g=new M1(t.options.maxExportDelayMs),m=yw();return g.waitUntil(m),{jsx:d.jsx(NQ,{editor:t,preserveAspectRatio:i,scale:r,bbox:u,background:o,singleFrameShapeId:h,isDarkMode:a,renderingShapes:c,onMount:m.resolve,waitUntil:g.waitUntil}),width:p,height:f,exportDelay:g}}function NQ({editor:t,preserveAspectRatio:e,scale:n,bbox:r,background:o,singleFrameShapeId:s,isDarkMode:i,renderingShapes:a,onMount:l,waitUntil:c}){const u=Jl(),h=ks({isDarkMode:i}),p=qw("export state",{defsById:{},shapeElements:null}),{defsById:f,shapeElements:g}=U(p),m=Hg(S=>{p.update(b=>{if(no(b.defsById,S.key))return b;const P=Promise.resolve(S.getElement());return c(P.then(C=>{p.update(_=>({..._,defsById:{..._.defsById,[S.key]:{pending:!1,element:C}}}))})),{...b,defsById:{...b.defsById,[S.key]:{pending:!0,element:P}}}})}),v=w.useMemo(()=>({isDarkMode:i,waitUntil:c,addExportDef:m}),[i,c,m]),y=w.useRef(!1);return w.useLayoutEffect(()=>{if(y.current)throw new Error("SvgExport should only render once - do not use with react strict mode");y.current=!0,(async()=>{const S={},b=a.map(async({id:C,opacity:_,index:E,backgroundIndex:k})=>{var $,M;if(C===s)return[];const D=t.getShape(C);if(t.isShapeOfType(D,"group"))return[];const T=[],j=t.getShapeUtil(D);if(j.toSvg||j.toBackgroundSvg){const[O,F]=await Promise.all([($=j.toSvg)==null?void 0:$.call(j,D,v),(M=j.toBackgroundSvg)==null?void 0:M.call(j,D,v)]),B=t.getShapePageTransform(D);let K=B.toCssString(),R=1;"scale"in D.props&&D.props.scale!==1&&(R=D.props.scale,K=`${K} scale(${D.props.scale}, ${D.props.scale})`);const H=t.getShapeMask(D.id),Y=H?q.From(q.Inverse(B)).applyToPoints(H):null,ee=d1(u,D.id);Y&&(S[ee]={pending:!1,element:d.jsx("clipPath",{id:ee,children:d.jsx("path",{d:`M${Y.map(({x:he,y:ue})=>`${he/R},${ue/R}`).join("L")}Z`})})}),O&&T.push({zIndex:E,element:d.jsx("g",{transform:K,opacity:_,clipPath:H?`url(#${ee})`:void 0,children:O},`fg_${D.id}`)}),F&&T.push({zIndex:k,element:d.jsx("g",{transform:K,opacity:_,clipPath:H?`url(#${ee})`:void 0,children:F},`bg_${D.id}`)})}else T.push({zIndex:E,element:d.jsx(jI,{shape:D,util:j,component:_j,className:"tl-shape",bbox:r,opacity:_},`fg_${D.id}`)}),j.backgroundComponent&&T.push({zIndex:k,element:d.jsx(jI,{shape:D,util:j,component:Ij,className:"tl-shape tl-shape-background",bbox:r,opacity:_},`bg_${D.id}`)});return T}),P=(await Promise.all(b)).flat();wa.flushSync(()=>{p.update(C=>({...C,shapeElements:P.sort((_,E)=>_.zIndex-E.zIndex).map(({element:_})=>_),defsById:{...C.defsById,...S}}))})})()},[r,t,v,u,a,s,p]),w.useEffect(()=>{g!==null&&l()},[l,g]),d.jsx(kQ,{editor:t,context:v,children:d.jsxs("svg",{preserveAspectRatio:e,direction:"ltr",width:r.width*n,height:r.height*n,viewBox:`${r.minX} ${r.minY} ${r.width} ${r.height}`,strokeLinecap:"round",strokeLinejoin:"round",style:{backgroundColor:o?s?h.solid:h.background:"transparent"},"data-color-mode":i?"dark":"light",className:`tl-container tl-theme__force-sRGB ${i?"tl-theme__dark":"tl-theme__light"}`,children:[d.jsx("defs",{children:Object.entries(f).map(([S,b])=>b.pending?null:d.jsx(w.Fragment,{children:b.element},S))}),g]})})}function jI({shape:t,util:e,className:n,component:r,bbox:o,opacity:s}){const i=z(),a=q.Translate(-o.minX,-o.minY).multiply(i.getShapePageTransform(t.id)),l=i.getShapeGeometry(t.id).bounds,c=Math.max(l.width,1),u=Math.max(l.height,1);return d.jsx(u1,{fallback:()=>null,children:d.jsx("foreignObject",{x:o.minX,y:o.minY,width:o.w,height:o.h,className:"tl-shape-foreign-object",children:d.jsx("div",{className:n,"data-shape-type":t.type,style:{clipPath:i.getShapeClipPath(t.id),transform:a.toCssString(),width:c,height:u,opacity:s},children:d.jsx(r,{shape:t,util:e})})})})}let zQ=1;async function BQ(t,e,n={}){const r=FQ(t,e,n);if(!r)return;const o=t.getContainer(),s=document.createElement("div");s.className="tldraw-svg-export",s.inert=!0,s.tabIndex=-1,Object.assign(s.style,{position:"absolute",top:"0px",left:"0px",width:r.width+"px",height:r.height+"px",pointerEvents:"none",opacity:0}),o.appendChild(s);const i=IT(s,{identifierPrefix:`export_${zQ++}_`});try{await Promise.resolve(),wa.flushSync(()=>{i.render(r.jsx)}),await r.exportDelay.resolve();const a=s.firstElementChild;return Le(a instanceof SVGSVGElement,"Expected an SVG element"),await UQ(a),{svg:a,width:r.width,height:r.height}}finally{setTimeout(()=>{i.unmount(),o.removeChild(s)},0)}}async function UQ(t){const e=[...t.querySelectorAll("foreignObject.tl-shape-foreign-object > *")];if(!e.length)return;const n=new xQ(t);try{n.fonts.startFindingCurrentDocumentFontFaces(),await Promise.all(e.map(s=>cO(s)));for(const s of e)n.readRootElementStyles(s);await n.fetchResources();const r=await n.getFontFaceCss();n.unwrapCustomElements();const o=n.embedStyles();if(r||o){const s=document.createElementNS("http://www.w3.org/2000/svg","style");s.textContent=`${r}
101
- ${o}`,t.prepend(s)}}finally{n.dispose()}}const Vr={menus:Et("open menus",[]),getOpenMenus(t){return t?this.menus.get().filter(e=>e.endsWith("-"+t)):this.menus.get()},addOpenMenu(t,e=""){const n=e?`${t}-${e}`:t,r=new Set(this.menus.get());r.has(n)||(r.add(n),this.menus.set([...r]))},deleteOpenMenu(t,e=""){const n=e?`${t}-${e}`:t,r=new Set(this.menus.get());r.has(n)&&(r.delete(n),this.menus.set([...r]))},clearOpenMenus(t){this.menus.set(t?this.menus.get().filter(e=>!e.endsWith("-"+t)):[])},_hiddenMenus:[],hideOpenMenus(t){if(this._hiddenMenus=[...this.getOpenMenus(t)],this._hiddenMenus.length!==0)for(const e of this._hiddenMenus)this.deleteOpenMenu(e,t)},showOpenMenus(t){if(this._hiddenMenus.length!==0){for(const e of this._hiddenMenus)this.addOpenMenu(e,t);this._hiddenMenus=[]}},isMenuOpen(t,e){return this.getOpenMenus(e).includes(t)},hasOpenMenus(t){return this.getOpenMenus(t).length>0},hasAnyOpenMenus(){return this.getOpenMenus().length>0},forContext(t){return{getOpenMenus:()=>this.getOpenMenus(t),addOpenMenu:e=>this.addOpenMenu(e,t),deleteOpenMenu:e=>this.deleteOpenMenu(e,t),clearOpenMenus:()=>this.clearOpenMenus(t),isMenuOpen:e=>this.isMenuOpen(e,t),hasOpenMenus:()=>this.hasOpenMenus(t),hasAnyOpenMenus:()=>this.hasAnyOpenMenus()}}},kx=new h7,HQ={maxShapesPerPage:4e3,maxFilesAtOnce:100,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,laserDelayMs:1200,maxExportDelayMs:5e3,temporaryAssetPreviewLifetimeMs:18e4,actionShortcutsLocation:"swap",createTextOnCanvasDoubleClick:!0,exportProvider:w.Fragment};function OI(t,e){if(!e)return!1;switch(t.type){case"mixed":return e.type==="mixed";case"shared":return e.type==="shared"&&t.value===e.value;default:throw Ot(t)}}class KQ{constructor(e){I(this,"map");this.map=new Map(e)}get(e){return this.map.get(e)}getAsKnownValue(e){const n=this.get(e);if(n&&n.type!=="mixed")return n.value}get size(){return this.map.size}equals(e){if(this.size!==e.size)return!1;const n=new Set;for(const[r,o]of this){if(!OI(o,e.get(r)))return!1;n.add(r)}for(const[r,o]of e)if(!n.has(r)&&!OI(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 Tx extends KQ{set(e,n){this.map.set(e,n)}applyValue(e,n){const r=this.get(e);if(!r){this.set(e,{type:"shared",value:n});return}switch(r.type){case"mixed":return;case"shared":r.value!==n&&this.set(e,{type:"mixed"});return;default:Ot(r,"type")}}}function WQ(t,e,n){return Lo(t).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],e,{type:n})})}const GQ="https://cdn.tldraw.com";function ei(){return`${GQ}/${oj}`}function VQ(t){switch(t.type){case"shapes":return`s${t.shapeIds.map(n=>Zy(n.slice(6))).join(".")}`;case"page":return"p"+Zy(yr.parseId(t.pageId));case"viewport":{const{bounds:e,pageId:n}=t;let r=`v${Math.round(e.x)}.${Math.round(e.y)}.${Math.round(e.w)}.${Math.round(e.h)}`;return n&&(r+="."+Zy(yr.parseId(n))),r}default:Ot(t)}}function YQ(t){switch(t[0]){case"s":return{type:"shapes",shapeIds:t.slice(1).split(".").filter(Boolean).map(r=>Ke(decodeURIComponent(r)))};case"p":return{type:"page",pageId:yr.createId(decodeURIComponent(t.slice(1)))};case"v":{const[n,r,o,s,i]=t.slice(1).split(".");return{type:"viewport",bounds:new Z(Number(n),Number(r),Number(o),Number(s)),pageId:i?yr.createId(decodeURIComponent(i)):void 0}}default:throw Error("Invalid deep link string")}}function Zy(t){return encodeURIComponent(t).replace(/\./g,"%2E")}function XQ(t,e){var o;let n=t;const r=new Set(e);for(;r.has(n);)n=(o=/^.*(\d+)$/.exec(n))!=null&&o[1]?n.replace(/(\d+)(?=\D?)$/,s=>(+s+1).toString()):`${n} 1`;return n}function Sh(t,e,n,r){if(n.length===0)return[];const o=new Map;for(const i of me(n.map(a=>t.getShape(a)))){const{parentId:a}=i;o.has(a)||o.set(a,{children:me(t.getSortedChildIdsForParent(a).map(l=>t.getShape(l))),moving:new Set}),o.get(a).moving.add(i)}const s=[];switch(e){case"toBack":{o.forEach(({moving:i,children:a})=>qQ(i,a,s));break}case"toFront":{o.forEach(({moving:i,children:a})=>ZQ(i,a,s));break}case"forward":{o.forEach(({moving:i,children:a})=>QQ(t,i,a,s,r));break}case"backward":{o.forEach(({moving:i,children:a})=>JQ(t,i,a,s,r));break}}return s}function qQ(t,e,n){const r=e.length;if(t.size===r)return;let o,s;for(let i=0;i<r;i++){const a=e[i];if(t.has(a))o=a.index,t.delete(a);else{s=a.index;break}}if(t.size!==0){const i=Dl(o,s,t.size);n.push(...Array.from(t.values()).sort(cn).map((a,l)=>({...a,index:i[l]})))}}function ZQ(t,e,n){const r=e.length;if(t.size===r)return;let o,s;for(let i=r-1;i>-1;i--){const a=e[i];if(t.has(a))s=a.index,t.delete(a);else{o=a.index;break}}if(t.size!==0){const i=Dl(o,s,t.size);n.push(...Array.from(t.values()).sort(cn).map((a,l)=>({...a,index:i[l]})))}}function DI(t,e){const n=t.getShapeGeometry(e),r=t.getShapePageTransform(e);return!n||!r?null:r.applyToPoints(n.vertices)}function mO(t,e){const n=Array.from(e).map(o=>{const s=DI(t,o);return s?{shape:o,vertices:s}:null}).filter(Boolean);return o=>{const s=DI(t,o);return s?n.some(i=>_1(i.vertices,s)):!1}}function QQ(t,e,n,r,o){var l;const s=mO(t,e),i=n.length;if(e.size===i)return;let a={name:"skipping"};for(let c=0;c<i;c++){const u=e.has(n[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(o!=null&&o.considerAllShapes)&&!s(n[c]))continue;const{selectIndex:h}=a;Dl(n[c].index,(l=n[c+1])==null?void 0:l.index,c-h).forEach((p,f)=>{const g=n[h+f];e.has(g)&&r.push({...g,index:p})}),a={name:"skipping"};break}}}}function JQ(t,e,n,r,o){var l;const s=mO(t,e),i=n.length;if(e.size===i)return;let a={name:"skipping"};for(let c=i-1;c>-1;c--){const u=e.has(n[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(o!=null&&o.considerAllShapes)&&!s(n[c]))continue;Dl((l=n[c-1])==null?void 0:l.index,n[c].index,a.selectIndex-c).forEach((h,p)=>{const f=n[c+p+1];e.has(f)&&r.push({...f,index:h})}),a={name:"skipping"};break}}}}function yO({editor:t,ids:e}){const n=me(e.map(i=>t.getShape(i))),r=t.getShapesSharedRotation(e),o=t.getShapesRotatedPageBounds(e);if(!o)return null;const s=o.center.clone().rotWith(o.point,r);return{pageCenter:s,initialCursorAngle:s.angle(t.inputs.originPagePoint),initialShapesRotation:r,shapeSnapshots:n.map(i=>({shape:i,initialPagePoint:t.getShapePageTransform(i.id).point()}))}}function up({delta:t,editor:e,snapshot:n,stage:r,centerOverride:o}){const{pageCenter:s,shapeSnapshots:i}=n;e.updateShapes(i.map(({shape:l,initialPagePoint:c})=>{const u=Fn(l.parentId)?e.getShapePageTransform(l.parentId):q.Identity(),h=x.RotWith(c,o??s,t),p=q.applyToPoint(q.Inverse(u),h),f=Ji(l.rotation+t);return{id:l.id,type:l.type,x:p.x,y:p.y,rotation:f}}));const a=[];i.forEach(({shape:l})=>{var p,f,g;const c=e.getShape(l.id);if(!c)return;const u=e.getShapeUtil(l);if(r==="start"||r==="one-off"){const m=(p=u.onRotateStart)==null?void 0:p.call(u,l);m&&a.push(m)}const h=(f=u.onRotate)==null?void 0:f.call(u,l,c);if(h&&a.push(h),r==="end"||r==="one-off"){const m=(g=u.onRotateEnd)==null?void 0:g.call(u,l,c);m&&a.push(m)}}),a.length>0&&e.updateShapes(a)}const eJ=t=>{const{store:e}=t,n=e.query.filterHistory("binding"),r=e.query.records("binding");function o(){const s=r.get(),i=new Map;for(const a of s){const{fromId:l,toId:c}=a,u=i.get(l);u?u.push(a):i.set(l,[a]);const h=i.get(c);h?h.push(a):i.set(c,[a])}return i}return G("arrowBindingsIndex",(s,i)=>{if(Zi(s))return o();const a=s,l=n.getDiffSince(i);if(l===ur)return o();let c;function u(f){c??(c=new Map(a));const g=c.get(f.fromId),m=g==null?void 0:g.filter(S=>S.id!==f.id);m!=null&&m.length?c.set(f.fromId,m):c.delete(f.fromId);const v=c.get(f.toId),y=v==null?void 0:v.filter(S=>S.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 g=c.get(f);return g?g===a.get(f)&&(g=g.slice(0),c.set(f,g)):(g=[],c.set(f,g)),g}function p(f){h(f.fromId).push(f),h(f.toId).push(f)}for(const f of l){for(const g of ut(f.added))p(g);for(const[g,m]of ut(f.updated))u(g),p(m);for(const g of ut(f.removed))u(g)}return c??a})};function tJ(t,e,n){const r=t.getShapeMaskedPageBounds(e);return r===void 0?!0:!n.includes(r)}const nJ=t=>{function e(n){const r=n.getCurrentPageShapeIds(),o=n.getViewportPageBounds(),s=new Set;return r.forEach(i=>{tJ(n,i,o)&&s.add(i)}),s}return G("getCulledShapes",n=>{if(Zi(n))return e(t);const r=e(t);if(n.size!==r.size)return r;for(const o of n)if(!r.has(o))return r;return n})},rJ=t=>{const e=t.query.ids("shape"),n=t.query.filterHistory("shape");function r(){const o={},s=e.get(),i=Array(s.size);return s.forEach(a=>i.push(t.get(a))),i.sort(cn),i.forEach(a=>{o[a.parentId]||(o[a.parentId]=[]),o[a.parentId].push(a.id)}),o}return G("parentsToChildrenWithIndexes",(o,s)=>{if(Zi(o))return r();const i=n.getDiffSince(s);if(i===ur)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 u;for(let h=0,p=i.length;h<p;h++){u=i[h];for(const f of Object.values(u.added))al(f)&&(l(f.parentId),a[f.parentId].push(f.id),c.add(a[f.parentId]));for(const[f,g]of Object.values(u.updated))if(al(g)&&al(f)){if(f.parentId!==g.parentId)l(f.parentId),l(g.parentId),a[f.parentId].splice(a[f.parentId].indexOf(g.id),1),a[g.parentId].push(g.id),c.add(a[g.parentId]);else if(f.index!==g.index){l(g.parentId);const m=a[g.parentId].indexOf(g.id);a[g.parentId][m]=g.id,c.add(a[g.parentId])}}for(const f of Object.values(u.removed))al(f)&&(l(f.parentId),a[f.parentId].splice(a[f.parentId].indexOf(f.id),1))}for(const h of c){const p=me(h.map(f=>t.get(f)));p.sort(cn),h.splice(0,h.length,...p.map(f=>f.id))}return a??o})},Qy=(t,e,n)=>{for(;!Rn(n.parentId);){const r=t.get(n.parentId);if(!r)return!1;n=r}return n.parentId===e},oJ=(t,e)=>{const n=t.query.ids("shape");let r=null;function o(){const s=e();return r=s,new Set([...n.get()].filter(i=>Qy(t,s,t.get(i))))}return G("_shapeIdsInCurrentPage",(s,i)=>{if(Zi(s))return o();const a=e();if(a!==r)return o();const l=t.history.getDiffSince(i);if(l===ur)return o();const c=new sp(s);for(const h of l){for(const p of Object.values(h.added))al(p)&&Qy(t,a,p)&&c.add(p.id);for(const[p,f]of Object.values(h.updated))al(f)&&(Qy(t,a,f)?c.add(f.id):c.remove(f.id));for(const p of Object.keys(h.removed))Fn(p)&&c.remove(p)}const u=c.get();return u?Wc(u.value,u.diff):s})};var sJ=Object.create,SO=Object.defineProperty,iJ=Object.getOwnPropertyDescriptor,aJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),vO=t=>{throw TypeError(t)},xO=(t,e,n)=>e in t?SO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lJ=t=>[,,,sJ(null)],wO=["class","method","getter","setter","accessor","field","value","get","set"],bO=t=>t!==void 0&&typeof t!="function"?vO("Function expected"):t,cJ=(t,e,n,r,o)=>({kind:wO[t],name:e,metadata:r,addInitializer:s=>n._?vO("Already initialized"):o.push(bO(s||null))}),uJ=(t,e)=>xO(e,aJ("metadata"),t[3]),dJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},PO=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=wO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,iJ(o,n)),y=r.length-1;y>=0;y--)l=cJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,bO(i)&&(v[g]=i);return v&&SO(o,n,v),o},La=(t,e,n)=>xO(t,typeof e!="symbol"?e+"":e,n),CO,_O,yd;const hJ=40;_O=[Kn],CO=[Kn];class Wg{constructor(e){this.editor=e,dJ(yd,5,this),La(this,"_clickId",""),La(this,"_clickTimeout"),La(this,"_clickScreenPoint"),La(this,"_previousScreenPoint"),La(this,"_clickState","idle"),La(this,"lastPointerInfo",{})}_getClickTimeout(e,n=ze()){this._clickId=n,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===e&&this._clickId===n){switch(this._clickState){case"pendingTriple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"double_click",phase:"settle"});break}case"pendingQuadruple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"triple_click",phase:"settle"});break}case"pendingOverflow":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"settle"});break}}this._clickState="idle"}},e==="idle"||e==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)}get clickState(){return this._clickState}handlePointerEvent(e){switch(e.name){case"pointer_down":{if(!this._clickState)return e;switch(this._clickScreenPoint=x.From(e.point),this._previousScreenPoint&&x.Dist2(this._previousScreenPoint,this._clickScreenPoint)>hJ**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=e,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"quadruple_click",phase:"down"};case"idle":{this._clickState="pendingDouble";break}case"pendingOverflow":{this._clickState="overflow";break}}return this._clickTimeout=this._getClickTimeout(this._clickState),e}case"pointer_up":{if(!this._clickState)return e;switch(this._clickScreenPoint=x.From(e.point),this._clickState){case"pendingTriple":return{...this.lastPointerInfo,type:"click",name:"double_click",phase:"up"};case"pendingQuadruple":return{...this.lastPointerInfo,type:"click",name:"triple_click",phase:"up"};case"pendingOverflow":return{...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"up"}}return e}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&x.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),e}return e}cancelDoubleClickTimeout(){this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"}}yd=lJ();PO(yd,1,"_getClickTimeout",_O,Wg);PO(yd,1,"cancelDoubleClickTimeout",CO,Wg);uJ(yd,Wg);class pJ{constructor(e){I(this,"_isEdgeScrolling",!1);I(this,"_edgeScrollDuration",-1);this.editor=e}updateEdgeScrolling(e){const{editor:n}=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+=e,this._edgeScrollDuration>n.options.edgeScrollDelay){const o=n.options.edgeScrollEaseDuration>0?Dt.easeInCubic(Math.min(1,this._edgeScrollDuration/(n.options.edgeScrollDelay+n.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*o,y:r.y*o})}}getEdgeProximityFactors(e,n,r,o,s){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=e-l,u=e+l,h=o?0:a,p=s?n:n-a;return c<h?Math.min(1,(h-c)/a):u>p?-Math.min(1,(u-p)/a):0}getEdgeScroll(){const{editor:e}=this,{inputs:{currentScreenPoint:{x:n,y:r}}}=e,o=e.getViewportScreenBounds(),{isCoarsePointer:s,insets:[i,a,l,c]}=e.getInstanceState(),u=this.getEdgeProximityFactors(n,o.w,s,c,a),h=this.getEdgeProximityFactors(r,o.h,s,i,l);return{x:u,y:h}}moveCameraWhenCloseToEdge(e){const{editor:n}=this;if(!n.inputs.isDragging||n.inputs.isPanning||n.getCameraOptions().isLocked||e.x===0&&e.y===0)return;const r=n.getViewportScreenBounds(),o=r.w<1e3?.612:1,s=r.h<1e3?.612:1,i=n.getZoomLevel(),a=n.user.getEdgeScrollSpeed()*n.options.edgeScrollSpeed,l=a*e.x*o/i,c=a*e.y*s/i,{x:u,y:h,z:p}=n.getCamera();n.setCamera(new x(u+l,h+c,p))}}class fJ{constructor(e,n){I(this,"disposeSideEffectListener");this.editor=e,this.disposeSideEffectListener=e.sideEffects.registerAfterChangeHandler("instance",(o,s)=>{o.isFocused!==s.isFocused&&this.updateContainerClass()});const r=e.getInstanceState().isFocused;n!==r&&e.updateInstanceState({isFocused:!!n}),this.updateContainerClass()}updateContainerClass(){const e=this.editor.getContainer();this.editor.getInstanceState().isFocused?e.classList.add("tl-container__focused"):e.classList.remove("tl-container__focused")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var e;(e=this.disposeSideEffectListener)==null||e.call(this)}}function Ac(t){return mJ}class gJ{constructor(){I(this,"length",0);I(this,"head",null);I(this,"tail",this)}push(e){return new A1(e,this)}toArray(){return ps}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const mJ=new gJ;class A1{constructor(e,n){I(this,"length");this.head=e,this.tail=n,this.length=n.length+1}push(e){return new A1(e,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let e=this;return{next(){if(e.length){const n=e.head;return e=e.tail,{value:n,done:!1}}else return{value:void 0,done:!0}}}}}class yJ{constructor(e){I(this,"store");I(this,"dispose");I(this,"state","recording");I(this,"pendingDiff",new vJ);I(this,"stacks",Et("HistoryManager.stacks",{undos:Ac(),redos:Ac()},{isEqual:(e,n)=>e.undos===n.undos&&e.redos===n.redos}));I(this,"annotateError");I(this,"_isInBatch",!1);this.store=e.store,this.annotateError=e.annotateError??Ru,this.dispose=this.store.addHistoryInterceptor((n,r)=>{if(r==="user")switch(this.state){case"recording":this.pendingDiff.apply(n.changes),this.stacks.update(({undos:o})=>({undos:o,redos:Ac()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(n.changes);break;case"paused":break;default:Ot(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const e=this.pendingDiff.clear();this.stacks.update(({undos:n,redos:r})=>({undos:n.push({type:"diff",diff:e}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}batch(e,n){const r=this.state;r!=="paused"&&(n!=null&&n.history)&&(this.state=SJ[n.history]);try{if(this._isInBatch)return Oo(e),this;this._isInBatch=!0;try{Oo(e)}catch(o){throw this.annotateError(o),o}finally{this._isInBatch=!1}return this}finally{this.state=r}}_undo({pushToRedoStack:e,toMark:n=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=fA(a),c=fx(a);e&&!l&&(i=i.push({type:"diff",diff:a}));let u=!1;if(l)for(;((o=s.head)==null?void 0:o.type)==="stop";){const h=s.head;if(s=s.tail,e&&(i=i.push(h)),h.id===n){u=!0;break}}if(!u)e:for(;s.head;){const h=s.head;switch(s=s.tail,e&&(i=i.push(h)),h.type){case"diff":cu(c,[fx(h.diff)]);break;case"stop":if(!n)break e;if(h.id===n){u=!0;break e}break;default:Ot(h)}}if(!u&&n)return this;this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:s,redos:i})}finally{this.state=r}return this}undo(){return this._undo({pushToRedoStack:!0}),this}redo(){var n;const e=this.state;this.state="paused";try{this.flushPendingDiff();let{undos:r,redos:o}=this.stacks.get();if(o.length===0)return this;for(;((n=o.head)==null?void 0:n.type)==="stop";)r=r.push(o.head),o=o.tail;const s=wf();for(;o.head;){const i=o.head;if(r=r.push(i),o=o.tail,i.type==="diff")cu(s,[i.diff]);else break}this.store.applyDiff(s,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:o})}finally{this.state=e}return this}bail(){return this._undo({pushToRedoStack:!1}),this}bailToMark(e){return this._undo({pushToRedoStack:!1,toMark:e}),this}squashToMark(e){var s;let n=this.stacks.get().undos;const r=[];for(;n.head&&!(n.head.type==="stop"&&n.head.id===e);)n.head.type==="diff"&&r.push(n.head.diff),n=n.tail;if(!n.head||((s=n.head)==null?void 0:s.id)!==e)return console.error("Could not find mark to squash to: ",e),this;if(r.length===0)return this;const o=wf();return cu(o,r.reverse()),this.stacks.update(({redos:i})=>({undos:n.push({type:"diff",diff:o}),redos:i})),this}_mark(e){Oo(()=>{this.flushPendingDiff(),this.stacks.update(({undos:n,redos:r})=>({undos:n.push({type:"stop",id:e}),redos:r}))})}clear(){this.stacks.set({undos:Ac(),redos:Ac()}),this.pendingDiff.clear()}getMarkIdMatching(e){let n=this.stacks.get().undos;for(;n.head;){if(n.head.type==="stop"&&n.head.id.includes(e))return n.head.id;n=n.tail}return null}debug(){const{undos:e,redos:n}=this.stacks.get();return{undos:e.toArray(),redos:n.toArray(),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const SJ={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class vJ{constructor(){I(this,"diff",wf());I(this,"isEmptyAtom",Et("PendingDiff.isEmpty",!0))}clear(){const e=this.diff;return this.diff=wf(),this.isEmptyAtom.set(!0),e}isEmpty(){return this.isEmptyAtom.get()}apply(e){cu(this.diff,[e]),this.isEmptyAtom.set(fA(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}class xJ{constructor(e){I(this,"scribbleItems",new Map);I(this,"state","paused");this.editor=e}addScribble(e,n=ze()){const r={id:n,scribble:{id:n,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...e,state:"starting"},timeoutMs:0,delayRemaining:e.delay??0,prev:null,next:null};return this.scribbleItems.set(n,r),r}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}stop(e){const n=this.scribbleItems.get(e);if(!n)throw Error(`Scribble with id ${e} not found`);return n.delayRemaining=Math.min(n.delayRemaining,200),n.scribble.state="stopping",n}addPoint(e,n,r,o=.5){const s=this.scribbleItems.get(e);if(!s)throw Error(`Scribble with id ${e} not found`);const{prev:i}=s,a={x:n,y:r,z:o};return(!i||x.Dist(i,a)>=1)&&(s.next=a),s}tick(e){this.scribbleItems.size!==0&&this.editor.run(()=>{this.scribbleItems.forEach(n=>{if(n.scribble.state==="starting"){const{next:l,prev:c}=n;l&&l!==c&&(n.prev=l,n.scribble.points.push(l)),n.scribble.points.length>8&&(n.scribble.state="active");return}n.delayRemaining>0&&(n.delayRemaining=Math.max(0,n.delayRemaining-e)),n.timeoutMs+=e,n.timeoutMs>=16&&(n.timeoutMs=0);const{delayRemaining:r,timeoutMs:o,prev:s,next:i,scribble:a}=n;switch(a.state){case"active":{i&&i!==s?(n.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):o===0&&(a.points.length>1?a.points.shift():n.delayRemaining=a.delay);break}case"stopping":{if(n.delayRemaining===0&&o===0){if(a.points.length===1){this.scribbleItems.delete(n.id);return}a.shrink&&(a.size=Math.max(1,a.size*(1-a.shrink))),a.points.shift()}break}}}),this.editor.updateInstanceState({scribbles:Array.from(this.scribbleItems.values()).map(({scribble:n})=>({...n,points:[...n.points]})).slice(-5)})})}}var wJ=Object.create,IO=Object.defineProperty,bJ=Object.getOwnPropertyDescriptor,PJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),EO=t=>{throw TypeError(t)},kO=(t,e,n)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,CJ=t=>[,,,wJ(null)],TO=["class","method","getter","setter","accessor","field","value","get","set"],MO=t=>t!==void 0&&typeof t!="function"?EO("Function expected"):t,_J=(t,e,n,r,o)=>({kind:TO[t],name:e,metadata:r,addInitializer:s=>n._?EO("Already initialized"):o.push(MO(s||null))}),IJ=(t,e)=>kO(e,PJ("metadata"),t[3]),EJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Gg=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=TO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,bJ(o,n)),y=r.length-1;y>=0;y--)l=_J(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,MO(i)&&(v[g]=i);return v&&IO(o,n,v),o},kJ=(t,e,n)=>kO(t,e+"",n),AO,jO,OO,DO,_a;const pe=t=>Math.round(t*10**8)/10**8;function ns(t,e,n,r,o){const s=t.filter(a=>(r==="forward"?a.startNode.id===e:a.endNode.id===e)&&pe(a.length)===pe(n)&&Gr(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=ns(t,l,n,r,Gr(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));s.push(...c)}}),s}function TJ(t){t.sort((e,n)=>n.gaps.length-e.gaps.length);for(let e=t.length-1;e>0;e--){const n=t[e];for(let r=e-1;r>=0;r--){const o=t[r];if(o.direction===n.direction&&n.gaps.every(s=>o.gaps.some(i=>pe(s.startEdge[0].x)===pe(i.startEdge[0].x)&&pe(s.startEdge[0].y)===pe(i.startEdge[0].y)&&pe(s.startEdge[1].x)===pe(i.startEdge[1].x)&&pe(s.startEdge[1].y)===pe(i.startEdge[1].y))&&o.gaps.some(i=>pe(s.endEdge[0].x)===pe(i.endEdge[0].x)&&pe(s.endEdge[0].y)===pe(i.endEdge[0].y)&&pe(s.endEdge[1].x)===pe(i.endEdge[1].x)&&pe(s.endEdge[1].y)===pe(i.endEdge[1].y)))){t.splice(e,1);break}}}}DO=[G],OO=[G],jO=[G],AO=[G];class rc{constructor(e){this.manager=e,EJ(_a,5,this),kJ(this,"editor"),this.editor=e.editor}getSnapPointsCache(){const{editor:e}=this;return e.store.createComputedCache("snapPoints",n=>{const r=e.getShapePageTransform(n.id);if(!r)return;const s=e.getShapeUtil(n).getBoundsSnapGeometry(n).points??e.getShapeGeometry(n).bounds.cornersAndCenter;if(!(!r||!s))return s.map((i,a)=>{const{x:l,y:c}=q.applyToPoint(r,i);return{x:l,y:c,id:`${n.id}:${a}`}})})}getSnapPoints(e){return this.getSnapPointsCache().get(e)??[]}getSnappablePoints(){const e=this.getSnapPointsCache(),n=this.manager.getSnappableShapes(),r=[];for(const o of n){const s=e.get(o);s&&r.push(...s)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),e=>({id:e,pageBounds:zn(this.editor.getShapePageBounds(e))}))}getVisibleGaps(){const e=[],n=[];let r,o;const s=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;a<s.length;a++){r=s[a];for(let l=a+1;l<s.length;l++)o=s[l],r.pageBounds.maxX<o.pageBounds.minX&&Mc(r.pageBounds.minY,r.pageBounds.maxY,o.pageBounds.minY,o.pageBounds.maxY)&&e.push({startNode:r,endNode:o,startEdge:[new x(r.pageBounds.maxX,r.pageBounds.minY),new x(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new x(o.pageBounds.minX,o.pageBounds.minY),new x(o.pageBounds.minX,o.pageBounds.maxY)],length:o.pageBounds.minX-r.pageBounds.maxX,breadthIntersection:Gr(r.pageBounds.minY,r.pageBounds.maxY,o.pageBounds.minY,o.pageBounds.maxY)})}const i=s.sort((a,l)=>a.pageBounds.minY-l.pageBounds.minY);for(let a=0;a<i.length;a++){r=i[a];for(let l=a+1;l<i.length;l++)o=i[l],r.pageBounds.maxY<o.pageBounds.minY&&Mc(r.pageBounds.minX,r.pageBounds.maxX,o.pageBounds.minX,o.pageBounds.maxX)&&n.push({startNode:r,endNode:o,startEdge:[new x(r.pageBounds.minX,r.pageBounds.maxY),new x(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new x(o.pageBounds.minX,o.pageBounds.minY),new x(o.pageBounds.maxX,o.pageBounds.minY)],length:o.pageBounds.minY-r.pageBounds.maxY,breadthIntersection:Gr(r.pageBounds.minX,r.pageBounds.maxX,o.pageBounds.minX,o.pageBounds.maxX)})}return{horizontal:e,vertical:n}}snapTranslateShapes({lockedAxis:e,initialSelectionPageBounds:n,initialSelectionSnapPoints:r,dragDelta:o}){var v,y;const s=this.manager.getSnapThreshold(),i=this.getSnappablePoints(),a=n.clone().translate(o),l=r.map(({x:S,y:b},P)=>({id:"selection:"+P,x:S+o.x,y:b+o.y})),c=i,u=[],h=[],p=new x(s,s);this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const f=new x(e==="x"?0:((v=u[0])==null?void 0:v.nudge)??0,e==="y"?0:((y=h[0])==null?void 0:y.nudge)??0);p.x=0,p.y=0,u.length=0,h.length=0,l.forEach(S=>{S.x+=f.x,S.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const g=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:h}),m=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h});return this.manager.setIndicators([...m,...g]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:e,dragDelta:n,handle:r,isAspectRatioLocked:o,isResizingFromCenter:s}){var E,k;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=Z.Resize(e,r,s?n.x*2:n.x,s?n.y*2:n.y,o);let u=r;l<0&&(u=Fq(u)),c<0&&(u=$q(u)),s&&(a.center=e.center);const h=u==="top"||u==="bottom",p=u==="left"||u==="right",f=RI(u,a),g=this.getSnappablePoints(),m=[],v=[],y=new x(i,i);this.collectPointSnaps({minOffset:y,nearestSnapsX:m,nearestSnapsY:v,otherNodeSnapPoints:g,selectionSnapPoints:f});const S=new x(h?0:((E=m[0])==null?void 0:E.nudge)??0,p?0:((k=v[0])==null?void 0:k.nudge)??0);if(o&&Nq(u)&&S.len()!==0){const D=m.length&&v.length?Math.abs(S.x)<Math.abs(S.y)?"x":"y":m.length?"x":"y",T=e.aspectRatio;D==="x"?(v.length=0,S.y=S.x/T,(u==="bottom_left"||u==="top_right")&&(S.y=-S.y)):(m.length=0,S.x=S.y*T,(u==="bottom_left"||u==="top_right")&&(S.x=-S.x))}const b=x.Add(n,S),{box:P}=Z.Resize(e,r,s?b.x*2:b.x,s?b.y*2:b.y,o);s&&(P.center=e.center);const C=RI("any",P);m.length=0,v.length=0,y.x=0,y.y=0,this.collectPointSnaps({minOffset:y,nearestSnapsX:m,nearestSnapsY:v,otherNodeSnapPoints:g,selectionSnapPoints:C});const _=this.getPointSnapLines({nearestSnapsX:m,nearestSnapsY:v});return this.manager.setIndicators([..._]),{nudge:S}}collectPointSnaps({selectionSnapPoints:e,otherNodeSnapPoints:n,minOffset:r,nearestSnapsX:o,nearestSnapsY:s}){for(const i of e)for(const a of n){const l=x.Sub(i,a),c=Math.abs(l.x),u=Math.abs(l.y);pe(c)<=pe(r.x)&&(pe(c)<pe(r.x)&&(o.length=0),o.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.x-i.x}),r.x=c),pe(u)<=pe(r.y)&&(pe(u)<pe(r.y)&&(s.length=0),s.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.y-i.y}),r.y=u)}}collectGapSnaps({selectionPageBounds:e,minOffset:n,nearestSnapsX:r,nearestSnapsY:o}){const{horizontal:s,vertical:i}=this.getVisibleGaps();for(const a of s){if(!Mc(a.breadthIntersection[0],a.breadthIntersection[1],e.minY,e.maxY))continue;const c=a.startEdge[0].x+a.length/2-e.center.x;if(a.length>e.width&&pe(Math.abs(c))<=pe(n.x)){pe(Math.abs(c))<pe(n.x)&&(r.length=0),n.x=Math.abs(c);const y={type:"gap_center",gap:a,nudge:c},S=r.find(({type:P})=>P==="gap_center"),b=S&&Gr(a.breadthIntersection[0],a.breadthIntersection[1],S.gap.breadthIntersection[0],S.gap.breadthIntersection[1]);S&&S.gap.length>a.length&&b?r[r.indexOf(S)]=y:(!S||!b)&&r.push(y)}const h=a.startNode.pageBounds.minX-a.length,p=e.maxX,f=h-p;pe(Math.abs(f))<=pe(n.x)&&(pe(Math.abs(f))<pe(n.x)&&(r.length=0),n.x=Math.abs(f),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"left",nudge:f}));const g=a.endNode.pageBounds.maxX+a.length,m=e.minX,v=g-m;pe(Math.abs(v))<=pe(n.x)&&(pe(Math.abs(v))<pe(n.x)&&(r.length=0),n.x=Math.abs(v),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"right",nudge:v}))}for(const a of i){if(!Mc(a.breadthIntersection[0],a.breadthIntersection[1],e.minX,e.maxX))continue;const c=a.startEdge[0].y+a.length/2-e.center.y;if(a.length>e.height&&pe(Math.abs(c))<=pe(n.y)){pe(Math.abs(c))<pe(n.y)&&(o.length=0),n.y=Math.abs(c);const y={type:"gap_center",gap:a,nudge:c},S=o.find(({type:P})=>P==="gap_center"),b=S&&Mc(S.gap.breadthIntersection[0],S.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);S&&S.gap.length>a.length&&b?o[o.indexOf(S)]=y:(!S||!b)&&o.push(y);continue}const h=a.startNode.pageBounds.minY-a.length,p=e.maxY,f=h-p;pe(Math.abs(f))<=pe(n.y)&&(pe(Math.abs(f))<pe(n.y)&&(o.length=0),n.y=Math.abs(f),o.push({type:"gap_duplicate",gap:a,protrusionDirection:"top",nudge:f}));const g=a.endNode.pageBounds.maxY+a.length,m=e.minY,v=g-m;pe(Math.abs(v))<=pe(n.y)&&(pe(Math.abs(v))<pe(n.y)&&(o.length=0),n.y=Math.abs(v),o.push({type:"gap_duplicate",gap:a,protrusionDirection:"bottom",nudge:v}))}}getPointSnapLines({nearestSnapsX:e,nearestSnapsY:n}){const r={},o={};if(e.length>0){for(const s of e)if(s.type==="points"){const i=pe(s.points.otherPoint.x);r[i]||(r[i]=[]),r[i].push(s.points)}}if(n.length>0){for(const s of n)if(s.type==="points"){const i=pe(s.points.otherPoint.y);o[i]||(o[i]=[]),o[i].push(s.points)}}return Object.values(r).concat(Object.values(o)).map(s=>({id:ze(),type:"points",points:Sw(s.map(i=>x.From(i.otherPoint)).concat(s.map(i=>x.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:e,nearestSnapsX:n,nearestSnapsY:r}){const{vertical:o,horizontal:s}=this.getVisibleGaps(),i={top:e.sides[0],right:e.sides[1],bottom:[e.corners[3],e.corners[2]],left:[e.corners[0],e.corners[3]]},a=[];if(n.length>0)for(const l of n){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.width)/2,v=Gr(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:ze(),gaps:[...ns(s,h.id,m,"backward",v),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:g},...ns(s,p.id,m,"forward",v)]});break}case"gap_duplicate":{const m=Gr(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:ze(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(v=>v.clone().addXY(-h.pageBounds.width,0))},{startEdge:u,endEdge:g},...ns(s,p.id,f,"forward",m)]:[...ns(s,h.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(v=>v.clone().addXY(l.gap.endNode.pageBounds.width,0)),endEdge:i.left}]});break}}}if(r.length>0)for(const l of r){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.height)/2,v=Gr(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:ze(),gaps:[...ns(o,h.id,m,"backward",v),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:g},...ns(o,l.gap.endNode.id,m,"forward",v)]});break}case"gap_duplicate":{const m=Gr(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:ze(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(v=>v.clone().addXY(0,-h.pageBounds.height))},{startEdge:u,endEdge:g},...ns(o,p.id,f,"forward",m)]:[...ns(o,h.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(v=>v.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return TJ(a),a}}_a=CJ();Gg(_a,1,"getSnapPointsCache",DO,rc);Gg(_a,1,"getSnappablePoints",OO,rc);Gg(_a,1,"getSnappableGapNodes",jO,rc);Gg(_a,1,"getVisibleGaps",AO,rc);IJ(_a,rc);function RI(t,e){const{minX:n,maxX:r,minY:o,maxY:s}=e,i=[];switch(t){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:n,y:o})}switch(t){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:o})}switch(t){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:s})}switch(t){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:n,y:s})}return i}var MJ=Object.create,RO=Object.defineProperty,AJ=Object.getOwnPropertyDescriptor,jJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),LO=t=>{throw TypeError(t)},$O=(t,e,n)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OJ=t=>[,,,MJ(null)],FO=["class","method","getter","setter","accessor","field","value","get","set"],NO=t=>t!==void 0&&typeof t!="function"?LO("Function expected"):t,DJ=(t,e,n,r,o)=>({kind:FO[t],name:e,metadata:r,addInitializer:s=>n._?LO("Already initialized"):o.push(NO(s||null))}),RJ=(t,e)=>$O(e,jJ("metadata"),t[3]),LJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},$J=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=FO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,AJ(o,n)),y=r.length-1;y>=0;y--)l=DJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,NO(i)&&(v[g]=i);return v&&RO(o,n,v),o},FJ=(t,e,n)=>$O(t,e+"",n),zO,Vg;const NJ=()=>null,zJ=()=>[];zO=[G];class j1{constructor(e){this.manager=e,LJ(Vg,5,this),FJ(this,"editor"),this.editor=e.editor}getSnapGeometryCache(){const{editor:e}=this;return e.store.createComputedCache("handle snap geometry",n=>{const r=e.getShapeUtil(n).getHandleSnapGeometry(n),o=r.getSelfSnapOutline?r.getSelfSnapOutline.bind(r):NJ,s=r.getSelfSnapPoints?r.getSelfSnapPoints.bind(r):zJ;return{outline:r.outline===void 0?e.getShapeGeometry(n):r.outline,points:r.points??[],getSelfSnapOutline:o,getSelfSnapPoints:s}})}*iterateSnapPointsInPageSpace(e,n){var o,s;const r=(o=this.getSnapGeometryCache().get(e))==null?void 0:o.getSelfSnapPoints(n);if(r&&r.length){const i=zn(this.editor.getShapePageTransform(e));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.points;if(!a||!a.length)continue;const l=zn(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(e,n){var o,s;const r=(o=this.getSnapGeometryCache().get(e))==null?void 0:o.getSelfSnapOutline(n);r&&(yield{shapeId:e,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:e,handle:n,handleInPageSpace:r}){const o=this.manager.getSnapThreshold();let s=o,i=null;for(const c of this.iterateSnapPointsInPageSpace(e,n))x.DistMin(r,c,s)&&(s=x.Dist(r,c),i=c);if(i)return i;let a=o,l=null;for(const{shapeId:c,outline:u}of this.iterateSnapOutlines(e,n)){const h=zn(this.editor.getShapePageTransform(c)),p=this.editor.getPointInShapeSpace(c,r),f=u.nearestPoint(p),g=h.applyToPoint(f);x.DistMin(r,g,a)&&(a=x.Dist(r,g),l=g)}return l||null}snapHandle({currentShapeId:e,handle:n}){const o=zn(this.editor.getShapePageTransform(e)).applyToPoint(n),s=this.getHandleSnapPosition({currentShapeId:e,handle:n,handleInPageSpace:o});return s?(this.manager.setIndicators([{id:ze(),type:"points",points:[s]}]),{nudge:x.Sub(s,o)}):null}}Vg=OJ();$J(Vg,1,"getSnapGeometryCache",zO,j1);RJ(Vg,j1);var BJ=Object.create,BO=Object.defineProperty,UJ=Object.getOwnPropertyDescriptor,HJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),UO=t=>{throw TypeError(t)},HO=(t,e,n)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,KJ=t=>[,,,BJ(null)],KO=["class","method","getter","setter","accessor","field","value","get","set"],WO=t=>t!==void 0&&typeof t!="function"?UO("Function expected"):t,WJ=(t,e,n,r,o)=>({kind:KO[t],name:e,metadata:r,addInitializer:s=>n._?UO("Already initialized"):o.push(WO(s||null))}),GJ=(t,e)=>HO(e,HJ("metadata"),t[3]),VJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},O1=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=KO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,UJ(o,n)),y=r.length-1;y>=0;y--)l=WJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,WO(i)&&(v[g]=i);return v&&BO(o,n,v),o},Jy=(t,e,n)=>HO(t,typeof e!="symbol"?e+"":e,n),GO,VO,YO,oc;YO=[G],VO=[G],GO=[G];class Sd{constructor(e){this.editor=e,VJ(oc,5,this),Jy(this,"shapeBounds"),Jy(this,"handles"),Jy(this,"_snapIndicators",Et("snapLines",void 0)),this.shapeBounds=new rc(this),this.handles=new j1(this)}getIndicators(){return this._snapIndicators.get()??ps}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(e){this._snapIndicators.set(e)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:e}=this,n=e.getViewportPageBounds(),r=e.getSelectedShapeIds(),o=new Set,s=i=>{if(Fn(i)){const l=e.getShape(i);l&&e.isShapeOfType(l,"frame")&&o.add(i)}const a=e.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=e.getShape(l);if(!c||!e.getShapeUtil(c).canSnap(c))continue;const h=e.getShapePageBounds(l);if(h&&n.includes(h)){if(e.isShapeOfType(c,"group")){s(l);continue}o.add(l)}}};return s(this.getCurrentCommonAncestor()??e.getCurrentPageId()),o}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}}oc=KJ();O1(oc,1,"getSnapThreshold",YO,Sd);O1(oc,1,"getSnappableShapes",VO,Sd);O1(oc,1,"getCurrentCommonAncestor",GO,Sd);GJ(oc,Sd);const YJ=/\r?\n|\r/g;function LI(t){return t.replace(YJ,`
101
+ ${o}`,t.prepend(s)}}finally{n.dispose()}}const Vr={menus:Et("open menus",[]),getOpenMenus(t){return t?this.menus.get().filter(e=>e.endsWith("-"+t)):this.menus.get()},addOpenMenu(t,e=""){const n=e?`${t}-${e}`:t,r=new Set(this.menus.get());r.has(n)||(r.add(n),this.menus.set([...r]))},deleteOpenMenu(t,e=""){const n=e?`${t}-${e}`:t,r=new Set(this.menus.get());r.has(n)&&(r.delete(n),this.menus.set([...r]))},clearOpenMenus(t){this.menus.set(t?this.menus.get().filter(e=>!e.endsWith("-"+t)):[])},_hiddenMenus:[],hideOpenMenus(t){if(this._hiddenMenus=[...this.getOpenMenus(t)],this._hiddenMenus.length!==0)for(const e of this._hiddenMenus)this.deleteOpenMenu(e,t)},showOpenMenus(t){if(this._hiddenMenus.length!==0){for(const e of this._hiddenMenus)this.addOpenMenu(e,t);this._hiddenMenus=[]}},isMenuOpen(t,e){return this.getOpenMenus(e).includes(t)},hasOpenMenus(t){return this.getOpenMenus(t).length>0},hasAnyOpenMenus(){return this.getOpenMenus().length>0},forContext(t){return{getOpenMenus:()=>this.getOpenMenus(t),addOpenMenu:e=>this.addOpenMenu(e,t),deleteOpenMenu:e=>this.deleteOpenMenu(e,t),clearOpenMenus:()=>this.clearOpenMenus(t),isMenuOpen:e=>this.isMenuOpen(e,t),hasOpenMenus:()=>this.hasOpenMenus(t),hasAnyOpenMenus:()=>this.hasAnyOpenMenus()}}},kx=new hB,HQ={maxShapesPerPage:4e3,maxFilesAtOnce:100,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,laserDelayMs:1200,maxExportDelayMs:5e3,temporaryAssetPreviewLifetimeMs:18e4,actionShortcutsLocation:"swap",createTextOnCanvasDoubleClick:!0,exportProvider:w.Fragment};function OI(t,e){if(!e)return!1;switch(t.type){case"mixed":return e.type==="mixed";case"shared":return e.type==="shared"&&t.value===e.value;default:throw Ot(t)}}class KQ{constructor(e){I(this,"map");this.map=new Map(e)}get(e){return this.map.get(e)}getAsKnownValue(e){const n=this.get(e);if(n&&n.type!=="mixed")return n.value}get size(){return this.map.size}equals(e){if(this.size!==e.size)return!1;const n=new Set;for(const[r,o]of this){if(!OI(o,e.get(r)))return!1;n.add(r)}for(const[r,o]of e)if(!n.has(r)&&!OI(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 Tx extends KQ{set(e,n){this.map.set(e,n)}applyValue(e,n){const r=this.get(e);if(!r){this.set(e,{type:"shared",value:n});return}switch(r.type){case"mixed":return;case"shared":r.value!==n&&this.set(e,{type:"mixed"});return;default:Ot(r,"type")}}}function WQ(t,e,n){return Lo(t).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],e,{type:n})})}const GQ="https://cdn.tldraw.com";function ei(){return`${GQ}/${oj}`}function VQ(t){switch(t.type){case"shapes":return`s${t.shapeIds.map(n=>Zy(n.slice(6))).join(".")}`;case"page":return"p"+Zy(yr.parseId(t.pageId));case"viewport":{const{bounds:e,pageId:n}=t;let r=`v${Math.round(e.x)}.${Math.round(e.y)}.${Math.round(e.w)}.${Math.round(e.h)}`;return n&&(r+="."+Zy(yr.parseId(n))),r}default:Ot(t)}}function YQ(t){switch(t[0]){case"s":return{type:"shapes",shapeIds:t.slice(1).split(".").filter(Boolean).map(r=>Ke(decodeURIComponent(r)))};case"p":return{type:"page",pageId:yr.createId(decodeURIComponent(t.slice(1)))};case"v":{const[n,r,o,s,i]=t.slice(1).split(".");return{type:"viewport",bounds:new Z(Number(n),Number(r),Number(o),Number(s)),pageId:i?yr.createId(decodeURIComponent(i)):void 0}}default:throw Error("Invalid deep link string")}}function Zy(t){return encodeURIComponent(t).replace(/\./g,"%2E")}function XQ(t,e){var o;let n=t;const r=new Set(e);for(;r.has(n);)n=(o=/^.*(\d+)$/.exec(n))!=null&&o[1]?n.replace(/(\d+)(?=\D?)$/,s=>(+s+1).toString()):`${n} 1`;return n}function Sh(t,e,n,r){if(n.length===0)return[];const o=new Map;for(const i of me(n.map(a=>t.getShape(a)))){const{parentId:a}=i;o.has(a)||o.set(a,{children:me(t.getSortedChildIdsForParent(a).map(l=>t.getShape(l))),moving:new Set}),o.get(a).moving.add(i)}const s=[];switch(e){case"toBack":{o.forEach(({moving:i,children:a})=>qQ(i,a,s));break}case"toFront":{o.forEach(({moving:i,children:a})=>ZQ(i,a,s));break}case"forward":{o.forEach(({moving:i,children:a})=>QQ(t,i,a,s,r));break}case"backward":{o.forEach(({moving:i,children:a})=>JQ(t,i,a,s,r));break}}return s}function qQ(t,e,n){const r=e.length;if(t.size===r)return;let o,s;for(let i=0;i<r;i++){const a=e[i];if(t.has(a))o=a.index,t.delete(a);else{s=a.index;break}}if(t.size!==0){const i=Dl(o,s,t.size);n.push(...Array.from(t.values()).sort(cn).map((a,l)=>({...a,index:i[l]})))}}function ZQ(t,e,n){const r=e.length;if(t.size===r)return;let o,s;for(let i=r-1;i>-1;i--){const a=e[i];if(t.has(a))s=a.index,t.delete(a);else{o=a.index;break}}if(t.size!==0){const i=Dl(o,s,t.size);n.push(...Array.from(t.values()).sort(cn).map((a,l)=>({...a,index:i[l]})))}}function DI(t,e){const n=t.getShapeGeometry(e),r=t.getShapePageTransform(e);return!n||!r?null:r.applyToPoints(n.vertices)}function mO(t,e){const n=Array.from(e).map(o=>{const s=DI(t,o);return s?{shape:o,vertices:s}:null}).filter(Boolean);return o=>{const s=DI(t,o);return s?n.some(i=>_1(i.vertices,s)):!1}}function QQ(t,e,n,r,o){var l;const s=mO(t,e),i=n.length;if(e.size===i)return;let a={name:"skipping"};for(let c=0;c<i;c++){const u=e.has(n[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(o!=null&&o.considerAllShapes)&&!s(n[c]))continue;const{selectIndex:h}=a;Dl(n[c].index,(l=n[c+1])==null?void 0:l.index,c-h).forEach((p,f)=>{const g=n[h+f];e.has(g)&&r.push({...g,index:p})}),a={name:"skipping"};break}}}}function JQ(t,e,n,r,o){var l;const s=mO(t,e),i=n.length;if(e.size===i)return;let a={name:"skipping"};for(let c=i-1;c>-1;c--){const u=e.has(n[c]);switch(a.name){case"skipping":{if(!u)continue;a={name:"selecting",selectIndex:c};break}case"selecting":{if(u||!(o!=null&&o.considerAllShapes)&&!s(n[c]))continue;Dl((l=n[c-1])==null?void 0:l.index,n[c].index,a.selectIndex-c).forEach((h,p)=>{const f=n[c+p+1];e.has(f)&&r.push({...f,index:h})}),a={name:"skipping"};break}}}}function yO({editor:t,ids:e}){const n=me(e.map(i=>t.getShape(i))),r=t.getShapesSharedRotation(e),o=t.getShapesRotatedPageBounds(e);if(!o)return null;const s=o.center.clone().rotWith(o.point,r);return{pageCenter:s,initialCursorAngle:s.angle(t.inputs.originPagePoint),initialShapesRotation:r,shapeSnapshots:n.map(i=>({shape:i,initialPagePoint:t.getShapePageTransform(i.id).point()}))}}function up({delta:t,editor:e,snapshot:n,stage:r,centerOverride:o}){const{pageCenter:s,shapeSnapshots:i}=n;e.updateShapes(i.map(({shape:l,initialPagePoint:c})=>{const u=Fn(l.parentId)?e.getShapePageTransform(l.parentId):q.Identity(),h=x.RotWith(c,o??s,t),p=q.applyToPoint(q.Inverse(u),h),f=Ji(l.rotation+t);return{id:l.id,type:l.type,x:p.x,y:p.y,rotation:f}}));const a=[];i.forEach(({shape:l})=>{var p,f,g;const c=e.getShape(l.id);if(!c)return;const u=e.getShapeUtil(l);if(r==="start"||r==="one-off"){const m=(p=u.onRotateStart)==null?void 0:p.call(u,l);m&&a.push(m)}const h=(f=u.onRotate)==null?void 0:f.call(u,l,c);if(h&&a.push(h),r==="end"||r==="one-off"){const m=(g=u.onRotateEnd)==null?void 0:g.call(u,l,c);m&&a.push(m)}}),a.length>0&&e.updateShapes(a)}const eJ=t=>{const{store:e}=t,n=e.query.filterHistory("binding"),r=e.query.records("binding");function o(){const s=r.get(),i=new Map;for(const a of s){const{fromId:l,toId:c}=a,u=i.get(l);u?u.push(a):i.set(l,[a]);const h=i.get(c);h?h.push(a):i.set(c,[a])}return i}return G("arrowBindingsIndex",(s,i)=>{if(Zi(s))return o();const a=s,l=n.getDiffSince(i);if(l===ur)return o();let c;function u(f){c??(c=new Map(a));const g=c.get(f.fromId),m=g==null?void 0:g.filter(S=>S.id!==f.id);m!=null&&m.length?c.set(f.fromId,m):c.delete(f.fromId);const v=c.get(f.toId),y=v==null?void 0:v.filter(S=>S.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 g=c.get(f);return g?g===a.get(f)&&(g=g.slice(0),c.set(f,g)):(g=[],c.set(f,g)),g}function p(f){h(f.fromId).push(f),h(f.toId).push(f)}for(const f of l){for(const g of ut(f.added))p(g);for(const[g,m]of ut(f.updated))u(g),p(m);for(const g of ut(f.removed))u(g)}return c??a})};function tJ(t,e,n){const r=t.getShapeMaskedPageBounds(e);return r===void 0?!0:!n.includes(r)}const nJ=t=>{function e(n){const r=n.getCurrentPageShapeIds(),o=n.getViewportPageBounds(),s=new Set;return r.forEach(i=>{tJ(n,i,o)&&s.add(i)}),s}return G("getCulledShapes",n=>{if(Zi(n))return e(t);const r=e(t);if(n.size!==r.size)return r;for(const o of n)if(!r.has(o))return r;return n})},rJ=t=>{const e=t.query.ids("shape"),n=t.query.filterHistory("shape");function r(){const o={},s=e.get(),i=Array(s.size);return s.forEach(a=>i.push(t.get(a))),i.sort(cn),i.forEach(a=>{o[a.parentId]||(o[a.parentId]=[]),o[a.parentId].push(a.id)}),o}return G("parentsToChildrenWithIndexes",(o,s)=>{if(Zi(o))return r();const i=n.getDiffSince(s);if(i===ur)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 u;for(let h=0,p=i.length;h<p;h++){u=i[h];for(const f of Object.values(u.added))al(f)&&(l(f.parentId),a[f.parentId].push(f.id),c.add(a[f.parentId]));for(const[f,g]of Object.values(u.updated))if(al(g)&&al(f)){if(f.parentId!==g.parentId)l(f.parentId),l(g.parentId),a[f.parentId].splice(a[f.parentId].indexOf(g.id),1),a[g.parentId].push(g.id),c.add(a[g.parentId]);else if(f.index!==g.index){l(g.parentId);const m=a[g.parentId].indexOf(g.id);a[g.parentId][m]=g.id,c.add(a[g.parentId])}}for(const f of Object.values(u.removed))al(f)&&(l(f.parentId),a[f.parentId].splice(a[f.parentId].indexOf(f.id),1))}for(const h of c){const p=me(h.map(f=>t.get(f)));p.sort(cn),h.splice(0,h.length,...p.map(f=>f.id))}return a??o})},Qy=(t,e,n)=>{for(;!Rn(n.parentId);){const r=t.get(n.parentId);if(!r)return!1;n=r}return n.parentId===e},oJ=(t,e)=>{const n=t.query.ids("shape");let r=null;function o(){const s=e();return r=s,new Set([...n.get()].filter(i=>Qy(t,s,t.get(i))))}return G("_shapeIdsInCurrentPage",(s,i)=>{if(Zi(s))return o();const a=e();if(a!==r)return o();const l=t.history.getDiffSince(i);if(l===ur)return o();const c=new sp(s);for(const h of l){for(const p of Object.values(h.added))al(p)&&Qy(t,a,p)&&c.add(p.id);for(const[p,f]of Object.values(h.updated))al(f)&&(Qy(t,a,f)?c.add(f.id):c.remove(f.id));for(const p of Object.keys(h.removed))Fn(p)&&c.remove(p)}const u=c.get();return u?Wc(u.value,u.diff):s})};var sJ=Object.create,SO=Object.defineProperty,iJ=Object.getOwnPropertyDescriptor,aJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),vO=t=>{throw TypeError(t)},xO=(t,e,n)=>e in t?SO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lJ=t=>[,,,sJ(null)],wO=["class","method","getter","setter","accessor","field","value","get","set"],bO=t=>t!==void 0&&typeof t!="function"?vO("Function expected"):t,cJ=(t,e,n,r,o)=>({kind:wO[t],name:e,metadata:r,addInitializer:s=>n._?vO("Already initialized"):o.push(bO(s||null))}),uJ=(t,e)=>xO(e,aJ("metadata"),t[3]),dJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},PO=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=wO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,iJ(o,n)),y=r.length-1;y>=0;y--)l=cJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,bO(i)&&(v[g]=i);return v&&SO(o,n,v),o},La=(t,e,n)=>xO(t,typeof e!="symbol"?e+"":e,n),CO,_O,yd;const hJ=40;_O=[Kn],CO=[Kn];class Wg{constructor(e){this.editor=e,dJ(yd,5,this),La(this,"_clickId",""),La(this,"_clickTimeout"),La(this,"_clickScreenPoint"),La(this,"_previousScreenPoint"),La(this,"_clickState","idle"),La(this,"lastPointerInfo",{})}_getClickTimeout(e,n=ze()){this._clickId=n,clearTimeout(this._clickTimeout),this._clickTimeout=this.editor.timers.setTimeout(()=>{if(this._clickState===e&&this._clickId===n){switch(this._clickState){case"pendingTriple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"double_click",phase:"settle"});break}case"pendingQuadruple":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"triple_click",phase:"settle"});break}case"pendingOverflow":{this.editor.dispatch({...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"settle"});break}}this._clickState="idle"}},e==="idle"||e==="pendingDouble"?this.editor.options.doubleClickDurationMs:this.editor.options.multiClickDurationMs)}get clickState(){return this._clickState}handlePointerEvent(e){switch(e.name){case"pointer_down":{if(!this._clickState)return e;switch(this._clickScreenPoint=x.From(e.point),this._previousScreenPoint&&x.Dist2(this._previousScreenPoint,this._clickScreenPoint)>hJ**2&&(this._clickState="idle"),this._previousScreenPoint=this._clickScreenPoint,this.lastPointerInfo=e,this._clickState){case"pendingDouble":return this._clickState="pendingTriple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"double_click",phase:"down"};case"pendingTriple":return this._clickState="pendingQuadruple",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"triple_click",phase:"down"};case"pendingQuadruple":return this._clickState="pendingOverflow",this._clickTimeout=this._getClickTimeout(this._clickState),{...e,type:"click",name:"quadruple_click",phase:"down"};case"idle":{this._clickState="pendingDouble";break}case"pendingOverflow":{this._clickState="overflow";break}}return this._clickTimeout=this._getClickTimeout(this._clickState),e}case"pointer_up":{if(!this._clickState)return e;switch(this._clickScreenPoint=x.From(e.point),this._clickState){case"pendingTriple":return{...this.lastPointerInfo,type:"click",name:"double_click",phase:"up"};case"pendingQuadruple":return{...this.lastPointerInfo,type:"click",name:"triple_click",phase:"up"};case"pendingOverflow":return{...this.lastPointerInfo,type:"click",name:"quadruple_click",phase:"up"}}return e}case"pointer_move":return this._clickState!=="idle"&&this._clickScreenPoint&&x.Dist2(this._clickScreenPoint,this.editor.inputs.currentScreenPoint)>(this.editor.getInstanceState().isCoarsePointer?this.editor.options.coarseDragDistanceSquared:this.editor.options.dragDistanceSquared)&&this.cancelDoubleClickTimeout(),e}return e}cancelDoubleClickTimeout(){this._clickTimeout=clearTimeout(this._clickTimeout),this._clickState="idle"}}yd=lJ();PO(yd,1,"_getClickTimeout",_O,Wg);PO(yd,1,"cancelDoubleClickTimeout",CO,Wg);uJ(yd,Wg);class pJ{constructor(e){I(this,"_isEdgeScrolling",!1);I(this,"_edgeScrollDuration",-1);this.editor=e}updateEdgeScrolling(e){const{editor:n}=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+=e,this._edgeScrollDuration>n.options.edgeScrollDelay){const o=n.options.edgeScrollEaseDuration>0?Dt.easeInCubic(Math.min(1,this._edgeScrollDuration/(n.options.edgeScrollDelay+n.options.edgeScrollEaseDuration))):1;this.moveCameraWhenCloseToEdge({x:r.x*o,y:r.y*o})}}getEdgeProximityFactors(e,n,r,o,s){const{editor:i}=this,a=i.options.edgeScrollDistance,l=r?i.options.coarsePointerWidth:0,c=e-l,u=e+l,h=o?0:a,p=s?n:n-a;return c<h?Math.min(1,(h-c)/a):u>p?-Math.min(1,(u-p)/a):0}getEdgeScroll(){const{editor:e}=this,{inputs:{currentScreenPoint:{x:n,y:r}}}=e,o=e.getViewportScreenBounds(),{isCoarsePointer:s,insets:[i,a,l,c]}=e.getInstanceState(),u=this.getEdgeProximityFactors(n,o.w,s,c,a),h=this.getEdgeProximityFactors(r,o.h,s,i,l);return{x:u,y:h}}moveCameraWhenCloseToEdge(e){const{editor:n}=this;if(!n.inputs.isDragging||n.inputs.isPanning||n.getCameraOptions().isLocked||e.x===0&&e.y===0)return;const r=n.getViewportScreenBounds(),o=r.w<1e3?.612:1,s=r.h<1e3?.612:1,i=n.getZoomLevel(),a=n.user.getEdgeScrollSpeed()*n.options.edgeScrollSpeed,l=a*e.x*o/i,c=a*e.y*s/i,{x:u,y:h,z:p}=n.getCamera();n.setCamera(new x(u+l,h+c,p))}}class fJ{constructor(e,n){I(this,"disposeSideEffectListener");this.editor=e,this.disposeSideEffectListener=e.sideEffects.registerAfterChangeHandler("instance",(o,s)=>{o.isFocused!==s.isFocused&&this.updateContainerClass()});const r=e.getInstanceState().isFocused;n!==r&&e.updateInstanceState({isFocused:!!n}),this.updateContainerClass()}updateContainerClass(){const e=this.editor.getContainer();this.editor.getInstanceState().isFocused?e.classList.add("tl-container__focused"):e.classList.remove("tl-container__focused")}focus(){this.editor.getContainer().focus()}blur(){this.editor.complete(),this.editor.getContainer().blur()}dispose(){var e;(e=this.disposeSideEffectListener)==null||e.call(this)}}function Ac(t){return mJ}class gJ{constructor(){I(this,"length",0);I(this,"head",null);I(this,"tail",this)}push(e){return new A1(e,this)}toArray(){return ps}[Symbol.iterator](){return{next(){return{value:void 0,done:!0}}}}}const mJ=new gJ;class A1{constructor(e,n){I(this,"length");this.head=e,this.tail=n,this.length=n.length+1}push(e){return new A1(e,this)}toArray(){return Array.from(this)}[Symbol.iterator](){let e=this;return{next(){if(e.length){const n=e.head;return e=e.tail,{value:n,done:!1}}else return{value:void 0,done:!0}}}}}class yJ{constructor(e){I(this,"store");I(this,"dispose");I(this,"state","recording");I(this,"pendingDiff",new vJ);I(this,"stacks",Et("HistoryManager.stacks",{undos:Ac(),redos:Ac()},{isEqual:(e,n)=>e.undos===n.undos&&e.redos===n.redos}));I(this,"annotateError");I(this,"_isInBatch",!1);this.store=e.store,this.annotateError=e.annotateError??Ru,this.dispose=this.store.addHistoryInterceptor((n,r)=>{if(r==="user")switch(this.state){case"recording":this.pendingDiff.apply(n.changes),this.stacks.update(({undos:o})=>({undos:o,redos:Ac()}));break;case"recordingPreserveRedoStack":this.pendingDiff.apply(n.changes);break;case"paused":break;default:Ot(this.state)}})}flushPendingDiff(){if(this.pendingDiff.isEmpty())return;const e=this.pendingDiff.clear();this.stacks.update(({undos:n,redos:r})=>({undos:n.push({type:"diff",diff:e}),redos:r}))}getNumUndos(){return this.stacks.get().undos.length+(this.pendingDiff.isEmpty()?0:1)}getNumRedos(){return this.stacks.get().redos.length}batch(e,n){const r=this.state;r!=="paused"&&(n!=null&&n.history)&&(this.state=SJ[n.history]);try{if(this._isInBatch)return Oo(e),this;this._isInBatch=!0;try{Oo(e)}catch(o){throw this.annotateError(o),o}finally{this._isInBatch=!1}return this}finally{this.state=r}}_undo({pushToRedoStack:e,toMark:n=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=fA(a),c=fx(a);e&&!l&&(i=i.push({type:"diff",diff:a}));let u=!1;if(l)for(;((o=s.head)==null?void 0:o.type)==="stop";){const h=s.head;if(s=s.tail,e&&(i=i.push(h)),h.id===n){u=!0;break}}if(!u)e:for(;s.head;){const h=s.head;switch(s=s.tail,e&&(i=i.push(h)),h.type){case"diff":cu(c,[fx(h.diff)]);break;case"stop":if(!n)break e;if(h.id===n){u=!0;break e}break;default:Ot(h)}}if(!u&&n)return this;this.store.applyDiff(c,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:s,redos:i})}finally{this.state=r}return this}undo(){return this._undo({pushToRedoStack:!0}),this}redo(){var n;const e=this.state;this.state="paused";try{this.flushPendingDiff();let{undos:r,redos:o}=this.stacks.get();if(o.length===0)return this;for(;((n=o.head)==null?void 0:n.type)==="stop";)r=r.push(o.head),o=o.tail;const s=wf();for(;o.head;){const i=o.head;if(r=r.push(i),o=o.tail,i.type==="diff")cu(s,[i.diff]);else break}this.store.applyDiff(s,{ignoreEphemeralKeys:!0}),this.store.ensureStoreIsUsable(),this.stacks.set({undos:r,redos:o})}finally{this.state=e}return this}bail(){return this._undo({pushToRedoStack:!1}),this}bailToMark(e){return this._undo({pushToRedoStack:!1,toMark:e}),this}squashToMark(e){var s;let n=this.stacks.get().undos;const r=[];for(;n.head&&!(n.head.type==="stop"&&n.head.id===e);)n.head.type==="diff"&&r.push(n.head.diff),n=n.tail;if(!n.head||((s=n.head)==null?void 0:s.id)!==e)return console.error("Could not find mark to squash to: ",e),this;if(r.length===0)return this;const o=wf();return cu(o,r.reverse()),this.stacks.update(({redos:i})=>({undos:n.push({type:"diff",diff:o}),redos:i})),this}_mark(e){Oo(()=>{this.flushPendingDiff(),this.stacks.update(({undos:n,redos:r})=>({undos:n.push({type:"stop",id:e}),redos:r}))})}clear(){this.stacks.set({undos:Ac(),redos:Ac()}),this.pendingDiff.clear()}getMarkIdMatching(e){let n=this.stacks.get().undos;for(;n.head;){if(n.head.type==="stop"&&n.head.id.includes(e))return n.head.id;n=n.tail}return null}debug(){const{undos:e,redos:n}=this.stacks.get();return{undos:e.toArray(),redos:n.toArray(),pendingDiff:this.pendingDiff.debug(),state:this.state}}}const SJ={record:"recording","record-preserveRedoStack":"recordingPreserveRedoStack",ignore:"paused"};class vJ{constructor(){I(this,"diff",wf());I(this,"isEmptyAtom",Et("PendingDiff.isEmpty",!0))}clear(){const e=this.diff;return this.diff=wf(),this.isEmptyAtom.set(!0),e}isEmpty(){return this.isEmptyAtom.get()}apply(e){cu(this.diff,[e]),this.isEmptyAtom.set(fA(this.diff))}debug(){return{diff:this.diff,isEmpty:this.isEmpty()}}}class xJ{constructor(e){I(this,"scribbleItems",new Map);I(this,"state","paused");this.editor=e}addScribble(e,n=ze()){const r={id:n,scribble:{id:n,size:20,color:"accent",opacity:.8,delay:0,points:[],shrink:.1,taper:!0,...e,state:"starting"},timeoutMs:0,delayRemaining:e.delay??0,prev:null,next:null};return this.scribbleItems.set(n,r),r}reset(){this.editor.updateInstanceState({scribbles:[]}),this.scribbleItems.clear()}stop(e){const n=this.scribbleItems.get(e);if(!n)throw Error(`Scribble with id ${e} not found`);return n.delayRemaining=Math.min(n.delayRemaining,200),n.scribble.state="stopping",n}addPoint(e,n,r,o=.5){const s=this.scribbleItems.get(e);if(!s)throw Error(`Scribble with id ${e} not found`);const{prev:i}=s,a={x:n,y:r,z:o};return(!i||x.Dist(i,a)>=1)&&(s.next=a),s}tick(e){this.scribbleItems.size!==0&&this.editor.run(()=>{this.scribbleItems.forEach(n=>{if(n.scribble.state==="starting"){const{next:l,prev:c}=n;l&&l!==c&&(n.prev=l,n.scribble.points.push(l)),n.scribble.points.length>8&&(n.scribble.state="active");return}n.delayRemaining>0&&(n.delayRemaining=Math.max(0,n.delayRemaining-e)),n.timeoutMs+=e,n.timeoutMs>=16&&(n.timeoutMs=0);const{delayRemaining:r,timeoutMs:o,prev:s,next:i,scribble:a}=n;switch(a.state){case"active":{i&&i!==s?(n.prev=i,a.points.push(i),r===0&&a.points.length>8&&a.points.shift()):o===0&&(a.points.length>1?a.points.shift():n.delayRemaining=a.delay);break}case"stopping":{if(n.delayRemaining===0&&o===0){if(a.points.length===1){this.scribbleItems.delete(n.id);return}a.shrink&&(a.size=Math.max(1,a.size*(1-a.shrink))),a.points.shift()}break}}}),this.editor.updateInstanceState({scribbles:Array.from(this.scribbleItems.values()).map(({scribble:n})=>({...n,points:[...n.points]})).slice(-5)})})}}var wJ=Object.create,IO=Object.defineProperty,bJ=Object.getOwnPropertyDescriptor,PJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),EO=t=>{throw TypeError(t)},kO=(t,e,n)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,CJ=t=>[,,,wJ(null)],TO=["class","method","getter","setter","accessor","field","value","get","set"],MO=t=>t!==void 0&&typeof t!="function"?EO("Function expected"):t,_J=(t,e,n,r,o)=>({kind:TO[t],name:e,metadata:r,addInitializer:s=>n._?EO("Already initialized"):o.push(MO(s||null))}),IJ=(t,e)=>kO(e,PJ("metadata"),t[3]),EJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Gg=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=TO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,bJ(o,n)),y=r.length-1;y>=0;y--)l=_J(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,MO(i)&&(v[g]=i);return v&&IO(o,n,v),o},kJ=(t,e,n)=>kO(t,e+"",n),AO,jO,OO,DO,_a;const pe=t=>Math.round(t*10**8)/10**8;function ns(t,e,n,r,o){const s=t.filter(a=>(r==="forward"?a.startNode.id===e:a.endNode.id===e)&&pe(a.length)===pe(n)&&Gr(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=ns(t,l,n,r,Gr(a.breadthIntersection[0],a.breadthIntersection[1],o[0],o[1]));s.push(...c)}}),s}function TJ(t){t.sort((e,n)=>n.gaps.length-e.gaps.length);for(let e=t.length-1;e>0;e--){const n=t[e];for(let r=e-1;r>=0;r--){const o=t[r];if(o.direction===n.direction&&n.gaps.every(s=>o.gaps.some(i=>pe(s.startEdge[0].x)===pe(i.startEdge[0].x)&&pe(s.startEdge[0].y)===pe(i.startEdge[0].y)&&pe(s.startEdge[1].x)===pe(i.startEdge[1].x)&&pe(s.startEdge[1].y)===pe(i.startEdge[1].y))&&o.gaps.some(i=>pe(s.endEdge[0].x)===pe(i.endEdge[0].x)&&pe(s.endEdge[0].y)===pe(i.endEdge[0].y)&&pe(s.endEdge[1].x)===pe(i.endEdge[1].x)&&pe(s.endEdge[1].y)===pe(i.endEdge[1].y)))){t.splice(e,1);break}}}}DO=[G],OO=[G],jO=[G],AO=[G];class rc{constructor(e){this.manager=e,EJ(_a,5,this),kJ(this,"editor"),this.editor=e.editor}getSnapPointsCache(){const{editor:e}=this;return e.store.createComputedCache("snapPoints",n=>{const r=e.getShapePageTransform(n.id);if(!r)return;const s=e.getShapeUtil(n).getBoundsSnapGeometry(n).points??e.getShapeGeometry(n).bounds.cornersAndCenter;if(!(!r||!s))return s.map((i,a)=>{const{x:l,y:c}=q.applyToPoint(r,i);return{x:l,y:c,id:`${n.id}:${a}`}})})}getSnapPoints(e){return this.getSnapPointsCache().get(e)??[]}getSnappablePoints(){const e=this.getSnapPointsCache(),n=this.manager.getSnappableShapes(),r=[];for(const o of n){const s=e.get(o);s&&r.push(...s)}return r}getSnappableGapNodes(){return Array.from(this.manager.getSnappableShapes(),e=>({id:e,pageBounds:zn(this.editor.getShapePageBounds(e))}))}getVisibleGaps(){const e=[],n=[];let r,o;const s=this.getSnappableGapNodes().sort((a,l)=>a.pageBounds.minX-l.pageBounds.minX);for(let a=0;a<s.length;a++){r=s[a];for(let l=a+1;l<s.length;l++)o=s[l],r.pageBounds.maxX<o.pageBounds.minX&&Mc(r.pageBounds.minY,r.pageBounds.maxY,o.pageBounds.minY,o.pageBounds.maxY)&&e.push({startNode:r,endNode:o,startEdge:[new x(r.pageBounds.maxX,r.pageBounds.minY),new x(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new x(o.pageBounds.minX,o.pageBounds.minY),new x(o.pageBounds.minX,o.pageBounds.maxY)],length:o.pageBounds.minX-r.pageBounds.maxX,breadthIntersection:Gr(r.pageBounds.minY,r.pageBounds.maxY,o.pageBounds.minY,o.pageBounds.maxY)})}const i=s.sort((a,l)=>a.pageBounds.minY-l.pageBounds.minY);for(let a=0;a<i.length;a++){r=i[a];for(let l=a+1;l<i.length;l++)o=i[l],r.pageBounds.maxY<o.pageBounds.minY&&Mc(r.pageBounds.minX,r.pageBounds.maxX,o.pageBounds.minX,o.pageBounds.maxX)&&n.push({startNode:r,endNode:o,startEdge:[new x(r.pageBounds.minX,r.pageBounds.maxY),new x(r.pageBounds.maxX,r.pageBounds.maxY)],endEdge:[new x(o.pageBounds.minX,o.pageBounds.minY),new x(o.pageBounds.maxX,o.pageBounds.minY)],length:o.pageBounds.minY-r.pageBounds.maxY,breadthIntersection:Gr(r.pageBounds.minX,r.pageBounds.maxX,o.pageBounds.minX,o.pageBounds.maxX)})}return{horizontal:e,vertical:n}}snapTranslateShapes({lockedAxis:e,initialSelectionPageBounds:n,initialSelectionSnapPoints:r,dragDelta:o}){var v,y;const s=this.manager.getSnapThreshold(),i=this.getSnappablePoints(),a=n.clone().translate(o),l=r.map(({x:S,y:b},P)=>({id:"selection:"+P,x:S+o.x,y:b+o.y})),c=i,u=[],h=[],p=new x(s,s);this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const f=new x(e==="x"?0:((v=u[0])==null?void 0:v.nudge)??0,e==="y"?0:((y=h[0])==null?void 0:y.nudge)??0);p.x=0,p.y=0,u.length=0,h.length=0,l.forEach(S=>{S.x+=f.x,S.y+=f.y}),a.translate(f),this.collectPointSnaps({minOffset:p,nearestSnapsX:u,nearestSnapsY:h,otherNodeSnapPoints:c,selectionSnapPoints:l}),this.collectGapSnaps({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h,minOffset:p});const g=this.getPointSnapLines({nearestSnapsX:u,nearestSnapsY:h}),m=this.getGapSnapLines({selectionPageBounds:a,nearestSnapsX:u,nearestSnapsY:h});return this.manager.setIndicators([...m,...g]),{nudge:f}}snapResizeShapes({initialSelectionPageBounds:e,dragDelta:n,handle:r,isAspectRatioLocked:o,isResizingFromCenter:s}){var E,k;const i=this.manager.getSnapThreshold(),{box:a,scaleX:l,scaleY:c}=Z.Resize(e,r,s?n.x*2:n.x,s?n.y*2:n.y,o);let u=r;l<0&&(u=Fq(u)),c<0&&(u=$q(u)),s&&(a.center=e.center);const h=u==="top"||u==="bottom",p=u==="left"||u==="right",f=RI(u,a),g=this.getSnappablePoints(),m=[],v=[],y=new x(i,i);this.collectPointSnaps({minOffset:y,nearestSnapsX:m,nearestSnapsY:v,otherNodeSnapPoints:g,selectionSnapPoints:f});const S=new x(h?0:((E=m[0])==null?void 0:E.nudge)??0,p?0:((k=v[0])==null?void 0:k.nudge)??0);if(o&&Nq(u)&&S.len()!==0){const D=m.length&&v.length?Math.abs(S.x)<Math.abs(S.y)?"x":"y":m.length?"x":"y",T=e.aspectRatio;D==="x"?(v.length=0,S.y=S.x/T,(u==="bottom_left"||u==="top_right")&&(S.y=-S.y)):(m.length=0,S.x=S.y*T,(u==="bottom_left"||u==="top_right")&&(S.x=-S.x))}const b=x.Add(n,S),{box:P}=Z.Resize(e,r,s?b.x*2:b.x,s?b.y*2:b.y,o);s&&(P.center=e.center);const C=RI("any",P);m.length=0,v.length=0,y.x=0,y.y=0,this.collectPointSnaps({minOffset:y,nearestSnapsX:m,nearestSnapsY:v,otherNodeSnapPoints:g,selectionSnapPoints:C});const _=this.getPointSnapLines({nearestSnapsX:m,nearestSnapsY:v});return this.manager.setIndicators([..._]),{nudge:S}}collectPointSnaps({selectionSnapPoints:e,otherNodeSnapPoints:n,minOffset:r,nearestSnapsX:o,nearestSnapsY:s}){for(const i of e)for(const a of n){const l=x.Sub(i,a),c=Math.abs(l.x),u=Math.abs(l.y);pe(c)<=pe(r.x)&&(pe(c)<pe(r.x)&&(o.length=0),o.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.x-i.x}),r.x=c),pe(u)<=pe(r.y)&&(pe(u)<pe(r.y)&&(s.length=0),s.push({type:"points",points:{thisPoint:i,otherPoint:a},nudge:a.y-i.y}),r.y=u)}}collectGapSnaps({selectionPageBounds:e,minOffset:n,nearestSnapsX:r,nearestSnapsY:o}){const{horizontal:s,vertical:i}=this.getVisibleGaps();for(const a of s){if(!Mc(a.breadthIntersection[0],a.breadthIntersection[1],e.minY,e.maxY))continue;const c=a.startEdge[0].x+a.length/2-e.center.x;if(a.length>e.width&&pe(Math.abs(c))<=pe(n.x)){pe(Math.abs(c))<pe(n.x)&&(r.length=0),n.x=Math.abs(c);const y={type:"gap_center",gap:a,nudge:c},S=r.find(({type:P})=>P==="gap_center"),b=S&&Gr(a.breadthIntersection[0],a.breadthIntersection[1],S.gap.breadthIntersection[0],S.gap.breadthIntersection[1]);S&&S.gap.length>a.length&&b?r[r.indexOf(S)]=y:(!S||!b)&&r.push(y)}const h=a.startNode.pageBounds.minX-a.length,p=e.maxX,f=h-p;pe(Math.abs(f))<=pe(n.x)&&(pe(Math.abs(f))<pe(n.x)&&(r.length=0),n.x=Math.abs(f),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"left",nudge:f}));const g=a.endNode.pageBounds.maxX+a.length,m=e.minX,v=g-m;pe(Math.abs(v))<=pe(n.x)&&(pe(Math.abs(v))<pe(n.x)&&(r.length=0),n.x=Math.abs(v),r.push({type:"gap_duplicate",gap:a,protrusionDirection:"right",nudge:v}))}for(const a of i){if(!Mc(a.breadthIntersection[0],a.breadthIntersection[1],e.minX,e.maxX))continue;const c=a.startEdge[0].y+a.length/2-e.center.y;if(a.length>e.height&&pe(Math.abs(c))<=pe(n.y)){pe(Math.abs(c))<pe(n.y)&&(o.length=0),n.y=Math.abs(c);const y={type:"gap_center",gap:a,nudge:c},S=o.find(({type:P})=>P==="gap_center"),b=S&&Mc(S.gap.breadthIntersection[0],S.gap.breadthIntersection[1],a.breadthIntersection[0],a.breadthIntersection[1]);S&&S.gap.length>a.length&&b?o[o.indexOf(S)]=y:(!S||!b)&&o.push(y);continue}const h=a.startNode.pageBounds.minY-a.length,p=e.maxY,f=h-p;pe(Math.abs(f))<=pe(n.y)&&(pe(Math.abs(f))<pe(n.y)&&(o.length=0),n.y=Math.abs(f),o.push({type:"gap_duplicate",gap:a,protrusionDirection:"top",nudge:f}));const g=a.endNode.pageBounds.maxY+a.length,m=e.minY,v=g-m;pe(Math.abs(v))<=pe(n.y)&&(pe(Math.abs(v))<pe(n.y)&&(o.length=0),n.y=Math.abs(v),o.push({type:"gap_duplicate",gap:a,protrusionDirection:"bottom",nudge:v}))}}getPointSnapLines({nearestSnapsX:e,nearestSnapsY:n}){const r={},o={};if(e.length>0){for(const s of e)if(s.type==="points"){const i=pe(s.points.otherPoint.x);r[i]||(r[i]=[]),r[i].push(s.points)}}if(n.length>0){for(const s of n)if(s.type==="points"){const i=pe(s.points.otherPoint.y);o[i]||(o[i]=[]),o[i].push(s.points)}}return Object.values(r).concat(Object.values(o)).map(s=>({id:ze(),type:"points",points:Sw(s.map(i=>x.From(i.otherPoint)).concat(s.map(i=>x.From(i.thisPoint))),(i,a)=>i.equals(a))}))}getGapSnapLines({selectionPageBounds:e,nearestSnapsX:n,nearestSnapsY:r}){const{vertical:o,horizontal:s}=this.getVisibleGaps(),i={top:e.sides[0],right:e.sides[1],bottom:[e.corners[3],e.corners[2]],left:[e.corners[0],e.corners[3]]},a=[];if(n.length>0)for(const l of n){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.width)/2,v=Gr(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:ze(),gaps:[...ns(s,h.id,m,"backward",v),{startEdge:u,endEdge:i.left},{startEdge:i.right,endEdge:g},...ns(s,p.id,m,"forward",v)]});break}case"gap_duplicate":{const m=Gr(c[0],c[1],e.minY,e.maxY);a.push({type:"gaps",direction:"horizontal",id:ze(),gaps:l.protrusionDirection==="left"?[{startEdge:i.right,endEdge:u.map(v=>v.clone().addXY(-h.pageBounds.width,0))},{startEdge:u,endEdge:g},...ns(s,p.id,f,"forward",m)]:[...ns(s,h.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(v=>v.clone().addXY(l.gap.endNode.pageBounds.width,0)),endEdge:i.left}]});break}}}if(r.length>0)for(const l of r){if(l.type==="points")continue;const{gap:{breadthIntersection:c,startEdge:u,startNode:h,endNode:p,length:f,endEdge:g}}=l;switch(l.type){case"gap_center":{const m=(f-e.height)/2,v=Gr(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:ze(),gaps:[...ns(o,h.id,m,"backward",v),{startEdge:u,endEdge:i.top},{startEdge:i.bottom,endEdge:g},...ns(o,l.gap.endNode.id,m,"forward",v)]});break}case"gap_duplicate":{const m=Gr(c[0],c[1],e.minX,e.maxX);a.push({type:"gaps",direction:"vertical",id:ze(),gaps:l.protrusionDirection==="top"?[{startEdge:i.bottom,endEdge:u.map(v=>v.clone().addXY(0,-h.pageBounds.height))},{startEdge:u,endEdge:g},...ns(o,p.id,f,"forward",m)]:[...ns(o,h.id,f,"backward",m),{startEdge:u,endEdge:g},{startEdge:g.map(v=>v.clone().addXY(0,p.pageBounds.height)),endEdge:i.top}]})}break}}return TJ(a),a}}_a=CJ();Gg(_a,1,"getSnapPointsCache",DO,rc);Gg(_a,1,"getSnappablePoints",OO,rc);Gg(_a,1,"getSnappableGapNodes",jO,rc);Gg(_a,1,"getVisibleGaps",AO,rc);IJ(_a,rc);function RI(t,e){const{minX:n,maxX:r,minY:o,maxY:s}=e,i=[];switch(t){case"top":case"left":case"top_left":case"any":i.push({id:"top_left",handle:"top_left",x:n,y:o})}switch(t){case"top":case"right":case"top_right":case"any":i.push({id:"top_right",handle:"top_right",x:r,y:o})}switch(t){case"bottom":case"right":case"bottom_right":case"any":i.push({id:"bottom_right",handle:"bottom_right",x:r,y:s})}switch(t){case"bottom":case"left":case"bottom_left":case"any":i.push({id:"bottom_left",handle:"bottom_left",x:n,y:s})}return i}var MJ=Object.create,RO=Object.defineProperty,AJ=Object.getOwnPropertyDescriptor,jJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),LO=t=>{throw TypeError(t)},$O=(t,e,n)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OJ=t=>[,,,MJ(null)],FO=["class","method","getter","setter","accessor","field","value","get","set"],NO=t=>t!==void 0&&typeof t!="function"?LO("Function expected"):t,DJ=(t,e,n,r,o)=>({kind:FO[t],name:e,metadata:r,addInitializer:s=>n._?LO("Already initialized"):o.push(NO(s||null))}),RJ=(t,e)=>$O(e,jJ("metadata"),t[3]),LJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},$J=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=FO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,AJ(o,n)),y=r.length-1;y>=0;y--)l=DJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,NO(i)&&(v[g]=i);return v&&RO(o,n,v),o},FJ=(t,e,n)=>$O(t,e+"",n),zO,Vg;const NJ=()=>null,zJ=()=>[];zO=[G];class j1{constructor(e){this.manager=e,LJ(Vg,5,this),FJ(this,"editor"),this.editor=e.editor}getSnapGeometryCache(){const{editor:e}=this;return e.store.createComputedCache("handle snap geometry",n=>{const r=e.getShapeUtil(n).getHandleSnapGeometry(n),o=r.getSelfSnapOutline?r.getSelfSnapOutline.bind(r):NJ,s=r.getSelfSnapPoints?r.getSelfSnapPoints.bind(r):zJ;return{outline:r.outline===void 0?e.getShapeGeometry(n):r.outline,points:r.points??[],getSelfSnapOutline:o,getSelfSnapPoints:s}})}*iterateSnapPointsInPageSpace(e,n){var o,s;const r=(o=this.getSnapGeometryCache().get(e))==null?void 0:o.getSelfSnapPoints(n);if(r&&r.length){const i=zn(this.editor.getShapePageTransform(e));for(const a of r)yield i.applyToPoint(a)}for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.points;if(!a||!a.length)continue;const l=zn(this.editor.getShapePageTransform(i));for(const c of a)yield l.applyToPoint(c)}}*iterateSnapOutlines(e,n){var o,s;const r=(o=this.getSnapGeometryCache().get(e))==null?void 0:o.getSelfSnapOutline(n);r&&(yield{shapeId:e,outline:r});for(const i of this.manager.getSnappableShapes()){if(i===e)continue;const a=(s=this.getSnapGeometryCache().get(i))==null?void 0:s.outline;a&&(yield{shapeId:i,outline:a})}}getHandleSnapPosition({currentShapeId:e,handle:n,handleInPageSpace:r}){const o=this.manager.getSnapThreshold();let s=o,i=null;for(const c of this.iterateSnapPointsInPageSpace(e,n))x.DistMin(r,c,s)&&(s=x.Dist(r,c),i=c);if(i)return i;let a=o,l=null;for(const{shapeId:c,outline:u}of this.iterateSnapOutlines(e,n)){const h=zn(this.editor.getShapePageTransform(c)),p=this.editor.getPointInShapeSpace(c,r),f=u.nearestPoint(p),g=h.applyToPoint(f);x.DistMin(r,g,a)&&(a=x.Dist(r,g),l=g)}return l||null}snapHandle({currentShapeId:e,handle:n}){const o=zn(this.editor.getShapePageTransform(e)).applyToPoint(n),s=this.getHandleSnapPosition({currentShapeId:e,handle:n,handleInPageSpace:o});return s?(this.manager.setIndicators([{id:ze(),type:"points",points:[s]}]),{nudge:x.Sub(s,o)}):null}}Vg=OJ();$J(Vg,1,"getSnapGeometryCache",zO,j1);RJ(Vg,j1);var BJ=Object.create,BO=Object.defineProperty,UJ=Object.getOwnPropertyDescriptor,HJ=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),UO=t=>{throw TypeError(t)},HO=(t,e,n)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,KJ=t=>[,,,BJ(null)],KO=["class","method","getter","setter","accessor","field","value","get","set"],WO=t=>t!==void 0&&typeof t!="function"?UO("Function expected"):t,WJ=(t,e,n,r,o)=>({kind:KO[t],name:e,metadata:r,addInitializer:s=>n._?UO("Already initialized"):o.push(WO(s||null))}),GJ=(t,e)=>HO(e,HJ("metadata"),t[3]),VJ=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},O1=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=KO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,UJ(o,n)),y=r.length-1;y>=0;y--)l=WJ(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,WO(i)&&(v[g]=i);return v&&BO(o,n,v),o},Jy=(t,e,n)=>HO(t,typeof e!="symbol"?e+"":e,n),GO,VO,YO,oc;YO=[G],VO=[G],GO=[G];class Sd{constructor(e){this.editor=e,VJ(oc,5,this),Jy(this,"shapeBounds"),Jy(this,"handles"),Jy(this,"_snapIndicators",Et("snapLines",void 0)),this.shapeBounds=new rc(this),this.handles=new j1(this)}getIndicators(){return this._snapIndicators.get()??ps}clearIndicators(){this.getIndicators().length&&this._snapIndicators.set(void 0)}setIndicators(e){this._snapIndicators.set(e)}getSnapThreshold(){return 8/this.editor.getZoomLevel()}getSnappableShapes(){const{editor:e}=this,n=e.getViewportPageBounds(),r=e.getSelectedShapeIds(),o=new Set,s=i=>{if(Fn(i)){const l=e.getShape(i);l&&e.isShapeOfType(l,"frame")&&o.add(i)}const a=e.getSortedChildIdsForParent(i);for(const l of a){if(r.includes(l))continue;const c=e.getShape(l);if(!c||!e.getShapeUtil(c).canSnap(c))continue;const h=e.getShapePageBounds(l);if(h&&n.includes(h)){if(e.isShapeOfType(c,"group")){s(l);continue}o.add(l)}}};return s(this.getCurrentCommonAncestor()??e.getCurrentPageId()),o}getCurrentCommonAncestor(){return this.editor.findCommonAncestor(this.editor.getSelectedShapes())}}oc=KJ();O1(oc,1,"getSnapThreshold",YO,Sd);O1(oc,1,"getSnappableShapes",VO,Sd);O1(oc,1,"getCurrentCommonAncestor",GO,Sd);GJ(oc,Sd);const YJ=/\r?\n|\r/g;function LI(t){return t.replace(YJ,`
102
102
  `).split(`
103
103
  `).map(e=>e||" ").join(`
104
104
  `)}const XJ={start:"left","start-legacy":"left",middle:"center","middle-legacy":"center",end:"right","end-legacy":"right"},qJ=/\s/;class ZJ{constructor(e){I(this,"baseElem");this.editor=e,this.baseElem=document.createElement("div"),this.baseElem.classList.add("tl-text"),this.baseElem.classList.add("tl-text-measure"),this.baseElem.tabIndex=-1}measureText(e,n){const r=this.baseElem.cloneNode();this.editor.getContainer().appendChild(r),r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("font-family",n.fontFamily),r.style.setProperty("font-style",n.fontStyle),r.style.setProperty("font-weight",n.fontWeight),r.style.setProperty("font-size",n.fontSize+"px"),r.style.setProperty("line-height",n.lineHeight*n.fontSize+"px"),r.style.setProperty("max-width",n.maxWidth===null?null:n.maxWidth+"px"),r.style.setProperty("min-width",n.minWidth===null?null:n.minWidth+"px"),r.style.setProperty("padding",n.padding),r.style.setProperty("overflow-wrap",n.disableOverflowWrapBreaking?"normal":"break-word"),r.textContent=LI(e);const o=r.scrollWidth,s=r.getBoundingClientRect();return r.remove(),{x:0,y:0,w:s.width,h:s.height,scrollWidth:o}}measureElementTextNodeSpans(e,{shouldTruncateToFirstLine:n=!1}={}){const r=[],o=e.getBoundingClientRect(),s=-o.left,i=-o.top,a=new Range,l=e.childNodes[0];let c=0,u=null,h=null,p=0,f=0,g=!1;for(const m of e.childNodes)if(m.nodeType===Node.TEXT_NODE)for(const v of m.textContent??""){a.setStart(l,c),a.setEnd(l,c+v.length);const y=a.getClientRects(),S=y[y.length-1],b=S.top+i,P=S.left+s,C=S.right+s,_=P<f,E=qJ.test(v);if(E!==h||b!==p||!u){if(u){if(n&&b!==p){g=!0;break}r.push(u)}u={box:{x:P,y:b,w:S.width,h:S.height},text:v},f=P}else _&&(u.box.x=P),u.box.w=_?u.box.w+S.width:C-u.box.x,u.text+=v;v===`
105
- `&&(f=0),h=E,p=b,c+=v.length}return u&&r.push(u),{spans:r,didTruncate:g}}measureTextSpans(e,n){if(e==="")return[];const r=this.baseElem.cloneNode();this.editor.getContainer().appendChild(r);const o=Math.ceil(n.width-n.padding*2);r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("width",`${o}px`),r.style.setProperty("height","min-content"),r.style.setProperty("font-size",`${n.fontSize}px`),r.style.setProperty("font-family",n.fontFamily),r.style.setProperty("font-weight",n.fontWeight),r.style.setProperty("line-height",`${n.lineHeight*n.fontSize}px`),r.style.setProperty("text-align",XJ[n.textAlign]);const s=n.overflow==="truncate-ellipsis"||n.overflow==="truncate-clip";s&&(r.style.setProperty("overflow-wrap","anywhere"),r.style.setProperty("word-break","break-all"));const i=LI(e);r.textContent=i;const{spans:a,didTruncate:l}=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:s});if(n.overflow==="truncate-ellipsis"&&l){r.textContent="…";const c=Math.ceil(this.measureElementTextNodeSpans(r).spans[0].box.w);r.style.setProperty("width",`${o-c}px`),r.textContent=i;const u=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:!0}).spans,h=u[u.length-1];return u.push({text:"…",box:{x:Math.min(h.box.x+h.box.w,n.width-n.padding-c),y:h.box.y,w:c,h:h.box.h}}),u}return r.remove(),a}}var QJ=Object.create,XO=Object.defineProperty,JJ=Object.getOwnPropertyDescriptor,eee=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),qO=t=>{throw TypeError(t)},ZO=(t,e,n)=>e in t?XO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tee=t=>[,,,QJ(null)],QO=["class","method","getter","setter","accessor","field","value","get","set"],JO=t=>t!==void 0&&typeof t!="function"?qO("Function expected"):t,nee=(t,e,n,r,o)=>({kind:QO[t],name:e,metadata:r,addInitializer:s=>n._?qO("Already initialized"):o.push(JO(s||null))}),ree=(t,e)=>ZO(e,eee("metadata"),t[3]),oee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},eD=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=QO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,JJ(o,n)),y=r.length-1;y>=0;y--)l=nee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,JO(i)&&(v[g]=i);return v&&XO(o,n,v),o},vh=(t,e,n)=>ZO(t,typeof e!="symbol"?e+"":e,n),tD,nD,vd;const $I=tM;nD=[Kn],tD=[Kn];class Yg{constructor(e){this.editor=e,oee(vd,5,this),vh(this,"cancelRaf"),vh(this,"isPaused",!0),vh(this,"now",0),vh(this,"prevPoint",new x),this.editor.disposables.add(this.dispose),this.start()}start(){var e;this.isPaused=!1,(e=this.cancelRaf)==null||e.call(this),this.cancelRaf=$I(this.tick),this.now=Date.now()}tick(){if(this.isPaused)return;const e=Date.now(),n=e-this.now;this.now=e,this.updatePointerVelocity(n),this.editor.emit("frame",n),this.editor.emit("tick",n),this.cancelRaf=$I(this.tick)}dispose(){var e;this.isPaused=!0,(e=this.cancelRaf)==null||e.call(this)}updatePointerVelocity(e){const{prevPoint:n,editor:{inputs:{currentScreenPoint:r,pointerVelocity:o}}}=this;if(e===0)return;const s=x.Sub(r,n);this.prevPoint=r.clone();const i=s.len(),a=i?s.div(i):new x(0,0),l=o.clone().lrp(a.mul(i/e),.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)}}vd=tee();eD(vd,1,"tick",nD,Yg);eD(vd,1,"dispose",tD,Yg);ree(vd,Yg);var see=Object.create,rD=Object.defineProperty,iee=Object.getOwnPropertyDescriptor,aee=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),oD=t=>{throw TypeError(t)},sD=(t,e,n)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lee=t=>[,,,see(null)],iD=["class","method","getter","setter","accessor","field","value","get","set"],aD=t=>t!==void 0&&typeof t!="function"?oD("Function expected"):t,cee=(t,e,n,r,o)=>({kind:iD[t],name:e,metadata:r,addInitializer:s=>n._?oD("Already initialized"):o.push(aD(s||null))}),uee=(t,e)=>sD(e,aee("metadata"),t[3]),dee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Nr=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=iD[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,iee(o,n)),y=r.length-1;y>=0;y--)l=cee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,aD(i)&&(v[g]=i);return v&&rD(o,n,v),o},FI=(t,e,n)=>sD(t,typeof e!="symbol"?e+"":e,n),lD,cD,uD,dD,hD,pD,fD,gD,mD,yD,SD,vD,Mn;vD=[G],SD=[G],yD=[G],mD=[G],gD=[G],fD=[G],pD=[G],hD=[G],dD=[G],uD=[G],cD=[G],lD=[G];class Qn{constructor(e,n){if(this.user=e,this.inferDarkMode=n,dee(Mn,5,this),FI(this,"systemColorScheme",Et("systemColorScheme","light")),FI(this,"disposables",new Set),typeof window>"u"||!("matchMedia"in window))return;const r=window.matchMedia("(prefers-color-scheme: dark)");r!=null&&r.matches&&this.systemColorScheme.set("dark");const o=s=>{s.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")};r==null||r.addEventListener("change",o),this.disposables.add(()=>r==null?void 0:r.removeEventListener("change",o))}dispose(){this.disposables.forEach(e=>e())}updateUserPreferences(e){this.user.setUserPreferences({...this.user.userPreferences.get(),...e})}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),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??xo.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??xo.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??xo.name}getLocale(){return this.user.userPreferences.get().locale??xo.locale}getColor(){return this.user.userPreferences.get().color??xo.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??xo.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??xo.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??xo.isDynamicSizeMode}getIsPasteAtCursorMode(){return this.user.userPreferences.get().isPasteAtCursorMode??xo.isPasteAtCursorMode}}Mn=lee();Nr(Mn,1,"getUserPreferences",vD,Qn);Nr(Mn,1,"getIsDarkMode",SD,Qn);Nr(Mn,1,"getEdgeScrollSpeed",yD,Qn);Nr(Mn,1,"getAnimationSpeed",mD,Qn);Nr(Mn,1,"getId",gD,Qn);Nr(Mn,1,"getName",fD,Qn);Nr(Mn,1,"getLocale",pD,Qn);Nr(Mn,1,"getColor",hD,Qn);Nr(Mn,1,"getIsSnapMode",dD,Qn);Nr(Mn,1,"getIsWrapMode",uD,Qn);Nr(Mn,1,"getIsDynamicResizeMode",cD,Qn);Nr(Mn,1,"getIsPasteAtCursorMode",lD,Qn);uee(Mn,Qn);const hee={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"},pee=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class ie{constructor(e,n){I(this,"performanceTracker");I(this,"id");I(this,"type");I(this,"shapeType");I(this,"initial");I(this,"children");I(this,"isLockable");I(this,"parent");I(this,"_path");I(this,"_current");I(this,"_isActive");I(this,"_currentToolIdMask",Et("curent tool id mask",void 0));this.editor=e;const{id:r,children:o,initial:s,isLockable:i}=this.constructor;this.id=r,this._isActive=Et("toolIsActive"+this.id,!1),this._current=Et("toolState"+this.id,void 0),this._path=G("toolPath"+this.id,()=>{const a=this.getCurrent();return this.id+(a?`.${a.getPath()}`:"")}),this.parent=n??{},this.parent?o&&s?(this.type="branch",this.initial=s,this.children=Object.fromEntries(o().map(a=>[a.id,new a(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(a=>[a.id,new a(this.editor,this)])),this._current.set(this.children[this.initial]))),this.isLockable=i,this.performanceTracker=new DT}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}transition(e,n={}){var s;const r=e.split(".");let o=this;for(let i=0;i<r.length;i++){const a=r[i],l=o.getCurrent(),c=(s=o.children)==null?void 0:s[a];if(!c)throw Error(`${o.id} - no child state exists with the id ${a}.`);if((l==null?void 0:l.id)!==c.id&&(l==null||l.exit(n,a),o._current.set(c),c.enter(n,(l==null?void 0:l.id)||"initial"),!c.getIsActive()))break;o=c}return this}handleEvent(e){var o;const n=hee[e.name],r=this._current.__unsafe__getWithoutCapture();(o=this[n])==null||o.call(this,e),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(e)}enter(e,n){var r;if(bt.measurePerformance.get()&&pee.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,e,n),this.children&&this.initial&&this.getIsActive()){const o=this.children[this.initial];this._current.set(o),o.enter(e,n)}}exit(e,n){var r,o;bt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,e,n),this.getIsActive()||(o=this.getCurrent())==null||o.exit(e,n)}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(e){this._currentToolIdMask.set(e)}}I(ie,"id"),I(ie,"initial"),I(ie,"children"),I(ie,"isLockable",!0);class Mx extends ie{static children(){return[]}onKeyDown(e){var n;switch(e.code){case"KeyZ":{if(!(e.shiftKey||e.ctrlKey)){const r=this.getCurrent();r&&((n=r.getCurrent())==null?void 0:n.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...e,onInteractionEnd:r.id})}break}}}}I(Mx,"id","root"),I(Mx,"initial","");var fee=Object.create,xD=Object.defineProperty,gee=Object.getOwnPropertyDescriptor,wD=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),bD=t=>{throw TypeError(t)},PD=(t,e,n)=>e in t?xD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mee=t=>[,,,fee((t==null?void 0:t[wD("metadata")])??null)],CD=["class","method","getter","setter","accessor","field","value","get","set"],_D=t=>t!==void 0&&typeof t!="function"?bD("Function expected"):t,yee=(t,e,n,r,o)=>({kind:CD[t],name:e,metadata:r,addInitializer:s=>n._?bD("Already initialized"):o.push(_D(s||null))}),See=(t,e)=>PD(e,wD("metadata"),t[3]),vee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},te=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=CD[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,gee(o,n)),y=r.length-1;y>=0;y--)l=yee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,_D(i)&&(v[g]=i);return v&&xD(o,n,v),o},de=(t,e,n)=>PD(t,typeof e!="symbol"?e+"":e,n),ID,ED,kD,TD,MD,AD,jD,OD,DD,RD,LD,$D,FD,ND,zD,BD,UD,HD,KD,WD,GD,VD,YD,XD,qD,ZD,QD,JD,eR,tR,nR,rR,oR,sR,iR,aR,lR,cR,uR,dR,hR,pR,fR,gR,mR,yR,SR,vR,xR,wR,bR,PR,CR,_R,IR,ER,kR,TR,MR,AR,jR,OR,DR,RR,LR,$R,FR,NR,zR,BR,UR,HR,Ax,J;class Q extends(Ax=BZ,HR=[G],UR=[G],BR=[G],zR=[G],NR=[G],FR=[G],$R=[G],LR=[G],RR=[G],DR=[G],OR=[G],jR=[G],AR=[G],MR=[G],TR=[G],kR=[G],ER=[G],IR=[G],_R=[G],CR=[G],PR=[G],bR=[G],wR=[G],xR=[G],vR=[G],SR=[G],yR=[G],mR=[G],gR=[G],fR=[G],pR=[G],hR=[G],dR=[G],uR=[G],cR=[G],lR=[G],aR=[G],iR=[G],sR=[G],oR=[G],rR=[G],nR=[G],tR=[G],eR=[G],JD=[G],QD=[G],ZD=[G],qD=[G],XD=[G],YD=[G],VD=[G],GD=[G],WD=[G],KD=[G],HD=[G],UD=[G],BD=[G],zD=[G],ND=[G],FD=[G],$D=[G],LD=[G],RD=[G],DD=[G],OD=[G({isEqual:(e,n)=>e.equals(n)})],jD=[G],AD=[G],MD=[G],TD=[Kn],kD=[Kn],ED=[Kn],ID=[Kn],Ax){constructor({store:e,user:n,shapeUtils:r,bindingUtils:o,tools:s,getContainer:i,cameraOptions:a,initialState:l,autoFocus:c,inferDarkMode:u,options:h,isShapeHidden:p}){var D;super(),vee(J,5,this),de(this,"_isShapeHiddenPredicate"),de(this,"options"),de(this,"contextId",ze()),de(this,"store"),de(this,"root"),de(this,"disposables",new Set),de(this,"isDisposed",!1),de(this,"_tickManager"),de(this,"snaps"),de(this,"timers",kx.forContext(this.contextId)),de(this,"user"),de(this,"textMeasure"),de(this,"environment",Ge),de(this,"scribbles"),de(this,"sideEffects"),de(this,"edgeScrollManager"),de(this,"focusManager"),de(this,"getContainer"),de(this,"shapeUtils"),de(this,"styleProps"),de(this,"bindingUtils"),de(this,"history"),de(this,"_shouldIgnoreShapeLock",!1),de(this,"_crashingError",null),de(this,"_isChangingStyleTimeout",-1),de(this,"menus",Vr.forContext(this.contextId)),de(this,"_cameraOptions",Et("camera options",rI)),de(this,"_viewportAnimation",null),de(this,"_willSetInitialBounds",!0),de(this,"_isLockedOnFollowingUser",Et("isLockedOnFollowingUser",!1)),de(this,"_cameraState",Et("camera state","idle")),de(this,"_cameraStateTimeoutRemaining",0),de(this,"_currentPageShapeIds"),de(this,"_parentIdsToChildIds"),de(this,"animatingShapes",new Map),de(this,"externalAssetContentHandlers",{file:null,url:null}),de(this,"temporaryAssetPreview",new Map),de(this,"externalContentHandlers",{text:null,files:null,embed:null,"svg-text":null,url:null}),de(this,"inputs",{originPagePoint:new x,originScreenPoint:new x,previousPagePoint:new x,previousScreenPoint:new x,currentPagePoint:new x,currentScreenPoint:new x,keys:new Set,buttons:new Set,isPen:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1,isDragging:!1,isPointing:!1,isPinching:!1,isEditing:!1,isPanning:!1,isSpacebarPanning:!1,pointerVelocity:new x}),de(this,"_clickManager",new Wg(this)),de(this,"_prevCursor","default"),de(this,"_shiftKeyTimeout",-1),de(this,"_altKeyTimeout",-1),de(this,"_ctrlKeyTimeout",-1),de(this,"_metaKeyTimeout",-1),de(this,"_restoreToolId","select"),de(this,"_pinchStart",1),de(this,"_didPinch",!1),de(this,"_selectedShapeIdsAtPointerDown",[]),de(this,"_longPressTimeout",-1),de(this,"capturedPointerId",null),de(this,"performanceTracker"),de(this,"performanceTrackerTimeout",-1),de(this,"_pendingEventsForNextTick",[]),this._isShapeHiddenPredicate=p,this.options={...HQ,...h},this.store=e,this.disposables.add(this.store.dispose.bind(this.store)),this.history=new yJ({store:e,annotateError:T=>{this.annotateError(T,{origin:"history.batch",willCrashApp:!0}),this.crash(T)}}),this.snaps=new Sd(this),this.disposables.add(this.timers.dispose),this._cameraOptions.set({...rI,...a}),this.user=new Qn(n??Bj(),u??!1),this.disposables.add(()=>this.user.dispose()),this.getContainer=i,this.textMeasure=new ZJ(this),this._tickManager=new Yg(this);class f extends Mx{}I(f,"initial",l??""),this.root=new f(this),this.root.children={};const g=Xj(r),m={},v={},y=new Map;for(const T of g){const j=new T(this);m[T.type]=j;const $=xA(T.props??{});v[T.type]=$;for(const M of $.keys())if(!y.has(M.id))y.set(M.id,M);else if(y.get(M.id)!==M)throw Error(`Multiple style props with id "${M.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=m,this.styleProps=v;const S=Vj(o),b={};for(const T of S){const j=new T(this);b[T.type]=j}this.bindingUtils=b;for(const T of[...s]){if(no(this.root.children,T.id))throw Error(`Can't override tool with id "${T.id}"`);this.root.children[T.id]=new T(this,this.root)}this.scribbles=new xJ(this);const P=(T,j)=>{let $=null;const M=T.selectedShapeIds.filter(B=>!j.has(B));M.length!==T.selectedShapeIds.length&&($||($={...T}),$.selectedShapeIds=M);const O=T.erasingShapeIds.filter(B=>!j.has(B));O.length!==T.erasingShapeIds.length&&($||($={...T}),$.erasingShapeIds=O),T.hoveredShapeId&&j.has(T.hoveredShapeId)&&($||($={...T}),$.hoveredShapeId=null),T.editingShapeId&&j.has(T.editingShapeId)&&($||($={...T}),$.editingShapeId=null);const F=T.hintingShapeIds.filter(B=>!j.has(B));return F.length!==T.hintingShapeIds.length&&($||($={...T}),$.hintingShapeIds=F),T.focusedGroupId&&j.has(T.focusedGroupId)&&($||($={...T}),$.focusedGroupId=null),$};this.sideEffects=this.store.sideEffects;let C=new Map;const _=new Set,E=new Set;let k=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var T,j,$,M;_.clear();for(const O of E){E.delete(O);const F=this.getShape(O);if(!F)continue;const B=this.getShapeUtil(F),K=(T=B.onChildrenChange)==null?void 0:T.call(B,F);K!=null&&K.length&&this.updateShapes(K)}if(k.size){const O=k;k=new Set;for(const F of O){const B=this.getBindingUtil(F);(j=B.onOperationComplete)==null||j.call(B)}}if(C.size){const O=C;C=new Map;for(const F of O.values())(M=($=this.getBindingUtil(F.binding)).onAfterDelete)==null||M.call($,F)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(T,j)=>{var $,M,O,F;for(const B of this.getBindingsInvolvingShape(j))k.add(B.type),B.fromId===j.id&&((M=($=this.getBindingUtil(B)).onAfterChangeFromShape)==null||M.call($,{binding:B,shapeBefore:T,shapeAfter:j})),B.toId===j.id&&((F=(O=this.getBindingUtil(B)).onAfterChangeToShape)==null||F.call(O,{binding:B,shapeBefore:T,shapeAfter:j}));if(T.parentId!==j.parentId){const B=K=>{var H,Y,ee,he;const R=this.getShape(K);if(R)for(const ue of this.getBindingsInvolvingShape(R))k.add(ue.type),ue.fromId===R.id&&((Y=(H=this.getBindingUtil(ue)).onAfterChangeFromShape)==null||Y.call(H,{binding:ue,shapeBefore:R,shapeAfter:R})),ue.toId===R.id&&((he=(ee=this.getBindingUtil(ue)).onAfterChangeToShape)==null||he.call(ee,{binding:ue,shapeBefore:R,shapeAfter:R}))};B(j.id),this.visitDescendants(j.id,B)}if(T.parentId!==j.parentId&&Rn(j.parentId)){const B=new Set([T.id]);this.visitDescendants(T.id,K=>{B.add(K)});for(const K of this.getPageStates()){if(K.pageId===j.parentId)continue;const R=P(K,B);R&&this.store.put([R])}}T.parentId&&Fn(T.parentId)&&E.add(T.parentId),j.parentId!==T.parentId&&Fn(j.parentId)&&E.add(j.parentId)},beforeDelete:T=>{var O,F,B,K;if(_.has(T.id))return;T.parentId&&Fn(T.parentId)&&E.add(T.parentId),_.add(T.id);const j=[];for(const R of this.getBindingsInvolvingShape(T)){k.add(R.type),j.push(R.id);const H=this.getBindingUtil(R);R.fromId===T.id?((O=H.onBeforeIsolateToShape)==null||O.call(H,{binding:R,removedShape:T}),(F=H.onBeforeDeleteFromShape)==null||F.call(H,{binding:R,shape:T})):((B=H.onBeforeIsolateFromShape)==null||B.call(H,{binding:R,removedShape:T}),(K=H.onBeforeDeleteToShape)==null||K.call(H,{binding:R,shape:T}))}j.length&&this.deleteBindings(j);const $=new Set([T.id]),M=me(this.getPageStates().map(R=>P(R,$)));M.length&&this.store.put(M)}},binding:{beforeCreate:T=>{var $,M;const j=(M=($=this.getBindingUtil(T)).onBeforeCreate)==null?void 0:M.call($,{binding:T});return j||T},afterCreate:T=>{var j,$;k.add(T.type),($=(j=this.getBindingUtil(T)).onAfterCreate)==null||$.call(j,{binding:T})},beforeChange:(T,j)=>{var M,O;const $=(O=(M=this.getBindingUtil(j)).onBeforeChange)==null?void 0:O.call(M,{bindingBefore:T,bindingAfter:j});return $||j},afterChange:(T,j)=>{var $,M;k.add(j.type),(M=($=this.getBindingUtil(j)).onAfterChange)==null||M.call($,{bindingBefore:T,bindingAfter:j})},beforeDelete:T=>{var j,$;($=(j=this.getBindingUtil(T)).onBeforeDelete)==null||$.call(j,{binding:T})},afterDelete:T=>{var j,$;($=(j=this.getBindingUtil(T)).onAfterDelete)==null||$.call(j,{binding:T}),k.add(T.type)}},page:{afterCreate:T=>{const j=Eo.createId(T.id),$=Qr.createId(T.id);this.store.has(j)||this.store.put([Eo.create({id:j})]),this.store.has($)||this.store.put([Qr.create({id:$,pageId:T.id})])},afterDelete:(T,j)=>{var O,F;if(((O=this.getInstanceState())==null?void 0:O.currentPageId)===T.id){const B=(F=this.getPages().find(K=>K.id!==T.id))==null?void 0:F.id;B?this.store.put([{...this.getInstanceState(),currentPageId:B}]):j==="user"&&this.store.ensureStoreIsUsable()}const $=Eo.createId(T.id),M=Qr.createId(T.id);this.store.remove([$,M])}},instance:{afterChange:(T,j,$)=>{var M;if(!this.store.has(j.currentPageId)){const O=this.store.has(T.currentPageId)?T.currentPageId:(M=this.getPages()[0])==null?void 0:M.id;O?this.store.update(j.id,F=>({...F,currentPageId:O})):$==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(T,j)=>{if((T==null?void 0:T.selectedShapeIds)!==(j==null?void 0:j.selectedShapeIds)){const $=j.selectedShapeIds.filter(O=>{var B,K;let F=(B=this.getShape(O))==null?void 0:B.parentId;for(;Fn(F);){if(j.selectedShapeIds.includes(F))return!1;F=(K=this.getShape(F))==null?void 0:K.parentId}return!0});let M=null;if($.length>0){const O=this.findCommonAncestor(me($.map(F=>this.getShape(F))),F=>this.isShapeOfType(F,"group"));O&&(M=O)}else j!=null&&j.focusedGroupId&&(M=j.focusedGroupId);($.length!==j.selectedShapeIds.length||M!==j.focusedGroupId)&&this.store.put([{...j,selectedShapeIds:$,focusedGroupId:M??null}])}}}})),this._currentPageShapeIds=oJ(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=rJ(this.store),this.disposables.add(this.store.listen(T=>{this.emit("change",T)})),this.disposables.add(this.history.dispose),this.run(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})},{history:"ignore"}),l&&this.root.children[l]===void 0)throw Error(`No state found for initialState "${l}".`);if(this.root.enter(void 0,"initial"),this.edgeScrollManager=new pJ(this),this.focusManager=new fJ(this,c),this.disposables.add(this.focusManager.dispose.bind(this.focusManager)),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this.on("tick",this._flushEventsForTick),this.timers.requestAnimationFrame(()=>{this._tickManager.start()}),this.performanceTracker=new DT,(D=this.store.props.collaboration)!=null&&D.mode){const T=this.store.props.collaboration.mode;this.disposables.add(jo("update collaboration mode",()=>{this.store.put([{...this.getInstanceState(),isReadonly:T.get()==="readonly"}])}))}}getIsShapeHiddenCache(){return this._isShapeHiddenPredicate?this.store.createComputedCache("isShapeHidden",e=>this.findShapeAncestor(e,r=>this.isShapeHidden(r))?!0:this._isShapeHiddenPredicate(e,this)??!1):null}isShapeHidden(e){return this._isShapeHiddenPredicate?!!this.getIsShapeHiddenCache().get(typeof e=="string"?e:e.id):!1}dispose(){this.disposables.forEach(e=>e()),this.disposables.clear(),this.isDisposed=!0}getShapeUtil(e){const n=typeof e=="string"?e:e.type,r=hn(this.shapeUtils,n);return Le(r,`No shape util found for type "${n}"`),r}getBindingUtil(e){const n=typeof e=="string"?e:e.type,r=hn(this.bindingUtils,n);return Le(r,`No binding util found for type "${n}"`),r}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}clearHistory(){return this.history.clear(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(e){return console.warn(typeof e=="string"?`[tldraw] \`editor.history.mark("${e}")\` is deprecated. Please use \`const myMarkId = editor.markHistoryStoppingPoint()\` instead.`:"[tldraw] `editor.mark()` is deprecated. Use `editor.markHistoryStoppingPoint()` instead."),this.history._mark(e??ze()),this}markHistoryStoppingPoint(e){const n=`[${e??"stop"}]_${ze()}`;return this.history._mark(n),n}getMarkIdMatching(e){return this.history.getMarkIdMatching(e)}squashToMark(e){return this.history.squashToMark(e),this}bail(){return this.history.bail(),this}bailToMark(e){return this.history.bailToMark(e),this}run(e,n){const r=this._shouldIgnoreShapeLock;this._shouldIgnoreShapeLock=(n==null?void 0:n.ignoreShapeLock)??r;try{this.history.batch(e,n)}finally{this._shouldIgnoreShapeLock=r}return this}batch(e,n){return this.run(e,n)}annotateError(e,{origin:n,willCrashApp:r,tags:o,extras:s}){const i=this.createErrorAnnotations(n,r);return vw(e,{tags:{...i.tags,...o},extras:{...i.extras,...s}}),r&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(e,n){try{const r=this.getEditingShapeId();return{tags:{origin:e,willCrashApp:n},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:r?this.getShape(r):void 0,inputs:this.inputs}}}catch{return{tags:{origin:e,willCrashApp:n},extras:{}}}}getCrashingError(){return this._crashingError}crash(e){return this._crashingError=e,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:e}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(e){const n=e.split(".").reverse();let r=this.root;for(;n.length>0;){const o=n.pop();if(!o)return!0;const s=r.getCurrent();if((s==null?void 0:s.id)===o){if(n.length===0)return!0;r=s;continue}else return!1}return!1}isInAny(...e){return e.some(n=>this.isIn(n))}setCurrentTool(e,n={}){return this.root.transition(e,n),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const e=this.getCurrentTool();return e?e.getCurrentToolIdMask()??e.id:""}getStateDescendant(e){var o;const n=e.split(".").reverse();let r=this.root;for(;n.length>0;){const s=n.pop();if(!s)return r;const i=(o=r.children)==null?void 0:o[s];if(!i)return;r=i}return r}getDocumentSettings(){return this.store.get(yx)}updateDocumentSettings(e){return this.run(()=>{this.store.put([{...this.getDocumentSettings(),...e}])},{history:"ignore"}),this}getInstanceState(){return this.store.get(bn)}updateInstanceState(e,n){return this._updateInstanceState(e,{history:"ignore",...n}),e.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),e.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},2e3))),this}_updateInstanceState(e,n){this.run(()=>{this.store.put([{...this.getInstanceState(),...e}])},n)}getOpenMenus(){return this.menus.getOpenMenus()}addOpenMenu(e){return this.menus.addOpenMenu(e),this}deleteOpenMenu(e){return this.menus.deleteOpenMenu(e),this}clearOpenMenus(){return this.menus.clearOpenMenus(),this}getIsMenuOpen(){return this.menus.hasAnyOpenMenus()}setCursor(e){return this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...e}}),this}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return Qr.createId(this.getCurrentPageId())}updateCurrentPageState(e){return this._updateCurrentPageState(e),this}_updateCurrentPageState(e){this.store.update(e.id??this.getCurrentPageState().id,n=>({...n,...e}))}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:e}=this.getCurrentPageState();return me(e.map(n=>this.store.get(n)))}setSelectedShapes(e){return this.run(()=>{const n=e.map(s=>typeof s=="string"?s:s.id),{selectedShapeIds:r}=this.getCurrentPageState(),o=new Set(r);if(n.length===o.size&&n.every(s=>o.has(s)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:n}])},{history:"record-preserveRedoStack"})}isAncestorSelected(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null,r=this.getShape(n);if(!r)return!1;const o=this.getSelectedShapeIds();return!!this.findShapeAncestor(r,s=>o.includes(s.id))}select(...e){const n=typeof e[0]=="string"?e:e.map(r=>r.id);return this.setSelectedShapes(n),this}deselect(...e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=this.getSelectedShapeIds();return r.length>0&&n.length>0&&this.setSelectedShapes(r.filter(o=>!n.includes(o))),this}selectAll(){const e=this.getSortedChildIdsForParent(this.getCurrentPageId());return e.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(e)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var e;return((e=this.getOnlySelectedShape())==null?void 0:e.id)??null}getOnlySelectedShape(){const e=this.getSelectedShapes();return e.length===1?e[0]:null}getShapesPageBounds(e){const n=me(e.map(r=>this.getShapePageBounds(r)));return n.length===0?null:Z.Common(n)}getSelectionPageBounds(){return this.getShapesPageBounds(this.getSelectedShapeIds())}getShapesSharedRotation(e){let n=!1,r=0;for(let o=0,s=e.length;o<s;o++){const i=this.getShapePageTransform(e[o]);if(i)if(n){if(i.rotation()!==r)return 0}else n=!0,r=i.rotation()}return r}getSelectionRotation(){return this.getShapesSharedRotation(this.getSelectedShapeIds())}getShapesRotatedPageBounds(e){if(e.length===0)return;const n=this.getShapesSharedRotation(e);if(n===0)return this.getShapesPageBounds(e)??void 0;if(e.length===1){const o=this.getShapeGeometry(e[0]).bounds.clone(),s=this.getShapePageTransform(e[0]);return o.point=s.applyToPoint(o.point),o}const r=Z.FromPoints(e.flatMap(o=>{const s=this.getShapePageTransform(o);return s?s.applyToPoints(this.getShapeGeometry(o).bounds.corners):[]}).map(o=>o.rot(-n)));return r.point=r.point.rot(n),r}getSelectionRotatedPageBounds(){return this.getShapesRotatedPageBounds(this.getSelectedShapeIds())}getSelectionRotatedScreenBounds(){const e=this.getSelectionRotatedPageBounds();if(!e)return;const{x:n,y:r}=this.pageToScreen(e.point),o=this.getZoomLevel();return new Z(n,r,e.width*o,e.height*o)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const e=this.getFocusedGroupId();return e?this.getShape(e):void 0}setFocusedGroup(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(n!==null){const r=this.getShape(n);if(!r)throw Error(`Editor.setFocusedGroup: Shape with id ${n} does not exist`);if(!this.isShapeOfType(r,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${r.type}`)}return n===this.getFocusedGroupId()?this:this.run(()=>{this.store.update(this.getCurrentPageState().id,r=>({...r,focusedGroupId:n}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const e=this.getFocusedGroup();if(e){const n=this.findShapeAncestor(e,r=>this.isShapeOfType(r,"group"));this.setFocusedGroup((n==null?void 0:n.id)??null),this.select(e.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const e=this.getEditingShapeId();return e?this.getShape(e):void 0}setEditingShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(n!==this.getEditingShapeId()){if(n){const r=this.getShape(n);if(r&&this.getShapeUtil(r).canEdit(r))return this.run(()=>{this._updateCurrentPageState({editingShapeId:n})},{history:"ignore"}),this}this.run(()=>{this._updateCurrentPageState({editingShapeId:null})},{history:"ignore"})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const e=this.getHoveredShapeId();return e?this.getShape(e):void 0}setHoveredShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;return n===this.getHoveredShapeId()?this:(this.run(()=>{this.updateCurrentPageState({hoveredShapeId:n})},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const e=this.getHintingShapeIds();return me(e.map(n=>this.getShape(n)))}setHintingShapes(e){const n=typeof e[0]=="string"?e:e.map(r=>r.id);return this.run(()=>{this._updateCurrentPageState({hintingShapeIds:Sw(n)})},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const e=this.getErasingShapeIds();return me(e.map(n=>this.getShape(n)))}setErasingShapes(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id);n.sort();const r=this.getErasingShapeIds();return this.run(()=>{if(n.length===r.length){for(let o=0;o<n.length;o++)if(n[o]!==r[o]){this._updateCurrentPageState({erasingShapeIds:n});break}}else this._updateCurrentPageState({erasingShapeIds:n})},{history:"ignore"}),this}getCroppingShapeId(){return this.getCurrentPageState().croppingShapeId}setCroppingShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;return n!==this.getCroppingShapeId()&&this.run(()=>{if(!n)this.updateCurrentPageState({croppingShapeId:null});else{const r=this.getShape(n),o=this.getShapeUtil(r);r&&o.canCrop(r)&&this.updateCurrentPageState({croppingShapeId:n})}},{history:"ignore"}),this}_unsafe_getCameraId(){return Eo.createId(this.getCurrentPageId())}getCamera(){const e=this.store.get(this._unsafe_getCameraId());if(this._isLockedOnFollowingUser.get()){const n=this.getCameraForFollowing();if(n)return{...e,...n}}return e}getViewportPageBoundsForFollowing(){const e=this.getInstanceState().followingUserId;if(!e)return null;const n=this.getCollaborators().find(h=>h.userId===e);if(!n||!n.camera||!n.screenBounds)return null;const{w:r,h:o}=n.screenBounds,{x:s,y:i,z:a}=n.camera,l=new Z(-s,-i,r/a,o/a),c=this.getViewportScreenBounds().clone(),u=c.width/c.height;return c.width=l.width,c.height=c.width/u,c.height<l.height&&(c.height=l.height,c.width=c.height*u),c.center=l.center,c}getCameraForFollowing(){const e=this.getViewportPageBoundsForFollowing();return e?{x:-e.x,y:-e.y,z:this.getViewportScreenBounds().w/e.width}:null}getZoomLevel(){return this.getCamera().z}getInitialZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.initialZoom==="default")return 1;const{zx:n,zy:r}=zI(this,e);switch(e.constraints.initialZoom){case"fit-min":return Math.max(n,r);case"fit-max":return Math.min(n,r);case"fit-x":return n;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(n,r));case"fit-max-100":return Math.min(1,Math.min(n,r));case"fit-x-100":return Math.min(1,n);case"fit-y-100":return Math.min(1,r);default:throw Ot(e.constraints.initialZoom)}}getBaseZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.baseZoom==="default")return 1;const{zx:n,zy:r}=zI(this,e);switch(e.constraints.baseZoom){case"fit-min":return Math.max(n,r);case"fit-max":return Math.min(n,r);case"fit-x":return n;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(n,r));case"fit-max-100":return Math.min(1,Math.min(n,r));case"fit-x-100":return Math.min(1,n);case"fit-y-100":return Math.min(1,r);default:throw Ot(e.constraints.baseZoom)}}getCameraOptions(){return this._cameraOptions.get()}setCameraOptions(e){var r;const n=tt({...this._cameraOptions.__unsafe__getWithoutCapture(),...e});return((r=n.zoomSteps)==null?void 0:r.length)<1&&(n.zoomSteps=[1]),this._cameraOptions.set(n),this.setCamera(this.getCamera()),this}getConstrainedCamera(e,n){const r=this.getCamera();let{x:o,y:s,z:i=r.z}=e;if(!(n!=null&&n.force)){const a=this.getCameraOptions(),l=a.zoomSteps[0],c=Ut(a.zoomSteps),u=this.getViewportScreenBounds();if(a.constraints){const{constraints:h}=a,p=Math.min(h.padding.y,u.w/2),f=Math.min(h.padding.x,u.h/2),g=Z.From(a.constraints.bounds),m=(u.w-f*2)/g.w,v=(u.h-p*2)/g.h,y=this.getBaseZoom(),S=c*y,b=l*y;if(n!=null&&n.reset&&(i=this.getInitialZoom()),i<b||i>S){const{x:$,y:M,z:O}=r,F=-$+u.w/O/2,B=-M+u.h/O/2;i=zt(i,b,S);const K=-$+u.w/i/2,R=-M+u.h/i/2;o=$+K-F,s=M+R-B}const P=f/i-g.x,C=p/i-g.y,_=(u.w-f*2)/i-g.w,E=(u.h-p*2)/i-g.h,k=P+_*h.origin.x,D=C+E*h.origin.y,T=typeof h.behavior=="string"?h.behavior:h.behavior.x,j=typeof h.behavior=="string"?h.behavior:h.behavior.y;if(n!=null&&n.reset)o=k,s=D;else{switch(T){case"fixed":{o=k;break}case"contain":{i<m?o=k:o=zt(o,P+_,P);break}case"inside":{i<m?o=zt(o,P,(u.w-f)/i-g.w):o=zt(o,P+_,P);break}case"outside":{o=zt(o,f/i-g.w,(u.w-f)/i);break}case"free":break;default:throw Ot(T)}switch(j){case"fixed":{s=D;break}case"contain":{i<v?s=D:s=zt(s,C+E,C);break}case"inside":{i<v?s=zt(s,C,(u.h-p)/i-g.h):s=zt(s,C+E,C);break}case"outside":{s=zt(s,p/i-g.h,(u.h-p)/i);break}case"free":break;default:throw Ot(j)}}}else if(i>c||i<l){const{x:h,y:p,z:f}=r;i=zt(i,l,c),o=h+(-h+u.w/i/2)-(-h+u.w/f/2),s=p+(-p+u.h/i/2)-(-p+u.h/f/2)}}return{x:o,y:s,z:i}}_setCamera(e,n){const r=this.getCamera(),{x:o,y:s,z:i}=this.getConstrainedCamera(e,n);return r.x===o&&r.y===s&&r.z===i?this:(Oo(()=>{const a={...r,x:o,y:s,z:i};this.run(()=>{this.store.put([a])},{history:"ignore"});const{currentScreenPoint:l,currentPagePoint:c}=this.inputs,{screenBounds:u}=this.store.unsafeGetWithoutCapture(bn);if(l.x/i-o!==c.x||l.y/i-s!==c.y){const h={type:"pointer",target:"canvas",name:"pointer_move",point:x.AddXY(l,u.x,u.y),pointerId:oI.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),button:0,isPen:this.getInstanceState().isPenMode??!1};n!=null&&n.immediate?this._flushEventForTick(h):this.dispatch(h)}this._tickCameraState()}),this)}setCamera(e,n){const{isLocked:r}=this._cameraOptions.__unsafe__getWithoutCapture();if(r&&!(n!=null&&n.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const o=x.Cast(e);Number.isFinite(o.x)||(o.x=0),Number.isFinite(o.y)||(o.y=0),(o.z===void 0||!Number.isFinite(o.z))&&(e.z=this.getZoomLevel());const s=this.getConstrainedCamera(o,n);if(n!=null&&n.animation){const{width:i,height:a}=this.getViewportScreenBounds();this._animateToViewport(new Z(-s.x,-s.y,i/s.z,a/s.z),n)}else this._setCamera(s,{...n,force:!0});return this}centerOnPoint(e,n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const{width:o,height:s}=this.getViewportPageBounds();return this.setCamera(new x(-(e.x-o/2),-(e.y-s/2),this.getCamera().z),n),this}zoomToFit(e){const n=[...this.getCurrentPageShapeIds()];if(n.length<=0)return this;const r=Z.Common(me(n.map(o=>this.getShapePageBounds(o))));return this.zoomToBounds(r,e),this}resetZoom(e=this.getViewportScreenCenter(),n){const{isLocked:r,constraints:o}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const s=this.getCamera(),{x:i,y:a,z:l}=s,{x:c,y:u}=e;let h=1;if(o){const p=this.getInitialZoom();l!==p&&(h=p)}return this.setCamera(new x(i+(c/h-c)-(c/l-c),a+(u/h-u)-(u/l-u),h),n),this}zoomIn(e=this.getViewportScreenCenter(),n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))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=Ut(a)*l;for(let u=1;u<a.length;u++){const h=a[u-1]*l,p=a[u]*l;if(!(p-i<=(p-h)/2)){c=p;break}}this.setCamera(new x(o+(e.x/c-e.x)-(e.x/i-e.x),s+(e.y/c-e.y)-(e.y/i-e.y),c),n)}return this}zoomOut(e=this.getViewportScreenCenter(),n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const{zoomSteps:o}=this.getCameraOptions();if(o!==null&&o.length>1){const s=this.getBaseZoom(),{x:i,y:a,z:l}=this.getCamera();let c=o[0]*s;for(let u=o.length-1;u>0;u--){const h=o[u-1]*s,p=o[u]*s;if(!(p-l>=(p-h)/2)){c=h;break}}this.setCamera(new x(i+(e.x/c-e.x)-(e.x/l-e.x),a+(e.y/c-e.y)-(e.y/l-e.y),c),n)}return this}zoomToSelection(e){const{isLocked:n}=this.getCameraOptions();if(n&&!(e!=null&&e.force))return this;const r=this.getSelectionPageBounds();return r&&this.zoomToBounds(r,{targetZoom:Math.max(1,this.getZoomLevel()),...e}),this}zoomToBounds(e,n){const r=this._cameraOptions.__unsafe__getWithoutCapture();if(r.isLocked&&!(n!=null&&n.force))return this;const o=this.getViewportScreenBounds(),s=(n==null?void 0:n.inset)??Math.min(wX,o.width*.28),i=this.getBaseZoom(),a=r.zoomSteps[0],l=Ut(r.zoomSteps);let c=zt(Math.min((o.width-s)/e.w,(o.height-s)/e.h),a*i,l*i);return(n==null?void 0:n.targetZoom)!==void 0&&(c=Math.min(n.targetZoom,c)),this.setCamera(new x(-e.x+(o.width-e.w*c)/2/c,-e.y+(o.height-e.h*c)/2/c,c),n),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(e){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=e;const{elapsed:n,easing:r,duration:o,start:s,end:i}=this._viewportAnimation;if(n>o){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new x(-i.x,-i.y,this.getViewportScreenBounds().width/i.width));return}const a=o-n,l=r(1-a/o),c=s.minX+(i.minX-s.minX)*l,u=s.minY+(i.minY-s.minY)*l,h=s.maxX+(i.maxX-s.maxX)*l;this._setCamera(new x(-c,-u,this.getViewportScreenBounds().width/(h-c)),{force:!0})}_animateToViewport(e,n={animation:Ky}){const{animation:r,...o}=n;if(!r)return;const{duration:s=0,easing:i=Dt.easeInOutCubic}=r,a=this.user.getAnimationSpeed(),l=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),s===0||a===0?this._setCamera(new x(-e.x,-e.y,this.getViewportScreenBounds().width/e.width),{...o}):(this._viewportAnimation={elapsed:0,duration:s/a,easing:i,start:l.clone(),end:e.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(e={}){const{isLocked:n}=this.getCameraOptions();if(n&&!(e!=null&&e.force))return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:o,friction:s=this.options.cameraSlideFriction,direction:i,speedThreshold:a=.01}=e;let l=Math.min(o,1);const c=()=>{this.off("tick",u),this.off("stop-camera-animation",c)};this.once("stop-camera-animation",c);const u=h=>{const{x:p,y:f,z:g}=this.getCamera(),m=x.Mul(i,l*h/g);l*=1-s,l<a?c():this._setCamera(new x(p+m.x,f+m.y,g))};return this.on("tick",u),this}zoomToUser(e,n={animation:{duration:500}}){const r=this.getCollaborators().find(s=>s.userId===e);if(!r)return this;const o=r.cursor;return o?(this.run(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const s=r.currentPageId===this.getCurrentPageId();s||this.setCurrentPage(r.currentPageId),n&&n.animation&&!s&&(n.animation=void 0),this.centerOnPoint(o,n);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,e]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(e);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(e,n=!1){if(e instanceof HTMLElement){const a=e.getBoundingClientRect();e=new Z(a.left||a.x,a.top||a.y,Math.max(a.width,1),Math.max(a.height,1))}else e.width=Math.max(e.width,1),e.height=Math.max(e.height,1);const r=[e.minY!==0,!ui(document.body.scrollWidth,e.maxX,1),!ui(document.body.scrollHeight,e.maxY,1),e.minX!==0],{_willSetInitialBounds:o}=this;this._willSetInitialBounds=!1;const{screenBounds:s,insets:i}=this.getInstanceState();if(e.equals(s)&&r.every((a,l)=>a===i[l]))return this;if(o)this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.setCamera(this.getCamera());else if(n&&!this.getInstanceState().followingUserId){const a=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.centerOnPoint(a)}else this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this._setCamera(x.From({...this.getCamera()}));return this._tickCameraState(),this}getViewportScreenBounds(){const{x:e,y:n,w:r,h:o}=this.getInstanceState().screenBounds;return new Z(e,n,r,o)}getViewportScreenCenter(){const e=this.getViewportScreenBounds();return new x(e.midX-e.minX,e.midY-e.minY)}getViewportPageBounds(){const{w:e,h:n}=this.getViewportScreenBounds(),{x:r,y:o,z:s}=this.getCamera();return new Z(-r,-o,e/s,n/s)}screenToPage(e){const{screenBounds:n}=this.store.unsafeGetWithoutCapture(bn),{x:r,y:o,z:s=1}=this.getCamera();return new x((e.x-n.x)/s-r,(e.y-n.y)/s-o,e.z??.5)}pageToScreen(e){const{screenBounds:n}=this.store.unsafeGetWithoutCapture(bn),{x:r,y:o,z:s=1}=this.getCamera();return new x((e.x+r)*s+n.x,(e.y+o)*s+n.y,e.z??.5)}pageToViewport(e){const{x:n,y:r,z:o=1}=this.getCamera();return new x((e.x+n)*o,(e.y+r)*o,e.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const e=this._getCollaboratorsQuery().get();return e.length?[...new Set(e.map(r=>r.userId))].sort().map(r=>M9(e.filter(s=>s.userId===r),s=>s.lastActivityTimestamp??0)):ps}getCollaboratorsOnCurrentPage(){const e=this.getCurrentPageId();return this.getCollaborators().filter(n=>n.currentPageId===e)}startFollowingUser(e){this.stopFollowingUser();const n=this._getCollaboratorsQuery().get().filter(s=>s.userId===e);if(!n.length)return console.warn("User not found"),this;const r=this.user.getId();if(r||console.warn("You should set the userId for the current instance before following a user"),n.some(s=>s.followingUserId===r))return this;const o=G("latestLeaderPresence",()=>this.getCollaborators().find(s=>s.userId===e));return Oo(()=>{this.updateInstanceState({followingUserId:e},{history:"ignore"});const s=jo("update current page",()=>{const l=o.get();if(!l){this.stopFollowingUser();return}l.currentPageId!==this.getCurrentPageId()&&this.getPage(l.currentPageId)&&this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:l.currentPageId}]),this._isLockedOnFollowingUser.set(!0)},{history:"ignore"})}),i=()=>{s(),this._isLockedOnFollowingUser.set(!1),this.off("frame",a),this.off("stop-following",i)},a=()=>{if(!o.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const c=this.user.getAnimationSpeed();if(c===0){this._isLockedOnFollowingUser.set(!0);return}const u=this.getViewportPageBoundsForFollowing();if(!u){this.stopFollowingUser();return}const h=this.getViewportPageBounds(),p=Math.abs(u.minX-h.minX)+Math.abs(u.maxX-h.maxX),f=Math.abs(u.minY-h.minY)+Math.abs(u.maxY-h.maxY);if(p<this.options.followChaseViewportSnap&&f<this.options.followChaseViewportSnap){this._isLockedOnFollowingUser.set(!0);return}const g=zt(c*.5,.1,.8),m=new Z(_e(h.minX,u.minX,g),_e(h.minY,u.minY,g),_e(h.width,u.width,g),_e(h.height,u.height,g)),v=new x(-m.x,-m.y,this.getViewportScreenBounds().width/m.width);this.stopCameraAnimation(),this._setCamera(v)};this.once("stop-following",i),this.addListener("frame",a),a()}),this}stopFollowingUser(){return this.run(()=>{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")},{history:"ignore"}),this}getUnorderedRenderingShapes(e){const n=[];let r=this.options.maxShapesPerPage*2,o=this.options.maxShapesPerPage;const s=this.getErasingShapeIds(),i=(l,c,u)=>{const h=this.getShape(l);if(!h||this.isShapeHidden(h))return;c*=h.opacity;let p=!1;const f=this.getShapeUtil(h);e&&(p=!u&&s.includes(l),p&&(c*=.32)),n.push({id:l,shape:h,util:f,index:r,backgroundIndex:o,opacity:c}),r+=1,o+=1;const g=this.getSortedChildIdsForParent(l);if(!g.length)return;let m=null;f.providesBackgroundForChildren(h)&&(m=o,o=r,r+=this.options.maxShapesPerPage);for(const v of g)i(v,c,u||p);m!==null&&(o=m)},a=e?[this.getCurrentPage()]:this.getPages();for(const l of a)for(const c of this.getSortedChildIdsForParent(l.id))i(c,1,!1);return n}_decayCameraStateTimeout(e){this._cameraStateTimeoutRemaining-=e,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"))}_tickCameraState(){this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))}getCameraState(){return this._cameraState.get()}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(a7)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return Array.from(this._getAllPagesQuery().get()).sort(cn)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(e){return this.store.get(typeof e=="string"?e:e.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(e){const n=typeof e=="string"?e:e.id,r=this.store.query.exec("shape",{parentId:{eq:n}});return this.getShapeAndDescendantIds(r.map(o=>o.id))}setCurrentPage(e){const n=typeof e=="string"?e:e.id;return this.store.has(n)?(this.stopFollowingUser(),this.complete(),this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:n}]),this.setCamera(this.getCamera())},{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(e){return this.getIsReadonly()?this:this.getPage(e.id)?this.run(()=>this.store.update(e.id,r=>({...r,...e}))):this}createPage(e){return this.run(()=>{if(this.getIsReadonly()||this.getPages().length>=this.options.maxPages)return;const n=this.getPages(),r=XQ(e.name??"Page 1",n.map(i=>i.name));let o=e.index;(!o||n.some(i=>i.index===o))&&(o=Io(n[n.length-1].index));const s=yr.create({meta:{},...e,name:r,index:o});this.store.put([s])}),this}deletePage(e){const n=typeof e=="string"?e:e.id;return this.run(()=>{if(this.getIsReadonly())return;const r=this.getPages();if(r.length===1)return;const o=this.getPage(n);if(o){if(n===this.getCurrentPageId()){const s=r.findIndex(a=>a.id===n),i=r[s-1]??r[s+1];this.setCurrentPage(i.id)}this.store.remove([o.id])}}),this}duplicatePage(e,n=yr.createId()){if(this.getPages().length>=this.options.maxPages)return this;const r=typeof e=="string"?e:e.id,o=this.getPage(r);if(!o)return this;const s={...this.getCamera()},i=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(o.id));return this.run(()=>{var c;const a=this.getPages(),l=$u(o.index,(c=a[a.indexOf(o)+1])==null?void 0:c.index);if(this.createPage({name:o.name+" Copy",id:n,index:l}),this.setCurrentPage(n),this.setCamera(s),i)return this.putContentOntoCurrentPage(i)}),this}renamePage(e,n){const r=typeof e=="string"?e:e.id;return this.getIsReadonly()?this:(this.updatePage({id:r,name:n}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>this.store.put(e),{history:"ignore"}),this)}updateAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>{this.store.put(e.map(n=>({...this.store.get(n.id),...n})))},{history:"ignore"}),this)}deleteAssets(e){if(this.getIsReadonly())return this;const n=typeof e[0]=="string"?e:e.map(r=>r.id);return n.length<=0?this:(this.run(()=>this.store.remove(n),{history:"ignore"}),this)}getAsset(e){return this.store.get(typeof e=="string"?e:e.id)}async resolveAssetUrl(e,n){if(!e)return null;const r=this.getAsset(e);if(!r)return null;const{screenScale:o=1,shouldResolveToOriginal:s=!1}=n,a=Math.max(.125,(u=>Math.pow(2,Math.ceil(Math.log2(u))))(o)),l="connection"in navigator?navigator.connection.effectiveType:null,c=this.getInstanceState().devicePixelRatio;return await this.store.props.assets.resolve(r,{screenScale:o||1,steppedScreenScale:a,dpr:c,networkEffectiveType:l,shouldResolveToOriginal:s})}async uploadAsset(e,n,r){return await this.store.props.assets.upload(e,n,r)}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",e=>this.getShapeUtil(e).getGeometry(e),(e,n)=>e.props===n.props)}getShapeGeometry(e){return this._getShapeGeometryCache().get(typeof e=="string"?e:e.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",e=>{var n,r;return(r=(n=this.getShapeUtil(e)).getHandles)==null?void 0:r.call(n,e)})}getShapeHandles(e){return this._getShapeHandlesCache().get(typeof e=="string"?e:e.id)}getShapeLocalTransform(e){const n=typeof e=="string"?e:e.id,r=this.getShape(n);if(!r)throw Error("Editor.getTransform: shape not found");return q.Identity().translate(r.x,r.y).rotate(r.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",e=>{if(Rn(e.parentId))return this.getShapeLocalTransform(e);const n=this._getShapePageTransformCache().get(e.parentId)??q.Identity();return q.Compose(n,this.getShapeLocalTransform(e))})}getShapeParentTransform(e){const n=typeof e=="string"?e:e.id,r=this.getShape(n);return!r||Rn(r.parentId)?q.Identity():this._getShapePageTransformCache().get(r.parentId)??q.Identity()}getShapePageTransform(e){const n=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(n)??q.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",e=>{const n=this._getShapePageTransformCache().get(e.id);return n?Z.FromPoints(q.applyToPoints(n,this.getShapeGeometry(e).vertices)):new Z})}getShapePageBounds(e){return this._getShapePageBoundsCache().get(typeof e=="string"?e:e.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",e=>{const n=this._getShapeMaskCache().get(e.id);if(!n)return;if(n.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const r=this._getShapePageTransformCache().get(e.id);return r?`polygon(${q.applyToPoints(q.Inverse(r),n).map(s=>`${s.x}px ${s.y}px`).join(",")})`:void 0})}getShapeClipPath(e){return this._getShapeClipPathCache().get(typeof e=="string"?e:e.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",e=>{if(Rn(e.parentId))return;const n=this.getShapeAncestors(e.id).filter(o=>this.isShapeOfType(o,"frame"));return n.length===0?void 0:n.map(o=>this._getShapePageTransformCache().get(o.id).applyToPoints(this.getShapeGeometry(o).vertices)).reduce((o,s)=>{if(!(s&&o))return;const i=CI(o,s);return i?i.map(x.Cast):[]})})}getShapeMask(e){return this._getShapeMaskCache().get(typeof e=="string"?e:e.id)}getShapeMaskedPageBounds(e){return typeof e!="string"&&(e=e.id),this._getShapeMaskedPageBoundsCache().get(e)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",e=>{const n=this._getShapePageBoundsCache().get(e.id);if(!n)return;const r=this._getShapeMaskCache().get(e.id);if(r){if(r.length===0)return;const{corners:o}=n;if(o.every((i,a)=>i&&x.Equals(i,r[a])))return n.clone();const s=CI(r,o);return s?Z.FromPoints(s):void 0}return n})}getShapeAncestors(e,n=[]){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return n;const s=o.parentId;if(Rn(s))return n.reverse(),n;const i=this.store.get(s);return i?(n.push(i),this.getShapeAncestors(i,n)):n}findShapeAncestor(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return;const s=o.parentId;if(Rn(s))return;const i=this.getShape(s);if(i)return n(i)?i:this.findShapeAncestor(i,n)}hasAncestor(e,n){const r=typeof e=="string"?e:e==null?void 0:e.id,o=r&&this.getShape(r);return o?o.parentId===n?!0:this.hasAncestor(this.getShapeParent(o),n):!1}findCommonAncestor(e,n){var l;if(e.length===0)return;const r=typeof e[0]=="string"?e:e.map(c=>c.id),o=me(r.map(c=>this.getShape(c)));if(o.length===1){const c=o[0].parentId;return Rn(c)?void 0:n?(l=this.findShapeAncestor(o[0],n))==null?void 0:l.id:c}const[s,...i]=o;let a=this.getShapeParent(s);for(;a;){if(n&&!n(a)){a=this.getShapeParent(a);continue}if(i.every(c=>this.hasAncestor(c,a.id)))return a.id;a=this.getShapeParent(a)}}isShapeOrAncestorLocked(e){const n=typeof e=="string"?this.getShape(e):e;return n===void 0?!1:n.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(n))}_notVisibleShapes(){return nJ(this)}getCulledShapes(){const e=this._notVisibleShapes().get(),n=this.getSelectedShapeIds(),r=this.getEditingShapeId(),o=new Set(e);return r&&o.delete(r),n.forEach(s=>{o.delete(s)}),o}getCurrentPageBounds(){let e;return this.getCurrentPageShapeIdsSorted().forEach(n=>{const r=this.getShapeMaskedPageBounds(n);r&&(e?e=e.expand(r):e=r.clone())}),e}getSelectedShapeAtPoint(e){const n=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(r=>r.type!=="group"&&n.includes(r.id)).reverse().find(r=>this.isPointInShape(r,e,{hitInside:!0,margin:0}))}getShapeAtPoint(e,n={}){const r=this.getZoomLevel(),o=this.getViewportPageBounds(),{filter:s,margin:i=0,hitLocked:a=!1,hitLabels:l=!1,hitInside:c=!1,hitFrameInside:u=!1}=n;let h=1/0,p=null,f=1/0,g=null;const m=(n.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(v=>{if(v.isLocked&&!a||this.isShapeHidden(v)||this.isShapeOfType(v,"group"))return!1;const y=this.getShapeMask(v);return y&&!hr(e,y)?!1:s?s(v):!0});for(let v=m.length-1;v>=0;v--){const y=m[v],S=this.getShapeGeometry(y),b=S instanceof $r,P=this.getPointInShapeSpace(y,e);if(this.isShapeOfType(y,"frame")||(this.isShapeOfType(y,"arrow")||this.isShapeOfType(y,"geo")&&y.props.fill==="none")&&y.props.text.trim()){for(const _ of S.children)if(_.isLabel&&_.isPointInBounds(P))return y}if(this.isShapeOfType(y,"frame")){const _=S.distanceToPoint(P,c);if(Math.abs(_)<=i)return g||y;if(S.hitTestPoint(P,0,!0))return g||p||(u?y:void 0);continue}let C;if(b){let _=1/0;for(const E of S.children){if(E.isLabel&&!l)continue;const k=E.distanceToPoint(P,c);k<_&&(_=k)}C=_}else i===0&&(S.bounds.w<1||S.bounds.h<1)||S.bounds.containsPoint(P,i)?C=S.distanceToPoint(P,c):C=1/0;if(S.isClosed){if(C<=i){if(S.isFilled||b&&S.children[0].isFilled)return g||y;if(this.getShapePageBounds(y).contains(o))continue;if(Math.abs(C)<i)Math.abs(C)<f&&(f=Math.abs(C),g=y);else if(!g){const{area:_}=S;_<h&&(h=_,p=y)}}}else if(C<this.options.hitTestMargin/r)return y}return g||p||void 0}getShapesAtPoint(e,n={}){return this.getCurrentPageShapes().filter(r=>!this.isShapeHidden(r)&&this.isPointInShape(r,e,n))}isPointInShape(e,n,r={}){const{hitInside:o=!1,margin:s=0}=r,i=typeof e=="string"?e:e.id,a=this.getShapeMask(i);return a&&!hr(n,a)?!1:this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(e,n),s,o)}getPointInShapeSpace(e,n){const r=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(r).clone().invert().applyToPoint(n)}getPointInParentSpace(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return new x(0,0);if(Rn(o.parentId))return x.From(n);const s=this.getShapePageTransform(o.parentId);return s?s.clone().invert().applyToPoint(n):x.From(n)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),e=>this.store.get(e))}getCurrentPageShapesSorted(){const e=[],n=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let r=0,o=n.length;r<o;r++)KR(this,n[r],e);return e}getCurrentPageRenderingShapesSorted(){const e=this.getCulledShapes();return this.getCurrentPageShapesSorted().filter(({id:n})=>!e.has(n)&&!this.isShapeHidden(n))}isShapeOfType(e,n){const r=typeof e=="string"?this.getShape(e):e;return r?r.type===n:!1}getShape(e){const n=typeof e=="string"?e:e.id;if(Fn(n))return this.store.get(n)}getShapeParent(e){const n=typeof e=="string"?e:e==null?void 0:e.id;if(!n)return;const r=this.getShape(n);if(!(r===void 0||!Fn(r.parentId)))return this.store.get(r.parentId)}getShapeNearestSibling(e,n){return n?n.parentId===e.parentId?n:this.findShapeAncestor(n,o=>o.parentId===e.parentId):void 0}isShapeInPage(e,n=this.getCurrentPageId()){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return!1;let s=!1;if(o.parentId===n)s=!0;else{let i=this.getShape(o.parentId);e:for(;i;){if(i.parentId===n){s=!0;break e}i=this.getShape(i.parentId)}}return s}getAncestorPageId(e){const n=typeof e=="string"?e:e==null?void 0:e.id,r=n&&this.getShape(n);if(r)return Rn(r.parentId)?r.parentId:this.getAncestorPageId(this.getShape(r.parentId))}reparentShapes(e,n,r){const o=typeof e[0]=="string"?e:e.map(p=>p.id);if(o.length===0)return this;const s=[],i=Rn(n)?q.Identity():this.getShapePageTransform(n),a=i.rotation();let l=[];const c=me(this.getSortedChildIdsForParent(n).map(p=>this.getShape(p)));if(r){const p=c.find(f=>f.index===r);if(p){const f=c[c.indexOf(p)+1];f?l=Dl(r,f.index,o.length):l=gy(r,o.length)}else{const f=c.sort(cn).find(g=>g.index>r);f?l=Dl(r,f.index,o.length):l=gy(r,o.length)}}else{const p=c.length&&c[c.length-1];l=p?gy(p.index,o.length):Fu(o.length)}const u=i.clone().invert(),h=me(o.map(p=>this.getShape(p)));return this.run(()=>{for(let p=0;p<h.length;p++){const f=h[p],g=this.getShapePageTransform(f);if(!g)continue;const m=g.point();if(!m)continue;const v=u.applyToPoint(m),y=g.rotation()-a;s.push({id:f.id,type:f.type,parentId:n,x:v.x,y:v.y,rotation:y,index:l[p]})}this.updateShapes(s)},{ignoreShapeLock:!0}),this}getHighestIndexForParent(e){const n=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[n];if(!r||r.length===0)return"a1";const o=this.getShape(r[r.length-1]);return Io(o.index)}getSortedChildIdsForParent(e){const n=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[n];return r||ps}visitDescendants(e,n){const r=typeof e=="string"?e:e.id,o=this.getSortedChildIdsForParent(r);for(const s of o)n(s)!==!1&&this.visitDescendants(s,n);return this}getShapeAndDescendantIds(e){const n=new Set;for(const r of e.map(o=>this.getShape(o)).sort(cn))n.add(r.id),this.visitDescendants(r,o=>{n.add(o)});return n}getDroppingOverShape(e,n=[]){const r=this.getCurrentPageShapesSorted();for(let o=r.length-1;o>=0;o--){const s=r[o];if(this.isShapeHidden(s)||this.getSelectedShapeIds().includes(s.id)||!this.getShapeUtil(s).canDropShapes(s,n)||n.find(a=>a.id===s.id||this.hasAncestor(s,a.id)))continue;const i=this.getShapeMaskedPageBounds(s.id);if(i&&i.containsPoint(e)&&this.getShapeGeometry(s).hitTestPoint(this.getPointInShapeSpace(s,e),0,!0))return s}}getOutermostSelectableShape(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);let s=o,i=o;const a=this.getFocusedGroup();for(;i;){if(this.isShapeOfType(i,"group")&&(a==null?void 0:a.id)!==i.id&&!this.hasAncestor(a,i.id)&&((n==null?void 0:n(i))??!0))s=i;else if((a==null?void 0:a.id)===i.id)break;i=this.getShapeParent(i)}return s}_getBindingsIndexCache(){const e=eJ(this);return this.store.createComputedCache("bindingsIndex",n=>e.get().get(n.id))}getBinding(e){return this.store.get(e)}getBindingsFromShape(e,n){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(o=>o.fromId===r&&o.type===n)}getBindingsToShape(e,n){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(o=>o.toId===r&&o.type===n)}getBindingsInvolvingShape(e,n){const r=typeof e=="string"?e:e.id,o=this._getBindingsIndexCache().get(r)??ps;return n?o.filter(s=>s.type===n):o}createBindings(e){const n=[];for(const r of e){const o=this.getShape(r.fromId),s=this.getShape(r.toId);if(!o||!s||!this.canBindShapes({fromShape:o,toShape:s,binding:r}))continue;const a=this.getBindingUtil(r.type).getDefaultProps(),l=this.store.schema.types.binding.create({...r,id:r.id??Qi(),props:{...a,...r.props}});n.push(l)}return this.store.put(n),this}createBinding(e){return this.createBindings([e])}updateBindings(e){const n=[];for(const r of e){if(!r)continue;const o=this.getBinding(r.id);if(!o)continue;const s=So(o,r);if(s===o)continue;const i=this.getShape(s.fromId),a=this.getShape(s.toId);!i||!a||this.canBindShapes({fromShape:i,toShape:a,binding:s})&&n.push(s)}return this.store.put(n),this}updateBinding(e){return this.updateBindings([e])}deleteBindings(e,{isolateShapes:n=!1}={}){const r=e.map(o=>typeof o=="string"?o:o.id);return n?this.store.atomic(()=>{var o,s;for(const i of r){const a=this.getBinding(i);if(!a)continue;const l=this.getBindingUtil(a);(o=l.onBeforeIsolateFromShape)==null||o.call(l,{binding:a,removedShape:this.getShape(a.toId)}),(s=l.onBeforeIsolateToShape)==null||s.call(l,{binding:a,removedShape:this.getShape(a.fromId)}),this.store.remove([i])}}):this.store.remove(r),this}deleteBinding(e,n){return this.deleteBindings([e],n)}canBindShapes({fromShape:e,toShape:n,binding:r}){const o=typeof e=="string"?e:e.type,s=typeof n=="string"?n:n.type,i=typeof r=="string"?r:r.type,a={fromShapeType:o,toShapeType:s,bindingType:i};return o===s?this.getShapeUtil(o).canBind(a):this.getShapeUtil(o).canBind(a)&&this.getShapeUtil(s).canBind(a)}rotateShapesBy(e,n,r){const o=typeof e[0]=="string"?e:e.map(i=>i.id);if(o.length<=0)return this;const s=yO({editor:this,ids:o});return s?(up({delta:n,snapshot:s,editor:this,stage:"one-off",centerOverride:r==null?void 0:r.center}),this):this}getChangesToTranslateShape(e,n){var s,i,a;let r=e;const o=this.getShapeUtil(e);return r=So(r,((s=o.onTranslateStart)==null?void 0:s.call(o,r))??void 0),r=So(r,{id:e.id,type:e.type,x:n.x,y:n.y}),r=So(r,((i=o.onTranslate)==null?void 0:i.call(o,e,r))??void 0),r=So(r,((a=o.onTranslateEnd)==null?void 0:a.call(o,e,r))??void 0),r}nudgeShapes(e,n){const r=typeof e[0]=="string"?e:e.map(s=>s.id);if(r.length<=0)return this;const o=[];for(const s of r){const i=this.getShape(s),a=x.From(n),l=this.getShapeParentTransform(i);l&&a.rot(-l.rotation()),o.push(this.getChangesToTranslateShape(i,a.add(i)))}return this.updateShapes(o),this}duplicateShapes(e,n){return this.run(()=>{const r=typeof e[0]=="string"?e:e.map(p=>p.id);if(r.length<=0)return this;const o=new Set(r),s=this.getShapeAndDescendantIds(r),i=[...s].reverse(),a=new Map;for(const p of s)a.set(p,Ke());const{shapesToCreateWithOriginals:l,bindingsToCreate:c}=NI(this,s,p=>{const f=[];for(const m of p){const v=this.getBinding(m);if(!v)continue;const y=Qi();f.push({...v,id:y,fromId:zn(a.get(v.fromId)),toId:zn(a.get(v.toId))})}const g=[];for(const m of i){const v=zn(a.get(m)),y=this.getShape(m);if(!y)continue;let S=0,b=0;if(n&&o.has(m)){const P=this.getShapeParentTransform(y),C=new x(n.x,n.y).rot(-P.rotation());S=C.x,b=C.y}g.push({shape:{...y,id:v,x:y.x+S,y:y.y+b,index:"a1",parentId:a.get(y.parentId)??y.parentId},originalShape:y})}return{shapesToCreateWithOriginals:g,bindingsToCreate:f}});l.forEach(({shape:p,originalShape:f})=>{const g=f.parentId,m=this.getSortedChildIdsForParent(g),v=m.indexOf(f.id),y=m[v+1],S=y?this.getShape(y):void 0,b=$u(f.index,S==null?void 0:S.index);p.index=b});const u=l.map(({shape:p})=>p);if(u.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage){xh(this);return}if(this.createShapes(u),this.createBindings(c),this.setSelectedShapes(me(r.map(p=>a.get(p)))),n!==void 0){const p=this.getSelectionPageBounds(),f=this.getViewportPageBounds();p&&!f.contains(p)&&this.centerOnPoint(p.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(e,n){const r=typeof e[0]=="string"?e:e.map(a=>a.id);if(r.length===0)return this;if(this.getIsReadonly())return this;const o=this.getCurrentPageId();if(n===o)return this;if(!this.store.has(n))return this;const s=this.getContentFromCurrentPage(r);if(!s)return this;if(this.getPageShapeIds(n).size+s.shapes.length>this.options.maxShapesPerPage)return xh(this,n),this;const i=this.getCamera().z;return this.run(()=>{this.deleteShapes(r),this.setCurrentPage(n),this.setFocusedGroup(null),this.selectNone(),this.putContentOntoCurrentPage(s,{select:!0,preserveIds:!0,preservePosition:!0}),this.setCamera({...this.getCamera(),z:i}),this.centerOnPoint(this.getSelectionRotatedPageBounds().center)}),this}toggleLock(e){const n=typeof e[0]=="string"?e:e.map(i=>i.id);if(this.getIsReadonly()||n.length===0)return this;let r=!0,o=!0;const s=[];for(const i of n){const a=this.getShape(i);a&&(s.push(a),a.isLocked?o=!1:r=!1)}return this.run(()=>{o?(this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!0}))),this.setSelectedShapes([])):r?this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!1}))):this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!0})))}),this}sendToBack(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=Sh(this,"toBack",n,{considerAllShapes:!0});return r&&this.updateShapes(r),this}sendBackward(e,n={}){const r=typeof e[0]=="string"?e:e.map(s=>s.id),o=Sh(this,"backward",r,n);return o&&this.updateShapes(o),this}bringForward(e,n={}){const r=typeof e[0]=="string"?e:e.map(s=>s.id),o=Sh(this,"forward",r,n);return o&&this.updateShapes(o),this}bringToFront(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=Sh(this,"toFront",n);return r&&this.updateShapes(r),this}flipShapes(e,n){const r=typeof e[0]=="string"?e:e.map(i=>i.id);if(this.getIsReadonly())return this;let o=me(r.map(i=>this.getShape(i)));if(!o.length)return this;o=me(o.map(i=>this.isShapeOfType(i,"group")?this.getSortedChildIdsForParent(i.id).map(a=>this.getShape(a)):i).flat());const s=Z.Common(me(o.map(i=>this.getShapePageBounds(i)))).center;return this.run(()=>{for(const i of o){const a=this.getShapeGeometry(i).bounds,l=this.getShapePageTransform(i.id);l&&this.resizeShape(i.id,{x:n==="horizontal"?-1:1,y:n==="vertical"?-1:1},{initialBounds:a,initialPageTransform:l,initialShape:i,mode:"scale_shape",isAspectRatioLocked:this.getShapeUtil(i).isAspectRatioLocked(i),scaleOrigin:s,scaleAxisRotation:0})}}),this}stackShapes(e,n,r){const o=typeof e[0]=="string"?e:e.map(m=>m.id);if(this.getIsReadonly())return this;const s=o.map(m=>this.getShape(m)).filter(m=>m?this.getShapeUtil(m).canBeLaidOut(m):!1),i=s.length;if(r===0&&i<3||i<2)return this;const a=Object.fromEntries(s.map(m=>[m.id,this.getShapePageBounds(m)]));let l,c,u,h;n==="horizontal"?(l="x",c="minX",u="maxX",h="width"):(l="y",c="minY",u="maxY",h="height");let p;if(r===0){const m=[];s.sort((y,S)=>a[y.id][c]-a[S.id][c]);for(let y=0;y<i-1;y++){const S=s[y],b=s[y+1],P=a[S.id],_=a[b.id][c]-P[u],E=m.find(k=>k.gap===_);E?E.count++:m.push({gap:_,count:1})}let v=0;m.forEach(y=>{y.count>v&&(v=y.count,p=y.gap)}),v===1&&(p=Math.max(0,m.reduce((y,S)=>y+S.gap*S.count,0)/(i-1)))}else p=r;const f=[];let g=a[s[0].id][u];return s.forEach((m,v)=>{var C,_;if(v===0)return;const y={x:0,y:0};y[l]=g+p-a[m.id][l];const S=this.getShapeParent(m),b=S?x.Rot(y,-this.getShapePageTransform(S).decompose().rotation):y,P=(_=(C=this.getShapeUtil(m)).onTranslateStart)==null?void 0:_.call(C,m);f.push(P?{...P,[l]:m[l]+b[l]}:{id:m.id,type:m.type,[l]:m[l]+b[l]}),g+=a[m.id][h]+p}),this.updateShapes(f),this}packShapes(e,n){var _,E;const r=typeof e[0]=="string"?e:e.map(k=>k.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=r.map(k=>this.getShape(k)).filter(k=>k?this.getShapeUtil(k).canBeLaidOut(k):!1),s={},i={};let a,l,c=0;for(let k=0;k<o.length;k++)a=o[k],l=this.getShapePageBounds(a),s[a.id]=l,i[a.id]=l.clone(),c+=l.width*l.height;const u=Z.Common(me(Object.values(s))),h=u.width;o.sort((k,D)=>s[D.id].height-s[k.id].height);const p=Math.max(Math.ceil(Math.sqrt(c/.95)),h),f=[new Z(u.x,u.y,p,1/0)];let g=0,m=0,v,y;for(let k=0;k<o.length;k++){a=o[k],l=i[a.id];for(let D=f.length-1;D>=0;D--)if(v=f[D],!(l.width>v.width||l.height>v.height)){l.x=v.x,l.y=v.y,m=Math.max(m,l.maxY),g=Math.max(g,l.maxX),l.width===v.width&&l.height===v.height?(y=f.pop(),D<f.length&&(f[D]=y)):l.height===v.height?(v.x+=l.width+n,v.width-=l.width+n):l.width===v.width?(v.y+=l.height+n,v.height-=l.height+n):(f.push(new Z(v.x+(l.width+n),v.y,v.width-(l.width+n),l.height)),v.y+=l.height+n,v.height-=l.height+n);break}}const S=Z.Common(Object.values(i)),b=x.Sub(u.center,S.center);let P;const C=[];for(let k=0;k<o.length;k++){a=o[k],l=s[a.id],P=i[a.id];const D=x.Sub(P.point,l.point).add(b),T=this.getShapeParentTransform(a);T&&D.rot(-T.rotation());const j={id:a.id,type:a.type,x:a.x+D.x,y:a.y+D.y},$=(E=(_=this.getShapeUtil(a)).onTranslateStart)==null?void 0:E.call(_,{...a,...j});$?C.push({...j,...$}):C.push(j)}return C.length&&this.updateShapes(C),this}alignShapes(e,n){const r=typeof e[0]=="string"?e:e.map(l=>l.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=me(r.map(l=>this.getShape(l))),s=Object.fromEntries(o.map(l=>[l.id,this.getShapePageBounds(l)])),i=Z.Common(me(Object.values(s))),a=[];return o.forEach(l=>{const c=s[l.id];if(!c)return;const u={x:0,y:0};switch(n){case"top":{u.y=i.minY-c.minY;break}case"center-vertical":{u.y=i.midY-c.minY-c.height/2;break}case"bottom":{u.y=i.maxY-c.minY-c.height;break}case"left":{u.x=i.minX-c.minX;break}case"center-horizontal":{u.x=i.midX-c.minX-c.width/2;break}case"right":{u.x=i.maxX-c.minX-c.width;break}}const h=this.getShapeParent(l),p=h?x.Rot(u,-this.getShapePageTransform(h).decompose().rotation):u;a.push(this.getChangesToTranslateShape(l,x.Add(l,p)))}),this.updateShapes(a),this}distributeShapes(e,n){const r=typeof e[0]=="string"?e:e.map(S=>S.id);if(this.getIsReadonly())return this;if(r.length<3)return this;const o=r.length,s=me(r.map(S=>this.getShape(S))),i=Object.fromEntries(s.map(S=>[S.id,this.getShapePageBounds(S)]));let a,l,c,u,h;n==="horizontal"?(a="x",l="minX",c="maxX",u="midX",h="width"):(a="y",l="minY",c="maxY",u="midY",h="height");const p=[],f=s.sort((S,b)=>i[S.id][l]-i[b.id][l])[0],g=s.sort((S,b)=>i[b.id][c]-i[S.id][c])[0],m=i[f.id][u],v=(i[g.id][u]-m)/(o-1),y=m+v;return s.filter(S=>S!==f&&S!==g).sort((S,b)=>i[S.id][u]-i[b.id][u]).forEach((S,b)=>{const P={x:0,y:0};P[a]=y+v*b-i[S.id][h]/2-i[S.id][a];const C=this.getShapeParent(S),_=C?x.Rot(P,-this.getShapePageTransform(C).rotation()):P;p.push(this.getChangesToTranslateShape(S,x.Add(S,_)))}),this.updateShapes(p),this}stretchShapes(e,n){const r=typeof e[0]=="string"?e:e.map(l=>l.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=me(r.map(l=>this.getShape(l))),s=Object.fromEntries(r.map(l=>[l,this.getShapeGeometry(l).bounds])),i=Object.fromEntries(r.map(l=>[l,this.getShapePageBounds(l)])),a=Z.Common(me(Object.values(i)));switch(n){case"vertical":{this.run(()=>{for(const l of o){if(this.getShapePageTransform(l).rotation()%Ne)continue;const u=s[l.id],h=i[l.id],p=new x(0,a.minY-h.minY),f=this.getShapeParentTransform(l);f&&p.rot(-f.rotation());const{x:g,y:m}=x.Add(p,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:m}]);const v=new x(1,a.height/h.height);this.resizeShape(l.id,v,{initialBounds:u,scaleOrigin:new x(h.center.x,a.minY),isAspectRatioLocked:this.getShapeUtil(l).isAspectRatioLocked(l),scaleAxisRotation:0})}});break}case"horizontal":{this.run(()=>{for(const l of o){const c=s[l.id],u=i[l.id];if(this.getShapePageTransform(l).rotation()%Ne)continue;const p=new x(a.minX-u.minX,0),f=this.getShapeParentTransform(l);f&&p.rot(-f.rotation());const{x:g,y:m}=x.Add(p,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:m}]);const v=new x(a.width/u.width,1);this.resizeShape(l.id,v,{initialBounds:c,scaleOrigin:new x(a.minX,u.center.y),isAspectRatioLocked:this.getShapeUtil(l).isAspectRatioLocked(l),scaleAxisRotation:0})}});break}}return this}resizeShape(e,n,r={}){var f,g,m;const o=typeof e=="string"?e:e.id;if(this.getIsReadonly())return this;Number.isFinite(n.x)||(n=new x(1,n.y)),Number.isFinite(n.y)||(n=new x(n.x,1));const s=r.initialShape??this.getShape(o);if(!s)return this;const i=r.scaleOrigin??((f=this.getShapePageBounds(o))==null?void 0:f.center);if(!i)return this;const a=r.initialPageTransform?q.Cast(r.initialPageTransform):this.getShapePageTransform(o);if(!a)return this;const l=a.rotation();if(l==null)return this;const c=r.scaleAxisRotation??l,u=r.initialBounds??this.getShapeGeometry(o).bounds;if(!u)return this;const h=r.isAspectRatioLocked??this.getShapeUtil(s).isAspectRatioLocked(s);if(!lj(l,c))return this._resizeUnalignedShape(o,n,{...r,initialBounds:u,scaleOrigin:i,scaleAxisRotation:c,initialPageTransform:a,isAspectRatioLocked:h,initialShape:s});const p=this.getShapeUtil(s);if(h&&(Math.abs(n.x)>Math.abs(n.y)?n=new x(n.x,Math.sign(n.y)*Math.abs(n.x)):n=new x(Math.sign(n.x)*Math.abs(n.y),n.y)),p.onResize&&p.canResize(s)){const v=this._scalePagePoint(q.applyToPoint(a,new x(0,0)),i,n,c),y=this.getPointInParentSpace(s.id,v),S=new x(n.x,n.y),b=ui((l-c)%Math.PI,0);S.x=b?n.x:n.y,S.y=b?n.y:n.x;const P=q.applyToPoint(a,new x),{x:C,y:_}=this.getPointInParentSpace(s.id,P);let E=s;r.skipStartAndEndCallbacks||(E=So(s,((g=p.onResizeStart)==null?void 0:g.call(p,s))??void 0)),E=So(E,{id:o,type:s.type,x:y.x,y:y.y,...p.onResize({...s,x:C,y:_},{newPoint:y,handle:r.dragHandle??"bottom_right",mode:r.mode??"scale_shape",scaleX:S.x,scaleY:S.y,initialBounds:u,initialShape:s})}),r.skipStartAndEndCallbacks||(E=So(E,((m=p.onResizeEnd)==null?void 0:m.call(p,s,E))??void 0)),this.updateShapes([E])}else{const v=q.applyToPoint(a,u.center),y=this._scalePagePoint(v,i,n,c),S=this.getPointInParentSpace(s.id,v),b=this.getPointInParentSpace(s.id,y),P=x.Sub(b,S);this.updateShapes([{id:o,type:s.type,x:s.x+P.x,y:s.y+P.y}])}return this}_scalePagePoint(e,n,r,o){const s=x.RotWith(e,n,-o).sub(n),i=x.MulV(s,r);return x.Add(i,n).rotWith(n,o)}_resizeUnalignedShape(e,n,r){const{type:o}=r.initialShape,s=new x(n.x,n.y);if(Math.abs(n.x)>Math.abs(n.y)?s.x=Math.sign(n.x)*Math.abs(n.y):s.y=Math.sign(n.y)*Math.abs(n.x),this.resizeShape(e,s,{initialShape:r.initialShape,initialBounds:r.initialBounds,isAspectRatioLocked:r.isAspectRatioLocked}),Math.sign(n.x)*Math.sign(n.y)<0){let{rotation:v}=q.Decompose(r.initialPageTransform);v-=2*v,this.updateShapes([{id:e,type:o,rotation:v}])}const i=q.applyToPoint(r.initialPageTransform,r.initialBounds.center),a=this._scalePagePoint(i,r.scaleOrigin,n,r.scaleAxisRotation),l=this.getShapePageBounds(e),c=this.getShapePageTransform(e),u=l.center,h=c.point();if(!u||!h)return this;const p=x.Sub(a,u),f=x.Add(h,p),{x:g,y:m}=this.getPointInParentSpace(e,f);return this.updateShapes([{id:e,type:o,x:g,y:m}]),this}getInitialMetaForShape(e){return{}}createShape(e){return this.createShapes([e]),this}createShapes(e){if(!Array.isArray(e))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getIsReadonly())return this;if(e.length<=0)return this;const n=this.getCurrentPageShapeIds();if(e.length+n.size>this.options.maxShapesPerPage)return xh(this),this;const o=this.getFocusedGroupId();return this.run(()=>{var u,h;const s=this.getCurrentPageShapesSorted(),i=e.map(p=>{if(p.id||(p={id:Ke(),...p}),!p.parentId||!(this.store.has(p.parentId)||e.some(f=>f.id===p.parentId))){let f=this.getFocusedGroupId();for(let m=s.length-1;m>=0;m--){const v=s[m];if(!this.isShapeHidden(v)&&this.getShapeUtil(v).canReceiveNewChildrenOfType(v,p.type)&&this.isPointInShape(v,{x:p.x??0,y:p.y??0},{margin:0,hitInside:!0})){f=v.id;break}}const g=p.parentId;if(f===p.id&&(f=o),f!==g&&(p={...p},p.parentId=f,Fn(f))){const m=this.getPointInShapeSpace(this.getShape(f),{x:p.x??0,y:p.y??0});p.x=m.x,p.y=m.y,p.rotation=-this.getShapePageTransform(f).rotation()+(p.rotation??0)}}return p}),a=new Map,l=[],{opacityForNextShape:c}=this.getInstanceState();for(const p of i){const f=this.getShapeUtil(p);let g=p.index;if(!g){const S=p.parentId??o;a.has(S)||a.set(S,this.getHighestIndexForParent(S)),g=a.get(S),a.set(S,Io(g))}const m=f.getDefaultProps();for(const[S,b]of this.styleProps[p.type])m[b]=this.getStyleForNextShape(S);let v=this.store.schema.types.shape.create({...p,index:g,opacity:p.opacity??c,parentId:p.parentId??o,props:"props"in p?{...m,...p.props}:m});if(v.index===void 0)throw Error("no index!");const y=(h=(u=this.getShapeUtil(v)).onBeforeCreate)==null?void 0:h.call(u,v);y&&(v=y),l.push(v)}l.forEach(p=>{p.meta={...this.getInitialMetaForShape(p),...p.meta}}),this.store.put(l)}),this}animateShape(e,n={animation:Ky}){return this.animateShapes([e],n)}animateShapes(e,n={animation:Ky}){if(!n.animation)return this;const{duration:r=500,easing:o=Dt.linear}=n.animation,s=ze();let i=r,a;const l=[];let c,u;for(let p=0,f=e.length;p<f;p++){if(c=e[p],!c)continue;const g=this.getShape(c.id);g&&(u={start:tt(g),end:So(tt(g),c)},l.push(u),this.animatingShapes.set(g.id,s))}const h=p=>{var v,y;if(i-=p,i<0){const{animatingShapes:S}=this,b=e.filter(P=>P&&S.get(P.id)===s);b.length&&this.updateShapes(b),this.off("tick",h);return}a=o(1-i/r);const{animatingShapes:f}=this,g=[];let m;for(let S=0,b=l.length;S<b;S++){const{start:P,end:C}=l[S];m=f.get(P.id),m===s&&g.push({...C,x:P.x+(C.x-P.x)*a,y:P.y+(C.y-P.y)*a,opacity:P.opacity+(C.opacity-P.opacity)*a,rotation:P.rotation+(C.rotation-P.rotation)*a,props:((y=(v=this.getShapeUtil(C)).getInterpolatedProps)==null?void 0:y.call(v,P,C,a))??C.props})}this._updateShapes(g)};return this.on("tick",h),this}groupShapes(e,n={}){var g;const{groupId:r=Ke(),select:o=!0}=n;if(!Array.isArray(e))throw Error("Editor.groupShapes: must provide an array of shapes or shape ids");if(this.getIsReadonly())return this;const s=typeof e[0]=="string"?e:e.map(m=>m.id);if(s.length<=1)return this;const i=me((this._shouldIgnoreShapeLock?s:this._getUnlockedShapeIds(s)).map(m=>this.getShape(m))),a=i.sort(cn).map(m=>m.id),l=Z.Common(me(i.map(m=>this.getShapePageBounds(m)))),{x:c,y:u}=l.point,h=this.findCommonAncestor(i)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const p=i.filter(m=>m.parentId===h).sort(cn),f=(g=p[p.length-1])==null?void 0:g.index;return this.run(()=>{this.createShapes([{id:r,type:"group",parentId:h,index:f,x:c,y:u,opacity:1,props:{}}]),this.reparentShapes(a,r),o&&this.select(r)}),this}ungroupShapes(e,n={}){if(this.getIsReadonly())return this;const{select:r=!0}=n,o=typeof e[0]=="string"?e:e.map(l=>l.id),s=me((this._shouldIgnoreShapeLock?o:this._getUnlockedShapeIds(o)).map(l=>this.getShape(l)));if(s.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const i=new Set,a=[];return s.forEach(l=>{this.isShapeOfType(l,"group")?a.push(l):i.add(l.id)}),a.length===0?this:(this.run(()=>{let l;for(let c=0,u=a.length;c<u;c++){l=a[c];const h=this.getSortedChildIdsForParent(l.id);for(let p=0,f=h.length;p<f;p++)i.add(h[p]);this.reparentShapes(h,l.parentId,l.index)}this.deleteShapes(a.map(c=>c.id)),r&&this.select(...i)}),this)}updateShape(e){return this.updateShapes([e]),this}updateShapes(e){const n=Array(e.length);for(let r=0,o=e.length;r<o;r++){const s=e[r];if(!s)continue;const i=this.getShape(s.id);if(i){if(!this._shouldIgnoreShapeLock){if(i.isLocked){if(!(Object.hasOwn(s,"isLocked")&&!s.isLocked))continue}else if(this.isShapeOrAncestorLocked(i))continue}this.animatingShapes.delete(s.id),n.push(s)}}return this._updateShapes(n),this}_updateShapes(e){this.getIsReadonly()||this.run(()=>{var s,i;const n=[];let r,o;for(let a=0,l=e.length;a<l;a++){const c=e[a];c&&(r=this.getShape(c.id),r&&(o=So(r,c),o!==r&&(o=((i=(s=this.getShapeUtil(r)).onBeforeUpdate)==null?void 0:i.call(s,r,o))??o,n.push(o))))}this.store.put(n)})}_getUnlockedShapeIds(e){return e.filter(n=>{var r;return!((r=this.getShape(n))!=null&&r.isLocked)})}deleteShapes(e){if(this.getIsReadonly())return this;if(!Array.isArray(e))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const n=typeof e[0]=="string"?e:e.map(s=>s.id),r=this._shouldIgnoreShapeLock?n:this._getUnlockedShapeIds(n);if(r.length===0)return this;const o=new Set(r);for(const s of r)this.visitDescendants(s,i=>{o.add(i)});return this.run(()=>this.store.remove([...o]))}deleteShape(e){return this.deleteShapes([typeof e=="string"?e:e.id]),this}_extractSharedStyles(e,n){if(this.isShapeOfType(e,"group")){const r=this._parentIdsToChildIds.get()[e.id];if(!r)return;for(let o=0,s=r.length;o<s;o++)this._extractSharedStyles(this.getShape(r[o]),n)}else for(const[r,o]of this.styleProps[e.type])n.applyValue(r,hn(e.props,o))}_getSelectionSharedStyles(){const e=this.getSelectedShapes(),n=new Tx;for(const r of e)this._extractSharedStyles(r,n);return n}getStyleForNextShape(e){const n=this.getInstanceState().stylesForNextShape[e.id];return n===void 0?e.defaultValue:n}getShapeStyleIfExists(e,n){const r=this.styleProps[e.type].get(n);if(r!==void 0)return hn(e.props,r)}getSharedStyles(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0)return this._getSelectionSharedStyles();const e=this.root.getCurrent(),n=new Tx;if(!e)return n;if(e.shapeType)for(const r of this.styleProps[e.shapeType].keys())n.applyValue(r,this.getStyleForNextShape(r));return n}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const e=[],n=o=>{const s=this.getShape(o);if(s)if(this.isShapeOfType(s,"group"))for(const i of this.getSortedChildIdsForParent(s.id))n(i);else e.push(s)};for(const o of this.getSelectedShapeIds())n(o);let r=null;for(const o of e)if(r===null)r=o.opacity;else if(r!==o.opacity)return{type:"mixed"};if(r!==null)return{type:"shared",value:r}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(e,n){return this.updateInstanceState({opacityForNextShape:e},n),this}setOpacityForSelectedShapes(e){const n=this.getSelectedShapes();if(n.length>0){const r=[],o=s=>{if(this.isShapeOfType(s,"group")){const i=this.getSortedChildIdsForParent(s);for(const a of i)o(this.getShape(a))}else r.push(s)};for(const s of n)o(s);this.updateShapes(r.map(s=>({id:s.id,type:s.type,opacity:e})))}return this}setStyleForNextShapes(e,n,r){const o=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...o,[e.id]:n}},r),this}setStyleForSelectedShapes(e,n){const r=this.getSelectedShapes();if(r.length>0){const o=[],s=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i.id);for(const l of a)s(this.getShape(l))}else{const a=this.getShapeUtil(i),l=this.styleProps[i.type].get(e);if(l){const c={id:i.id,type:i.type,props:{[l]:n}};o.push({util:a,originalShape:i,updatePartial:c})}}};for(const i of r)s(i);this.updateShapes(o.map(({updatePartial:i})=>i))}return this}registerExternalAssetHandler(e,n){return this.externalAssetContentHandlers[e]=n,this}createTemporaryAssetPreview(e,n){if(this.temporaryAssetPreview.has(e))return this.temporaryAssetPreview.get(e);const r=URL.createObjectURL(n);return this.temporaryAssetPreview.set(e,r),setTimeout(()=>{this.temporaryAssetPreview.delete(e),URL.revokeObjectURL(r)},this.options.temporaryAssetPreviewLifetimeMs),r}getTemporaryAssetPreview(e){return this.temporaryAssetPreview.get(e)}async getAssetForExternalContent(e){var n,r;return await((r=(n=this.externalAssetContentHandlers)[e.type])==null?void 0:r.call(n,e))}hasExternalAssetHandler(e){return!!this.externalAssetContentHandlers[e]}registerExternalContentHandler(e,n){return this.externalContentHandlers[e]=n,this}async putExternalContent(e){var n,r;return(r=(n=this.externalContentHandlers)[e.type])==null?void 0:r.call(n,e)}getContentFromCurrentPage(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id);if(!n||n.length===0)return;const r=this.getShapeAndDescendantIds(n);return NI(this,r,o=>{const s=[];for(const u of o){const h=this.getBinding(u);h&&s.push(h)}const i=[],a=[];for(const u of r){const h=this.getShape(u);if(!h)continue;if(!r.has(h.parentId)){const f=this.getShapePageTransform(h.id),g=f.point();a.push({...h,x:g.x,y:g.y,rotation:f.rotation(),parentId:this.getCurrentPageId()}),i.push(h.id)}else a.push(h)}const l=[],c=new Set;for(const u of a){if(!("assetId"in u.props))continue;const h=u.props.assetId;if(!h||c.has(h))continue;c.add(h);const p=this.getAsset(h);p&&l.push(p)}return{schema:this.store.schema.serialize(),shapes:a,rootShapeIds:i,bindings:s,assets:l}})}async resolveAssetsInContent(e){if(!e)return;const n=[];return await Promise.allSettled(e.assets.map(async r=>{var o,s,i;if((r.type==="image"||r.type==="video")&&!((o=r.props.src)!=null&&o.startsWith("data:image"))&&!((s=r.props.src)!=null&&s.startsWith("data:video"))&&!((i=r.props.src)!=null&&i.startsWith("http"))){const a=tt(r),l=await this.store.props.assets.resolve(r,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginal:!0});a.props.src=await Zr.blobToDataUrl(await Lo(l).then(c=>c.blob())),n.push(a)}else n.push(r)})),e.assets=n,e}putContentOntoCurrentPage(e,n={}){var T,j,$;if(this.getIsReadonly())return this;if(!e.schema)throw Error(`Could not put content:
105
+ `&&(f=0),h=E,p=b,c+=v.length}return u&&r.push(u),{spans:r,didTruncate:g}}measureTextSpans(e,n){if(e==="")return[];const r=this.baseElem.cloneNode();this.editor.getContainer().appendChild(r);const o=Math.ceil(n.width-n.padding*2);r.setAttribute("dir","auto"),r.style.setProperty("unicode-bidi","plaintext"),r.style.setProperty("width",`${o}px`),r.style.setProperty("height","min-content"),r.style.setProperty("font-size",`${n.fontSize}px`),r.style.setProperty("font-family",n.fontFamily),r.style.setProperty("font-weight",n.fontWeight),r.style.setProperty("line-height",`${n.lineHeight*n.fontSize}px`),r.style.setProperty("text-align",XJ[n.textAlign]);const s=n.overflow==="truncate-ellipsis"||n.overflow==="truncate-clip";s&&(r.style.setProperty("overflow-wrap","anywhere"),r.style.setProperty("word-break","break-all"));const i=LI(e);r.textContent=i;const{spans:a,didTruncate:l}=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:s});if(n.overflow==="truncate-ellipsis"&&l){r.textContent="…";const c=Math.ceil(this.measureElementTextNodeSpans(r).spans[0].box.w);r.style.setProperty("width",`${o-c}px`),r.textContent=i;const u=this.measureElementTextNodeSpans(r,{shouldTruncateToFirstLine:!0}).spans,h=u[u.length-1];return u.push({text:"…",box:{x:Math.min(h.box.x+h.box.w,n.width-n.padding-c),y:h.box.y,w:c,h:h.box.h}}),u}return r.remove(),a}}var QJ=Object.create,XO=Object.defineProperty,JJ=Object.getOwnPropertyDescriptor,eee=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),qO=t=>{throw TypeError(t)},ZO=(t,e,n)=>e in t?XO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,tee=t=>[,,,QJ(null)],QO=["class","method","getter","setter","accessor","field","value","get","set"],JO=t=>t!==void 0&&typeof t!="function"?qO("Function expected"):t,nee=(t,e,n,r,o)=>({kind:QO[t],name:e,metadata:r,addInitializer:s=>n._?qO("Already initialized"):o.push(JO(s||null))}),ree=(t,e)=>ZO(e,eee("metadata"),t[3]),oee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},eD=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=QO[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,JJ(o,n)),y=r.length-1;y>=0;y--)l=nee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,JO(i)&&(v[g]=i);return v&&XO(o,n,v),o},vh=(t,e,n)=>ZO(t,typeof e!="symbol"?e+"":e,n),tD,nD,vd;const $I=tM;nD=[Kn],tD=[Kn];class Yg{constructor(e){this.editor=e,oee(vd,5,this),vh(this,"cancelRaf"),vh(this,"isPaused",!0),vh(this,"now",0),vh(this,"prevPoint",new x),this.editor.disposables.add(this.dispose),this.start()}start(){var e;this.isPaused=!1,(e=this.cancelRaf)==null||e.call(this),this.cancelRaf=$I(this.tick),this.now=Date.now()}tick(){if(this.isPaused)return;const e=Date.now(),n=e-this.now;this.now=e,this.updatePointerVelocity(n),this.editor.emit("frame",n),this.editor.emit("tick",n),this.cancelRaf=$I(this.tick)}dispose(){var e;this.isPaused=!0,(e=this.cancelRaf)==null||e.call(this)}updatePointerVelocity(e){const{prevPoint:n,editor:{inputs:{currentScreenPoint:r,pointerVelocity:o}}}=this;if(e===0)return;const s=x.Sub(r,n);this.prevPoint=r.clone();const i=s.len(),a=i?s.div(i):new x(0,0),l=o.clone().lrp(a.mul(i/e),.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)}}vd=tee();eD(vd,1,"tick",nD,Yg);eD(vd,1,"dispose",tD,Yg);ree(vd,Yg);var see=Object.create,rD=Object.defineProperty,iee=Object.getOwnPropertyDescriptor,aee=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),oD=t=>{throw TypeError(t)},sD=(t,e,n)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lee=t=>[,,,see(null)],iD=["class","method","getter","setter","accessor","field","value","get","set"],aD=t=>t!==void 0&&typeof t!="function"?oD("Function expected"):t,cee=(t,e,n,r,o)=>({kind:iD[t],name:e,metadata:r,addInitializer:s=>n._?oD("Already initialized"):o.push(aD(s||null))}),uee=(t,e)=>sD(e,aee("metadata"),t[3]),dee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Nr=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=iD[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,iee(o,n)),y=r.length-1;y>=0;y--)l=cee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,aD(i)&&(v[g]=i);return v&&rD(o,n,v),o},FI=(t,e,n)=>sD(t,typeof e!="symbol"?e+"":e,n),lD,cD,uD,dD,hD,pD,fD,gD,mD,yD,SD,vD,Mn;vD=[G],SD=[G],yD=[G],mD=[G],gD=[G],fD=[G],pD=[G],hD=[G],dD=[G],uD=[G],cD=[G],lD=[G];class Qn{constructor(e,n){if(this.user=e,this.inferDarkMode=n,dee(Mn,5,this),FI(this,"systemColorScheme",Et("systemColorScheme","light")),FI(this,"disposables",new Set),typeof window>"u"||!("matchMedia"in window))return;const r=window.matchMedia("(prefers-color-scheme: dark)");r!=null&&r.matches&&this.systemColorScheme.set("dark");const o=s=>{s.matches?this.systemColorScheme.set("dark"):this.systemColorScheme.set("light")};r==null||r.addEventListener("change",o),this.disposables.add(()=>r==null?void 0:r.removeEventListener("change",o))}dispose(){this.disposables.forEach(e=>e())}updateUserPreferences(e){this.user.setUserPreferences({...this.user.userPreferences.get(),...e})}getUserPreferences(){return{id:this.getId(),name:this.getName(),locale:this.getLocale(),color:this.getColor(),animationSpeed:this.getAnimationSpeed(),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??xo.edgeScrollSpeed}getAnimationSpeed(){return this.user.userPreferences.get().animationSpeed??xo.animationSpeed}getId(){return this.user.userPreferences.get().id}getName(){return this.user.userPreferences.get().name??xo.name}getLocale(){return this.user.userPreferences.get().locale??xo.locale}getColor(){return this.user.userPreferences.get().color??xo.color}getIsSnapMode(){return this.user.userPreferences.get().isSnapMode??xo.isSnapMode}getIsWrapMode(){return this.user.userPreferences.get().isWrapMode??xo.isWrapMode}getIsDynamicResizeMode(){return this.user.userPreferences.get().isDynamicSizeMode??xo.isDynamicSizeMode}getIsPasteAtCursorMode(){return this.user.userPreferences.get().isPasteAtCursorMode??xo.isPasteAtCursorMode}}Mn=lee();Nr(Mn,1,"getUserPreferences",vD,Qn);Nr(Mn,1,"getIsDarkMode",SD,Qn);Nr(Mn,1,"getEdgeScrollSpeed",yD,Qn);Nr(Mn,1,"getAnimationSpeed",mD,Qn);Nr(Mn,1,"getId",gD,Qn);Nr(Mn,1,"getName",fD,Qn);Nr(Mn,1,"getLocale",pD,Qn);Nr(Mn,1,"getColor",hD,Qn);Nr(Mn,1,"getIsSnapMode",dD,Qn);Nr(Mn,1,"getIsWrapMode",uD,Qn);Nr(Mn,1,"getIsDynamicResizeMode",cD,Qn);Nr(Mn,1,"getIsPasteAtCursorMode",lD,Qn);uee(Mn,Qn);const hee={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"},pee=["brushing","cropping","dragging","dragging_handle","drawing","erasing","lasering","resizing","rotating","scribble_brushing","translating"];class ie{constructor(e,n){I(this,"performanceTracker");I(this,"id");I(this,"type");I(this,"shapeType");I(this,"initial");I(this,"children");I(this,"isLockable");I(this,"parent");I(this,"_path");I(this,"_current");I(this,"_isActive");I(this,"_currentToolIdMask",Et("curent tool id mask",void 0));this.editor=e;const{id:r,children:o,initial:s,isLockable:i}=this.constructor;this.id=r,this._isActive=Et("toolIsActive"+this.id,!1),this._current=Et("toolState"+this.id,void 0),this._path=G("toolPath"+this.id,()=>{const a=this.getCurrent();return this.id+(a?`.${a.getPath()}`:"")}),this.parent=n??{},this.parent?o&&s?(this.type="branch",this.initial=s,this.children=Object.fromEntries(o().map(a=>[a.id,new a(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(a=>[a.id,new a(this.editor,this)])),this._current.set(this.children[this.initial]))),this.isLockable=i,this.performanceTracker=new DT}getPath(){return this._path.get()}getCurrent(){return this._current.get()}getIsActive(){return this._isActive.get()}transition(e,n={}){var s;const r=e.split(".");let o=this;for(let i=0;i<r.length;i++){const a=r[i],l=o.getCurrent(),c=(s=o.children)==null?void 0:s[a];if(!c)throw Error(`${o.id} - no child state exists with the id ${a}.`);if((l==null?void 0:l.id)!==c.id&&(l==null||l.exit(n,a),o._current.set(c),c.enter(n,(l==null?void 0:l.id)||"initial"),!c.getIsActive()))break;o=c}return this}handleEvent(e){var o;const n=hee[e.name],r=this._current.__unsafe__getWithoutCapture();(o=this[n])==null||o.call(this,e),this._isActive.__unsafe__getWithoutCapture()&&r&&r===this._current.__unsafe__getWithoutCapture()&&r.handleEvent(e)}enter(e,n){var r;if(bt.measurePerformance.get()&&pee.includes(this.id)&&this.performanceTracker.start(this.id),this._isActive.set(!0),(r=this.onEnter)==null||r.call(this,e,n),this.children&&this.initial&&this.getIsActive()){const o=this.children[this.initial];this._current.set(o),o.enter(e,n)}}exit(e,n){var r,o;bt.measurePerformance.get()&&this.performanceTracker.isStarted()&&this.performanceTracker.stop(),this._isActive.set(!1),(r=this.onExit)==null||r.call(this,e,n),this.getIsActive()||(o=this.getCurrent())==null||o.exit(e,n)}getCurrentToolIdMask(){return this._currentToolIdMask.get()}setCurrentToolIdMask(e){this._currentToolIdMask.set(e)}}I(ie,"id"),I(ie,"initial"),I(ie,"children"),I(ie,"isLockable",!0);class Mx extends ie{static children(){return[]}onKeyDown(e){var n;switch(e.code){case"KeyZ":{if(!(e.shiftKey||e.ctrlKey)){const r=this.getCurrent();r&&((n=r.getCurrent())==null?void 0:n.id)==="idle"&&this.children.zoom&&this.editor.setCurrentTool("zoom",{...e,onInteractionEnd:r.id})}break}}}}I(Mx,"id","root"),I(Mx,"initial","");var fee=Object.create,xD=Object.defineProperty,gee=Object.getOwnPropertyDescriptor,wD=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),bD=t=>{throw TypeError(t)},PD=(t,e,n)=>e in t?xD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mee=t=>[,,,fee((t==null?void 0:t[wD("metadata")])??null)],CD=["class","method","getter","setter","accessor","field","value","get","set"],_D=t=>t!==void 0&&typeof t!="function"?bD("Function expected"):t,yee=(t,e,n,r,o)=>({kind:CD[t],name:e,metadata:r,addInitializer:s=>n._?bD("Already initialized"):o.push(_D(s||null))}),See=(t,e)=>PD(e,wD("metadata"),t[3]),vee=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},te=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=CD[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,gee(o,n)),y=r.length-1;y>=0;y--)l=yee(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,_D(i)&&(v[g]=i);return v&&xD(o,n,v),o},de=(t,e,n)=>PD(t,typeof e!="symbol"?e+"":e,n),ID,ED,kD,TD,MD,AD,jD,OD,DD,RD,LD,$D,FD,ND,zD,BD,UD,HD,KD,WD,GD,VD,YD,XD,qD,ZD,QD,JD,eR,tR,nR,rR,oR,sR,iR,aR,lR,cR,uR,dR,hR,pR,fR,gR,mR,yR,SR,vR,xR,wR,bR,PR,CR,_R,IR,ER,kR,TR,MR,AR,jR,OR,DR,RR,LR,$R,FR,NR,zR,BR,UR,HR,Ax,J;class Q extends(Ax=BZ,HR=[G],UR=[G],BR=[G],zR=[G],NR=[G],FR=[G],$R=[G],LR=[G],RR=[G],DR=[G],OR=[G],jR=[G],AR=[G],MR=[G],TR=[G],kR=[G],ER=[G],IR=[G],_R=[G],CR=[G],PR=[G],bR=[G],wR=[G],xR=[G],vR=[G],SR=[G],yR=[G],mR=[G],gR=[G],fR=[G],pR=[G],hR=[G],dR=[G],uR=[G],cR=[G],lR=[G],aR=[G],iR=[G],sR=[G],oR=[G],rR=[G],nR=[G],tR=[G],eR=[G],JD=[G],QD=[G],ZD=[G],qD=[G],XD=[G],YD=[G],VD=[G],GD=[G],WD=[G],KD=[G],HD=[G],UD=[G],BD=[G],zD=[G],ND=[G],FD=[G],$D=[G],LD=[G],RD=[G],DD=[G],OD=[G({isEqual:(e,n)=>e.equals(n)})],jD=[G],AD=[G],MD=[G],TD=[Kn],kD=[Kn],ED=[Kn],ID=[Kn],Ax){constructor({store:e,user:n,shapeUtils:r,bindingUtils:o,tools:s,getContainer:i,cameraOptions:a,initialState:l,autoFocus:c,inferDarkMode:u,options:h,isShapeHidden:p}){var D;super(),vee(J,5,this),de(this,"_isShapeHiddenPredicate"),de(this,"options"),de(this,"contextId",ze()),de(this,"store"),de(this,"root"),de(this,"disposables",new Set),de(this,"isDisposed",!1),de(this,"_tickManager"),de(this,"snaps"),de(this,"timers",kx.forContext(this.contextId)),de(this,"user"),de(this,"textMeasure"),de(this,"environment",Ge),de(this,"scribbles"),de(this,"sideEffects"),de(this,"edgeScrollManager"),de(this,"focusManager"),de(this,"getContainer"),de(this,"shapeUtils"),de(this,"styleProps"),de(this,"bindingUtils"),de(this,"history"),de(this,"_shouldIgnoreShapeLock",!1),de(this,"_crashingError",null),de(this,"_isChangingStyleTimeout",-1),de(this,"menus",Vr.forContext(this.contextId)),de(this,"_cameraOptions",Et("camera options",rI)),de(this,"_viewportAnimation",null),de(this,"_willSetInitialBounds",!0),de(this,"_isLockedOnFollowingUser",Et("isLockedOnFollowingUser",!1)),de(this,"_cameraState",Et("camera state","idle")),de(this,"_cameraStateTimeoutRemaining",0),de(this,"_currentPageShapeIds"),de(this,"_parentIdsToChildIds"),de(this,"animatingShapes",new Map),de(this,"externalAssetContentHandlers",{file:null,url:null}),de(this,"temporaryAssetPreview",new Map),de(this,"externalContentHandlers",{text:null,files:null,embed:null,"svg-text":null,url:null}),de(this,"inputs",{originPagePoint:new x,originScreenPoint:new x,previousPagePoint:new x,previousScreenPoint:new x,currentPagePoint:new x,currentScreenPoint:new x,keys:new Set,buttons:new Set,isPen:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,altKey:!1,isDragging:!1,isPointing:!1,isPinching:!1,isEditing:!1,isPanning:!1,isSpacebarPanning:!1,pointerVelocity:new x}),de(this,"_clickManager",new Wg(this)),de(this,"_prevCursor","default"),de(this,"_shiftKeyTimeout",-1),de(this,"_altKeyTimeout",-1),de(this,"_ctrlKeyTimeout",-1),de(this,"_metaKeyTimeout",-1),de(this,"_restoreToolId","select"),de(this,"_pinchStart",1),de(this,"_didPinch",!1),de(this,"_selectedShapeIdsAtPointerDown",[]),de(this,"_longPressTimeout",-1),de(this,"capturedPointerId",null),de(this,"performanceTracker"),de(this,"performanceTrackerTimeout",-1),de(this,"_pendingEventsForNextTick",[]),this._isShapeHiddenPredicate=p,this.options={...HQ,...h},this.store=e,this.disposables.add(this.store.dispose.bind(this.store)),this.history=new yJ({store:e,annotateError:T=>{this.annotateError(T,{origin:"history.batch",willCrashApp:!0}),this.crash(T)}}),this.snaps=new Sd(this),this.disposables.add(this.timers.dispose),this._cameraOptions.set({...rI,...a}),this.user=new Qn(n??Bj(),u??!1),this.disposables.add(()=>this.user.dispose()),this.getContainer=i,this.textMeasure=new ZJ(this),this._tickManager=new Yg(this);class f extends Mx{}I(f,"initial",l??""),this.root=new f(this),this.root.children={};const g=Xj(r),m={},v={},y=new Map;for(const T of g){const j=new T(this);m[T.type]=j;const $=xA(T.props??{});v[T.type]=$;for(const M of $.keys())if(!y.has(M.id))y.set(M.id,M);else if(y.get(M.id)!==M)throw Error(`Multiple style props with id "${M.id}" in use. Style prop IDs must be unique.`)}this.shapeUtils=m,this.styleProps=v;const S=Vj(o),b={};for(const T of S){const j=new T(this);b[T.type]=j}this.bindingUtils=b;for(const T of[...s]){if(no(this.root.children,T.id))throw Error(`Can't override tool with id "${T.id}"`);this.root.children[T.id]=new T(this,this.root)}this.scribbles=new xJ(this);const P=(T,j)=>{let $=null;const M=T.selectedShapeIds.filter(B=>!j.has(B));M.length!==T.selectedShapeIds.length&&($||($={...T}),$.selectedShapeIds=M);const O=T.erasingShapeIds.filter(B=>!j.has(B));O.length!==T.erasingShapeIds.length&&($||($={...T}),$.erasingShapeIds=O),T.hoveredShapeId&&j.has(T.hoveredShapeId)&&($||($={...T}),$.hoveredShapeId=null),T.editingShapeId&&j.has(T.editingShapeId)&&($||($={...T}),$.editingShapeId=null);const F=T.hintingShapeIds.filter(B=>!j.has(B));return F.length!==T.hintingShapeIds.length&&($||($={...T}),$.hintingShapeIds=F),T.focusedGroupId&&j.has(T.focusedGroupId)&&($||($={...T}),$.focusedGroupId=null),$};this.sideEffects=this.store.sideEffects;let C=new Map;const _=new Set,E=new Set;let k=new Set;if(this.disposables.add(this.sideEffects.registerOperationCompleteHandler(()=>{var T,j,$,M;_.clear();for(const O of E){E.delete(O);const F=this.getShape(O);if(!F)continue;const B=this.getShapeUtil(F),K=(T=B.onChildrenChange)==null?void 0:T.call(B,F);K!=null&&K.length&&this.updateShapes(K)}if(k.size){const O=k;k=new Set;for(const F of O){const B=this.getBindingUtil(F);(j=B.onOperationComplete)==null||j.call(B)}}if(C.size){const O=C;C=new Map;for(const F of O.values())(M=($=this.getBindingUtil(F.binding)).onAfterDelete)==null||M.call($,F)}this.emit("update")})),this.disposables.add(this.sideEffects.register({shape:{afterChange:(T,j)=>{var $,M,O,F;for(const B of this.getBindingsInvolvingShape(j))k.add(B.type),B.fromId===j.id&&((M=($=this.getBindingUtil(B)).onAfterChangeFromShape)==null||M.call($,{binding:B,shapeBefore:T,shapeAfter:j})),B.toId===j.id&&((F=(O=this.getBindingUtil(B)).onAfterChangeToShape)==null||F.call(O,{binding:B,shapeBefore:T,shapeAfter:j}));if(T.parentId!==j.parentId){const B=K=>{var H,Y,ee,he;const R=this.getShape(K);if(R)for(const ue of this.getBindingsInvolvingShape(R))k.add(ue.type),ue.fromId===R.id&&((Y=(H=this.getBindingUtil(ue)).onAfterChangeFromShape)==null||Y.call(H,{binding:ue,shapeBefore:R,shapeAfter:R})),ue.toId===R.id&&((he=(ee=this.getBindingUtil(ue)).onAfterChangeToShape)==null||he.call(ee,{binding:ue,shapeBefore:R,shapeAfter:R}))};B(j.id),this.visitDescendants(j.id,B)}if(T.parentId!==j.parentId&&Rn(j.parentId)){const B=new Set([T.id]);this.visitDescendants(T.id,K=>{B.add(K)});for(const K of this.getPageStates()){if(K.pageId===j.parentId)continue;const R=P(K,B);R&&this.store.put([R])}}T.parentId&&Fn(T.parentId)&&E.add(T.parentId),j.parentId!==T.parentId&&Fn(j.parentId)&&E.add(j.parentId)},beforeDelete:T=>{var O,F,B,K;if(_.has(T.id))return;T.parentId&&Fn(T.parentId)&&E.add(T.parentId),_.add(T.id);const j=[];for(const R of this.getBindingsInvolvingShape(T)){k.add(R.type),j.push(R.id);const H=this.getBindingUtil(R);R.fromId===T.id?((O=H.onBeforeIsolateToShape)==null||O.call(H,{binding:R,removedShape:T}),(F=H.onBeforeDeleteFromShape)==null||F.call(H,{binding:R,shape:T})):((B=H.onBeforeIsolateFromShape)==null||B.call(H,{binding:R,removedShape:T}),(K=H.onBeforeDeleteToShape)==null||K.call(H,{binding:R,shape:T}))}j.length&&this.deleteBindings(j);const $=new Set([T.id]),M=me(this.getPageStates().map(R=>P(R,$)));M.length&&this.store.put(M)}},binding:{beforeCreate:T=>{var $,M;const j=(M=($=this.getBindingUtil(T)).onBeforeCreate)==null?void 0:M.call($,{binding:T});return j||T},afterCreate:T=>{var j,$;k.add(T.type),($=(j=this.getBindingUtil(T)).onAfterCreate)==null||$.call(j,{binding:T})},beforeChange:(T,j)=>{var M,O;const $=(O=(M=this.getBindingUtil(j)).onBeforeChange)==null?void 0:O.call(M,{bindingBefore:T,bindingAfter:j});return $||j},afterChange:(T,j)=>{var $,M;k.add(j.type),(M=($=this.getBindingUtil(j)).onAfterChange)==null||M.call($,{bindingBefore:T,bindingAfter:j})},beforeDelete:T=>{var j,$;($=(j=this.getBindingUtil(T)).onBeforeDelete)==null||$.call(j,{binding:T})},afterDelete:T=>{var j,$;($=(j=this.getBindingUtil(T)).onAfterDelete)==null||$.call(j,{binding:T}),k.add(T.type)}},page:{afterCreate:T=>{const j=Eo.createId(T.id),$=Qr.createId(T.id);this.store.has(j)||this.store.put([Eo.create({id:j})]),this.store.has($)||this.store.put([Qr.create({id:$,pageId:T.id})])},afterDelete:(T,j)=>{var O,F;if(((O=this.getInstanceState())==null?void 0:O.currentPageId)===T.id){const B=(F=this.getPages().find(K=>K.id!==T.id))==null?void 0:F.id;B?this.store.put([{...this.getInstanceState(),currentPageId:B}]):j==="user"&&this.store.ensureStoreIsUsable()}const $=Eo.createId(T.id),M=Qr.createId(T.id);this.store.remove([$,M])}},instance:{afterChange:(T,j,$)=>{var M;if(!this.store.has(j.currentPageId)){const O=this.store.has(T.currentPageId)?T.currentPageId:(M=this.getPages()[0])==null?void 0:M.id;O?this.store.update(j.id,F=>({...F,currentPageId:O})):$==="user"&&this.store.ensureStoreIsUsable()}}},instance_page_state:{afterChange:(T,j)=>{if((T==null?void 0:T.selectedShapeIds)!==(j==null?void 0:j.selectedShapeIds)){const $=j.selectedShapeIds.filter(O=>{var B,K;let F=(B=this.getShape(O))==null?void 0:B.parentId;for(;Fn(F);){if(j.selectedShapeIds.includes(F))return!1;F=(K=this.getShape(F))==null?void 0:K.parentId}return!0});let M=null;if($.length>0){const O=this.findCommonAncestor(me($.map(F=>this.getShape(F))),F=>this.isShapeOfType(F,"group"));O&&(M=O)}else j!=null&&j.focusedGroupId&&(M=j.focusedGroupId);($.length!==j.selectedShapeIds.length||M!==j.focusedGroupId)&&this.store.put([{...j,selectedShapeIds:$,focusedGroupId:M??null}])}}}})),this._currentPageShapeIds=oJ(this.store,()=>this.getCurrentPageId()),this._parentIdsToChildIds=rJ(this.store),this.disposables.add(this.store.listen(T=>{this.emit("change",T)})),this.disposables.add(this.history.dispose),this.run(()=>{this.store.ensureStoreIsUsable(),this._updateCurrentPageState({editingShapeId:null,hoveredShapeId:null,erasingShapeIds:[]})},{history:"ignore"}),l&&this.root.children[l]===void 0)throw Error(`No state found for initialState "${l}".`);if(this.root.enter(void 0,"initial"),this.edgeScrollManager=new pJ(this),this.focusManager=new fJ(this,c),this.disposables.add(this.focusManager.dispose.bind(this.focusManager)),this.getInstanceState().followingUserId&&this.stopFollowingUser(),this.on("tick",this._flushEventsForTick),this.timers.requestAnimationFrame(()=>{this._tickManager.start()}),this.performanceTracker=new DT,(D=this.store.props.collaboration)!=null&&D.mode){const T=this.store.props.collaboration.mode;this.disposables.add(jo("update collaboration mode",()=>{this.store.put([{...this.getInstanceState(),isReadonly:T.get()==="readonly"}])}))}}getIsShapeHiddenCache(){return this._isShapeHiddenPredicate?this.store.createComputedCache("isShapeHidden",e=>this.findShapeAncestor(e,r=>this.isShapeHidden(r))?!0:this._isShapeHiddenPredicate(e,this)??!1):null}isShapeHidden(e){return this._isShapeHiddenPredicate?!!this.getIsShapeHiddenCache().get(typeof e=="string"?e:e.id):!1}dispose(){this.disposables.forEach(e=>e()),this.disposables.clear(),this.isDisposed=!0}getShapeUtil(e){const n=typeof e=="string"?e:e.type,r=hn(this.shapeUtils,n);return Le(r,`No shape util found for type "${n}"`),r}getBindingUtil(e){const n=typeof e=="string"?e:e.type,r=hn(this.bindingUtils,n);return Le(r,`No binding util found for type "${n}"`),r}undo(){return this._flushEventsForTick(0),this.complete(),this.history.undo(),this}getCanUndo(){return this.history.getNumUndos()>0}redo(){return this._flushEventsForTick(0),this.complete(),this.history.redo(),this}clearHistory(){return this.history.clear(),this}getCanRedo(){return this.history.getNumRedos()>0}mark(e){return console.warn(typeof e=="string"?`[tldraw] \`editor.history.mark("${e}")\` is deprecated. Please use \`const myMarkId = editor.markHistoryStoppingPoint()\` instead.`:"[tldraw] `editor.mark()` is deprecated. Use `editor.markHistoryStoppingPoint()` instead."),this.history._mark(e??ze()),this}markHistoryStoppingPoint(e){const n=`[${e??"stop"}]_${ze()}`;return this.history._mark(n),n}getMarkIdMatching(e){return this.history.getMarkIdMatching(e)}squashToMark(e){return this.history.squashToMark(e),this}bail(){return this.history.bail(),this}bailToMark(e){return this.history.bailToMark(e),this}run(e,n){const r=this._shouldIgnoreShapeLock;this._shouldIgnoreShapeLock=(n==null?void 0:n.ignoreShapeLock)??r;try{this.history.batch(e,n)}finally{this._shouldIgnoreShapeLock=r}return this}batch(e,n){return this.run(e,n)}annotateError(e,{origin:n,willCrashApp:r,tags:o,extras:s}){const i=this.createErrorAnnotations(n,r);return vw(e,{tags:{...i.tags,...o},extras:{...i.extras,...s}}),r&&this.store.markAsPossiblyCorrupted(),this}createErrorAnnotations(e,n){try{const r=this.getEditingShapeId();return{tags:{origin:e,willCrashApp:n},extras:{activeStateNode:this.root.getPath(),selectedShapes:this.getSelectedShapes(),editingShape:r?this.getShape(r):void 0,inputs:this.inputs}}}catch{return{tags:{origin:e,willCrashApp:n},extras:{}}}}getCrashingError(){return this._crashingError}crash(e){return this._crashingError=e,this.store.markAsPossiblyCorrupted(),this.emit("crash",{error:e}),this}getPath(){return this.root.getPath().split("root.")[1]}isIn(e){const n=e.split(".").reverse();let r=this.root;for(;n.length>0;){const o=n.pop();if(!o)return!0;const s=r.getCurrent();if((s==null?void 0:s.id)===o){if(n.length===0)return!0;r=s;continue}else return!1}return!1}isInAny(...e){return e.some(n=>this.isIn(n))}setCurrentTool(e,n={}){return this.root.transition(e,n),this}getCurrentTool(){return this.root.getCurrent()}getCurrentToolId(){const e=this.getCurrentTool();return e?e.getCurrentToolIdMask()??e.id:""}getStateDescendant(e){var o;const n=e.split(".").reverse();let r=this.root;for(;n.length>0;){const s=n.pop();if(!s)return r;const i=(o=r.children)==null?void 0:o[s];if(!i)return;r=i}return r}getDocumentSettings(){return this.store.get(yx)}updateDocumentSettings(e){return this.run(()=>{this.store.put([{...this.getDocumentSettings(),...e}])},{history:"ignore"}),this}getInstanceState(){return this.store.get(bn)}updateInstanceState(e,n){return this._updateInstanceState(e,{history:"ignore",...n}),e.isChangingStyle!==void 0&&(clearTimeout(this._isChangingStyleTimeout),e.isChangingStyle===!0&&(this._isChangingStyleTimeout=this.timers.setTimeout(()=>{this._updateInstanceState({isChangingStyle:!1},{history:"ignore"})},2e3))),this}_updateInstanceState(e,n){this.run(()=>{this.store.put([{...this.getInstanceState(),...e}])},n)}getOpenMenus(){return this.menus.getOpenMenus()}addOpenMenu(e){return this.menus.addOpenMenu(e),this}deleteOpenMenu(e){return this.menus.deleteOpenMenu(e),this}clearOpenMenus(){return this.menus.clearOpenMenus(),this}getIsMenuOpen(){return this.menus.hasAnyOpenMenus()}setCursor(e){return this.updateInstanceState({cursor:{...this.getInstanceState().cursor,...e}}),this}getPageStates(){return this._getPageStatesQuery().get()}_getPageStatesQuery(){return this.store.query.records("instance_page_state")}getCurrentPageState(){return this.store.get(this._getCurrentPageStateId())}_getCurrentPageStateId(){return Qr.createId(this.getCurrentPageId())}updateCurrentPageState(e){return this._updateCurrentPageState(e),this}_updateCurrentPageState(e){this.store.update(e.id??this.getCurrentPageState().id,n=>({...n,...e}))}getSelectedShapeIds(){return this.getCurrentPageState().selectedShapeIds}getSelectedShapes(){const{selectedShapeIds:e}=this.getCurrentPageState();return me(e.map(n=>this.store.get(n)))}setSelectedShapes(e){return this.run(()=>{const n=e.map(s=>typeof s=="string"?s:s.id),{selectedShapeIds:r}=this.getCurrentPageState(),o=new Set(r);if(n.length===o.size&&n.every(s=>o.has(s)))return null;this.store.put([{...this.getCurrentPageState(),selectedShapeIds:n}])},{history:"record-preserveRedoStack"})}isAncestorSelected(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null,r=this.getShape(n);if(!r)return!1;const o=this.getSelectedShapeIds();return!!this.findShapeAncestor(r,s=>o.includes(s.id))}select(...e){const n=typeof e[0]=="string"?e:e.map(r=>r.id);return this.setSelectedShapes(n),this}deselect(...e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=this.getSelectedShapeIds();return r.length>0&&n.length>0&&this.setSelectedShapes(r.filter(o=>!n.includes(o))),this}selectAll(){const e=this.getSortedChildIdsForParent(this.getCurrentPageId());return e.length<=0?this:(this.setSelectedShapes(this._getUnlockedShapeIds(e)),this)}selectNone(){return this.getSelectedShapeIds().length>0&&this.setSelectedShapes([]),this}getOnlySelectedShapeId(){var e;return((e=this.getOnlySelectedShape())==null?void 0:e.id)??null}getOnlySelectedShape(){const e=this.getSelectedShapes();return e.length===1?e[0]:null}getShapesPageBounds(e){const n=me(e.map(r=>this.getShapePageBounds(r)));return n.length===0?null:Z.Common(n)}getSelectionPageBounds(){return this.getShapesPageBounds(this.getSelectedShapeIds())}getShapesSharedRotation(e){let n=!1,r=0;for(let o=0,s=e.length;o<s;o++){const i=this.getShapePageTransform(e[o]);if(i)if(n){if(i.rotation()!==r)return 0}else n=!0,r=i.rotation()}return r}getSelectionRotation(){return this.getShapesSharedRotation(this.getSelectedShapeIds())}getShapesRotatedPageBounds(e){if(e.length===0)return;const n=this.getShapesSharedRotation(e);if(n===0)return this.getShapesPageBounds(e)??void 0;if(e.length===1){const o=this.getShapeGeometry(e[0]).bounds.clone(),s=this.getShapePageTransform(e[0]);return o.point=s.applyToPoint(o.point),o}const r=Z.FromPoints(e.flatMap(o=>{const s=this.getShapePageTransform(o);return s?s.applyToPoints(this.getShapeGeometry(o).bounds.corners):[]}).map(o=>o.rot(-n)));return r.point=r.point.rot(n),r}getSelectionRotatedPageBounds(){return this.getShapesRotatedPageBounds(this.getSelectedShapeIds())}getSelectionRotatedScreenBounds(){const e=this.getSelectionRotatedPageBounds();if(!e)return;const{x:n,y:r}=this.pageToScreen(e.point),o=this.getZoomLevel();return new Z(n,r,e.width*o,e.height*o)}getFocusedGroupId(){return this.getCurrentPageState().focusedGroupId??this.getCurrentPageId()}getFocusedGroup(){const e=this.getFocusedGroupId();return e?this.getShape(e):void 0}setFocusedGroup(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(n!==null){const r=this.getShape(n);if(!r)throw Error(`Editor.setFocusedGroup: Shape with id ${n} does not exist`);if(!this.isShapeOfType(r,"group"))throw Error(`Editor.setFocusedGroup: Cannot set focused group to shape of type ${r.type}`)}return n===this.getFocusedGroupId()?this:this.run(()=>{this.store.update(this.getCurrentPageState().id,r=>({...r,focusedGroupId:n}))},{history:"record-preserveRedoStack"})}popFocusedGroupId(){const e=this.getFocusedGroup();if(e){const n=this.findShapeAncestor(e,r=>this.isShapeOfType(r,"group"));this.setFocusedGroup((n==null?void 0:n.id)??null),this.select(e.id)}else this.setFocusedGroup(null),this.selectNone();return this}getEditingShapeId(){return this.getCurrentPageState().editingShapeId}getEditingShape(){const e=this.getEditingShapeId();return e?this.getShape(e):void 0}setEditingShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;if(n!==this.getEditingShapeId()){if(n){const r=this.getShape(n);if(r&&this.getShapeUtil(r).canEdit(r))return this.run(()=>{this._updateCurrentPageState({editingShapeId:n})},{history:"ignore"}),this}this.run(()=>{this._updateCurrentPageState({editingShapeId:null})},{history:"ignore"})}return this}getHoveredShapeId(){return this.getCurrentPageState().hoveredShapeId}getHoveredShape(){const e=this.getHoveredShapeId();return e?this.getShape(e):void 0}setHoveredShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;return n===this.getHoveredShapeId()?this:(this.run(()=>{this.updateCurrentPageState({hoveredShapeId:n})},{history:"ignore"}),this)}getHintingShapeIds(){return this.getCurrentPageState().hintingShapeIds}getHintingShape(){const e=this.getHintingShapeIds();return me(e.map(n=>this.getShape(n)))}setHintingShapes(e){const n=typeof e[0]=="string"?e:e.map(r=>r.id);return this.run(()=>{this._updateCurrentPageState({hintingShapeIds:Sw(n)})},{history:"ignore"}),this}getErasingShapeIds(){return this.getCurrentPageState().erasingShapeIds}getErasingShapes(){const e=this.getErasingShapeIds();return me(e.map(n=>this.getShape(n)))}setErasingShapes(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id);n.sort();const r=this.getErasingShapeIds();return this.run(()=>{if(n.length===r.length){for(let o=0;o<n.length;o++)if(n[o]!==r[o]){this._updateCurrentPageState({erasingShapeIds:n});break}}else this._updateCurrentPageState({erasingShapeIds:n})},{history:"ignore"}),this}getCroppingShapeId(){return this.getCurrentPageState().croppingShapeId}setCroppingShape(e){const n=typeof e=="string"?e:(e==null?void 0:e.id)??null;return n!==this.getCroppingShapeId()&&this.run(()=>{if(!n)this.updateCurrentPageState({croppingShapeId:null});else{const r=this.getShape(n),o=this.getShapeUtil(r);r&&o.canCrop(r)&&this.updateCurrentPageState({croppingShapeId:n})}},{history:"ignore"}),this}_unsafe_getCameraId(){return Eo.createId(this.getCurrentPageId())}getCamera(){const e=this.store.get(this._unsafe_getCameraId());if(this._isLockedOnFollowingUser.get()){const n=this.getCameraForFollowing();if(n)return{...e,...n}}return e}getViewportPageBoundsForFollowing(){const e=this.getInstanceState().followingUserId;if(!e)return null;const n=this.getCollaborators().find(h=>h.userId===e);if(!n||!n.camera||!n.screenBounds)return null;const{w:r,h:o}=n.screenBounds,{x:s,y:i,z:a}=n.camera,l=new Z(-s,-i,r/a,o/a),c=this.getViewportScreenBounds().clone(),u=c.width/c.height;return c.width=l.width,c.height=c.width/u,c.height<l.height&&(c.height=l.height,c.width=c.height*u),c.center=l.center,c}getCameraForFollowing(){const e=this.getViewportPageBoundsForFollowing();return e?{x:-e.x,y:-e.y,z:this.getViewportScreenBounds().w/e.width}:null}getZoomLevel(){return this.getCamera().z}getInitialZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.initialZoom==="default")return 1;const{zx:n,zy:r}=zI(this,e);switch(e.constraints.initialZoom){case"fit-min":return Math.max(n,r);case"fit-max":return Math.min(n,r);case"fit-x":return n;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(n,r));case"fit-max-100":return Math.min(1,Math.min(n,r));case"fit-x-100":return Math.min(1,n);case"fit-y-100":return Math.min(1,r);default:throw Ot(e.constraints.initialZoom)}}getBaseZoom(){const e=this.getCameraOptions();if(!e.constraints||e.constraints.baseZoom==="default")return 1;const{zx:n,zy:r}=zI(this,e);switch(e.constraints.baseZoom){case"fit-min":return Math.max(n,r);case"fit-max":return Math.min(n,r);case"fit-x":return n;case"fit-y":return r;case"fit-min-100":return Math.min(1,Math.max(n,r));case"fit-max-100":return Math.min(1,Math.min(n,r));case"fit-x-100":return Math.min(1,n);case"fit-y-100":return Math.min(1,r);default:throw Ot(e.constraints.baseZoom)}}getCameraOptions(){return this._cameraOptions.get()}setCameraOptions(e){var r;const n=tt({...this._cameraOptions.__unsafe__getWithoutCapture(),...e});return((r=n.zoomSteps)==null?void 0:r.length)<1&&(n.zoomSteps=[1]),this._cameraOptions.set(n),this.setCamera(this.getCamera()),this}getConstrainedCamera(e,n){const r=this.getCamera();let{x:o,y:s,z:i=r.z}=e;if(!(n!=null&&n.force)){const a=this.getCameraOptions(),l=a.zoomSteps[0],c=Ut(a.zoomSteps),u=this.getViewportScreenBounds();if(a.constraints){const{constraints:h}=a,p=Math.min(h.padding.y,u.w/2),f=Math.min(h.padding.x,u.h/2),g=Z.From(a.constraints.bounds),m=(u.w-f*2)/g.w,v=(u.h-p*2)/g.h,y=this.getBaseZoom(),S=c*y,b=l*y;if(n!=null&&n.reset&&(i=this.getInitialZoom()),i<b||i>S){const{x:$,y:M,z:O}=r,F=-$+u.w/O/2,B=-M+u.h/O/2;i=zt(i,b,S);const K=-$+u.w/i/2,R=-M+u.h/i/2;o=$+K-F,s=M+R-B}const P=f/i-g.x,C=p/i-g.y,_=(u.w-f*2)/i-g.w,E=(u.h-p*2)/i-g.h,k=P+_*h.origin.x,D=C+E*h.origin.y,T=typeof h.behavior=="string"?h.behavior:h.behavior.x,j=typeof h.behavior=="string"?h.behavior:h.behavior.y;if(n!=null&&n.reset)o=k,s=D;else{switch(T){case"fixed":{o=k;break}case"contain":{i<m?o=k:o=zt(o,P+_,P);break}case"inside":{i<m?o=zt(o,P,(u.w-f)/i-g.w):o=zt(o,P+_,P);break}case"outside":{o=zt(o,f/i-g.w,(u.w-f)/i);break}case"free":break;default:throw Ot(T)}switch(j){case"fixed":{s=D;break}case"contain":{i<v?s=D:s=zt(s,C+E,C);break}case"inside":{i<v?s=zt(s,C,(u.h-p)/i-g.h):s=zt(s,C+E,C);break}case"outside":{s=zt(s,p/i-g.h,(u.h-p)/i);break}case"free":break;default:throw Ot(j)}}}else if(i>c||i<l){const{x:h,y:p,z:f}=r;i=zt(i,l,c),o=h+(-h+u.w/i/2)-(-h+u.w/f/2),s=p+(-p+u.h/i/2)-(-p+u.h/f/2)}}return{x:o,y:s,z:i}}_setCamera(e,n){const r=this.getCamera(),{x:o,y:s,z:i}=this.getConstrainedCamera(e,n);return r.x===o&&r.y===s&&r.z===i?this:(Oo(()=>{const a={...r,x:o,y:s,z:i};this.run(()=>{this.store.put([a])},{history:"ignore"});const{currentScreenPoint:l,currentPagePoint:c}=this.inputs,{screenBounds:u}=this.store.unsafeGetWithoutCapture(bn);if(l.x/i-o!==c.x||l.y/i-s!==c.y){const h={type:"pointer",target:"canvas",name:"pointer_move",point:x.AddXY(l,u.x,u.y),pointerId:oI.CAMERA_MOVE,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,shiftKey:this.inputs.shiftKey,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),button:0,isPen:this.getInstanceState().isPenMode??!1};n!=null&&n.immediate?this._flushEventForTick(h):this.dispatch(h)}this._tickCameraState()}),this)}setCamera(e,n){const{isLocked:r}=this._cameraOptions.__unsafe__getWithoutCapture();if(r&&!(n!=null&&n.force))return this;this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser();const o=x.Cast(e);Number.isFinite(o.x)||(o.x=0),Number.isFinite(o.y)||(o.y=0),(o.z===void 0||!Number.isFinite(o.z))&&(e.z=this.getZoomLevel());const s=this.getConstrainedCamera(o,n);if(n!=null&&n.animation){const{width:i,height:a}=this.getViewportScreenBounds();this._animateToViewport(new Z(-s.x,-s.y,i/s.z,a/s.z),n)}else this._setCamera(s,{...n,force:!0});return this}centerOnPoint(e,n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const{width:o,height:s}=this.getViewportPageBounds();return this.setCamera(new x(-(e.x-o/2),-(e.y-s/2),this.getCamera().z),n),this}zoomToFit(e){const n=[...this.getCurrentPageShapeIds()];if(n.length<=0)return this;const r=Z.Common(me(n.map(o=>this.getShapePageBounds(o))));return this.zoomToBounds(r,e),this}resetZoom(e=this.getViewportScreenCenter(),n){const{isLocked:r,constraints:o}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const s=this.getCamera(),{x:i,y:a,z:l}=s,{x:c,y:u}=e;let h=1;if(o){const p=this.getInitialZoom();l!==p&&(h=p)}return this.setCamera(new x(i+(c/h-c)-(c/l-c),a+(u/h-u)-(u/l-u),h),n),this}zoomIn(e=this.getViewportScreenCenter(),n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))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=Ut(a)*l;for(let u=1;u<a.length;u++){const h=a[u-1]*l,p=a[u]*l;if(!(p-i<=(p-h)/2)){c=p;break}}this.setCamera(new x(o+(e.x/c-e.x)-(e.x/i-e.x),s+(e.y/c-e.y)-(e.y/i-e.y),c),n)}return this}zoomOut(e=this.getViewportScreenCenter(),n){const{isLocked:r}=this.getCameraOptions();if(r&&!(n!=null&&n.force))return this;const{zoomSteps:o}=this.getCameraOptions();if(o!==null&&o.length>1){const s=this.getBaseZoom(),{x:i,y:a,z:l}=this.getCamera();let c=o[0]*s;for(let u=o.length-1;u>0;u--){const h=o[u-1]*s,p=o[u]*s;if(!(p-l>=(p-h)/2)){c=h;break}}this.setCamera(new x(i+(e.x/c-e.x)-(e.x/l-e.x),a+(e.y/c-e.y)-(e.y/l-e.y),c),n)}return this}zoomToSelection(e){const{isLocked:n}=this.getCameraOptions();if(n&&!(e!=null&&e.force))return this;const r=this.getSelectionPageBounds();return r&&this.zoomToBounds(r,{targetZoom:Math.max(1,this.getZoomLevel()),...e}),this}zoomToBounds(e,n){const r=this._cameraOptions.__unsafe__getWithoutCapture();if(r.isLocked&&!(n!=null&&n.force))return this;const o=this.getViewportScreenBounds(),s=(n==null?void 0:n.inset)??Math.min(wX,o.width*.28),i=this.getBaseZoom(),a=r.zoomSteps[0],l=Ut(r.zoomSteps);let c=zt(Math.min((o.width-s)/e.w,(o.height-s)/e.h),a*i,l*i);return(n==null?void 0:n.targetZoom)!==void 0&&(c=Math.min(n.targetZoom,c)),this.setCamera(new x(-e.x+(o.width-e.w*c)/2/c,-e.y+(o.height-e.h*c)/2/c,c),n),this}stopCameraAnimation(){return this.emit("stop-camera-animation"),this}_animateViewport(e){if(!this._viewportAnimation)return;this._viewportAnimation.elapsed+=e;const{elapsed:n,easing:r,duration:o,start:s,end:i}=this._viewportAnimation;if(n>o){this.off("tick",this._animateViewport),this._viewportAnimation=null,this._setCamera(new x(-i.x,-i.y,this.getViewportScreenBounds().width/i.width));return}const a=o-n,l=r(1-a/o),c=s.minX+(i.minX-s.minX)*l,u=s.minY+(i.minY-s.minY)*l,h=s.maxX+(i.maxX-s.maxX)*l;this._setCamera(new x(-c,-u,this.getViewportScreenBounds().width/(h-c)),{force:!0})}_animateToViewport(e,n={animation:Ky}){const{animation:r,...o}=n;if(!r)return;const{duration:s=0,easing:i=Dt.easeInOutCubic}=r,a=this.user.getAnimationSpeed(),l=this.getViewportPageBounds();return this.stopCameraAnimation(),this.getInstanceState().followingUserId&&this.stopFollowingUser(),s===0||a===0?this._setCamera(new x(-e.x,-e.y,this.getViewportScreenBounds().width/e.width),{...o}):(this._viewportAnimation={elapsed:0,duration:s/a,easing:i,start:l.clone(),end:e.clone()},this.once("stop-camera-animation",()=>{this.off("tick",this._animateViewport),this._viewportAnimation=null}),this.on("tick",this._animateViewport),this)}slideCamera(e={}){const{isLocked:n}=this.getCameraOptions();if(n&&!(e!=null&&e.force))return this;if(this.user.getAnimationSpeed()===0)return this;this.stopCameraAnimation();const{speed:o,friction:s=this.options.cameraSlideFriction,direction:i,speedThreshold:a=.01}=e;let l=Math.min(o,1);const c=()=>{this.off("tick",u),this.off("stop-camera-animation",c)};this.once("stop-camera-animation",c);const u=h=>{const{x:p,y:f,z:g}=this.getCamera(),m=x.Mul(i,l*h/g);l*=1-s,l<a?c():this._setCamera(new x(p+m.x,f+m.y,g))};return this.on("tick",u),this}zoomToUser(e,n={animation:{duration:500}}){const r=this.getCollaborators().find(s=>s.userId===e);if(!r)return this;const o=r.cursor;return o?(this.run(()=>{this.getInstanceState().followingUserId!==null&&this.stopFollowingUser();const s=r.currentPageId===this.getCurrentPageId();s||this.setCurrentPage(r.currentPageId),n&&n.animation&&!s&&(n.animation=void 0),this.centerOnPoint(o,n);const{highlightedUserIds:i}=this.getInstanceState();this.updateInstanceState({highlightedUserIds:[...i,e]}),this.timers.setTimeout(()=>{const a=[...this.getInstanceState().highlightedUserIds],l=a.indexOf(e);l<0||(a.splice(l,1),this.updateInstanceState({highlightedUserIds:a}))},this.options.collaboratorIdleTimeoutMs)}),this):this}updateViewportScreenBounds(e,n=!1){if(e instanceof HTMLElement){const a=e.getBoundingClientRect();e=new Z(a.left||a.x,a.top||a.y,Math.max(a.width,1),Math.max(a.height,1))}else e.width=Math.max(e.width,1),e.height=Math.max(e.height,1);const r=[e.minY!==0,!ui(document.body.scrollWidth,e.maxX,1),!ui(document.body.scrollHeight,e.maxY,1),e.minX!==0],{_willSetInitialBounds:o}=this;this._willSetInitialBounds=!1;const{screenBounds:s,insets:i}=this.getInstanceState();if(e.equals(s)&&r.every((a,l)=>a===i[l]))return this;if(o)this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.setCamera(this.getCamera());else if(n&&!this.getInstanceState().followingUserId){const a=this.getViewportPageBounds().center;this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this.centerOnPoint(a)}else this.updateInstanceState({screenBounds:e.toJson(),insets:r}),this._setCamera(x.From({...this.getCamera()}));return this._tickCameraState(),this}getViewportScreenBounds(){const{x:e,y:n,w:r,h:o}=this.getInstanceState().screenBounds;return new Z(e,n,r,o)}getViewportScreenCenter(){const e=this.getViewportScreenBounds();return new x(e.midX-e.minX,e.midY-e.minY)}getViewportPageBounds(){const{w:e,h:n}=this.getViewportScreenBounds(),{x:r,y:o,z:s}=this.getCamera();return new Z(-r,-o,e/s,n/s)}screenToPage(e){const{screenBounds:n}=this.store.unsafeGetWithoutCapture(bn),{x:r,y:o,z:s=1}=this.getCamera();return new x((e.x-n.x)/s-r,(e.y-n.y)/s-o,e.z??.5)}pageToScreen(e){const{screenBounds:n}=this.store.unsafeGetWithoutCapture(bn),{x:r,y:o,z:s=1}=this.getCamera();return new x((e.x+r)*s+n.x,(e.y+o)*s+n.y,e.z??.5)}pageToViewport(e){const{x:n,y:r,z:o=1}=this.getCamera();return new x((e.x+n)*o,(e.y+r)*o,e.z??.5)}_getCollaboratorsQuery(){return this.store.query.records("instance_presence",()=>({userId:{neq:this.user.getId()}}))}getCollaborators(){const e=this._getCollaboratorsQuery().get();return e.length?[...new Set(e.map(r=>r.userId))].sort().map(r=>M9(e.filter(s=>s.userId===r),s=>s.lastActivityTimestamp??0)):ps}getCollaboratorsOnCurrentPage(){const e=this.getCurrentPageId();return this.getCollaborators().filter(n=>n.currentPageId===e)}startFollowingUser(e){this.stopFollowingUser();const n=this._getCollaboratorsQuery().get().filter(s=>s.userId===e);if(!n.length)return console.warn("User not found"),this;const r=this.user.getId();if(r||console.warn("You should set the userId for the current instance before following a user"),n.some(s=>s.followingUserId===r))return this;const o=G("latestLeaderPresence",()=>this.getCollaborators().find(s=>s.userId===e));return Oo(()=>{this.updateInstanceState({followingUserId:e},{history:"ignore"});const s=jo("update current page",()=>{const l=o.get();if(!l){this.stopFollowingUser();return}l.currentPageId!==this.getCurrentPageId()&&this.getPage(l.currentPageId)&&this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:l.currentPageId}]),this._isLockedOnFollowingUser.set(!0)},{history:"ignore"})}),i=()=>{s(),this._isLockedOnFollowingUser.set(!1),this.off("frame",a),this.off("stop-following",i)},a=()=>{if(!o.get()){this.stopFollowingUser();return}if(this._isLockedOnFollowingUser.get())return;const c=this.user.getAnimationSpeed();if(c===0){this._isLockedOnFollowingUser.set(!0);return}const u=this.getViewportPageBoundsForFollowing();if(!u){this.stopFollowingUser();return}const h=this.getViewportPageBounds(),p=Math.abs(u.minX-h.minX)+Math.abs(u.maxX-h.maxX),f=Math.abs(u.minY-h.minY)+Math.abs(u.maxY-h.maxY);if(p<this.options.followChaseViewportSnap&&f<this.options.followChaseViewportSnap){this._isLockedOnFollowingUser.set(!0);return}const g=zt(c*.5,.1,.8),m=new Z(_e(h.minX,u.minX,g),_e(h.minY,u.minY,g),_e(h.width,u.width,g),_e(h.height,u.height,g)),v=new x(-m.x,-m.y,this.getViewportScreenBounds().width/m.width);this.stopCameraAnimation(),this._setCamera(v)};this.once("stop-following",i),this.addListener("frame",a),a()}),this}stopFollowingUser(){return this.run(()=>{this.store.put([this.getCamera()]),this._isLockedOnFollowingUser.set(!1),this.updateInstanceState({followingUserId:null}),this.emit("stop-following")},{history:"ignore"}),this}getUnorderedRenderingShapes(e){const n=[];let r=this.options.maxShapesPerPage*2,o=this.options.maxShapesPerPage;const s=this.getErasingShapeIds(),i=(l,c,u)=>{const h=this.getShape(l);if(!h||this.isShapeHidden(h))return;c*=h.opacity;let p=!1;const f=this.getShapeUtil(h);e&&(p=!u&&s.includes(l),p&&(c*=.32)),n.push({id:l,shape:h,util:f,index:r,backgroundIndex:o,opacity:c}),r+=1,o+=1;const g=this.getSortedChildIdsForParent(l);if(!g.length)return;let m=null;f.providesBackgroundForChildren(h)&&(m=o,o=r,r+=this.options.maxShapesPerPage);for(const v of g)i(v,c,u||p);m!==null&&(o=m)},a=e?[this.getCurrentPage()]:this.getPages();for(const l of a)for(const c of this.getSortedChildIdsForParent(l.id))i(c,1,!1);return n}_decayCameraStateTimeout(e){this._cameraStateTimeoutRemaining-=e,!(this._cameraStateTimeoutRemaining>0)&&(this.off("tick",this._decayCameraStateTimeout),this._cameraState.set("idle"))}_tickCameraState(){this._cameraStateTimeoutRemaining=this.options.cameraMovingTimeoutMs,this._cameraState.__unsafe__getWithoutCapture()==="idle"&&(this._cameraState.set("moving"),this.on("tick",this._decayCameraStateTimeout))}getCameraState(){return this._cameraState.get()}getRenderingShapes(){return this.getUnorderedRenderingShapes(!0).sort(aB)}_getAllPagesQuery(){return this.store.query.records("page")}getPages(){return Array.from(this._getAllPagesQuery().get()).sort(cn)}getCurrentPage(){return this.getPage(this.getCurrentPageId())}getCurrentPageId(){return this.getInstanceState().currentPageId}getPage(e){return this.store.get(typeof e=="string"?e:e.id)}getCurrentPageShapeIds(){return this._currentPageShapeIds.get()}getCurrentPageShapeIdsSorted(){return Array.from(this.getCurrentPageShapeIds()).sort()}getPageShapeIds(e){const n=typeof e=="string"?e:e.id,r=this.store.query.exec("shape",{parentId:{eq:n}});return this.getShapeAndDescendantIds(r.map(o=>o.id))}setCurrentPage(e){const n=typeof e=="string"?e:e.id;return this.store.has(n)?(this.stopFollowingUser(),this.complete(),this.run(()=>{this.store.put([{...this.getInstanceState(),currentPageId:n}]),this.setCamera(this.getCamera())},{history:"record-preserveRedoStack"})):(console.error("Tried to set the current page id to a page that doesn't exist."),this)}updatePage(e){return this.getIsReadonly()?this:this.getPage(e.id)?this.run(()=>this.store.update(e.id,r=>({...r,...e}))):this}createPage(e){return this.run(()=>{if(this.getIsReadonly()||this.getPages().length>=this.options.maxPages)return;const n=this.getPages(),r=XQ(e.name??"Page 1",n.map(i=>i.name));let o=e.index;(!o||n.some(i=>i.index===o))&&(o=Io(n[n.length-1].index));const s=yr.create({meta:{},...e,name:r,index:o});this.store.put([s])}),this}deletePage(e){const n=typeof e=="string"?e:e.id;return this.run(()=>{if(this.getIsReadonly())return;const r=this.getPages();if(r.length===1)return;const o=this.getPage(n);if(o){if(n===this.getCurrentPageId()){const s=r.findIndex(a=>a.id===n),i=r[s-1]??r[s+1];this.setCurrentPage(i.id)}this.store.remove([o.id])}}),this}duplicatePage(e,n=yr.createId()){if(this.getPages().length>=this.options.maxPages)return this;const r=typeof e=="string"?e:e.id,o=this.getPage(r);if(!o)return this;const s={...this.getCamera()},i=this.getContentFromCurrentPage(this.getSortedChildIdsForParent(o.id));return this.run(()=>{var c;const a=this.getPages(),l=$u(o.index,(c=a[a.indexOf(o)+1])==null?void 0:c.index);if(this.createPage({name:o.name+" Copy",id:n,index:l}),this.setCurrentPage(n),this.setCamera(s),i)return this.putContentOntoCurrentPage(i)}),this}renamePage(e,n){const r=typeof e=="string"?e:e.id;return this.getIsReadonly()?this:(this.updatePage({id:r,name:n}),this)}_getAllAssetsQuery(){return this.store.query.records("asset")}getAssets(){return this._getAllAssetsQuery().get()}createAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>this.store.put(e),{history:"ignore"}),this)}updateAssets(e){return this.getIsReadonly()?this:e.length<=0?this:(this.run(()=>{this.store.put(e.map(n=>({...this.store.get(n.id),...n})))},{history:"ignore"}),this)}deleteAssets(e){if(this.getIsReadonly())return this;const n=typeof e[0]=="string"?e:e.map(r=>r.id);return n.length<=0?this:(this.run(()=>this.store.remove(n),{history:"ignore"}),this)}getAsset(e){return this.store.get(typeof e=="string"?e:e.id)}async resolveAssetUrl(e,n){if(!e)return null;const r=this.getAsset(e);if(!r)return null;const{screenScale:o=1,shouldResolveToOriginal:s=!1}=n,a=Math.max(.125,(u=>Math.pow(2,Math.ceil(Math.log2(u))))(o)),l="connection"in navigator?navigator.connection.effectiveType:null,c=this.getInstanceState().devicePixelRatio;return await this.store.props.assets.resolve(r,{screenScale:o||1,steppedScreenScale:a,dpr:c,networkEffectiveType:l,shouldResolveToOriginal:s})}async uploadAsset(e,n,r){return await this.store.props.assets.upload(e,n,r)}_getShapeGeometryCache(){return this.store.createComputedCache("bounds",e=>this.getShapeUtil(e).getGeometry(e),(e,n)=>e.props===n.props)}getShapeGeometry(e){return this._getShapeGeometryCache().get(typeof e=="string"?e:e.id)}_getShapeHandlesCache(){return this.store.createComputedCache("handles",e=>{var n,r;return(r=(n=this.getShapeUtil(e)).getHandles)==null?void 0:r.call(n,e)})}getShapeHandles(e){return this._getShapeHandlesCache().get(typeof e=="string"?e:e.id)}getShapeLocalTransform(e){const n=typeof e=="string"?e:e.id,r=this.getShape(n);if(!r)throw Error("Editor.getTransform: shape not found");return q.Identity().translate(r.x,r.y).rotate(r.rotation)}_getShapePageTransformCache(){return this.store.createComputedCache("pageTransformCache",e=>{if(Rn(e.parentId))return this.getShapeLocalTransform(e);const n=this._getShapePageTransformCache().get(e.parentId)??q.Identity();return q.Compose(n,this.getShapeLocalTransform(e))})}getShapeParentTransform(e){const n=typeof e=="string"?e:e.id,r=this.getShape(n);return!r||Rn(r.parentId)?q.Identity():this._getShapePageTransformCache().get(r.parentId)??q.Identity()}getShapePageTransform(e){const n=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(n)??q.Identity()}_getShapePageBoundsCache(){return this.store.createComputedCache("pageBoundsCache",e=>{const n=this._getShapePageTransformCache().get(e.id);return n?Z.FromPoints(q.applyToPoints(n,this.getShapeGeometry(e).vertices)):new Z})}getShapePageBounds(e){return this._getShapePageBoundsCache().get(typeof e=="string"?e:e.id)}_getShapeClipPathCache(){return this.store.createComputedCache("clipPathCache",e=>{const n=this._getShapeMaskCache().get(e.id);if(!n)return;if(n.length===0)return"polygon(0px 0px, 0px 0px, 0px 0px)";const r=this._getShapePageTransformCache().get(e.id);return r?`polygon(${q.applyToPoints(q.Inverse(r),n).map(s=>`${s.x}px ${s.y}px`).join(",")})`:void 0})}getShapeClipPath(e){return this._getShapeClipPathCache().get(typeof e=="string"?e:e.id)}_getShapeMaskCache(){return this.store.createComputedCache("pageMaskCache",e=>{if(Rn(e.parentId))return;const n=this.getShapeAncestors(e.id).filter(o=>this.isShapeOfType(o,"frame"));return n.length===0?void 0:n.map(o=>this._getShapePageTransformCache().get(o.id).applyToPoints(this.getShapeGeometry(o).vertices)).reduce((o,s)=>{if(!(s&&o))return;const i=CI(o,s);return i?i.map(x.Cast):[]})})}getShapeMask(e){return this._getShapeMaskCache().get(typeof e=="string"?e:e.id)}getShapeMaskedPageBounds(e){return typeof e!="string"&&(e=e.id),this._getShapeMaskedPageBoundsCache().get(e)}_getShapeMaskedPageBoundsCache(){return this.store.createComputedCache("shapeMaskedPageBoundsCache",e=>{const n=this._getShapePageBoundsCache().get(e.id);if(!n)return;const r=this._getShapeMaskCache().get(e.id);if(r){if(r.length===0)return;const{corners:o}=n;if(o.every((i,a)=>i&&x.Equals(i,r[a])))return n.clone();const s=CI(r,o);return s?Z.FromPoints(s):void 0}return n})}getShapeAncestors(e,n=[]){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return n;const s=o.parentId;if(Rn(s))return n.reverse(),n;const i=this.store.get(s);return i?(n.push(i),this.getShapeAncestors(i,n)):n}findShapeAncestor(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return;const s=o.parentId;if(Rn(s))return;const i=this.getShape(s);if(i)return n(i)?i:this.findShapeAncestor(i,n)}hasAncestor(e,n){const r=typeof e=="string"?e:e==null?void 0:e.id,o=r&&this.getShape(r);return o?o.parentId===n?!0:this.hasAncestor(this.getShapeParent(o),n):!1}findCommonAncestor(e,n){var l;if(e.length===0)return;const r=typeof e[0]=="string"?e:e.map(c=>c.id),o=me(r.map(c=>this.getShape(c)));if(o.length===1){const c=o[0].parentId;return Rn(c)?void 0:n?(l=this.findShapeAncestor(o[0],n))==null?void 0:l.id:c}const[s,...i]=o;let a=this.getShapeParent(s);for(;a;){if(n&&!n(a)){a=this.getShapeParent(a);continue}if(i.every(c=>this.hasAncestor(c,a.id)))return a.id;a=this.getShapeParent(a)}}isShapeOrAncestorLocked(e){const n=typeof e=="string"?this.getShape(e):e;return n===void 0?!1:n.isLocked?!0:this.isShapeOrAncestorLocked(this.getShapeParent(n))}_notVisibleShapes(){return nJ(this)}getCulledShapes(){const e=this._notVisibleShapes().get(),n=this.getSelectedShapeIds(),r=this.getEditingShapeId(),o=new Set(e);return r&&o.delete(r),n.forEach(s=>{o.delete(s)}),o}getCurrentPageBounds(){let e;return this.getCurrentPageShapeIdsSorted().forEach(n=>{const r=this.getShapeMaskedPageBounds(n);r&&(e?e=e.expand(r):e=r.clone())}),e}getSelectedShapeAtPoint(e){const n=this.getSelectedShapeIds();return this.getCurrentPageShapesSorted().filter(r=>r.type!=="group"&&n.includes(r.id)).reverse().find(r=>this.isPointInShape(r,e,{hitInside:!0,margin:0}))}getShapeAtPoint(e,n={}){const r=this.getZoomLevel(),o=this.getViewportPageBounds(),{filter:s,margin:i=0,hitLocked:a=!1,hitLabels:l=!1,hitInside:c=!1,hitFrameInside:u=!1}=n;let h=1/0,p=null,f=1/0,g=null;const m=(n.renderingOnly?this.getCurrentPageRenderingShapesSorted():this.getCurrentPageShapesSorted()).filter(v=>{if(v.isLocked&&!a||this.isShapeHidden(v)||this.isShapeOfType(v,"group"))return!1;const y=this.getShapeMask(v);return y&&!hr(e,y)?!1:s?s(v):!0});for(let v=m.length-1;v>=0;v--){const y=m[v],S=this.getShapeGeometry(y),b=S instanceof $r,P=this.getPointInShapeSpace(y,e);if(this.isShapeOfType(y,"frame")||(this.isShapeOfType(y,"arrow")||this.isShapeOfType(y,"geo")&&y.props.fill==="none")&&y.props.text.trim()){for(const _ of S.children)if(_.isLabel&&_.isPointInBounds(P))return y}if(this.isShapeOfType(y,"frame")){const _=S.distanceToPoint(P,c);if(Math.abs(_)<=i)return g||y;if(S.hitTestPoint(P,0,!0))return g||p||(u?y:void 0);continue}let C;if(b){let _=1/0;for(const E of S.children){if(E.isLabel&&!l)continue;const k=E.distanceToPoint(P,c);k<_&&(_=k)}C=_}else i===0&&(S.bounds.w<1||S.bounds.h<1)||S.bounds.containsPoint(P,i)?C=S.distanceToPoint(P,c):C=1/0;if(S.isClosed){if(C<=i){if(S.isFilled||b&&S.children[0].isFilled)return g||y;if(this.getShapePageBounds(y).contains(o))continue;if(Math.abs(C)<i)Math.abs(C)<f&&(f=Math.abs(C),g=y);else if(!g){const{area:_}=S;_<h&&(h=_,p=y)}}}else if(C<this.options.hitTestMargin/r)return y}return g||p||void 0}getShapesAtPoint(e,n={}){return this.getCurrentPageShapes().filter(r=>!this.isShapeHidden(r)&&this.isPointInShape(r,e,n))}isPointInShape(e,n,r={}){const{hitInside:o=!1,margin:s=0}=r,i=typeof e=="string"?e:e.id,a=this.getShapeMask(i);return a&&!hr(n,a)?!1:this.getShapeGeometry(i).hitTestPoint(this.getPointInShapeSpace(e,n),s,o)}getPointInShapeSpace(e,n){const r=typeof e=="string"?e:e.id;return this._getShapePageTransformCache().get(r).clone().invert().applyToPoint(n)}getPointInParentSpace(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return new x(0,0);if(Rn(o.parentId))return x.From(n);const s=this.getShapePageTransform(o.parentId);return s?s.clone().invert().applyToPoint(n):x.From(n)}getCurrentPageShapes(){return Array.from(this.getCurrentPageShapeIds(),e=>this.store.get(e))}getCurrentPageShapesSorted(){const e=[],n=this.getSortedChildIdsForParent(this.getCurrentPageId());for(let r=0,o=n.length;r<o;r++)KR(this,n[r],e);return e}getCurrentPageRenderingShapesSorted(){const e=this.getCulledShapes();return this.getCurrentPageShapesSorted().filter(({id:n})=>!e.has(n)&&!this.isShapeHidden(n))}isShapeOfType(e,n){const r=typeof e=="string"?this.getShape(e):e;return r?r.type===n:!1}getShape(e){const n=typeof e=="string"?e:e.id;if(Fn(n))return this.store.get(n)}getShapeParent(e){const n=typeof e=="string"?e:e==null?void 0:e.id;if(!n)return;const r=this.getShape(n);if(!(r===void 0||!Fn(r.parentId)))return this.store.get(r.parentId)}getShapeNearestSibling(e,n){return n?n.parentId===e.parentId?n:this.findShapeAncestor(n,o=>o.parentId===e.parentId):void 0}isShapeInPage(e,n=this.getCurrentPageId()){const r=typeof e=="string"?e:e.id,o=this.getShape(r);if(!o)return!1;let s=!1;if(o.parentId===n)s=!0;else{let i=this.getShape(o.parentId);e:for(;i;){if(i.parentId===n){s=!0;break e}i=this.getShape(i.parentId)}}return s}getAncestorPageId(e){const n=typeof e=="string"?e:e==null?void 0:e.id,r=n&&this.getShape(n);if(r)return Rn(r.parentId)?r.parentId:this.getAncestorPageId(this.getShape(r.parentId))}reparentShapes(e,n,r){const o=typeof e[0]=="string"?e:e.map(p=>p.id);if(o.length===0)return this;const s=[],i=Rn(n)?q.Identity():this.getShapePageTransform(n),a=i.rotation();let l=[];const c=me(this.getSortedChildIdsForParent(n).map(p=>this.getShape(p)));if(r){const p=c.find(f=>f.index===r);if(p){const f=c[c.indexOf(p)+1];f?l=Dl(r,f.index,o.length):l=gy(r,o.length)}else{const f=c.sort(cn).find(g=>g.index>r);f?l=Dl(r,f.index,o.length):l=gy(r,o.length)}}else{const p=c.length&&c[c.length-1];l=p?gy(p.index,o.length):Fu(o.length)}const u=i.clone().invert(),h=me(o.map(p=>this.getShape(p)));return this.run(()=>{for(let p=0;p<h.length;p++){const f=h[p],g=this.getShapePageTransform(f);if(!g)continue;const m=g.point();if(!m)continue;const v=u.applyToPoint(m),y=g.rotation()-a;s.push({id:f.id,type:f.type,parentId:n,x:v.x,y:v.y,rotation:y,index:l[p]})}this.updateShapes(s)},{ignoreShapeLock:!0}),this}getHighestIndexForParent(e){const n=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[n];if(!r||r.length===0)return"a1";const o=this.getShape(r[r.length-1]);return Io(o.index)}getSortedChildIdsForParent(e){const n=typeof e=="string"?e:e.id,r=this._parentIdsToChildIds.get()[n];return r||ps}visitDescendants(e,n){const r=typeof e=="string"?e:e.id,o=this.getSortedChildIdsForParent(r);for(const s of o)n(s)!==!1&&this.visitDescendants(s,n);return this}getShapeAndDescendantIds(e){const n=new Set;for(const r of e.map(o=>this.getShape(o)).sort(cn))n.add(r.id),this.visitDescendants(r,o=>{n.add(o)});return n}getDroppingOverShape(e,n=[]){const r=this.getCurrentPageShapesSorted();for(let o=r.length-1;o>=0;o--){const s=r[o];if(this.isShapeHidden(s)||this.getSelectedShapeIds().includes(s.id)||!this.getShapeUtil(s).canDropShapes(s,n)||n.find(a=>a.id===s.id||this.hasAncestor(s,a.id)))continue;const i=this.getShapeMaskedPageBounds(s.id);if(i&&i.containsPoint(e)&&this.getShapeGeometry(s).hitTestPoint(this.getPointInShapeSpace(s,e),0,!0))return s}}getOutermostSelectableShape(e,n){const r=typeof e=="string"?e:e.id,o=this.getShape(r);let s=o,i=o;const a=this.getFocusedGroup();for(;i;){if(this.isShapeOfType(i,"group")&&(a==null?void 0:a.id)!==i.id&&!this.hasAncestor(a,i.id)&&((n==null?void 0:n(i))??!0))s=i;else if((a==null?void 0:a.id)===i.id)break;i=this.getShapeParent(i)}return s}_getBindingsIndexCache(){const e=eJ(this);return this.store.createComputedCache("bindingsIndex",n=>e.get().get(n.id))}getBinding(e){return this.store.get(e)}getBindingsFromShape(e,n){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(o=>o.fromId===r&&o.type===n)}getBindingsToShape(e,n){const r=typeof e=="string"?e:e.id;return this.getBindingsInvolvingShape(r).filter(o=>o.toId===r&&o.type===n)}getBindingsInvolvingShape(e,n){const r=typeof e=="string"?e:e.id,o=this._getBindingsIndexCache().get(r)??ps;return n?o.filter(s=>s.type===n):o}createBindings(e){const n=[];for(const r of e){const o=this.getShape(r.fromId),s=this.getShape(r.toId);if(!o||!s||!this.canBindShapes({fromShape:o,toShape:s,binding:r}))continue;const a=this.getBindingUtil(r.type).getDefaultProps(),l=this.store.schema.types.binding.create({...r,id:r.id??Qi(),props:{...a,...r.props}});n.push(l)}return this.store.put(n),this}createBinding(e){return this.createBindings([e])}updateBindings(e){const n=[];for(const r of e){if(!r)continue;const o=this.getBinding(r.id);if(!o)continue;const s=So(o,r);if(s===o)continue;const i=this.getShape(s.fromId),a=this.getShape(s.toId);!i||!a||this.canBindShapes({fromShape:i,toShape:a,binding:s})&&n.push(s)}return this.store.put(n),this}updateBinding(e){return this.updateBindings([e])}deleteBindings(e,{isolateShapes:n=!1}={}){const r=e.map(o=>typeof o=="string"?o:o.id);return n?this.store.atomic(()=>{var o,s;for(const i of r){const a=this.getBinding(i);if(!a)continue;const l=this.getBindingUtil(a);(o=l.onBeforeIsolateFromShape)==null||o.call(l,{binding:a,removedShape:this.getShape(a.toId)}),(s=l.onBeforeIsolateToShape)==null||s.call(l,{binding:a,removedShape:this.getShape(a.fromId)}),this.store.remove([i])}}):this.store.remove(r),this}deleteBinding(e,n){return this.deleteBindings([e],n)}canBindShapes({fromShape:e,toShape:n,binding:r}){const o=typeof e=="string"?e:e.type,s=typeof n=="string"?n:n.type,i=typeof r=="string"?r:r.type,a={fromShapeType:o,toShapeType:s,bindingType:i};return o===s?this.getShapeUtil(o).canBind(a):this.getShapeUtil(o).canBind(a)&&this.getShapeUtil(s).canBind(a)}rotateShapesBy(e,n,r){const o=typeof e[0]=="string"?e:e.map(i=>i.id);if(o.length<=0)return this;const s=yO({editor:this,ids:o});return s?(up({delta:n,snapshot:s,editor:this,stage:"one-off",centerOverride:r==null?void 0:r.center}),this):this}getChangesToTranslateShape(e,n){var s,i,a;let r=e;const o=this.getShapeUtil(e);return r=So(r,((s=o.onTranslateStart)==null?void 0:s.call(o,r))??void 0),r=So(r,{id:e.id,type:e.type,x:n.x,y:n.y}),r=So(r,((i=o.onTranslate)==null?void 0:i.call(o,e,r))??void 0),r=So(r,((a=o.onTranslateEnd)==null?void 0:a.call(o,e,r))??void 0),r}nudgeShapes(e,n){const r=typeof e[0]=="string"?e:e.map(s=>s.id);if(r.length<=0)return this;const o=[];for(const s of r){const i=this.getShape(s),a=x.From(n),l=this.getShapeParentTransform(i);l&&a.rot(-l.rotation()),o.push(this.getChangesToTranslateShape(i,a.add(i)))}return this.updateShapes(o),this}duplicateShapes(e,n){return this.run(()=>{const r=typeof e[0]=="string"?e:e.map(p=>p.id);if(r.length<=0)return this;const o=new Set(r),s=this.getShapeAndDescendantIds(r),i=[...s].reverse(),a=new Map;for(const p of s)a.set(p,Ke());const{shapesToCreateWithOriginals:l,bindingsToCreate:c}=NI(this,s,p=>{const f=[];for(const m of p){const v=this.getBinding(m);if(!v)continue;const y=Qi();f.push({...v,id:y,fromId:zn(a.get(v.fromId)),toId:zn(a.get(v.toId))})}const g=[];for(const m of i){const v=zn(a.get(m)),y=this.getShape(m);if(!y)continue;let S=0,b=0;if(n&&o.has(m)){const P=this.getShapeParentTransform(y),C=new x(n.x,n.y).rot(-P.rotation());S=C.x,b=C.y}g.push({shape:{...y,id:v,x:y.x+S,y:y.y+b,index:"a1",parentId:a.get(y.parentId)??y.parentId},originalShape:y})}return{shapesToCreateWithOriginals:g,bindingsToCreate:f}});l.forEach(({shape:p,originalShape:f})=>{const g=f.parentId,m=this.getSortedChildIdsForParent(g),v=m.indexOf(f.id),y=m[v+1],S=y?this.getShape(y):void 0,b=$u(f.index,S==null?void 0:S.index);p.index=b});const u=l.map(({shape:p})=>p);if(u.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage){xh(this);return}if(this.createShapes(u),this.createBindings(c),this.setSelectedShapes(me(r.map(p=>a.get(p)))),n!==void 0){const p=this.getSelectionPageBounds(),f=this.getViewportPageBounds();p&&!f.contains(p)&&this.centerOnPoint(p.center,{animation:{duration:this.options.animationMediumMs}})}}),this}moveShapesToPage(e,n){const r=typeof e[0]=="string"?e:e.map(a=>a.id);if(r.length===0)return this;if(this.getIsReadonly())return this;const o=this.getCurrentPageId();if(n===o)return this;if(!this.store.has(n))return this;const s=this.getContentFromCurrentPage(r);if(!s)return this;if(this.getPageShapeIds(n).size+s.shapes.length>this.options.maxShapesPerPage)return xh(this,n),this;const i=this.getCamera().z;return this.run(()=>{this.deleteShapes(r),this.setCurrentPage(n),this.setFocusedGroup(null),this.selectNone(),this.putContentOntoCurrentPage(s,{select:!0,preserveIds:!0,preservePosition:!0}),this.setCamera({...this.getCamera(),z:i}),this.centerOnPoint(this.getSelectionRotatedPageBounds().center)}),this}toggleLock(e){const n=typeof e[0]=="string"?e:e.map(i=>i.id);if(this.getIsReadonly()||n.length===0)return this;let r=!0,o=!0;const s=[];for(const i of n){const a=this.getShape(i);a&&(s.push(a),a.isLocked?o=!1:r=!1)}return this.run(()=>{o?(this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!0}))),this.setSelectedShapes([])):r?this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!1}))):this.updateShapes(s.map(i=>({id:i.id,type:i.type,isLocked:!0})))}),this}sendToBack(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=Sh(this,"toBack",n,{considerAllShapes:!0});return r&&this.updateShapes(r),this}sendBackward(e,n={}){const r=typeof e[0]=="string"?e:e.map(s=>s.id),o=Sh(this,"backward",r,n);return o&&this.updateShapes(o),this}bringForward(e,n={}){const r=typeof e[0]=="string"?e:e.map(s=>s.id),o=Sh(this,"forward",r,n);return o&&this.updateShapes(o),this}bringToFront(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id),r=Sh(this,"toFront",n);return r&&this.updateShapes(r),this}flipShapes(e,n){const r=typeof e[0]=="string"?e:e.map(i=>i.id);if(this.getIsReadonly())return this;let o=me(r.map(i=>this.getShape(i)));if(!o.length)return this;o=me(o.map(i=>this.isShapeOfType(i,"group")?this.getSortedChildIdsForParent(i.id).map(a=>this.getShape(a)):i).flat());const s=Z.Common(me(o.map(i=>this.getShapePageBounds(i)))).center;return this.run(()=>{for(const i of o){const a=this.getShapeGeometry(i).bounds,l=this.getShapePageTransform(i.id);l&&this.resizeShape(i.id,{x:n==="horizontal"?-1:1,y:n==="vertical"?-1:1},{initialBounds:a,initialPageTransform:l,initialShape:i,mode:"scale_shape",isAspectRatioLocked:this.getShapeUtil(i).isAspectRatioLocked(i),scaleOrigin:s,scaleAxisRotation:0})}}),this}stackShapes(e,n,r){const o=typeof e[0]=="string"?e:e.map(m=>m.id);if(this.getIsReadonly())return this;const s=o.map(m=>this.getShape(m)).filter(m=>m?this.getShapeUtil(m).canBeLaidOut(m):!1),i=s.length;if(r===0&&i<3||i<2)return this;const a=Object.fromEntries(s.map(m=>[m.id,this.getShapePageBounds(m)]));let l,c,u,h;n==="horizontal"?(l="x",c="minX",u="maxX",h="width"):(l="y",c="minY",u="maxY",h="height");let p;if(r===0){const m=[];s.sort((y,S)=>a[y.id][c]-a[S.id][c]);for(let y=0;y<i-1;y++){const S=s[y],b=s[y+1],P=a[S.id],_=a[b.id][c]-P[u],E=m.find(k=>k.gap===_);E?E.count++:m.push({gap:_,count:1})}let v=0;m.forEach(y=>{y.count>v&&(v=y.count,p=y.gap)}),v===1&&(p=Math.max(0,m.reduce((y,S)=>y+S.gap*S.count,0)/(i-1)))}else p=r;const f=[];let g=a[s[0].id][u];return s.forEach((m,v)=>{var C,_;if(v===0)return;const y={x:0,y:0};y[l]=g+p-a[m.id][l];const S=this.getShapeParent(m),b=S?x.Rot(y,-this.getShapePageTransform(S).decompose().rotation):y,P=(_=(C=this.getShapeUtil(m)).onTranslateStart)==null?void 0:_.call(C,m);f.push(P?{...P,[l]:m[l]+b[l]}:{id:m.id,type:m.type,[l]:m[l]+b[l]}),g+=a[m.id][h]+p}),this.updateShapes(f),this}packShapes(e,n){var _,E;const r=typeof e[0]=="string"?e:e.map(k=>k.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=r.map(k=>this.getShape(k)).filter(k=>k?this.getShapeUtil(k).canBeLaidOut(k):!1),s={},i={};let a,l,c=0;for(let k=0;k<o.length;k++)a=o[k],l=this.getShapePageBounds(a),s[a.id]=l,i[a.id]=l.clone(),c+=l.width*l.height;const u=Z.Common(me(Object.values(s))),h=u.width;o.sort((k,D)=>s[D.id].height-s[k.id].height);const p=Math.max(Math.ceil(Math.sqrt(c/.95)),h),f=[new Z(u.x,u.y,p,1/0)];let g=0,m=0,v,y;for(let k=0;k<o.length;k++){a=o[k],l=i[a.id];for(let D=f.length-1;D>=0;D--)if(v=f[D],!(l.width>v.width||l.height>v.height)){l.x=v.x,l.y=v.y,m=Math.max(m,l.maxY),g=Math.max(g,l.maxX),l.width===v.width&&l.height===v.height?(y=f.pop(),D<f.length&&(f[D]=y)):l.height===v.height?(v.x+=l.width+n,v.width-=l.width+n):l.width===v.width?(v.y+=l.height+n,v.height-=l.height+n):(f.push(new Z(v.x+(l.width+n),v.y,v.width-(l.width+n),l.height)),v.y+=l.height+n,v.height-=l.height+n);break}}const S=Z.Common(Object.values(i)),b=x.Sub(u.center,S.center);let P;const C=[];for(let k=0;k<o.length;k++){a=o[k],l=s[a.id],P=i[a.id];const D=x.Sub(P.point,l.point).add(b),T=this.getShapeParentTransform(a);T&&D.rot(-T.rotation());const j={id:a.id,type:a.type,x:a.x+D.x,y:a.y+D.y},$=(E=(_=this.getShapeUtil(a)).onTranslateStart)==null?void 0:E.call(_,{...a,...j});$?C.push({...j,...$}):C.push(j)}return C.length&&this.updateShapes(C),this}alignShapes(e,n){const r=typeof e[0]=="string"?e:e.map(l=>l.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=me(r.map(l=>this.getShape(l))),s=Object.fromEntries(o.map(l=>[l.id,this.getShapePageBounds(l)])),i=Z.Common(me(Object.values(s))),a=[];return o.forEach(l=>{const c=s[l.id];if(!c)return;const u={x:0,y:0};switch(n){case"top":{u.y=i.minY-c.minY;break}case"center-vertical":{u.y=i.midY-c.minY-c.height/2;break}case"bottom":{u.y=i.maxY-c.minY-c.height;break}case"left":{u.x=i.minX-c.minX;break}case"center-horizontal":{u.x=i.midX-c.minX-c.width/2;break}case"right":{u.x=i.maxX-c.minX-c.width;break}}const h=this.getShapeParent(l),p=h?x.Rot(u,-this.getShapePageTransform(h).decompose().rotation):u;a.push(this.getChangesToTranslateShape(l,x.Add(l,p)))}),this.updateShapes(a),this}distributeShapes(e,n){const r=typeof e[0]=="string"?e:e.map(S=>S.id);if(this.getIsReadonly())return this;if(r.length<3)return this;const o=r.length,s=me(r.map(S=>this.getShape(S))),i=Object.fromEntries(s.map(S=>[S.id,this.getShapePageBounds(S)]));let a,l,c,u,h;n==="horizontal"?(a="x",l="minX",c="maxX",u="midX",h="width"):(a="y",l="minY",c="maxY",u="midY",h="height");const p=[],f=s.sort((S,b)=>i[S.id][l]-i[b.id][l])[0],g=s.sort((S,b)=>i[b.id][c]-i[S.id][c])[0],m=i[f.id][u],v=(i[g.id][u]-m)/(o-1),y=m+v;return s.filter(S=>S!==f&&S!==g).sort((S,b)=>i[S.id][u]-i[b.id][u]).forEach((S,b)=>{const P={x:0,y:0};P[a]=y+v*b-i[S.id][h]/2-i[S.id][a];const C=this.getShapeParent(S),_=C?x.Rot(P,-this.getShapePageTransform(C).rotation()):P;p.push(this.getChangesToTranslateShape(S,x.Add(S,_)))}),this.updateShapes(p),this}stretchShapes(e,n){const r=typeof e[0]=="string"?e:e.map(l=>l.id);if(this.getIsReadonly())return this;if(r.length<2)return this;const o=me(r.map(l=>this.getShape(l))),s=Object.fromEntries(r.map(l=>[l,this.getShapeGeometry(l).bounds])),i=Object.fromEntries(r.map(l=>[l,this.getShapePageBounds(l)])),a=Z.Common(me(Object.values(i)));switch(n){case"vertical":{this.run(()=>{for(const l of o){if(this.getShapePageTransform(l).rotation()%Ne)continue;const u=s[l.id],h=i[l.id],p=new x(0,a.minY-h.minY),f=this.getShapeParentTransform(l);f&&p.rot(-f.rotation());const{x:g,y:m}=x.Add(p,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:m}]);const v=new x(1,a.height/h.height);this.resizeShape(l.id,v,{initialBounds:u,scaleOrigin:new x(h.center.x,a.minY),isAspectRatioLocked:this.getShapeUtil(l).isAspectRatioLocked(l),scaleAxisRotation:0})}});break}case"horizontal":{this.run(()=>{for(const l of o){const c=s[l.id],u=i[l.id];if(this.getShapePageTransform(l).rotation()%Ne)continue;const p=new x(a.minX-u.minX,0),f=this.getShapeParentTransform(l);f&&p.rot(-f.rotation());const{x:g,y:m}=x.Add(p,l);this.updateShapes([{id:l.id,type:l.type,x:g,y:m}]);const v=new x(a.width/u.width,1);this.resizeShape(l.id,v,{initialBounds:c,scaleOrigin:new x(a.minX,u.center.y),isAspectRatioLocked:this.getShapeUtil(l).isAspectRatioLocked(l),scaleAxisRotation:0})}});break}}return this}resizeShape(e,n,r={}){var f,g,m;const o=typeof e=="string"?e:e.id;if(this.getIsReadonly())return this;Number.isFinite(n.x)||(n=new x(1,n.y)),Number.isFinite(n.y)||(n=new x(n.x,1));const s=r.initialShape??this.getShape(o);if(!s)return this;const i=r.scaleOrigin??((f=this.getShapePageBounds(o))==null?void 0:f.center);if(!i)return this;const a=r.initialPageTransform?q.Cast(r.initialPageTransform):this.getShapePageTransform(o);if(!a)return this;const l=a.rotation();if(l==null)return this;const c=r.scaleAxisRotation??l,u=r.initialBounds??this.getShapeGeometry(o).bounds;if(!u)return this;const h=r.isAspectRatioLocked??this.getShapeUtil(s).isAspectRatioLocked(s);if(!lj(l,c))return this._resizeUnalignedShape(o,n,{...r,initialBounds:u,scaleOrigin:i,scaleAxisRotation:c,initialPageTransform:a,isAspectRatioLocked:h,initialShape:s});const p=this.getShapeUtil(s);if(h&&(Math.abs(n.x)>Math.abs(n.y)?n=new x(n.x,Math.sign(n.y)*Math.abs(n.x)):n=new x(Math.sign(n.x)*Math.abs(n.y),n.y)),p.onResize&&p.canResize(s)){const v=this._scalePagePoint(q.applyToPoint(a,new x(0,0)),i,n,c),y=this.getPointInParentSpace(s.id,v),S=new x(n.x,n.y),b=ui((l-c)%Math.PI,0);S.x=b?n.x:n.y,S.y=b?n.y:n.x;const P=q.applyToPoint(a,new x),{x:C,y:_}=this.getPointInParentSpace(s.id,P);let E=s;r.skipStartAndEndCallbacks||(E=So(s,((g=p.onResizeStart)==null?void 0:g.call(p,s))??void 0)),E=So(E,{id:o,type:s.type,x:y.x,y:y.y,...p.onResize({...s,x:C,y:_},{newPoint:y,handle:r.dragHandle??"bottom_right",mode:r.mode??"scale_shape",scaleX:S.x,scaleY:S.y,initialBounds:u,initialShape:s})}),r.skipStartAndEndCallbacks||(E=So(E,((m=p.onResizeEnd)==null?void 0:m.call(p,s,E))??void 0)),this.updateShapes([E])}else{const v=q.applyToPoint(a,u.center),y=this._scalePagePoint(v,i,n,c),S=this.getPointInParentSpace(s.id,v),b=this.getPointInParentSpace(s.id,y),P=x.Sub(b,S);this.updateShapes([{id:o,type:s.type,x:s.x+P.x,y:s.y+P.y}])}return this}_scalePagePoint(e,n,r,o){const s=x.RotWith(e,n,-o).sub(n),i=x.MulV(s,r);return x.Add(i,n).rotWith(n,o)}_resizeUnalignedShape(e,n,r){const{type:o}=r.initialShape,s=new x(n.x,n.y);if(Math.abs(n.x)>Math.abs(n.y)?s.x=Math.sign(n.x)*Math.abs(n.y):s.y=Math.sign(n.y)*Math.abs(n.x),this.resizeShape(e,s,{initialShape:r.initialShape,initialBounds:r.initialBounds,isAspectRatioLocked:r.isAspectRatioLocked}),Math.sign(n.x)*Math.sign(n.y)<0){let{rotation:v}=q.Decompose(r.initialPageTransform);v-=2*v,this.updateShapes([{id:e,type:o,rotation:v}])}const i=q.applyToPoint(r.initialPageTransform,r.initialBounds.center),a=this._scalePagePoint(i,r.scaleOrigin,n,r.scaleAxisRotation),l=this.getShapePageBounds(e),c=this.getShapePageTransform(e),u=l.center,h=c.point();if(!u||!h)return this;const p=x.Sub(a,u),f=x.Add(h,p),{x:g,y:m}=this.getPointInParentSpace(e,f);return this.updateShapes([{id:e,type:o,x:g,y:m}]),this}getInitialMetaForShape(e){return{}}createShape(e){return this.createShapes([e]),this}createShapes(e){if(!Array.isArray(e))throw Error("Editor.createShapes: must provide an array of shapes or shape partials");if(this.getIsReadonly())return this;if(e.length<=0)return this;const n=this.getCurrentPageShapeIds();if(e.length+n.size>this.options.maxShapesPerPage)return xh(this),this;const o=this.getFocusedGroupId();return this.run(()=>{var u,h;const s=this.getCurrentPageShapesSorted(),i=e.map(p=>{if(p.id||(p={id:Ke(),...p}),!p.parentId||!(this.store.has(p.parentId)||e.some(f=>f.id===p.parentId))){let f=this.getFocusedGroupId();for(let m=s.length-1;m>=0;m--){const v=s[m];if(!this.isShapeHidden(v)&&this.getShapeUtil(v).canReceiveNewChildrenOfType(v,p.type)&&this.isPointInShape(v,{x:p.x??0,y:p.y??0},{margin:0,hitInside:!0})){f=v.id;break}}const g=p.parentId;if(f===p.id&&(f=o),f!==g&&(p={...p},p.parentId=f,Fn(f))){const m=this.getPointInShapeSpace(this.getShape(f),{x:p.x??0,y:p.y??0});p.x=m.x,p.y=m.y,p.rotation=-this.getShapePageTransform(f).rotation()+(p.rotation??0)}}return p}),a=new Map,l=[],{opacityForNextShape:c}=this.getInstanceState();for(const p of i){const f=this.getShapeUtil(p);let g=p.index;if(!g){const S=p.parentId??o;a.has(S)||a.set(S,this.getHighestIndexForParent(S)),g=a.get(S),a.set(S,Io(g))}const m=f.getDefaultProps();for(const[S,b]of this.styleProps[p.type])m[b]=this.getStyleForNextShape(S);let v=this.store.schema.types.shape.create({...p,index:g,opacity:p.opacity??c,parentId:p.parentId??o,props:"props"in p?{...m,...p.props}:m});if(v.index===void 0)throw Error("no index!");const y=(h=(u=this.getShapeUtil(v)).onBeforeCreate)==null?void 0:h.call(u,v);y&&(v=y),l.push(v)}l.forEach(p=>{p.meta={...this.getInitialMetaForShape(p),...p.meta}}),this.store.put(l)}),this}animateShape(e,n={animation:Ky}){return this.animateShapes([e],n)}animateShapes(e,n={animation:Ky}){if(!n.animation)return this;const{duration:r=500,easing:o=Dt.linear}=n.animation,s=ze();let i=r,a;const l=[];let c,u;for(let p=0,f=e.length;p<f;p++){if(c=e[p],!c)continue;const g=this.getShape(c.id);g&&(u={start:tt(g),end:So(tt(g),c)},l.push(u),this.animatingShapes.set(g.id,s))}const h=p=>{var v,y;if(i-=p,i<0){const{animatingShapes:S}=this,b=e.filter(P=>P&&S.get(P.id)===s);b.length&&this.updateShapes(b),this.off("tick",h);return}a=o(1-i/r);const{animatingShapes:f}=this,g=[];let m;for(let S=0,b=l.length;S<b;S++){const{start:P,end:C}=l[S];m=f.get(P.id),m===s&&g.push({...C,x:P.x+(C.x-P.x)*a,y:P.y+(C.y-P.y)*a,opacity:P.opacity+(C.opacity-P.opacity)*a,rotation:P.rotation+(C.rotation-P.rotation)*a,props:((y=(v=this.getShapeUtil(C)).getInterpolatedProps)==null?void 0:y.call(v,P,C,a))??C.props})}this._updateShapes(g)};return this.on("tick",h),this}groupShapes(e,n={}){var g;const{groupId:r=Ke(),select:o=!0}=n;if(!Array.isArray(e))throw Error("Editor.groupShapes: must provide an array of shapes or shape ids");if(this.getIsReadonly())return this;const s=typeof e[0]=="string"?e:e.map(m=>m.id);if(s.length<=1)return this;const i=me((this._shouldIgnoreShapeLock?s:this._getUnlockedShapeIds(s)).map(m=>this.getShape(m))),a=i.sort(cn).map(m=>m.id),l=Z.Common(me(i.map(m=>this.getShapePageBounds(m)))),{x:c,y:u}=l.point,h=this.findCommonAncestor(i)??this.getCurrentPageId();if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const p=i.filter(m=>m.parentId===h).sort(cn),f=(g=p[p.length-1])==null?void 0:g.index;return this.run(()=>{this.createShapes([{id:r,type:"group",parentId:h,index:f,x:c,y:u,opacity:1,props:{}}]),this.reparentShapes(a,r),o&&this.select(r)}),this}ungroupShapes(e,n={}){if(this.getIsReadonly())return this;const{select:r=!0}=n,o=typeof e[0]=="string"?e:e.map(l=>l.id),s=me((this._shouldIgnoreShapeLock?o:this._getUnlockedShapeIds(o)).map(l=>this.getShape(l)));if(s.length===0)return this;if(this.getCurrentToolId()!=="select")return this;this.isIn("select.idle")||this.cancel();const i=new Set,a=[];return s.forEach(l=>{this.isShapeOfType(l,"group")?a.push(l):i.add(l.id)}),a.length===0?this:(this.run(()=>{let l;for(let c=0,u=a.length;c<u;c++){l=a[c];const h=this.getSortedChildIdsForParent(l.id);for(let p=0,f=h.length;p<f;p++)i.add(h[p]);this.reparentShapes(h,l.parentId,l.index)}this.deleteShapes(a.map(c=>c.id)),r&&this.select(...i)}),this)}updateShape(e){return this.updateShapes([e]),this}updateShapes(e){const n=Array(e.length);for(let r=0,o=e.length;r<o;r++){const s=e[r];if(!s)continue;const i=this.getShape(s.id);if(i){if(!this._shouldIgnoreShapeLock){if(i.isLocked){if(!(Object.hasOwn(s,"isLocked")&&!s.isLocked))continue}else if(this.isShapeOrAncestorLocked(i))continue}this.animatingShapes.delete(s.id),n.push(s)}}return this._updateShapes(n),this}_updateShapes(e){this.getIsReadonly()||this.run(()=>{var s,i;const n=[];let r,o;for(let a=0,l=e.length;a<l;a++){const c=e[a];c&&(r=this.getShape(c.id),r&&(o=So(r,c),o!==r&&(o=((i=(s=this.getShapeUtil(r)).onBeforeUpdate)==null?void 0:i.call(s,r,o))??o,n.push(o))))}this.store.put(n)})}_getUnlockedShapeIds(e){return e.filter(n=>{var r;return!((r=this.getShape(n))!=null&&r.isLocked)})}deleteShapes(e){if(this.getIsReadonly())return this;if(!Array.isArray(e))throw Error("Editor.deleteShapes: must provide an array of shapes or shapeIds");const n=typeof e[0]=="string"?e:e.map(s=>s.id),r=this._shouldIgnoreShapeLock?n:this._getUnlockedShapeIds(n);if(r.length===0)return this;const o=new Set(r);for(const s of r)this.visitDescendants(s,i=>{o.add(i)});return this.run(()=>this.store.remove([...o]))}deleteShape(e){return this.deleteShapes([typeof e=="string"?e:e.id]),this}_extractSharedStyles(e,n){if(this.isShapeOfType(e,"group")){const r=this._parentIdsToChildIds.get()[e.id];if(!r)return;for(let o=0,s=r.length;o<s;o++)this._extractSharedStyles(this.getShape(r[o]),n)}else for(const[r,o]of this.styleProps[e.type])n.applyValue(r,hn(e.props,o))}_getSelectionSharedStyles(){const e=this.getSelectedShapes(),n=new Tx;for(const r of e)this._extractSharedStyles(r,n);return n}getStyleForNextShape(e){const n=this.getInstanceState().stylesForNextShape[e.id];return n===void 0?e.defaultValue:n}getShapeStyleIfExists(e,n){const r=this.styleProps[e.type].get(n);if(r!==void 0)return hn(e.props,r)}getSharedStyles(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0)return this._getSelectionSharedStyles();const e=this.root.getCurrent(),n=new Tx;if(!e)return n;if(e.shapeType)for(const r of this.styleProps[e.shapeType].keys())n.applyValue(r,this.getStyleForNextShape(r));return n}getSharedOpacity(){if(this.isIn("select")&&this.getSelectedShapeIds().length>0){const e=[],n=o=>{const s=this.getShape(o);if(s)if(this.isShapeOfType(s,"group"))for(const i of this.getSortedChildIdsForParent(s.id))n(i);else e.push(s)};for(const o of this.getSelectedShapeIds())n(o);let r=null;for(const o of e)if(r===null)r=o.opacity;else if(r!==o.opacity)return{type:"mixed"};if(r!==null)return{type:"shared",value:r}}return{type:"shared",value:this.getInstanceState().opacityForNextShape}}setOpacityForNextShapes(e,n){return this.updateInstanceState({opacityForNextShape:e},n),this}setOpacityForSelectedShapes(e){const n=this.getSelectedShapes();if(n.length>0){const r=[],o=s=>{if(this.isShapeOfType(s,"group")){const i=this.getSortedChildIdsForParent(s);for(const a of i)o(this.getShape(a))}else r.push(s)};for(const s of n)o(s);this.updateShapes(r.map(s=>({id:s.id,type:s.type,opacity:e})))}return this}setStyleForNextShapes(e,n,r){const o=this.getInstanceState().stylesForNextShape;return this.updateInstanceState({stylesForNextShape:{...o,[e.id]:n}},r),this}setStyleForSelectedShapes(e,n){const r=this.getSelectedShapes();if(r.length>0){const o=[],s=i=>{if(this.isShapeOfType(i,"group")){const a=this.getSortedChildIdsForParent(i.id);for(const l of a)s(this.getShape(l))}else{const a=this.getShapeUtil(i),l=this.styleProps[i.type].get(e);if(l){const c={id:i.id,type:i.type,props:{[l]:n}};o.push({util:a,originalShape:i,updatePartial:c})}}};for(const i of r)s(i);this.updateShapes(o.map(({updatePartial:i})=>i))}return this}registerExternalAssetHandler(e,n){return this.externalAssetContentHandlers[e]=n,this}createTemporaryAssetPreview(e,n){if(this.temporaryAssetPreview.has(e))return this.temporaryAssetPreview.get(e);const r=URL.createObjectURL(n);return this.temporaryAssetPreview.set(e,r),setTimeout(()=>{this.temporaryAssetPreview.delete(e),URL.revokeObjectURL(r)},this.options.temporaryAssetPreviewLifetimeMs),r}getTemporaryAssetPreview(e){return this.temporaryAssetPreview.get(e)}async getAssetForExternalContent(e){var n,r;return await((r=(n=this.externalAssetContentHandlers)[e.type])==null?void 0:r.call(n,e))}hasExternalAssetHandler(e){return!!this.externalAssetContentHandlers[e]}registerExternalContentHandler(e,n){return this.externalContentHandlers[e]=n,this}async putExternalContent(e){var n,r;return(r=(n=this.externalContentHandlers)[e.type])==null?void 0:r.call(n,e)}getContentFromCurrentPage(e){const n=typeof e[0]=="string"?e:e.map(o=>o.id);if(!n||n.length===0)return;const r=this.getShapeAndDescendantIds(n);return NI(this,r,o=>{const s=[];for(const u of o){const h=this.getBinding(u);h&&s.push(h)}const i=[],a=[];for(const u of r){const h=this.getShape(u);if(!h)continue;if(!r.has(h.parentId)){const f=this.getShapePageTransform(h.id),g=f.point();a.push({...h,x:g.x,y:g.y,rotation:f.rotation(),parentId:this.getCurrentPageId()}),i.push(h.id)}else a.push(h)}const l=[],c=new Set;for(const u of a){if(!("assetId"in u.props))continue;const h=u.props.assetId;if(!h||c.has(h))continue;c.add(h);const p=this.getAsset(h);p&&l.push(p)}return{schema:this.store.schema.serialize(),shapes:a,rootShapeIds:i,bindings:s,assets:l}})}async resolveAssetsInContent(e){if(!e)return;const n=[];return await Promise.allSettled(e.assets.map(async r=>{var o,s,i;if((r.type==="image"||r.type==="video")&&!((o=r.props.src)!=null&&o.startsWith("data:image"))&&!((s=r.props.src)!=null&&s.startsWith("data:video"))&&!((i=r.props.src)!=null&&i.startsWith("http"))){const a=tt(r),l=await this.store.props.assets.resolve(r,{screenScale:1,steppedScreenScale:1,dpr:1,networkEffectiveType:null,shouldResolveToOriginal:!0});a.props.src=await Zr.blobToDataUrl(await Lo(l).then(c=>c.blob())),n.push(a)}else n.push(r)})),e.assets=n,e}putContentOntoCurrentPage(e,n={}){var T,j,$;if(this.getIsReadonly())return this;if(!e.schema)throw Error(`Could not put content:
106
106
  content is missing a schema.`);const{select:r=!1,preserveIds:o=!1,preservePosition:s=!1}=n;let{point:i=void 0}=n;const a=this.getCurrentPageId(),{rootShapeIds:l}=e,c=[],u=[],h=[],p={store:{...Object.fromEntries(e.assets.map(M=>[M.id,M])),...Object.fromEntries(e.shapes.map(M=>[M.id,M])),...Object.fromEntries(((T=e.bindings)==null?void 0:T.map(M=>[M.id,M]))??[])},schema:e.schema},f=this.store.schema.migrateStoreSnapshot(p);if(f.type==="error")throw Error("Could not put content: could not migrate content");for(const M of Object.values(f.value))switch(M.typeName){case"asset":{c.push(M);break}case"shape":{u.push(M);break}case"binding":{h.push(M);break}}const g=new Map(o?u.map(M=>[M.id,M.id]):u.map(M=>[M.id,Ke()])),m=new Map(o?h.map(M=>[M.id,M.id]):h.map(M=>[M.id,Qi()]));let v=this.getCurrentPageId(),y=1/0,S=[];for(const M of this.getSelectedShapes()){if(y===0)break;const O=this.isShapeOfType(M,"frame"),F=this.getShapeAncestors(M);O&&F.push(M);const B=O?F.length+1:F.length;if(B<y)y=B,S=F,v=O?M.id:M.parentId;else if(B===y){if(S.length!==F.length)throw Error(`Ancestors: ${S.length} !== ${F.length}`);if(S.length===0){v=a;break}else{v=a;for(let K=0;K<S.length&&F[K]===S[K];K++)v=F[K].id}}}let b=!1;if(!Rn(v)){const M=this.getShape(v);if(M){if(!this.getViewportPageBounds().includes(this.getShapePageBounds(M)))v=a;else if(l.length===1){const O=u.find(F=>F.id===l[0]);this.isShapeOfType(M,"frame")&&this.isShapeOfType(O,"frame")&&O.props.w===(M==null?void 0:M.props.w)&&O.props.h===(M==null?void 0:M.props.h)&&(b=!0)}}else v=a}b||(b=g.has(v)),b&&(v=this.getShape(v).parentId);let P=this.getHighestIndexForParent(v);const C=[],_=u.map(M=>{const O=g.get(M.id),F={...M,id:O};return l.includes(M.id)&&(F.parentId=a,C.push(F)),g.has(F.parentId)?F.parentId=g.get(M.parentId):(l.push(F.id),F.index=P,P=Io(P)),F});if(_.length+this.getCurrentPageShapeIds().size>this.options.maxShapesPerPage)return xh(this),this;const E=h.map(M=>({...M,id:zn(m.get(M.id)),fromId:zn(g.get(M.fromId)),toId:zn(g.get(M.toId))})),k=[],D=[];for(const M of c)this.store.has(M.id)||((M.type==="image"&&((j=M.props.src)!=null&&j.startsWith("data:image"))||M.type==="video"&&(($=M.props.src)!=null&&$.startsWith("data:video")))&&(D.push(tt(M)),M.props.src=null),k.push(M));return Promise.allSettled(D.map(async M=>{const O=await WQ(M.props.src,M.props.name,M.props.mimeType??"image/png"),F=await this.getAssetForExternalContent({type:"file",file:O,assetId:M.id});if(!F){this.deleteAssets([M.id]);return}this.updateAssets([{...F,id:M.id}])})),this.run(()=>{k.length>0&&this.createAssets(k),this.createShapes(_),this.createBindings(E),r&&this.select(...C.map(K=>K.id)),v!==a&&this.reparentShapes(C.map(K=>K.id),v);const M=_.map(K=>this.getShape(K.id)),O=Z.Common(M.map(K=>this.getShapePageBounds(K)));if(i===void 0)if(Rn(v)){const K=this.getViewportPageBounds();s||K.includes(Z.From(O))?i=O.center:i=K.center}else{const K=this.getShape(v);i=q.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(i).some(R=>this.isShapeOfType(R,"frame")&&R.props.w===K.props.w&&R.props.h===K.props.h);)i.x+=O.w+16}const F=Z.Common(me(C.map(({id:K})=>this.getShapePageBounds(K)))).center,B=x.Sub(i,F);this.updateShapes(C.map(({id:K})=>{const R=this.getShape(K),H=this.getShapeParentTransform(K).decompose().rotation,Y=x.Rot(B,-H);return{id:R.id,type:R.type,x:R.x+Y.x,y:R.y+Y.y}}))}),this}async getSvgElement(e,n={}){const r=typeof e[0]=="string"?e:e.map(o=>o.id);if(r.length!==0)return BQ(this,r,n)}async getSvgString(e,n={}){const r=await this.getSvgElement(e,n);return r?{svg:new XMLSerializer().serializeToString(r.svg),width:r.width,height:r.height}:void 0}async getSvg(e,n={}){const r=await this.getSvgElement(e,n);if(r)return r.svg}_updateInputsFromEvent(e){const{pointerVelocity:n,previousScreenPoint:r,previousPagePoint:o,currentScreenPoint:s,currentPagePoint:i}=this.inputs,{screenBounds:a}=this.store.unsafeGetWithoutCapture(bn),{x:l,y:c,z:u}=ah(()=>this.getCamera()),h=e.point.x-a.x,p=e.point.y-a.y,f=e.point.z??.5;r.setTo(s),o.setTo(i),s.set(h,p);const g=h/u-l,m=p/u-c;isFinite(g)&&isFinite(m)&&i.set(g,m,f),this.inputs.isPen=e.type==="pointer"&&e.isPen,(e.name==="pointer_down"||this.inputs.isPinching)&&(n.set(0,0),this.inputs.originScreenPoint.setTo(s),this.inputs.originPagePoint.setTo(i)),this.run(()=>{var v;this.store.put([{id:Mf,typeName:"pointer",x:i.x,y:i.y,lastActivityTimestamp:e.type==="pointer"&&e.pointerId===oI.CAMERA_MOVE?((v=this.store.unsafeGetWithoutCapture(Mf))==null?void 0:v.lastActivityTimestamp)??this._tickManager.now:this._tickManager.now,meta:{}}])},{history:"ignore"})}cancel(){return this.dispatch({type:"misc",name:"cancel"}),this}interrupt(){return this.dispatch({type:"misc",name:"interrupt"}),this}complete(){return this.dispatch({type:"misc",name:"complete"}),this}focus({focusContainer:e=!0}={}){return this.getIsFocused()?this:(e&&this.focusManager.focus(),this.updateInstanceState({isFocused:!0}),this)}blur({blurContainer:e=!0}={}){return this.getIsFocused()?(e?this.focusManager.blur():this.complete(),this.updateInstanceState({isFocused:!1}),this):this}getIsFocused(){return this.getInstanceState().isFocused}getIsReadonly(){return this.getInstanceState().isReadonly}getSnapshot(){return GZ(this.store)}loadSnapshot(e,n){return Wj(this.store,e,n),this}_zoomToFitPageContentAt100Percent(){const e=this.getCurrentPageBounds();e&&this.zoomToBounds(e,{immediate:!0,targetZoom:this.getBaseZoom()})}_navigateToDeepLink(e){this.run(()=>{switch(e.type){case"page":{const n=this.getPage(e.pageId);n&&this.setCurrentPage(n),this._zoomToFitPageContentAt100Percent();return}case"shapes":{const n=me(e.shapeIds.map(i=>this.getShape(i))),r={};for(const i of n){const a=this.getAncestorPageId(i);a&&(r[a]??(r[a]=[]),r[a].push(i))}const[o,s]=Object.entries(r).sort(([i,a],[l,c])=>c.length-a.length)[0]??["",[]];if(!o||!s.length)this._zoomToFitPageContentAt100Percent();else{this.setCurrentPage(o);const i=Z.Common(s.map(a=>this.getShapePageBounds(a)));this.zoomToBounds(i,{immediate:!0,targetZoom:this.getBaseZoom()})}return}case"viewport":{if(e.pageId){if(!this.getPage(e.pageId)){this._zoomToFitPageContentAt100Percent();return}this.setCurrentPage(e.pageId)}this.zoomToBounds(e.bounds,{immediate:!0,inset:0});return}default:Ot(e)}})}navigateToDeepLink(e){if(e&&"type"in e)return this._navigateToDeepLink(e),this;const r=new URL((e==null?void 0:e.url)??window.location.href).searchParams.get((e==null?void 0:e.param)??"d");if(!r)return this._zoomToFitPageContentAt100Percent(),this;try{this._navigateToDeepLink(YQ(r))}catch(o){console.warn(o),this._zoomToFitPageContentAt100Percent()}return this}createDeepLink(e){const n=new URL((e==null?void 0:e.url)??window.location.href);return n.searchParams.set((e==null?void 0:e.param)??"d",VQ((e==null?void 0:e.to)??{type:"viewport",pageId:this.options.maxPages===1?void 0:this.getCurrentPageId(),bounds:this.getViewportPageBounds()})),n}registerDeepLinkListener(e){if(e!=null&&e.getUrl&&!(e!=null&&e.onChange))throw Error("[tldraw:urlStateSync] If you specify getUrl, you must also specify the onChange callback.");const n=G("url with state",()=>{var l,c;const i=((l=e==null?void 0:e.getUrl)==null?void 0:l.call(e,this))??window.location.href;return this.createDeepLink({param:e==null?void 0:e.param,url:i,to:(c=e==null?void 0:e.getTarget)==null?void 0:c.call(e,this)}).toString()}),r=(e==null?void 0:e.onChange)??(()=>{var a;const i=this.createDeepLink({param:e==null?void 0:e.param,to:(a=e==null?void 0:e.getTarget)==null?void 0:a.call(e,this)});window.history.replaceState({},document.title,i.toString())}),o=vg(i=>i(),(e==null?void 0:e.debounceMs)??500),s=jo("update url on state change",()=>r(new URL(n.get()),this),{scheduleEffect:o});return()=>{s(),o.cancel()}}cancelDoubleClick(){this._clickManager.cancelDoubleClickTimeout()}_setShiftKeyTimeout(){this.inputs.shiftKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Shift",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),code:"ShiftLeft"})}_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,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),code:"AltLeft"})}_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,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),code:"ControlLeft"})}_setMetaKeyTimeout(){this.inputs.metaKey=!1,this.dispatch({type:"keyboard",name:"key_up",key:"Meta",shiftKey:this.inputs.shiftKey,ctrlKey:this.inputs.ctrlKey,altKey:this.inputs.altKey,metaKey:this.inputs.metaKey,accelKey:un(this.inputs),code:"MetaLeft"})}dispatch(e){return this._pendingEventsForNextTick.push(e),e.type==="pointer"&&e.name==="pointer_move"||e.type==="wheel"||e.type==="pinch"||this._flushEventsForTick(0),this}_flushEventsForTick(e){this.run(()=>{if(this._pendingEventsForNextTick.length>0){const n=[...this._pendingEventsForNextTick];this._pendingEventsForNextTick.length=0;for(const r of n)this._flushEventForTick(r)}e>0&&this.root.handleEvent({type:"misc",name:"tick",elapsed:e}),this.scribbles.tick(e)})}_flushEventForTick(e){if(this.getCrashingError())return this;const{inputs:n}=this,{type:r}=e;if(e.type==="misc"){(e.name==="cancel"||e.name==="complete")&&(this.inputs.isDragging=!1,this.inputs.isPanning&&(this.inputs.isPanning=!1,this.inputs.isSpacebarPanning=!1,this.setCursor({type:this._prevCursor,rotation:0}))),this.root.handleEvent(e);return}e.shiftKey?(clearTimeout(this._shiftKeyTimeout),this._shiftKeyTimeout=-1,n.shiftKey=!0):!e.shiftKey&&n.shiftKey&&this._shiftKeyTimeout===-1&&(this._shiftKeyTimeout=this.timers.setTimeout(this._setShiftKeyTimeout,150)),e.altKey?(clearTimeout(this._altKeyTimeout),this._altKeyTimeout=-1,n.altKey=!0):!e.altKey&&n.altKey&&this._altKeyTimeout===-1&&(this._altKeyTimeout=this.timers.setTimeout(this._setAltKeyTimeout,150)),e.ctrlKey?(clearTimeout(this._ctrlKeyTimeout),this._ctrlKeyTimeout=-1,n.ctrlKey=!0):!e.ctrlKey&&n.ctrlKey&&this._ctrlKeyTimeout===-1&&(this._ctrlKeyTimeout=this.timers.setTimeout(this._setCtrlKeyTimeout,150)),e.metaKey?(clearTimeout(this._metaKeyTimeout),this._metaKeyTimeout=-1,n.metaKey=!0):!e.metaKey&&n.metaKey&&this._metaKeyTimeout===-1&&(this._metaKeyTimeout=this.timers.setTimeout(this._setMetaKeyTimeout,150));const{originPagePoint:o,currentPagePoint:s}=n;n.isPointing||(n.isDragging=!1);const i=this.store.unsafeGetWithoutCapture(bn),a=this.store.get(this._getCurrentPageStateId()),l=this._cameraOptions.__unsafe__getWithoutCapture();switch(r){case"pinch":{if(l.isLocked)return;switch(clearTimeout(this._longPressTimeout),this._updateInputsFromEvent(e),e.name){case"pinch_start":{if(n.isPinching)return;n.isEditing||(this._pinchStart=this.getCamera().z,this._selectedShapeIdsAtPointerDown.length||(this._selectedShapeIdsAtPointerDown=[...a.selectedShapeIds]),this._didPinch=!0,n.isPinching=!0,this.interrupt());return}case"pinch":{if(!n.isPinching)return;const{point:{z:c=1},delta:{x:u,y:h}}=e,{x:p,y:f}=x.SubXY(e.point,i.screenBounds.x,i.screenBounds.y);this.stopCameraAnimation(),i.followingUserId&&this.stopFollowingUser();const{x:g,y:m,z:v}=ah(()=>this.getCamera()),{panSpeed:y,zoomSpeed:S}=l;this._setCamera(new x(g+u*y/v-p/v+p/(c*S),m+h*y/v-f/v+f/(c*S),c*S),{immediate:!0});return}case"pinch_end":{if(!n.isPinching)return this;n.isPinching=!1;const{_selectedShapeIdsAtPointerDown:c}=this;this.setSelectedShapes(this._selectedShapeIdsAtPointerDown),this._selectedShapeIdsAtPointerDown=[],this._didPinch&&(this._didPinch=!1,c.length>0&&this.once("tick",()=>{this._didPinch||this.setSelectedShapes(c)}));return}}}case"wheel":{if(l.isLocked)return;this._updateInputsFromEvent(e);const{panSpeed:c,zoomSpeed:u,wheelBehavior:h}=l;if(h!=="none"){this.stopCameraAnimation(),i.followingUserId&&this.stopFollowingUser();const{x:p,y:f,z:g}=ah(()=>this.getCamera()),{x:m,y:v,z:y=0}=e.delta;let S=h;switch(n.ctrlKey&&(S=h==="pan"?"zoom":"pan"),S){case"zoom":{const{x:b,y:P}=this.inputs.currentScreenPoint;let C=y;h==="zoom"&&(Math.abs(v)>10?C=10*Math.sign(v)/100:C=v/100);const _=g+(C??0)*u*g;this._setCamera(new x(p+(b/_-b)-(b/g-b),f+(P/_-P)-(P/g-P),_),{immediate:!0}),this.maybeTrackPerformance("Zooming");return}case"pan":{this._setCamera(new x(p+m*c/g,f+v*c/g,g),{immediate:!0}),this.maybeTrackPerformance("Panning");return}}}break}case"pointer":{if(n.isPinching)return;this._updateInputsFromEvent(e);const{isPen:c}=e,{isPenMode:u}=i;switch(e.name){case"pointer_down":{if(u&&!c)return;if(this.inputs.isPanning||(this._longPressTimeout=this.timers.setTimeout(()=>{const h=this.getViewportScreenBounds();this.dispatch({...e,point:this.inputs.originScreenPoint.clone().addXY(h.x,h.y),name:"long_press"})},this.options.longPressDurationMs)),this._selectedShapeIdsAtPointerDown=this.getSelectedShapeIds(),e.button===sI&&(this.capturedPointerId=e.pointerId),n.buttons.add(e.button),n.isPointing=!0,n.isDragging=!1,!u&&c&&this.updateInstanceState({isPenMode:!0}),e.button===iI?(this._restoreToolId=this.getCurrentToolId(),this.complete(),this.setCurrentTool("eraser")):e.button===fh&&(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(!c&&u)return;const{x:h,y:p,z:f}=ah(()=>this.getCamera());if(this.inputs.isPanning&&this.inputs.isPointing){const{currentScreenPoint:g,previousScreenPoint:m}=this.inputs,{panSpeed:v}=l,y=x.Sub(g,m);this.setCamera(new x(h+y.x*v/f,p+y.y*v/f,f),{immediate:!0}),this.maybeTrackPerformance("Panning");return}n.isPointing&&!n.isDragging&&x.Dist2(o,s)*this.getZoomLevel()>(i.isCoarsePointer?this.options.coarseDragDistanceSquared:this.options.dragDistanceSquared)/f&&(n.isDragging=!0,clearTimeout(this._longPressTimeout));break}case"pointer_up":{if(n.isDragging=!1,n.isPointing=!1,clearTimeout(this._longPressTimeout),n.buttons.delete(e.button),i.isPenMode&&!c)return;if(this.capturedPointerId===e.pointerId&&(this.capturedPointerId=null,e.button=0),n.isPanning){n.keys.has("Space")||(n.isPanning=!1,n.isSpacebarPanning=!1);const h=this.inputs.pointerVelocity,p=Math.min(2,h.len());switch(e.button){case sI:{this.setCursor({type:"grab",rotation:0});break}case fh:this.inputs.keys.has(" ")?this.setCursor({type:"grab",rotation:0}):this.setCursor({type:this._prevCursor,rotation:0})}p>0&&this.slideCamera({speed:p,direction:h})}else e.button===iI&&(this.complete(),this.setCurrentTool(this._restoreToolId));break}}break}case"keyboard":{switch(e.key==="ShiftRight"&&(e.key="ShiftLeft"),e.key==="AltRight"&&(e.key="AltLeft"),e.code==="ControlRight"&&(e.code="ControlLeft"),e.code==="MetaRight"&&(e.code="MetaLeft"),e.name){case"key_down":{if(n.keys.add(e.code),e.code==="Space"&&!e.ctrlKey&&(this.inputs.isPanning||(this._prevCursor=i.cursor.type),this.inputs.isPanning=!0,this.inputs.isSpacebarPanning=!0,clearTimeout(this._longPressTimeout),this.setCursor({type:this.inputs.isPointing?"grabbing":"grab",rotation:0})),this.inputs.isSpacebarPanning){let c;switch(e.code){case"ArrowUp":{c=new x(0,-1);break}case"ArrowRight":{c=new x(1,0);break}case"ArrowDown":{c=new x(0,1);break}case"ArrowLeft":{c=new x(-1,0);break}}if(c){const u=this.getViewportPageBounds(),h=u.clone().translate(c.mulV({x:u.w,y:u.h}));this._animateToViewport(h,{animation:{duration:320}})}}break}case"key_up":{n.keys.delete(e.code),e.code==="Space"&&(this.inputs.buttons.has(fh)||(this.inputs.isPanning=!1,this.inputs.isSpacebarPanning=!1,this.setCursor({type:this._prevCursor,rotation:0})));break}}break}}if(e.type==="pointer"){e.button===fh?e.name="middle_click":e.button===g1&&(e.name="right_click");const{isPenMode:c}=this.store.unsafeGetWithoutCapture(bn);if(e.isPen===c){const u=this._clickManager.handlePointerEvent(e);if(e.name!==u.name){this.root.handleEvent(e),this.emit("event",e),this.root.handleEvent(u),this.emit("event",u);return}}}return this.root.handleEvent(e),this.emit("event",e),e.type==="pointer"&&e.name==="pointer_down"&&this.menus.clearOpenMenus(),this}maybeTrackPerformance(e){bt.measurePerformance.get()&&(this.performanceTracker.isStarted()?clearTimeout(this.performanceTrackerTimeout):this.performanceTracker.start(e),this.performanceTrackerTimeout=this.timers.setTimeout(()=>{this.performanceTracker.stop()},50))}}J=mee(Ax);te(J,1,"getIsShapeHiddenCache",HR,Q);te(J,1,"getCanUndo",UR,Q);te(J,1,"getCanRedo",BR,Q);te(J,1,"getPath",zR,Q);te(J,1,"getCurrentTool",NR,Q);te(J,1,"getCurrentToolId",FR,Q);te(J,1,"getDocumentSettings",$R,Q);te(J,1,"getInstanceState",LR,Q);te(J,1,"getOpenMenus",RR,Q);te(J,1,"getIsMenuOpen",DR,Q);te(J,1,"getPageStates",OR,Q);te(J,1,"_getPageStatesQuery",jR,Q);te(J,1,"getCurrentPageState",AR,Q);te(J,1,"_getCurrentPageStateId",MR,Q);te(J,1,"getSelectedShapeIds",TR,Q);te(J,1,"getSelectedShapes",kR,Q);te(J,1,"getOnlySelectedShapeId",ER,Q);te(J,1,"getOnlySelectedShape",IR,Q);te(J,1,"getSelectionPageBounds",_R,Q);te(J,1,"getSelectionRotation",CR,Q);te(J,1,"getSelectionRotatedPageBounds",PR,Q);te(J,1,"getSelectionRotatedScreenBounds",bR,Q);te(J,1,"getFocusedGroupId",wR,Q);te(J,1,"getFocusedGroup",xR,Q);te(J,1,"getEditingShapeId",vR,Q);te(J,1,"getEditingShape",SR,Q);te(J,1,"getHoveredShapeId",yR,Q);te(J,1,"getHoveredShape",mR,Q);te(J,1,"getHintingShapeIds",gR,Q);te(J,1,"getHintingShape",fR,Q);te(J,1,"getErasingShapeIds",pR,Q);te(J,1,"getErasingShapes",hR,Q);te(J,1,"_unsafe_getCameraId",dR,Q);te(J,1,"getCamera",uR,Q);te(J,1,"getViewportPageBoundsForFollowing",cR,Q);te(J,1,"getCameraForFollowing",lR,Q);te(J,1,"getZoomLevel",aR,Q);te(J,1,"getViewportScreenBounds",iR,Q);te(J,1,"getViewportScreenCenter",sR,Q);te(J,1,"getViewportPageBounds",oR,Q);te(J,1,"_getCollaboratorsQuery",rR,Q);te(J,1,"getCollaborators",nR,Q);te(J,1,"getCollaboratorsOnCurrentPage",tR,Q);te(J,1,"getRenderingShapes",eR,Q);te(J,1,"_getAllPagesQuery",JD,Q);te(J,1,"getPages",QD,Q);te(J,1,"getCurrentPageId",ZD,Q);te(J,1,"getCurrentPageShapeIdsSorted",qD,Q);te(J,1,"_getAllAssetsQuery",XD,Q);te(J,1,"_getShapeGeometryCache",YD,Q);te(J,1,"_getShapeHandlesCache",VD,Q);te(J,1,"_getShapePageTransformCache",GD,Q);te(J,1,"_getShapePageBoundsCache",WD,Q);te(J,1,"_getShapeClipPathCache",KD,Q);te(J,1,"_getShapeMaskCache",HD,Q);te(J,1,"_getShapeMaskedPageBoundsCache",UD,Q);te(J,1,"_notVisibleShapes",BD,Q);te(J,1,"getCulledShapes",zD,Q);te(J,1,"getCurrentPageBounds",ND,Q);te(J,1,"getCurrentPageShapes",FD,Q);te(J,1,"getCurrentPageShapesSorted",$D,Q);te(J,1,"getCurrentPageRenderingShapesSorted",LD,Q);te(J,1,"_getBindingsIndexCache",RD,Q);te(J,1,"_getSelectionSharedStyles",DD,Q);te(J,1,"getSharedStyles",OD,Q);te(J,1,"getSharedOpacity",jD,Q);te(J,1,"getIsFocused",AD,Q);te(J,1,"getIsReadonly",MD,Q);te(J,1,"_setShiftKeyTimeout",TD,Q);te(J,1,"_setAltKeyTimeout",kD,Q);te(J,1,"_setCtrlKeyTimeout",ED,Q);te(J,1,"_setMetaKeyTimeout",ID,Q);See(J,Q);function xh(t,e=t.getCurrentPageId()){const n=t.getPage(e).name;t.emit("max-shapes",{name:n,pageId:e,count:t.options.maxShapesPerPage})}function So(t,e){if(!e)return t;let n=null;const r=Object.entries(e);for(let o=0,s=r.length;o<s;o++){const[i,a]=r[o];if(a!==void 0&&!(i==="id"||i==="type"||i==="typeName")&&a!==t[i]){if(n||(n={...t}),i==="props"||i==="meta"){n[i]={...t[i]};for(const[l,c]of Object.entries(a))n[i][l]=c;continue}n[i]=a}}return n||t}function KR(t,e,n){const r=t.getShape(e);if(!r)return;n.push(r);const o=t.getSortedChildIdsForParent(e);for(let s=0,i=o.length;s<i;s++)KR(t,o[s],n)}function NI(t,e,n){let r;if(t.run(()=>{const o=t.store.extractingChanges(()=>{const s=new Set,i=new Set;for(const a of e)if(t.getShape(a))for(const c of t.getBindingsInvolvingShape(a)){const u=e.has(c.fromId),h=e.has(c.toId);if(u&&h){s.add(c.id);continue}(!u||!h)&&i.add(c.id)}t.deleteBindings([...i],{isolateShapes:!0});try{r=wn.ok(n(s))}catch(a){r=wn.err(a)}});t.store.applyDiff(fx(o))},{history:"ignore"}),r.ok)return r.value;throw r.error}function zI(t,e){if(!e.constraints)throw Error("Should have constraints here");const{padding:{x:n,y:r}}=e.constraints,o=t.getViewportScreenBounds(),s=Z.From(e.constraints.bounds),i=(o.w-n*2)/s.w,a=(o.h-r*2)/s.h;return{zx:i,zy:a}}function xd(){const t=z(),e=md();return U("isDarkMode",()=>(e==null?void 0:e.isDarkMode)??t.user.getIsDarkMode(),[e,t])}const BI="<path d='m19.7432 17.0869-4.072 4.068 2.829 2.828-8.473-.013-.013-8.47 2.841 2.842 4.075-4.068 1.414-1.415-2.844-2.842h8.486v8.484l-2.83-2.827z' fill='%23fff'/><path d='m18.6826 16.7334-4.427 4.424 1.828 1.828-5.056-.016-.014-5.054 1.842 1.841 4.428-4.422 2.474-2.475-1.844-1.843h5.073v5.071l-1.83-1.828z' fill='%23000'/>",UI="<path d='m9 17.9907v.005l5.997 5.996.001-3.999h1.999 2.02v4l5.98-6.001-5.98-5.999.001 4.019-2.021.002h-2l.001-4.022zm1.411.003 3.587-3.588-.001 2.587h3.5 2.521v-2.585l3.565 3.586-3.564 3.585-.001-2.585h-2.521l-3.499-.001-.001 2.586z' fill='%23fff'/><path d='m17.4971 18.9932h2.521v2.586l3.565-3.586-3.565-3.585v2.605h-2.521-3.5v-2.607l-3.586 3.587 3.586 3.586v-2.587z' fill='%23000'/>",wh='<path d="M22.4789 9.45728L25.9935 12.9942L22.4789 16.5283V14.1032C18.126 14.1502 14.6071 17.6737 14.5675 22.0283H17.05L13.513 25.543L9.97889 22.0283H12.5674C12.6071 16.5691 17.0214 12.1503 22.4789 12.1031L22.4789 9.45728Z" fill="black"/><path fill-rule="evenodd" clip-rule="evenodd" d="M21.4789 7.03223L27.4035 12.9945L21.4789 18.9521V15.1868C18.4798 15.6549 16.1113 18.0273 15.649 21.0284H19.475L13.5128 26.953L7.55519 21.0284H11.6189C12.1243 15.8155 16.2679 11.6677 21.4789 11.1559L21.4789 7.03223ZM22.4789 12.1031C17.0214 12.1503 12.6071 16.5691 12.5674 22.0284H9.97889L13.513 25.543L17.05 22.0284H14.5675C14.5705 21.6896 14.5947 21.3558 14.6386 21.0284C15.1157 17.4741 17.9266 14.6592 21.4789 14.1761C21.8063 14.1316 22.1401 14.1069 22.4789 14.1032V16.5284L25.9935 12.9942L22.4789 9.45729L22.4789 12.1031Z" fill="white"/>';function Fs(t,e,n,r,o,s=16,i=16){const a=(-n-e)*(De/180),l=Math.sin(a),c=Math.cos(a),u=1*c-1*l,h=1*l+1*c;return`url("data:image/svg+xml,<svg height='32' width='32' viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' style='color: ${o};'><defs><filter id='shadow' y='-40%' x='-40%' width='180px' height='180%' color-interpolation-filters='sRGB'><feDropShadow dx='${u}' dy='${h}' stdDeviation='1.2' flood-opacity='.5'/></filter></defs><g fill='none' transform='rotate(${e+n} 16 16)${r?" scale(-1,-1) translate(0, -32)":""}' filter='url(%23shadow)'>`+t.replaceAll('"',"'")+`</g></svg>") ${s} ${i}, pointer`}const xee=["default","pointer","cross","move","grab","grabbing","text","zoom-in","zoom-out"],wee={none:()=>"none","ew-resize":(t,e,n)=>Fs(UI,t,0,e,n),"ns-resize":(t,e,n)=>Fs(UI,t,90,e,n),"nesw-resize":(t,e,n)=>Fs(BI,t,0,e,n),"nwse-resize":(t,e,n)=>Fs(BI,t,90,e,n),"nwse-rotate":(t,e,n)=>Fs(wh,t,0,e,n),"nesw-rotate":(t,e,n)=>Fs(wh,t,90,e,n),"senw-rotate":(t,e,n)=>Fs(wh,t,180,e,n),"swne-rotate":(t,e,n)=>Fs(wh,t,270,e,n)};function nr(t,e=0,n="black"){return wee[t](yX(e),!1,n)}function bee(){const t=z(),e=Mt(),n=xd();ci("useCursor",()=>{const{type:r,rotation:o}=t.getInstanceState().cursor;if(xee.includes(r)){e.style.setProperty("--tl-cursor",`var(--tl-cursor-${r})`);return}e.style.setProperty("--tl-cursor",nr(r,o,n?"white":"black"))},[t,e,n])}function Pee(){const t=z(),e=Mt(),n=xd(),r=U(bt.forceSrgb);Te.useEffect(()=>{n?(e.setAttribute("data-color-mode","dark"),e.classList.remove("tl-theme__light"),e.classList.add("tl-theme__dark")):(e.setAttribute("data-color-mode","light"),e.classList.remove("tl-theme__dark"),e.classList.add("tl-theme__light")),r?e.classList.add("tl-theme__force-sRGB"):e.classList.remove("tl-theme__force-sRGB")},[t,e,r,n])}function Cee(){const[t,e]=w.useState(0);w.useEffect(()=>e(n=>n+1),[])}const _ee=t=>t.props.src,Iee={upload:(t,e)=>Zr.blobToDataUrl(e)};function Eee(t){return"schema"in t&&t.schema?t.schema:iX({shapes:"shapeUtils"in t&&t.shapeUtils?HI(Xj(t.shapeUtils)):void 0,bindings:"bindingUtils"in t&&t.bindingUtils?HI(Vj(t.bindingUtils)):void 0,migrations:"migrations"in t?t.migrations:void 0})}function Hu({initialData:t,defaultName:e="",id:n,assets:r=Iee,onMount:o,collaboration:s,...i}={}){const a=Eee(i),l=new e1({id:n,schema:a,initialData:t,props:{defaultName:e,assets:{upload:r.upload,resolve:r.resolve??_ee},onMount:c=>{Le(c instanceof Q),o==null||o(c)},collaboration:s}});if(i.snapshot){if(t)throw new Error("Cannot provide both initialData and snapshot");Wj(l,i.snapshot)}return l}function HI(t){return Object.fromEntries(t.map(e=>[e.type,{props:e.props,migrations:e.migrations}]))}function kee(){window.alert(`Oops! We could not save changes to your browser's storage. We now need to reload the page and try again.
107
107
 
108
108
  Keep seeing this message?
@@ -192,7 +192,7 @@ To remove the watermark, please purchase a license at tldraw.dev.
192
192
  opacity: 1;
193
193
  pointer-events: all;
194
194
  }
195
- }`;return d.jsx("style",{children:n})}),ete=[],tte=[],nte=[],rte="tl-container",ote=w.memo(function({store:e,components:n,className:r,user:o,options:s,...i}){const[a,l]=w.useState(null),c=w.useMemo(()=>o??Bj(),[o]),u=(n==null?void 0:n.ErrorFallback)===void 0?jj:n==null?void 0:n.ErrorFallback,h={...i,shapeUtils:i.shapeUtils??ete,bindingUtils:i.bindingUtils??tte,tools:i.tools??nte,components:n,options:tc(s)};return d.jsx("div",{ref:l,"data-tldraw":oj,draggable:!1,className:le(`${rte} tl-theme__light`,r),onPointerDown:_t,tabIndex:-1,children:d.jsx(Uu,{fallback:u,onError:p=>vw(p,{tags:{origin:"react.tldraw-before-app"}}),children:a&&d.jsx(Wee,{licenseKey:i.licenseKey,children:d.jsx(dj,{container:a,children:d.jsx(MZ,{overrides:n,children:e?e instanceof e1?d.jsx(YR,{...h,store:e,user:c}):d.jsx(VR,{...h,store:e,user:c}):d.jsx(ste,{...h,store:e,user:c})})})})})})});function ste(t){const{defaultName:e,snapshot:n,initialData:r,shapeUtils:o,bindingUtils:s,persistenceKey:i,sessionId:a,user:l,assets:c}=t,u=Lee({shapeUtils:o,bindingUtils:s,initialData:r,persistenceKey:i,sessionId:a,defaultName:e,snapshot:n,assets:c});return d.jsx(VR,{...t,store:u,user:l})}const VR=w.memo(function({store:e,user:n,...r}){const o=Mt();w.useLayoutEffect(()=>{n.userPreferences.get().colorScheme==="dark"&&(o.classList.remove("tl-theme__light"),o.classList.add("tl-theme__dark"))},[o,n]);const{LoadingScreen:s}=rt();switch(e.status){case"error":throw e.error;case"loading":return s?d.jsx(s,{}):null}return d.jsx(YR,{...r,store:e.store,user:n})}),tS=()=>document.location.search.includes("tldraw_preserve_focus");function YR({onMount:t,children:e,store:n,tools:r,shapeUtils:o,bindingUtils:s,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:u,options:h,licenseKey:p,deepLinks:f,isShapeHidden:g}){const{ErrorFallback:m}=rt(),v=Mt(),[y,S]=WR(null),b=w.useRef(null),P=tc(f===!0?{}:f),C=w.useRef({autoFocus:l&&!tS(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P});w.useLayoutEffect(()=>{C.current={autoFocus:l&&!tS(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P}},[l,c,a,u,P]),w.useLayoutEffect(()=>{const{autoFocus:k,inferDarkMode:D,initialState:T,cameraOptions:j,deepLinks:$}=C.current,M=new Q({store:n,shapeUtils:o,bindingUtils:s,tools:r,getContainer:()=>v,user:i,initialState:T,autoFocus:k,inferDarkMode:D,cameraOptions:j,options:h,licenseKey:p,isShapeHidden:g});return M.updateViewportScreenBounds(b.current??v),$&&($!=null&&$.getUrl?M.navigateToDeepLink({...$,url:$.getUrl(M)}):M.navigateToDeepLink($)),S(M),()=>{M.dispose()}},[s,v,h,o,n,r,i,S,p,g]),w.useLayoutEffect(()=>{if(y&&P)return y.registerDeepLinkListener(P)},[y,P]),w.useLayoutEffect(()=>{y&&u&&y.setCameraOptions(u)},[y,u]);const _=w.useSyncExternalStore(w.useCallback(k=>y?(y.on("crash",k),()=>y.off("crash",k)):()=>{},[y]),()=>(y==null?void 0:y.getCrashingError())??null);w.useEffect(function(){if(!y)return;function D(){y&&y.focus()}function T(){y&&y.blur()}if(l&&tS())return y.getContainer().addEventListener("pointerdown",D),document.body.addEventListener("pointerdown",T),()=>{var j;(j=y.getContainer())==null||j.removeEventListener("pointerdown",D),document.body.removeEventListener("pointerdown",T)}},[y,l]);const{Canvas:E}=rt();return y?d.jsx(Uu,{fallback:m,onError:k=>y.annotateError(k,{origin:"react.tldraw",willCrashApp:!0}),children:_?d.jsx(ate,{crashingError:_}):d.jsx(p1,{editor:y,children:d.jsxs(ite,{onMount:t,children:[e??(E?d.jsx(E,{},y.contextId):null),d.jsx(Zee,{})]})})}):d.jsx("div",{className:"tl-canvas",ref:b})}function ite({children:t,onMount:e}){return $ee(),bee(),Pee(),Cee(),qR(n=>{const r=n.store.props.onMount(n),o=e==null?void 0:e(n);return()=>{r==null||r(),o==null||o()}}),t}function ate({crashingError:t}){throw t}function D1({children:t}){return d.jsx("div",{className:"tl-loading",children:t})}function XR({children:t}){return d.jsx("div",{className:"tl-loading",children:t})}function qR(t){const e=z(),n=Hg(r=>{let o;return r.run(()=>{o=t==null?void 0:t(r),r.emit("mount")},{history:"ignore"}),window.tldrawReady=!0,o});Te.useLayoutEffect(()=>{if(e)return n==null?void 0:n(e)},[e,n])}function di({children:t,className:e="",...n}){return d.jsx("div",{...n,className:le("tl-html-container",e),children:t})}class dp{constructor(e){this.editor=e}}I(dp,"props"),I(dp,"migrations"),I(dp,"type");function qg(t,e,n={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=e,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=n;let h=t.props.w*s,p=t.props.h*i;const f=new x(0,0);if(h>0){if(h<a){switch(o){case"top_left":case"left":case"bottom_left":{f.x=h-a;break}case"top":case"bottom":{f.x=(h-a)/2;break}default:f.x=0}h=a}}else if(f.x=h,h=-h,h<a){switch(o){case"top_left":case"left":case"bottom_left":{f.x=-h;break}default:f.x=-a}h=a}if(p>0){if(p<c){switch(o){case"top_left":case"top":case"top_right":{f.y=p-c;break}case"right":case"left":{f.y=(p-c)/2;break}default:f.y=0}p=c}}else if(f.y=p,p=-p,p<c){switch(o){case"top_left":case"top":case"top_right":{f.y=-p;break}default:f.y=-c}p=c}const{x:g,y:m}=f.rot(t.rotation).add(r);return{...t,x:g,y:m,props:{w:Math.min(l,h),h:Math.min(u,p)}}}class sc extends oo{getGeometry(e){return new No({width:e.props.w,height:e.props.h,isFilled:!0})}onResize(e,n){return qg(e,n)}getHandleSnapGeometry(e){return{points:this.getGeometry(e).bounds.cornersAndCenter}}getInterpolatedProps(e,n,r){return{...n.props,w:_e(e.props.w,n.props.w,r),h:_e(e.props.h,n.props.h,r)}}}var jS;let lte=(jS=class extends ie{onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onCancel(){this.editor.setCurrentTool("select")}},I(jS,"id","idle"),jS);var OS;let cte=(OS=class extends ie{onPointerMove(e){if(this.editor.inputs.isDragging){const{originPagePoint:n}=this.editor.inputs,r=this.parent.shapeType,o=Ke(),s=this.editor.markHistoryStoppingPoint(`creating_box:${o}`),i=io(n,this.editor);this.editor.createShapes([{id:o,type:r,x:i.x,y:i.y,props:{w:1,h:1}}]).select(o);const a=this.parent;this.editor.setCurrentTool("select.resizing",{...e,target:"selection",handle:"bottom_right",isCreating:!0,creatingMarkId:s,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:a.onCreate?l=>{var c;return(c=a.onCreate)==null?void 0:c.call(a,l)}:void 0})}}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.cancel()}complete(){const{originPagePoint:e}=this.editor.inputs,n=this.parent.shapeType,r=Ke();this.editor.markHistoryStoppingPoint(`creating_box:${r}`),this.editor.createShapes([{id:r,type:n,x:e.x,y:e.y}]);const o=this.editor.getShape(r);if(!o){this.cancel();return}let{w:s,h:i}=o.props;const a=new x(s/2,i/2),l=this.editor.getShapeParentTransform(o);l&&a.rot(-l.rotation());let c=1;this.editor.user.getIsDynamicResizeMode()&&(c=1/this.editor.getZoomLevel(),s*=c,i*=c,a.mul(c));const u=tt(o),h=io(new x(o.x-a.x,o.y-a.y),this.editor);u.x=h.x,u.y=h.y,u.props.w=s,u.props.h=i,"scale"in o.props&&(u.props.scale=c),this.editor.updateShape(u),this.editor.setSelectedShapes([r]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},I(OS,"id","pointing"),OS);function io(t,e){const n=e.getInstanceState().isGridMode,r=e.getDocumentSettings().gridSize;return n?t.clone().snapToGrid(r):t.clone()}class Ox extends ie{static children(){return[lte,cte]}}I(Ox,"id","box"),I(Ox,"initial","idle");function ute(t,e,n){const r=w.useRef(!1),o=w.useCallback(i=>{r.current=i,i?Vr.addOpenMenu(t):Vr.deleteOpenMenu(t),e==null||e(i)},[t,e]),s=U("is menu open",()=>Vr.getOpenMenus().includes(t),[t]);return w.useEffect(()=>(r.current&&(n==null||n("open-menu"),Vr.addOpenMenu(t)),()=>{r.current&&(Vr.deleteOpenMenu(t),Vr.getOpenMenus().forEach(i=>{i.startsWith(t)&&(n==null||n("close-menu"),Vr.deleteOpenMenu(i))}),r.current=!1)}),[t,n]),[s,o]}function Zg(t){const e=z();return U("isEditing",()=>e.getEditingShapeId()===t,[e,t])}function bo(t){const e=z();return w.useMemo(function(){const o=c=>{if(c.isKilled)return;if(c.button===g1){e.dispatch({type:"pointer",target:"selection",handle:t,name:"right_click",...lr(c)});return}if(c.button!==0)return;const u=Rf(c.currentTarget);function h(){u.removeEventListener("pointerup",h),hd(u,c)}dd(u,c),u.addEventListener("pointerup",h),e.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:t,...lr(c)}),_t(c)};let s,i;function a(c){c.isKilled||c.button===0&&(c.clientX===s&&c.clientY===i||(s=c.clientX,i=c.clientY,e.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:t,...lr(c)})))}return{onPointerDown:o,onPointerMove:a,onPointerUp:c=>{c.isKilled||c.button===0&&e.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:t,...lr(c)})}}},[e,t])}function dte(t){const[e,n]=w.useState(()=>({store:Hu(t),opts:t}));if(!NT(e.opts,t)){const r={store:Hu(t),opts:t};return n(r),r.store}return e.store}const hte=20,pte=8;function R1(t,e=hte){return Math.max(pte,Math.ceil(t/e))}class ll extends Ti{constructor(n){super({...n,isFilled:!1,isClosed:!1});I(this,"_center");I(this,"radius");I(this,"start");I(this,"end");I(this,"largeArcFlag");I(this,"sweepFlag");I(this,"measure");I(this,"angleStart");I(this,"angleEnd");const{center:r,sweepFlag:o,largeArcFlag:s,start:i,end:a}=n;if(i.equals(a))throw Error("Arc must have different start and end points.");this.angleStart=x.Angle(r,i),this.angleEnd=x.Angle(r,a),this.radius=x.Dist(r,i),this.measure=SX(this.angleStart,this.angleEnd,o,s),this.start=i,this.end=a,this.sweepFlag=o,this.largeArcFlag=s,this._center=r}nearestPoint(n){const{_center:r,measure:o,radius:s,angleEnd:i,angleStart:a,start:l,end:c}=this,u=xx(o,a,i,r.angle(n));if(u<=0)return l;if(u>=1)return c;const h=r.clone().add(n.clone().sub(r).uni().mul(s));let p,f=1/0,g;for(const m of[l,c,h])g=x.Dist2(n,m),g<f&&(p=m,f=g);if(!p)throw Error("nearest point not found");return p}hitTestLineSegment(n,r){const{_center:o,radius:s,measure:i,angleStart:a,angleEnd:l}=this,c=gd(n,r,o,s);return c===null?!1:c.some(u=>{const h=xx(i,a,l,o.angle(u));return h>=0&&h<=1})}getVertices(){const{_center:n,measure:r,length:o,radius:s,angleStart:i}=this,a=[];for(let l=0,c=R1(Math.abs(o));l<c+1;l++){const u=l/c*r,h=i+u;a.push(da(n,s,h))}return a}getSvgPathData(n=!0){const{start:r,end:o,radius:s,largeArcFlag:i,sweepFlag:a}=this;return`${n?`M${r.toFixed()}`:""} A${s} ${s} 0 ${i} ${a} ${o.toFixed()}`}getLength(){return this.measure*this.radius}}class L1 extends Ti{constructor(n){super({isClosed:!0,...n});I(this,"_center");I(this,"radius");I(this,"x");I(this,"y");this.config=n;const{x:r=0,y:o=0,radius:s}=n;this.x=r,this.y=o,this._center=new x(s+r,s+o),this.radius=s}getBounds(){return new Z(this.x,this.y,this.radius*2,this.radius*2)}getVertices(){const{_center:n,radius:r}=this,o=Ne*r,s=[];for(let i=0,a=R1(o);i<a;i++){const l=i/a*Ne;s.push(da(n,r,l))}return s}nearestPoint(n){const{_center:r,radius:o}=this;return r.equals(n)?x.AddXY(r,o,0):r.clone().add(n.clone().sub(r).uni().mul(o))}hitTestLineSegment(n,r,o=0){const{_center:s,radius:i}=this;return gd(n,r,s,i+o)!==null}getSvgPathData(){const{_center:n,radius:r}=this;return`M${n.x+r},${n.y} a${r},${r} 0 1,0 ${r*2},0a${r},${r} 0 1,0 -${r*2},0`}}class an extends nc{constructor(n){const{start:r,cp1:o,cp2:s,end:i}=n;super({...n,points:[r,i]});I(this,"a");I(this,"b");I(this,"c");I(this,"d");this.a=r,this.b=o,this.c=s,this.d=i}getVertices(){const n=[],{a:r,b:o,c:s,d:i}=this;for(let a=0,l=10;a<=l;a++){const c=a/l;n.push(new x((1-c)*(1-c)*(1-c)*r.x+3*((1-c)*(1-c))*c*o.x+3*(1-c)*(c*c)*s.x+c*c*c*i.x,(1-c)*(1-c)*(1-c)*r.y+3*((1-c)*(1-c))*c*o.y+3*(1-c)*(c*c)*s.y+c*c*c*i.y))}return n}midPoint(){return an.GetAtT(this,.5)}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}getSvgPathData(n=!0){const{a:r,b:o,c:s,d:i}=this;return`${n?`M ${r.toFixed()} `:""} C${o.toFixed()} ${s.toFixed()} ${i.toFixed()}`}static GetAtT(n,r){const{a:o,b:s,c:i,d:a}=n;return new x((1-r)*(1-r)*(1-r)*o.x+3*((1-r)*(1-r))*r*s.x+3*(1-r)*(r*r)*i.x+r*r*r*a.x,(1-r)*(1-r)*(1-r)*o.y+3*((1-r)*(1-r))*r*s.y+3*(1-r)*(r*r)*i.y+r*r*r*a.y)}getLength(n=32){let r,o=this.a,s=0;for(let i=1;i<=n;i++)r=an.GetAtT(this,i/n),s+=x.Dist(o,r),o=r;return s}}class fte extends Ti{constructor(n){super({...n,isClosed:!1,isFilled:!1});I(this,"points");I(this,"_segments");const{points:r}=n;this.points=r}get segments(){if(!this._segments){this._segments=[];const{points:n}=this,r=n.length,o=r-2,s=1.25;for(let i=0;i<r-1;i++){const a=i===0?n[0]:n[i-1],l=n[i],c=n[i+1],u=i===o?c:n[i+2],h=l,p=i===0?a:new x(l.x+(c.x-a.x)/6*s,l.y+(c.y-a.y)/6*s),f=i===o?c:new x(c.x-(u.x-l.x)/6*s,c.y-(u.y-l.y)/6*s),g=c;this._segments.push(new an({start:h,cp1:p,cp2:f,end:g}))}}return this._segments}getLength(){return this.segments.reduce((n,r)=>n+r.length,0)}getVertices(){const n=this.segments.reduce((r,o)=>r.concat(o.vertices),[]);return n.push(this.points[this.points.length-1]),n}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){return this.segments.some(o=>o.hitTestLineSegment(n,r))}getSvgPathData(){let n=this.segments.reduce((r,o,s)=>r+o.getSvgPathData(s===0),"");return this.isClosed&&(n+="Z"),n}}class gte extends Ti{constructor(n){super({...n,isClosed:!0});I(this,"w");I(this,"h");I(this,"_edges");this.config=n;const{width:r,height:o}=n;this.w=r,this.h=o}get edges(){if(!this._edges){const{vertices:n}=this;this._edges=[];for(let r=0,o=n.length;r<o;r++){const s=n[r],i=n[(r+1)%o];this._edges.push(new us({start:s,end:i}))}}return this._edges}getVertices(){const n=Math.max(1,this.w),r=Math.max(1,this.h),o=n/2,s=r/2,i=Math.pow(o-s,2)/Math.pow(o+s,2),a=De*(o+s)*(1+3*i/(10+Math.sqrt(4-3*i))),l=R1(a),c=Ne/l,u=Math.cos(c),h=Math.sin(c);let p=0,f=1,g=0,m=1;const v=Array(l);for(let y=0;y<l;y++)v[y]=new x(o+o*f,s+s*p),g=h*f+u*p,m=u*f-h*p,p=g,f=m;return v}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.edges)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){return this.edges.some(o=>o.hitTestLineSegment(n,r))}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{w:n,h:r}=this,o=n/2,s=r/2,i=Math.max(0,o),a=Math.max(0,s);return ij(i,a)}getSvgPathData(n=!1){const{w:r,h:o}=this,s=r/2,i=o/2,a=Math.max(0,s),l=Math.max(0,i);return`${n?`M${s-a},${i}`:""} a${a},${l},0,1,1,${a*2},0a${a},${l},0,1,1,-${a*2},0`}}class mte extends Ti{constructor(n){super({...n,isClosed:!0});I(this,"w");I(this,"h");I(this,"a");I(this,"b");I(this,"c");I(this,"d");this.config=n;const{width:r,height:o}=n;if(this.w=r,this.h=o,o>r){const s=r/2;this.a=new ll({start:new x(0,s),end:new x(r,s),center:new x(r/2,s),sweepFlag:1,largeArcFlag:1}),this.b=new us({start:new x(r,s),end:new x(r,o-s)}),this.c=new ll({start:new x(r,o-s),end:new x(0,o-s),center:new x(r/2,o-s),sweepFlag:1,largeArcFlag:1}),this.d=new us({start:new x(0,o-s),end:new x(0,s)})}else{const s=o/2;this.a=new ll({start:new x(s,o),end:new x(s,0),center:new x(s,s),sweepFlag:1,largeArcFlag:1}),this.b=new us({start:new x(s,0),end:new x(r-s,0)}),this.c=new ll({start:new x(r-s,0),end:new x(r-s,o),center:new x(r-s,s),sweepFlag:1,largeArcFlag:1}),this.d=new us({start:new x(r-s,o),end:new x(s,o)})}}nearestPoint(n){let r,o=1/0,s,i;const{a,b:l,c,d:u}=this;for(const h of[a,l,c,u])i=h.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){const{a:o,b:s,c:i,d:a}=this;return[o,s,i,a].some(l=>l.hitTestLineSegment(n,r))}getVertices(){const{a:n,b:r,c:o,d:s}=this;return[n,r,o,s].reduce((i,a)=>(i.push(...a.vertices),i),[])}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{h:n,w:r}=this;return n>r?(De*(r/2)+(n-r))*2:(De*(n/2)+(r-n))*2}getSvgPathData(){const{a:n,b:r,c:o,d:s}=this;return[n,r,o,s].map((i,a)=>i.getSvgPathData(a===0)).join(" ")+" Z"}}async function yte({shouldReload:t=!0}={}){c7();for(const e of xf.connectedInstances)await e.close();await Promise.all(Qw().map(e=>dA(e))),l7(),t&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=yte);function Ste(t,e="_blank"){$g.openWindow(t,e)}Ci("@tldraw/editor","3.7.0-canary.383dfd14bf86","esm");function ZR(){const[t,e]=w.useState(!1);return w.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{e(n.matches)};return r(),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}const QR=()=>{},JR=w.createContext(null);function vte({onEvent:t,children:e}){return d.jsx(JR.Provider,{value:t??QR,children:e})}function Qt(){return w.useContext(JR)??QR}function oe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t==null||t(o),n===!1||!o.defaultPrevented)return e==null?void 0:e(o)}}function xte(t,e){const n=w.createContext(e),r=s=>{const{children:i,...a}=s,l=w.useMemo(()=>a,Object.values(a));return d.jsx(n.Provider,{value:l,children:i})};r.displayName=t+"Provider";function o(s){const i=w.useContext(n);if(i)return i;if(e!==void 0)return e;throw new Error(`\`${s}\` must be used within \`${t}\``)}return[r,o]}function Go(t,e=[]){let n=[];function r(s,i){const a=w.createContext(i),l=n.length;n=[...n,i];const c=h=>{var y;const{scope:p,children:f,...g}=h,m=((y=p==null?void 0:p[t])==null?void 0:y[l])||a,v=w.useMemo(()=>g,Object.values(g));return d.jsx(m.Provider,{value:v,children:f})};c.displayName=s+"Provider";function u(h,p){var m;const f=((m=p==null?void 0:p[t])==null?void 0:m[l])||a,g=w.useContext(f);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${h}\` must be used within \`${s}\``)}return[c,u]}const o=()=>{const s=n.map(i=>w.createContext(i));return function(a){const l=(a==null?void 0:a[t])||s;return w.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,wte(o,...e)]}function wte(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const h=l(s)[`__scope${c}`];return{...a,...h}},{});return w.useMemo(()=>({[`__scope${e.scopeName}`]:i}),[i])}};return n.scopeName=e.scopeName,n}function WI(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Qg(...t){return e=>{let n=!1;const r=t.map(o=>{const s=WI(o,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():WI(t[o],null)}}}}function Ze(...t){return w.useCallback(Qg(...t),t)}var ha=w.forwardRef((t,e)=>{const{children:n,...r}=t,o=w.Children.toArray(n),s=o.find(Pte);if(s){const i=s.props.children,a=o.map(l=>l===s?w.Children.count(i)>1?w.Children.only(null):w.isValidElement(i)?i.props.children:null:l);return d.jsx(Dx,{...r,ref:e,children:w.isValidElement(i)?w.cloneElement(i,void 0,a):null})}return d.jsx(Dx,{...r,ref:e,children:n})});ha.displayName="Slot";var Dx=w.forwardRef((t,e)=>{const{children:n,...r}=t;if(w.isValidElement(n)){const o=_te(n);return w.cloneElement(n,{...Cte(r,n.props),ref:e?Qg(e,o):o})}return w.Children.count(n)>1?w.Children.only(null):null});Dx.displayName="SlotClone";var bte=({children:t})=>d.jsx(d.Fragment,{children:t});function Pte(t){return w.isValidElement(t)&&t.type===bte}function Cte(t,e){const n={...e};for(const r in e){const o=t[r],s=e[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...a)=>{s(...a),o(...a)}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...t,...n}}function _te(t){var r,o;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Ite=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=Ite.reduce((t,e)=>{const n=w.forwardRef((r,o)=>{const{asChild:s,...i}=r,a=s?ha:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(a,{...i,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function $1(t,e){t&&wa.flushSync(()=>t.dispatchEvent(e))}function Jg(t){const e=t+"CollectionProvider",[n,r]=Go(e),[o,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),i=f=>{const{scope:g,children:m}=f,v=Te.useRef(null),y=Te.useRef(new Map).current;return d.jsx(o,{scope:g,itemMap:y,collectionRef:v,children:m})};i.displayName=e;const a=t+"CollectionSlot",l=Te.forwardRef((f,g)=>{const{scope:m,children:v}=f,y=s(a,m),S=Ze(g,y.collectionRef);return d.jsx(ha,{ref:S,children:v})});l.displayName=a;const c=t+"CollectionItemSlot",u="data-radix-collection-item",h=Te.forwardRef((f,g)=>{const{scope:m,children:v,...y}=f,S=Te.useRef(null),b=Ze(g,S),P=s(c,m);return Te.useEffect(()=>(P.itemMap.set(S,{ref:S,...y}),()=>void P.itemMap.delete(S))),d.jsx(ha,{[u]:"",ref:b,children:v})});h.displayName=c;function p(f){const g=s(t+"CollectionConsumer",f);return Te.useCallback(()=>{const v=g.collectionRef.current;if(!v)return[];const y=Array.from(v.querySelectorAll(`[${u}]`));return Array.from(g.itemMap.values()).sort((P,C)=>y.indexOf(P.ref.current)-y.indexOf(C.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:i,Slot:l,ItemSlot:h},p,r]}var Ete=w.createContext(void 0);function F1(t){const e=w.useContext(Ete);return t||e||"ltr"}function Xt(t){const e=w.useRef(t);return w.useEffect(()=>{e.current=t}),w.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function kte(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t);w.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var Tte="DismissableLayer",Rx="dismissableLayer.update",Mte="dismissableLayer.pointerDownOutside",Ate="dismissableLayer.focusOutside",GI,e3=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),wd=w.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=t,c=w.useContext(e3),[u,h]=w.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=w.useState({}),g=Ze(e,E=>h(E)),m=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),S=u?m.indexOf(u):-1,b=c.layersWithOutsidePointerEventsDisabled.size>0,P=S>=y,C=Ote(E=>{const k=E.target,D=[...c.branches].some(T=>T.contains(k));!P||D||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),_=Dte(E=>{const k=E.target;[...c.branches].some(T=>T.contains(k))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return kte(E=>{S===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),w.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(GI=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),VI(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=GI)}},[u,p,n,c]),w.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),VI())},[u,c]),w.useEffect(()=>{const E=()=>f({});return document.addEventListener(Rx,E),()=>document.removeEventListener(Rx,E)},[]),d.jsx(Ae.div,{...l,ref:g,style:{pointerEvents:b?P?"auto":"none":void 0,...t.style},onFocusCapture:oe(t.onFocusCapture,_.onFocusCapture),onBlurCapture:oe(t.onBlurCapture,_.onBlurCapture),onPointerDownCapture:oe(t.onPointerDownCapture,C.onPointerDownCapture)})});wd.displayName=Tte;var jte="DismissableLayerBranch",t3=w.forwardRef((t,e)=>{const n=w.useContext(e3),r=w.useRef(null),o=Ze(e,r);return w.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),d.jsx(Ae.div,{...t,ref:o})});t3.displayName=jte;function Ote(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t),r=w.useRef(!1),o=w.useRef(()=>{});return w.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){n3(Mte,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=l,e.addEventListener("click",o.current,{once:!0})):l()}else e.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),e.removeEventListener("pointerdown",s),e.removeEventListener("click",o.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function Dte(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t),r=w.useRef(!1);return w.useEffect(()=>{const o=s=>{s.target&&!r.current&&n3(Ate,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function VI(){const t=new CustomEvent(Rx);document.dispatchEvent(t)}function n3(t,e,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?$1(o,s):o.dispatchEvent(s)}var Rte=wd,Lte=t3,nS=0;function N1(){w.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??YI()),document.body.insertAdjacentElement("beforeend",t[1]??YI()),nS++,()=>{nS===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),nS--}},[])}function YI(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var rS="focusScope.autoFocusOnMount",oS="focusScope.autoFocusOnUnmount",XI={bubbles:!1,cancelable:!0},$te="FocusScope",em=w.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=t,[a,l]=w.useState(null),c=Xt(o),u=Xt(s),h=w.useRef(null),p=Ze(e,m=>l(m)),f=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let m=function(b){if(f.paused||!a)return;const P=b.target;a.contains(P)?h.current=P:Bs(h.current,{select:!0})},v=function(b){if(f.paused||!a)return;const P=b.relatedTarget;P!==null&&(a.contains(P)||Bs(h.current,{select:!0}))},y=function(b){if(document.activeElement===document.body)for(const C of b)C.removedNodes.length>0&&Bs(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",v);const S=new MutationObserver(y);return a&&S.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",v),S.disconnect()}}},[r,a,f.paused]),w.useEffect(()=>{if(a){ZI.add(f);const m=document.activeElement;if(!a.contains(m)){const y=new CustomEvent(rS,XI);a.addEventListener(rS,c),a.dispatchEvent(y),y.defaultPrevented||(Fte(Hte(r3(a)),{select:!0}),document.activeElement===m&&Bs(a))}return()=>{a.removeEventListener(rS,c),setTimeout(()=>{const y=new CustomEvent(oS,XI);a.addEventListener(oS,u),a.dispatchEvent(y),y.defaultPrevented||Bs(m??document.body,{select:!0}),a.removeEventListener(oS,u),ZI.remove(f)},0)}}},[a,c,u,f]);const g=w.useCallback(m=>{if(!n&&!r||f.paused)return;const v=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,y=document.activeElement;if(v&&y){const S=m.currentTarget,[b,P]=Nte(S);b&&P?!m.shiftKey&&y===P?(m.preventDefault(),n&&Bs(b,{select:!0})):m.shiftKey&&y===b&&(m.preventDefault(),n&&Bs(P,{select:!0})):y===S&&m.preventDefault()}},[n,r,f.paused]);return d.jsx(Ae.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});em.displayName=$te;function Fte(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(Bs(r,{select:e}),document.activeElement!==n)return}function Nte(t){const e=r3(t),n=qI(e,t),r=qI(e.reverse(),t);return[n,r]}function r3(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function qI(t,e){for(const n of t)if(!zte(n,{upTo:e}))return n}function zte(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function Bte(t){return t instanceof HTMLInputElement&&"select"in t}function Bs(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Bte(t)&&e&&t.select()}}var ZI=Ute();function Ute(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=QI(t,e),t.unshift(e)},remove(e){var n;t=QI(t,e),(n=t[0])==null||n.resume()}}}function QI(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function Hte(t){return t.filter(e=>e.tagName!=="A")}var mi=globalThis!=null&&globalThis.document?w.useLayoutEffect:()=>{},Kte=e6.useId||(()=>{}),Wte=0;function ms(t){const[e,n]=w.useState(Kte());return mi(()=>{t||n(r=>r??String(Wte++))},[t]),t||(e?`radix-${e}`:"")}const Gte=["top","right","bottom","left"],yi=Math.min,sr=Math.max,Ff=Math.round,bh=Math.floor,Do=t=>({x:t,y:t}),Vte={left:"right",right:"left",bottom:"top",top:"bottom"},Yte={start:"end",end:"start"};function Lx(t,e,n){return sr(t,yi(e,n))}function bs(t,e){return typeof t=="function"?t(e):t}function Ps(t){return t.split("-")[0]}function ic(t){return t.split("-")[1]}function z1(t){return t==="x"?"y":"x"}function B1(t){return t==="y"?"height":"width"}function Si(t){return["top","bottom"].includes(Ps(t))?"y":"x"}function U1(t){return z1(Si(t))}function Xte(t,e,n){n===void 0&&(n=!1);const r=ic(t),o=U1(t),s=B1(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=Nf(i)),[i,Nf(i)]}function qte(t){const e=Nf(t);return[$x(t),e,$x(e)]}function $x(t){return t.replace(/start|end/g,e=>Yte[e])}function Zte(t,e,n){const r=["left","right"],o=["right","left"],s=["top","bottom"],i=["bottom","top"];switch(t){case"top":case"bottom":return n?e?o:r:e?r:o;case"left":case"right":return e?s:i;default:return[]}}function Qte(t,e,n,r){const o=ic(t);let s=Zte(Ps(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map($x)))),s}function Nf(t){return t.replace(/left|right|bottom|top/g,e=>Vte[e])}function Jte(t){return{top:0,right:0,bottom:0,left:0,...t}}function o3(t){return typeof t!="number"?Jte(t):{top:t,right:t,bottom:t,left:t}}function zf(t){const{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function JI(t,e,n){let{reference:r,floating:o}=t;const s=Si(e),i=U1(e),a=B1(i),l=Ps(e),c=s==="y",u=r.x+r.width/2-o.width/2,h=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let f;switch(l){case"top":f={x:u,y:r.y-o.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-o.width,y:h};break;default:f={x:r.x,y:r.y}}switch(ic(e)){case"start":f[i]-=p*(n&&c?-1:1);break;case"end":f[i]+=p*(n&&c?-1:1);break}return f}const ene=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(e));let c=await i.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:h}=JI(c,r,l),p=r,f={},g=0;for(let m=0;m<a.length;m++){const{name:v,fn:y}=a[m],{x:S,y:b,data:P,reset:C}=await y({x:u,y:h,initialPlacement:r,placement:p,strategy:o,middlewareData:f,rects:c,platform:i,elements:{reference:t,floating:e}});u=S??u,h=b??h,f={...f,[v]:{...f[v],...P}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):C.rects),{x:u,y:h}=JI(c,p,l)),m=-1)}return{x:u,y:h,placement:p,strategy:o,middlewareData:f}};async function Ku(t,e){var n;e===void 0&&(e={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:f=0}=bs(e,t),g=o3(f),v=a[p?h==="floating"?"reference":"floating":h],y=zf(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(v)))==null||n?v:v.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),S=h==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),P=await(s.isElement==null?void 0:s.isElement(b))?await(s.getScale==null?void 0:s.getScale(b))||{x:1,y:1}:{x:1,y:1},C=zf(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:S,offsetParent:b,strategy:l}):S);return{top:(y.top-C.top+g.top)/P.y,bottom:(C.bottom-y.bottom+g.bottom)/P.y,left:(y.left-C.left+g.left)/P.x,right:(C.right-y.right+g.right)/P.x}}const tne=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=bs(t,e)||{};if(c==null)return{};const h=o3(u),p={x:n,y:r},f=U1(o),g=B1(f),m=await i.getDimensions(c),v=f==="y",y=v?"top":"left",S=v?"bottom":"right",b=v?"clientHeight":"clientWidth",P=s.reference[g]+s.reference[f]-p[f]-s.floating[g],C=p[f]-s.reference[f],_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=_?_[b]:0;(!E||!await(i.isElement==null?void 0:i.isElement(_)))&&(E=a.floating[b]||s.floating[g]);const k=P/2-C/2,D=E/2-m[g]/2-1,T=yi(h[y],D),j=yi(h[S],D),$=T,M=E-m[g]-j,O=E/2-m[g]/2+k,F=Lx($,O,M),B=!l.arrow&&ic(o)!=null&&O!==F&&s.reference[g]/2-(O<$?T:j)-m[g]/2<0,K=B?O<$?O-$:O-M:0;return{[f]:p[f]+K,data:{[f]:F,centerOffset:O-F-K,...B&&{alignmentOffset:K}},reset:B}}}),nne=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...v}=bs(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const y=Ps(o),S=Si(a),b=Ps(a)===a,P=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(b||!m?[Nf(a)]:qte(a)),_=g!=="none";!p&&_&&C.push(...Qte(a,m,g,P));const E=[a,...C],k=await Ku(e,v),D=[];let T=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&D.push(k[y]),h){const O=Xte(o,i,P);D.push(k[O[0]],k[O[1]])}if(T=[...T,{placement:o,overflows:D}],!D.every(O=>O<=0)){var j,$;const O=(((j=s.flip)==null?void 0:j.index)||0)+1,F=E[O];if(F)return{data:{index:O,overflows:T},reset:{placement:F}};let B=($=T.filter(K=>K.overflows[0]<=0).sort((K,R)=>K.overflows[1]-R.overflows[1])[0])==null?void 0:$.placement;if(!B)switch(f){case"bestFit":{var M;const K=(M=T.filter(R=>{if(_){const H=Si(R.placement);return H===S||H==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(H=>H>0).reduce((H,Y)=>H+Y,0)]).sort((R,H)=>R[1]-H[1])[0])==null?void 0:M[0];K&&(B=K);break}case"initialPlacement":B=a;break}if(o!==B)return{reset:{placement:B}}}return{}}}};function eE(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function tE(t){return Gte.some(e=>t[e]>=0)}const rne=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:r="referenceHidden",...o}=bs(t,e);switch(r){case"referenceHidden":{const s=await Ku(e,{...o,elementContext:"reference"}),i=eE(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:tE(i)}}}case"escaped":{const s=await Ku(e,{...o,altBoundary:!0}),i=eE(s,n.floating);return{data:{escapedOffsets:i,escaped:tE(i)}}}default:return{}}}}};async function one(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ps(n),a=ic(n),l=Si(n)==="y",c=["left","top"].includes(i)?-1:1,u=s&&l?-1:1,h=bs(e,t);let{mainAxis:p,crossAxis:f,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return a&&typeof g=="number"&&(f=a==="end"?g*-1:g),l?{x:f*u,y:p*c}:{x:p*c,y:f*u}}const sne=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=e,l=await one(e,t);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},ine=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o}=e,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:v=>{let{x:y,y:S}=v;return{x:y,y:S}}},...l}=bs(t,e),c={x:n,y:r},u=await Ku(e,l),h=Si(Ps(o)),p=z1(h);let f=c[p],g=c[h];if(s){const v=p==="y"?"top":"left",y=p==="y"?"bottom":"right",S=f+u[v],b=f-u[y];f=Lx(S,f,b)}if(i){const v=h==="y"?"top":"left",y=h==="y"?"bottom":"right",S=g+u[v],b=g-u[y];g=Lx(S,g,b)}const m=a.fn({...e,[p]:f,[h]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[h]:i}}}}}},ane=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=bs(t,e),u={x:n,y:r},h=Si(o),p=z1(h);let f=u[p],g=u[h];const m=bs(a,e),v=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const b=p==="y"?"height":"width",P=s.reference[p]-s.floating[b]+v.mainAxis,C=s.reference[p]+s.reference[b]-v.mainAxis;f<P?f=P:f>C&&(f=C)}if(c){var y,S;const b=p==="y"?"width":"height",P=["top","left"].includes(Ps(o)),C=s.reference[h]-s.floating[b]+(P&&((y=i.offset)==null?void 0:y[h])||0)+(P?0:v.crossAxis),_=s.reference[h]+s.reference[b]+(P?0:((S=i.offset)==null?void 0:S[h])||0)-(P?v.crossAxis:0);g<C?g=C:g>_&&(g=_)}return{[p]:f,[h]:g}}}},lne=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:o,rects:s,platform:i,elements:a}=e,{apply:l=()=>{},...c}=bs(t,e),u=await Ku(e,c),h=Ps(o),p=ic(o),f=Si(o)==="y",{width:g,height:m}=s.floating;let v,y;h==="top"||h==="bottom"?(v=h,y=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(y=h,v=p==="end"?"top":"bottom");const S=m-u.top-u.bottom,b=g-u.left-u.right,P=yi(m-u[v],S),C=yi(g-u[y],b),_=!e.middlewareData.shift;let E=P,k=C;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(k=b),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(E=S),_&&!p){const T=sr(u.left,0),j=sr(u.right,0),$=sr(u.top,0),M=sr(u.bottom,0);f?k=g-2*(T!==0||j!==0?T+j:sr(u.left,u.right)):E=m-2*($!==0||M!==0?$+M:sr(u.top,u.bottom))}await l({...e,availableWidth:k,availableHeight:E});const D=await i.getDimensions(a.floating);return g!==D.width||m!==D.height?{reset:{rects:!0}}:{}}}};function tm(){return typeof window<"u"}function ac(t){return s3(t)?(t.nodeName||"").toLowerCase():"#document"}function pr(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Vo(t){var e;return(e=(s3(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function s3(t){return tm()?t instanceof Node||t instanceof pr(t).Node:!1}function ao(t){return tm()?t instanceof Element||t instanceof pr(t).Element:!1}function zo(t){return tm()?t instanceof HTMLElement||t instanceof pr(t).HTMLElement:!1}function nE(t){return!tm()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof pr(t).ShadowRoot}function bd(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=lo(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!["inline","contents"].includes(o)}function cne(t){return["table","td","th"].includes(ac(t))}function nm(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function H1(t){const e=K1(),n=ao(t)?lo(t):t;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function une(t){let e=vi(t);for(;zo(e)&&!Rl(e);){if(H1(e))return e;if(nm(e))return null;e=vi(e)}return null}function K1(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Rl(t){return["html","body","#document"].includes(ac(t))}function lo(t){return pr(t).getComputedStyle(t)}function rm(t){return ao(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function vi(t){if(ac(t)==="html")return t;const e=t.assignedSlot||t.parentNode||nE(t)&&t.host||Vo(t);return nE(e)?e.host:e}function i3(t){const e=vi(t);return Rl(e)?t.ownerDocument?t.ownerDocument.body:t.body:zo(e)&&bd(e)?e:i3(e)}function Wu(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=i3(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=pr(o);if(s){const a=Fx(i);return e.concat(i,i.visualViewport||[],bd(o)?o:[],a&&n?Wu(a):[])}return e.concat(o,Wu(o,[],n))}function Fx(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function a3(t){const e=lo(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=zo(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=Ff(n)!==s||Ff(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function W1(t){return ao(t)?t:t.contextElement}function Pl(t){const e=W1(t);if(!zo(e))return Do(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=a3(e);let i=(s?Ff(n.width):n.width)/r,a=(s?Ff(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const dne=Do(0);function l3(t){const e=pr(t);return!K1()||!e.visualViewport?dne:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function hne(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==pr(t)?!1:e}function pa(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=W1(t);let i=Do(1);e&&(r?ao(r)&&(i=Pl(r)):i=Pl(t));const a=hne(s,n,r)?l3(s):Do(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,u=o.width/i.x,h=o.height/i.y;if(s){const p=pr(s),f=r&&ao(r)?pr(r):r;let g=p,m=Fx(g);for(;m&&r&&f!==g;){const v=Pl(m),y=m.getBoundingClientRect(),S=lo(m),b=y.left+(m.clientLeft+parseFloat(S.paddingLeft))*v.x,P=y.top+(m.clientTop+parseFloat(S.paddingTop))*v.y;l*=v.x,c*=v.y,u*=v.x,h*=v.y,l+=b,c+=P,g=pr(m),m=Fx(g)}}return zf({width:u,height:h,x:l,y:c})}function G1(t,e){const n=rm(t).scrollLeft;return e?e.left+n:pa(Vo(t)).left+n}function c3(t,e,n){n===void 0&&(n=!1);const r=t.getBoundingClientRect(),o=r.left+e.scrollLeft-(n?0:G1(t,r)),s=r.top+e.scrollTop;return{x:o,y:s}}function pne(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=Vo(r),a=e?nm(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Do(1);const u=Do(0),h=zo(r);if((h||!h&&!s)&&((ac(r)!=="body"||bd(i))&&(l=rm(r)),zo(r))){const f=pa(r);c=Pl(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const p=i&&!h&&!s?c3(i,l,!0):Do(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}}function fne(t){return Array.from(t.getClientRects())}function gne(t){const e=Vo(t),n=rm(t),r=t.ownerDocument.body,o=sr(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=sr(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+G1(t);const a=-n.scrollTop;return lo(r).direction==="rtl"&&(i+=sr(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}function mne(t,e){const n=pr(t),r=Vo(t),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const c=K1();(!c||c&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}return{width:s,height:i,x:a,y:l}}function yne(t,e){const n=pa(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=zo(t)?Pl(t):Do(1),i=t.clientWidth*s.x,a=t.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function rE(t,e,n){let r;if(e==="viewport")r=mne(t,n);else if(e==="document")r=gne(Vo(t));else if(ao(e))r=yne(e,n);else{const o=l3(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return zf(r)}function u3(t,e){const n=vi(t);return n===e||!ao(n)||Rl(n)?!1:lo(n).position==="fixed"||u3(n,e)}function Sne(t,e){const n=e.get(t);if(n)return n;let r=Wu(t,[],!1).filter(a=>ao(a)&&ac(a)!=="body"),o=null;const s=lo(t).position==="fixed";let i=s?vi(t):t;for(;ao(i)&&!Rl(i);){const a=lo(i),l=H1(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||bd(i)&&!l&&u3(t,i))?r=r.filter(u=>u!==i):o=a,i=vi(i)}return e.set(t,r),r}function vne(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?nm(e)?[]:Sne(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const h=rE(e,u,o);return c.top=sr(h.top,c.top),c.right=yi(h.right,c.right),c.bottom=yi(h.bottom,c.bottom),c.left=sr(h.left,c.left),c},rE(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function xne(t){const{width:e,height:n}=a3(t);return{width:e,height:n}}function wne(t,e,n){const r=zo(e),o=Vo(e),s=n==="fixed",i=pa(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=Do(0);if(r||!r&&!s)if((ac(e)!=="body"||bd(o))&&(a=rm(e)),r){const p=pa(e,!0,s,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&(l.x=G1(o));const c=o&&!r&&!s?c3(o,a):Do(0),u=i.left+a.scrollLeft-l.x-c.x,h=i.top+a.scrollTop-l.y-c.y;return{x:u,y:h,width:i.width,height:i.height}}function sS(t){return lo(t).position==="static"}function oE(t,e){if(!zo(t)||lo(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Vo(t)===n&&(n=n.ownerDocument.body),n}function d3(t,e){const n=pr(t);if(nm(t))return n;if(!zo(t)){let o=vi(t);for(;o&&!Rl(o);){if(ao(o)&&!sS(o))return o;o=vi(o)}return n}let r=oE(t,e);for(;r&&cne(r)&&sS(r);)r=oE(r,e);return r&&Rl(r)&&sS(r)&&!H1(r)?n:r||une(t)||n}const bne=async function(t){const e=this.getOffsetParent||d3,n=this.getDimensions,r=await n(t.floating);return{reference:wne(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Pne(t){return lo(t).direction==="rtl"}const Cne={convertOffsetParentRelativeRectToViewportRelativeRect:pne,getDocumentElement:Vo,getClippingRect:vne,getOffsetParent:d3,getElementRects:bne,getClientRects:fne,getDimensions:xne,getScale:Pl,isElement:ao,isRTL:Pne};function _ne(t,e){let n=null,r;const o=Vo(t);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const{left:c,top:u,width:h,height:p}=t.getBoundingClientRect();if(a||e(),!h||!p)return;const f=bh(u),g=bh(o.clientWidth-(c+h)),m=bh(o.clientHeight-(u+p)),v=bh(c),S={rootMargin:-f+"px "+-g+"px "+-m+"px "+-v+"px",threshold:sr(0,yi(1,l))||1};let b=!0;function P(C){const _=C[0].intersectionRatio;if(_!==l){if(!b)return i();_?i(!1,_):r=setTimeout(()=>{i(!1,1e-7)},1e3)}b=!1}try{n=new IntersectionObserver(P,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(P,S)}n.observe(t)}return i(!0),s}function Ine(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=W1(t),u=o||s?[...c?Wu(c):[],...Wu(e)]:[];u.forEach(y=>{o&&y.addEventListener("scroll",n,{passive:!0}),s&&y.addEventListener("resize",n)});const h=c&&a?_ne(c,n):null;let p=-1,f=null;i&&(f=new ResizeObserver(y=>{let[S]=y;S&&S.target===c&&f&&(f.unobserve(e),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=f)==null||b.observe(e)})),n()}),c&&!l&&f.observe(c),f.observe(e));let g,m=l?pa(t):null;l&&v();function v(){const y=pa(t);m&&(y.x!==m.x||y.y!==m.y||y.width!==m.width||y.height!==m.height)&&n(),m=y,g=requestAnimationFrame(v)}return n(),()=>{var y;u.forEach(S=>{o&&S.removeEventListener("scroll",n),s&&S.removeEventListener("resize",n)}),h==null||h(),(y=f)==null||y.disconnect(),f=null,l&&cancelAnimationFrame(g)}}const Ene=sne,kne=ine,Tne=nne,Mne=lne,Ane=rne,sE=tne,jne=ane,One=(t,e,n)=>{const r=new Map,o={platform:Cne,...n},s={...o.platform,_c:r};return ene(t,e,{...o,platform:s})};var hp=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Bf(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,o;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!Bf(t[r],e[r]))return!1;return!0}if(o=Object.keys(t),n=o.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&t.$$typeof)&&!Bf(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function h3(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function iE(t,e){const n=h3(t);return Math.round(e*n)/n}function iS(t){const e=w.useRef(t);return hp(()=>{e.current=t}),e}function Dne(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=t,[u,h]=w.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[p,f]=w.useState(r);Bf(p,r)||f(r);const[g,m]=w.useState(null),[v,y]=w.useState(null),S=w.useCallback(R=>{R!==_.current&&(_.current=R,m(R))},[]),b=w.useCallback(R=>{R!==E.current&&(E.current=R,y(R))},[]),P=s||g,C=i||v,_=w.useRef(null),E=w.useRef(null),k=w.useRef(u),D=l!=null,T=iS(l),j=iS(o),$=iS(c),M=w.useCallback(()=>{if(!_.current||!E.current)return;const R={placement:e,strategy:n,middleware:p};j.current&&(R.platform=j.current),One(_.current,E.current,R).then(H=>{const Y={...H,isPositioned:$.current!==!1};O.current&&!Bf(k.current,Y)&&(k.current=Y,wa.flushSync(()=>{h(Y)}))})},[p,e,n,j,$]);hp(()=>{c===!1&&k.current.isPositioned&&(k.current.isPositioned=!1,h(R=>({...R,isPositioned:!1})))},[c]);const O=w.useRef(!1);hp(()=>(O.current=!0,()=>{O.current=!1}),[]),hp(()=>{if(P&&(_.current=P),C&&(E.current=C),P&&C){if(T.current)return T.current(P,C,M);M()}},[P,C,M,T,D]);const F=w.useMemo(()=>({reference:_,floating:E,setReference:S,setFloating:b}),[S,b]),B=w.useMemo(()=>({reference:P,floating:C}),[P,C]),K=w.useMemo(()=>{const R={position:n,left:0,top:0};if(!B.floating)return R;const H=iE(B.floating,u.x),Y=iE(B.floating,u.y);return a?{...R,transform:"translate("+H+"px, "+Y+"px)",...h3(B.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:Y}},[n,a,B.floating,u.x,u.y]);return w.useMemo(()=>({...u,update:M,refs:F,elements:B,floatingStyles:K}),[u,M,F,B,K])}const Rne=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:r,padding:o}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?sE({element:r.current,padding:o}).fn(n):{}:r?sE({element:r,padding:o}).fn(n):{}}}},Lne=(t,e)=>({...Ene(t),options:[t,e]}),$ne=(t,e)=>({...kne(t),options:[t,e]}),Fne=(t,e)=>({...jne(t),options:[t,e]}),Nne=(t,e)=>({...Tne(t),options:[t,e]}),zne=(t,e)=>({...Mne(t),options:[t,e]}),Bne=(t,e)=>({...Ane(t),options:[t,e]}),Une=(t,e)=>({...Rne(t),options:[t,e]});var Hne="Arrow",p3=w.forwardRef((t,e)=>{const{children:n,width:r=10,height:o=5,...s}=t;return d.jsx(Ae.svg,{...s,ref:e,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});p3.displayName=Hne;var Kne=p3;function f3(t){const[e,n]=w.useState(void 0);return mi(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=t.offsetWidth,a=t.offsetHeight;n({width:i,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var V1="Popper",[g3,om]=Go(V1),[Wne,m3]=g3(V1),y3=t=>{const{__scopePopper:e,children:n}=t,[r,o]=w.useState(null);return d.jsx(Wne,{scope:e,anchor:r,onAnchorChange:o,children:n})};y3.displayName=V1;var S3="PopperAnchor",v3=w.forwardRef((t,e)=>{const{__scopePopper:n,virtualRef:r,...o}=t,s=m3(S3,n),i=w.useRef(null),a=Ze(e,i);return w.useEffect(()=>{s.onAnchorChange((r==null?void 0:r.current)||i.current)}),r?null:d.jsx(Ae.div,{...o,ref:a})});v3.displayName=S3;var Y1="PopperContent",[Gne,Vne]=g3(Y1),x3=w.forwardRef((t,e)=>{var Fe,ot,$e,lt,Ue,er;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,...m}=t,v=m3(Y1,n),[y,S]=w.useState(null),b=Ze(e,$t=>S($t)),[P,C]=w.useState(null),_=f3(P),E=(_==null?void 0:_.width)??0,k=(_==null?void 0:_.height)??0,D=r+(s!=="center"?"-"+s:""),T=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},j=Array.isArray(c)?c:[c],$=j.length>0,M={padding:T,boundary:j.filter(Xne),altBoundary:$},{refs:O,floatingStyles:F,placement:B,isPositioned:K,middlewareData:R}=Dne({strategy:"fixed",placement:D,whileElementsMounted:(...$t)=>Ine(...$t,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[Lne({mainAxis:o+k,alignmentAxis:i}),l&&$ne({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?Fne():void 0,...M}),l&&Nne({...M}),zne({...M,apply:({elements:$t,rects:On,availableWidth:vt,availableHeight:Jt})=>{const{width:Xo,height:cc}=On.reference,js=$t.floating.style;js.setProperty("--radix-popper-available-width",`${vt}px`),js.setProperty("--radix-popper-available-height",`${Jt}px`),js.setProperty("--radix-popper-anchor-width",`${Xo}px`),js.setProperty("--radix-popper-anchor-height",`${cc}px`)}}),P&&Une({element:P,padding:a}),qne({arrowWidth:E,arrowHeight:k}),p&&Bne({strategy:"referenceHidden",...M})]}),[H,Y]=P3(B),ee=Xt(g);mi(()=>{K&&(ee==null||ee())},[K,ee]);const he=(Fe=R.arrow)==null?void 0:Fe.x,ue=(ot=R.arrow)==null?void 0:ot.y,ke=(($e=R.arrow)==null?void 0:$e.centerOffset)!==0,[se,We]=w.useState();return mi(()=>{y&&We(window.getComputedStyle(y).zIndex)},[y]),d.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...F,transform:K?F.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:se,"--radix-popper-transform-origin":[(lt=R.transformOrigin)==null?void 0:lt.x,(Ue=R.transformOrigin)==null?void 0:Ue.y].join(" "),...((er=R.hide)==null?void 0:er.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:d.jsx(Gne,{scope:n,placedSide:H,onArrowChange:C,arrowX:he,arrowY:ue,shouldHideArrow:ke,children:d.jsx(Ae.div,{"data-side":H,"data-align":Y,...m,ref:b,style:{...m.style,animation:K?void 0:"none"}})})})});x3.displayName=Y1;var w3="PopperArrow",Yne={top:"bottom",right:"left",bottom:"top",left:"right"},b3=w.forwardRef(function(e,n){const{__scopePopper:r,...o}=e,s=Vne(w3,r),i=Yne[s.placedSide];return d.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:d.jsx(Kne,{...o,ref:n,style:{...o.style,display:"block"}})})});b3.displayName=w3;function Xne(t){return t!==null}var qne=t=>({name:"transformOrigin",options:t,fn(e){var v,y,S;const{placement:n,rects:r,middlewareData:o}=e,i=((v=o.arrow)==null?void 0:v.centerOffset)!==0,a=i?0:t.arrowWidth,l=i?0:t.arrowHeight,[c,u]=P3(n),h={start:"0%",center:"50%",end:"100%"}[u],p=(((y=o.arrow)==null?void 0:y.x)??0)+a/2,f=(((S=o.arrow)==null?void 0:S.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?h:`${p}px`,m=`${-l}px`):c==="top"?(g=i?h:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?h:`${f}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?h:`${f}px`),{data:{x:g,y:m}}}});function P3(t){const[e,n="center"]=t.split("-");return[e,n]}var X1=y3,q1=v3,C3=x3,_3=b3,Zne="Portal",Pd=w.forwardRef((t,e)=>{var a;const{container:n,...r}=t,[o,s]=w.useState(!1);mi(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?u8.createPortal(d.jsx(Ae.div,{...r,ref:e}),i):null});Pd.displayName=Zne;function Qne(t,e){return w.useReducer((n,r)=>e[n][r]??n,t)}var ho=t=>{const{present:e,children:n}=t,r=Jne(e),o=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),s=Ze(r.ref,ere(o));return typeof n=="function"||r.isPresent?w.cloneElement(o,{ref:s}):null};ho.displayName="Presence";function Jne(t){const[e,n]=w.useState(),r=w.useRef({}),o=w.useRef(t),s=w.useRef("none"),i=t?"mounted":"unmounted",[a,l]=Qne(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const c=Ph(r.current);s.current=a==="mounted"?c:"none"},[a]),mi(()=>{const c=r.current,u=o.current;if(u!==t){const p=s.current,f=Ph(c);t?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),mi(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,h=f=>{const m=Ph(r.current).includes(f.animationName);if(f.target===e&&m&&(l("ANIMATION_END"),!o.current)){const v=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=v)})}},p=f=>{f.target===e&&(s.current=Ph(r.current))};return e.addEventListener("animationstart",p),e.addEventListener("animationcancel",h),e.addEventListener("animationend",h),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",p),e.removeEventListener("animationcancel",h),e.removeEventListener("animationend",h)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:w.useCallback(c=>{c&&(r.current=getComputedStyle(c)),n(c)},[])}}function Ph(t){return(t==null?void 0:t.animationName)||"none"}function ere(t){var r,o;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function Ai({prop:t,defaultProp:e,onChange:n=()=>{}}){const[r,o]=tre({defaultProp:e,onChange:n}),s=t!==void 0,i=s?t:r,a=Xt(n),l=w.useCallback(c=>{if(s){const h=typeof c=="function"?c(t):c;h!==t&&a(h)}else o(c)},[s,t,o,a]);return[i,l]}function tre({defaultProp:t,onChange:e}){const n=w.useState(t),[r]=n,o=w.useRef(r),s=Xt(e);return w.useEffect(()=>{o.current!==r&&(s(r),o.current=r)},[r,o,s]),n}var aS="rovingFocusGroup.onEntryFocus",nre={bubbles:!1,cancelable:!0},sm="RovingFocusGroup",[Nx,I3,rre]=Jg(sm),[ore,E3]=Go(sm,[rre]),[sre,ire]=ore(sm),k3=w.forwardRef((t,e)=>d.jsx(Nx.Provider,{scope:t.__scopeRovingFocusGroup,children:d.jsx(Nx.Slot,{scope:t.__scopeRovingFocusGroup,children:d.jsx(are,{...t,ref:e})})}));k3.displayName=sm;var are=w.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...h}=t,p=w.useRef(null),f=Ze(e,p),g=F1(s),[m=null,v]=Ai({prop:i,defaultProp:a,onChange:l}),[y,S]=w.useState(!1),b=Xt(c),P=I3(n),C=w.useRef(!1),[_,E]=w.useState(0);return w.useEffect(()=>{const k=p.current;if(k)return k.addEventListener(aS,b),()=>k.removeEventListener(aS,b)},[b]),d.jsx(sre,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:w.useCallback(k=>v(k),[v]),onItemShiftTab:w.useCallback(()=>S(!0),[]),onFocusableItemAdd:w.useCallback(()=>E(k=>k+1),[]),onFocusableItemRemove:w.useCallback(()=>E(k=>k-1),[]),children:d.jsx(Ae.div,{tabIndex:y||_===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...t.style},onMouseDown:oe(t.onMouseDown,()=>{C.current=!0}),onFocus:oe(t.onFocus,k=>{const D=!C.current;if(k.target===k.currentTarget&&D&&!y){const T=new CustomEvent(aS,nre);if(k.currentTarget.dispatchEvent(T),!T.defaultPrevented){const j=P().filter(B=>B.focusable),$=j.find(B=>B.active),M=j.find(B=>B.id===m),F=[$,M,...j].filter(Boolean).map(B=>B.ref.current);A3(F,u)}}C.current=!1}),onBlur:oe(t.onBlur,()=>S(!1))})})}),T3="RovingFocusGroupItem",M3=w.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,...i}=t,a=ms(),l=s||a,c=ire(T3,n),u=c.currentTabStopId===l,h=I3(n),{onFocusableItemAdd:p,onFocusableItemRemove:f}=c;return w.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),d.jsx(Nx.ItemSlot,{scope:n,id:l,focusable:r,active:o,children:d.jsx(Ae.span,{tabIndex:u?0:-1,"data-orientation":c.orientation,...i,ref:e,onMouseDown:oe(t.onMouseDown,g=>{r?c.onItemFocus(l):g.preventDefault()}),onFocus:oe(t.onFocus,()=>c.onItemFocus(l)),onKeyDown:oe(t.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){c.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const m=ure(g,c.orientation,c.dir);if(m!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let y=h().filter(S=>S.focusable).map(S=>S.ref.current);if(m==="last")y.reverse();else if(m==="prev"||m==="next"){m==="prev"&&y.reverse();const S=y.indexOf(g.currentTarget);y=c.loop?dre(y,S+1):y.slice(S+1)}setTimeout(()=>A3(y))}})})})});M3.displayName=T3;var lre={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cre(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function ure(t,e,n){const r=cre(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lre[r]}function A3(t,e=!1){const n=document.activeElement;for(const r of t)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function dre(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var hre=k3,pre=M3,fre=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},$a=new WeakMap,Ch=new WeakMap,_h={},lS=0,j3=function(t){return t&&(t.host||j3(t.parentNode))},gre=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=j3(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},mre=function(t,e,n,r){var o=gre(e,Array.isArray(t)?t:[t]);_h[n]||(_h[n]=new WeakMap);var s=_h[n],i=[],a=new Set,l=new Set(o),c=function(h){!h||a.has(h)||(a.add(h),c(h.parentNode))};o.forEach(c);var u=function(h){!h||l.has(h)||Array.prototype.forEach.call(h.children,function(p){if(a.has(p))u(p);else try{var f=p.getAttribute(r),g=f!==null&&f!=="false",m=($a.get(p)||0)+1,v=(s.get(p)||0)+1;$a.set(p,m),s.set(p,v),i.push(p),m===1&&g&&Ch.set(p,!0),v===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",p,y)}})};return u(e),a.clear(),lS++,function(){i.forEach(function(h){var p=$a.get(h)-1,f=s.get(h)-1;$a.set(h,p),s.set(h,f),p||(Ch.has(h)||h.removeAttribute(r),Ch.delete(h)),f||h.removeAttribute(n)}),lS--,lS||($a=new WeakMap,$a=new WeakMap,Ch=new WeakMap,_h={})}},Z1=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),o=fre(t);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),mre(r,o,n,"aria-hidden")):function(){return null}},_o=function(){return _o=Object.assign||function(e){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},_o.apply(this,arguments)};function O3(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]]);return n}function yre(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}var pp="right-scroll-bar-position",fp="width-before-scroll-bar",Sre="with-scroll-bars-hidden",vre="--removed-body-scroll-bar-size";function cS(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function xre(t,e){var n=w.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=e,n.facade}var wre=typeof window<"u"?w.useLayoutEffect:w.useEffect,aE=new WeakMap;function bre(t,e){var n=xre(null,function(r){return t.forEach(function(o){return cS(o,r)})});return wre(function(){var r=aE.get(n);if(r){var o=new Set(r),s=new Set(t),i=n.current;o.forEach(function(a){s.has(a)||cS(a,null)}),s.forEach(function(a){o.has(a)||cS(a,i)})}aE.set(n,t)},[t]),n}function Pre(t){return t}function Cre(t,e){e===void 0&&(e=Pre);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var i=e(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var u=i;i=[],u.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(u){i.push(u),c()},filter:function(u){return i=i.filter(u),n}}}};return o}function _re(t){t===void 0&&(t={});var e=Cre(null);return e.options=_o({async:!0,ssr:!1},t),e}var D3=function(t){var e=t.sideCar,n=O3(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,_o({},n))};D3.isSideCarExport=!0;function Ire(t,e){return t.useMedium(e),D3}var R3=_re(),uS=function(){},im=w.forwardRef(function(t,e){var n=w.useRef(null),r=w.useState({onScrollCapture:uS,onWheelCapture:uS,onTouchMoveCapture:uS}),o=r[0],s=r[1],i=t.forwardProps,a=t.children,l=t.className,c=t.removeScrollBar,u=t.enabled,h=t.shards,p=t.sideCar,f=t.noIsolation,g=t.inert,m=t.allowPinchZoom,v=t.as,y=v===void 0?"div":v,S=t.gapMode,b=O3(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),P=p,C=bre([n,e]),_=_o(_o({},b),o);return w.createElement(w.Fragment,null,u&&w.createElement(P,{sideCar:R3,removeScrollBar:c,shards:h,noIsolation:f,inert:g,setCallbacks:s,allowPinchZoom:!!m,lockRef:n,gapMode:S}),i?w.cloneElement(w.Children.only(a),_o(_o({},_),{ref:C})):w.createElement(y,_o({},_,{className:l,ref:C}),a))});im.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};im.classNames={fullWidth:fp,zeroRight:pp};var Ere=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function kre(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=Ere();return e&&t.setAttribute("nonce",e),t}function Tre(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function Mre(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var Are=function(){var t=0,e=null;return{add:function(n){t==0&&(e=kre())&&(Tre(e,n),Mre(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},jre=function(){var t=Are();return function(e,n){w.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},L3=function(){var t=jre(),e=function(n){var r=n.styles,o=n.dynamic;return t(r,o),null};return e},Ore={left:0,top:0,right:0,gap:0},dS=function(t){return parseInt(t||"",10)||0},Dre=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],o=e[t==="padding"?"paddingRight":"marginRight"];return[dS(n),dS(r),dS(o)]},Rre=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return Ore;var e=Dre(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},Lre=L3(),Cl="data-scroll-locked",$re=function(t,e,n,r){var o=t.left,s=t.top,i=t.right,a=t.gap;return n===void 0&&(n="margin"),`
195
+ }`;return d.jsx("style",{children:n})}),ete=[],tte=[],nte=[],rte="tl-container",ote=w.memo(function({store:e,components:n,className:r,user:o,options:s,...i}){const[a,l]=w.useState(null),c=w.useMemo(()=>o??Bj(),[o]),u=(n==null?void 0:n.ErrorFallback)===void 0?jj:n==null?void 0:n.ErrorFallback,h={...i,shapeUtils:i.shapeUtils??ete,bindingUtils:i.bindingUtils??tte,tools:i.tools??nte,components:n,options:tc(s)};return d.jsx("div",{ref:l,"data-tldraw":oj,draggable:!1,className:le(`${rte} tl-theme__light`,r),onPointerDown:_t,tabIndex:-1,children:d.jsx(Uu,{fallback:u,onError:p=>vw(p,{tags:{origin:"react.tldraw-before-app"}}),children:a&&d.jsx(Wee,{licenseKey:i.licenseKey,children:d.jsx(dj,{container:a,children:d.jsx(MZ,{overrides:n,children:e?e instanceof e1?d.jsx(YR,{...h,store:e,user:c}):d.jsx(VR,{...h,store:e,user:c}):d.jsx(ste,{...h,store:e,user:c})})})})})})});function ste(t){const{defaultName:e,snapshot:n,initialData:r,shapeUtils:o,bindingUtils:s,persistenceKey:i,sessionId:a,user:l,assets:c}=t,u=Lee({shapeUtils:o,bindingUtils:s,initialData:r,persistenceKey:i,sessionId:a,defaultName:e,snapshot:n,assets:c});return d.jsx(VR,{...t,store:u,user:l})}const VR=w.memo(function({store:e,user:n,...r}){const o=Mt();w.useLayoutEffect(()=>{n.userPreferences.get().colorScheme==="dark"&&(o.classList.remove("tl-theme__light"),o.classList.add("tl-theme__dark"))},[o,n]);const{LoadingScreen:s}=rt();switch(e.status){case"error":throw e.error;case"loading":return s?d.jsx(s,{}):null}return d.jsx(YR,{...r,store:e.store,user:n})}),tS=()=>document.location.search.includes("tldraw_preserve_focus");function YR({onMount:t,children:e,store:n,tools:r,shapeUtils:o,bindingUtils:s,user:i,initialState:a,autoFocus:l=!0,inferDarkMode:c,cameraOptions:u,options:h,licenseKey:p,deepLinks:f,isShapeHidden:g}){const{ErrorFallback:m}=rt(),v=Mt(),[y,S]=WR(null),b=w.useRef(null),P=tc(f===!0?{}:f),C=w.useRef({autoFocus:l&&!tS(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P});w.useLayoutEffect(()=>{C.current={autoFocus:l&&!tS(),inferDarkMode:c,initialState:a,cameraOptions:u,deepLinks:P}},[l,c,a,u,P]),w.useLayoutEffect(()=>{const{autoFocus:k,inferDarkMode:D,initialState:T,cameraOptions:j,deepLinks:$}=C.current,M=new Q({store:n,shapeUtils:o,bindingUtils:s,tools:r,getContainer:()=>v,user:i,initialState:T,autoFocus:k,inferDarkMode:D,cameraOptions:j,options:h,licenseKey:p,isShapeHidden:g});return M.updateViewportScreenBounds(b.current??v),$&&($!=null&&$.getUrl?M.navigateToDeepLink({...$,url:$.getUrl(M)}):M.navigateToDeepLink($)),S(M),()=>{M.dispose()}},[s,v,h,o,n,r,i,S,p,g]),w.useLayoutEffect(()=>{if(y&&P)return y.registerDeepLinkListener(P)},[y,P]),w.useLayoutEffect(()=>{y&&u&&y.setCameraOptions(u)},[y,u]);const _=w.useSyncExternalStore(w.useCallback(k=>y?(y.on("crash",k),()=>y.off("crash",k)):()=>{},[y]),()=>(y==null?void 0:y.getCrashingError())??null);w.useEffect(function(){if(!y)return;function D(){y&&y.focus()}function T(){y&&y.blur()}if(l&&tS())return y.getContainer().addEventListener("pointerdown",D),document.body.addEventListener("pointerdown",T),()=>{var j;(j=y.getContainer())==null||j.removeEventListener("pointerdown",D),document.body.removeEventListener("pointerdown",T)}},[y,l]);const{Canvas:E}=rt();return y?d.jsx(Uu,{fallback:m,onError:k=>y.annotateError(k,{origin:"react.tldraw",willCrashApp:!0}),children:_?d.jsx(ate,{crashingError:_}):d.jsx(p1,{editor:y,children:d.jsxs(ite,{onMount:t,children:[e??(E?d.jsx(E,{},y.contextId):null),d.jsx(Zee,{})]})})}):d.jsx("div",{className:"tl-canvas",ref:b})}function ite({children:t,onMount:e}){return $ee(),bee(),Pee(),Cee(),qR(n=>{const r=n.store.props.onMount(n),o=e==null?void 0:e(n);return()=>{r==null||r(),o==null||o()}}),t}function ate({crashingError:t}){throw t}function D1({children:t}){return d.jsx("div",{className:"tl-loading",children:t})}function XR({children:t}){return d.jsx("div",{className:"tl-loading",children:t})}function qR(t){const e=z(),n=Hg(r=>{let o;return r.run(()=>{o=t==null?void 0:t(r),r.emit("mount")},{history:"ignore"}),window.tldrawReady=!0,o});Te.useLayoutEffect(()=>{if(e)return n==null?void 0:n(e)},[e,n])}function di({children:t,className:e="",...n}){return d.jsx("div",{...n,className:le("tl-html-container",e),children:t})}class dp{constructor(e){this.editor=e}}I(dp,"props"),I(dp,"migrations"),I(dp,"type");function qg(t,e,n={}){const{newPoint:r,handle:o,scaleX:s,scaleY:i}=e,{minWidth:a=1,maxWidth:l=1/0,minHeight:c=1,maxHeight:u=1/0}=n;let h=t.props.w*s,p=t.props.h*i;const f=new x(0,0);if(h>0){if(h<a){switch(o){case"top_left":case"left":case"bottom_left":{f.x=h-a;break}case"top":case"bottom":{f.x=(h-a)/2;break}default:f.x=0}h=a}}else if(f.x=h,h=-h,h<a){switch(o){case"top_left":case"left":case"bottom_left":{f.x=-h;break}default:f.x=-a}h=a}if(p>0){if(p<c){switch(o){case"top_left":case"top":case"top_right":{f.y=p-c;break}case"right":case"left":{f.y=(p-c)/2;break}default:f.y=0}p=c}}else if(f.y=p,p=-p,p<c){switch(o){case"top_left":case"top":case"top_right":{f.y=-p;break}default:f.y=-c}p=c}const{x:g,y:m}=f.rot(t.rotation).add(r);return{...t,x:g,y:m,props:{w:Math.min(l,h),h:Math.min(u,p)}}}class sc extends oo{getGeometry(e){return new No({width:e.props.w,height:e.props.h,isFilled:!0})}onResize(e,n){return qg(e,n)}getHandleSnapGeometry(e){return{points:this.getGeometry(e).bounds.cornersAndCenter}}getInterpolatedProps(e,n,r){return{...n.props,w:_e(e.props.w,n.props.w,r),h:_e(e.props.h,n.props.h,r)}}}var jS;let lte=(jS=class extends ie{onPointerDown(e){this.parent.transition("pointing",e)}onEnter(){this.editor.setCursor({type:"cross",rotation:0})}onCancel(){this.editor.setCurrentTool("select")}},I(jS,"id","idle"),jS);var OS;let cte=(OS=class extends ie{onPointerMove(e){if(this.editor.inputs.isDragging){const{originPagePoint:n}=this.editor.inputs,r=this.parent.shapeType,o=Ke(),s=this.editor.markHistoryStoppingPoint(`creating_box:${o}`),i=io(n,this.editor);this.editor.createShapes([{id:o,type:r,x:i.x,y:i.y,props:{w:1,h:1}}]).select(o);const a=this.parent;this.editor.setCurrentTool("select.resizing",{...e,target:"selection",handle:"bottom_right",isCreating:!0,creatingMarkId:s,creationCursorOffset:{x:1,y:1},onInteractionEnd:this.parent.id,onCreate:a.onCreate?l=>{var c;return(c=a.onCreate)==null?void 0:c.call(a,l)}:void 0})}}onPointerUp(){this.complete()}onCancel(){this.cancel()}onComplete(){this.complete()}onInterrupt(){this.cancel()}complete(){const{originPagePoint:e}=this.editor.inputs,n=this.parent.shapeType,r=Ke();this.editor.markHistoryStoppingPoint(`creating_box:${r}`),this.editor.createShapes([{id:r,type:n,x:e.x,y:e.y}]);const o=this.editor.getShape(r);if(!o){this.cancel();return}let{w:s,h:i}=o.props;const a=new x(s/2,i/2),l=this.editor.getShapeParentTransform(o);l&&a.rot(-l.rotation());let c=1;this.editor.user.getIsDynamicResizeMode()&&(c=1/this.editor.getZoomLevel(),s*=c,i*=c,a.mul(c));const u=tt(o),h=io(new x(o.x-a.x,o.y-a.y),this.editor);u.x=h.x,u.y=h.y,u.props.w=s,u.props.h=i,"scale"in o.props&&(u.props.scale=c),this.editor.updateShape(u),this.editor.setSelectedShapes([r]),this.editor.getInstanceState().isToolLocked?this.parent.transition("idle"):this.editor.setCurrentTool("select.idle")}cancel(){this.parent.transition("idle")}},I(OS,"id","pointing"),OS);function io(t,e){const n=e.getInstanceState().isGridMode,r=e.getDocumentSettings().gridSize;return n?t.clone().snapToGrid(r):t.clone()}class Ox extends ie{static children(){return[lte,cte]}}I(Ox,"id","box"),I(Ox,"initial","idle");function ute(t,e,n){const r=w.useRef(!1),o=w.useCallback(i=>{r.current=i,i?Vr.addOpenMenu(t):Vr.deleteOpenMenu(t),e==null||e(i)},[t,e]),s=U("is menu open",()=>Vr.getOpenMenus().includes(t),[t]);return w.useEffect(()=>(r.current&&(n==null||n("open-menu"),Vr.addOpenMenu(t)),()=>{r.current&&(Vr.deleteOpenMenu(t),Vr.getOpenMenus().forEach(i=>{i.startsWith(t)&&(n==null||n("close-menu"),Vr.deleteOpenMenu(i))}),r.current=!1)}),[t,n]),[s,o]}function Zg(t){const e=z();return U("isEditing",()=>e.getEditingShapeId()===t,[e,t])}function bo(t){const e=z();return w.useMemo(function(){const o=c=>{if(c.isKilled)return;if(c.button===g1){e.dispatch({type:"pointer",target:"selection",handle:t,name:"right_click",...lr(c)});return}if(c.button!==0)return;const u=Rf(c.currentTarget);function h(){u.removeEventListener("pointerup",h),hd(u,c)}dd(u,c),u.addEventListener("pointerup",h),e.dispatch({name:"pointer_down",type:"pointer",target:"selection",handle:t,...lr(c)}),_t(c)};let s,i;function a(c){c.isKilled||c.button===0&&(c.clientX===s&&c.clientY===i||(s=c.clientX,i=c.clientY,e.dispatch({name:"pointer_move",type:"pointer",target:"selection",handle:t,...lr(c)})))}return{onPointerDown:o,onPointerMove:a,onPointerUp:c=>{c.isKilled||c.button===0&&e.dispatch({name:"pointer_up",type:"pointer",target:"selection",handle:t,...lr(c)})}}},[e,t])}function dte(t){const[e,n]=w.useState(()=>({store:Hu(t),opts:t}));if(!NT(e.opts,t)){const r={store:Hu(t),opts:t};return n(r),r.store}return e.store}const hte=20,pte=8;function R1(t,e=hte){return Math.max(pte,Math.ceil(t/e))}class ll extends Ti{constructor(n){super({...n,isFilled:!1,isClosed:!1});I(this,"_center");I(this,"radius");I(this,"start");I(this,"end");I(this,"largeArcFlag");I(this,"sweepFlag");I(this,"measure");I(this,"angleStart");I(this,"angleEnd");const{center:r,sweepFlag:o,largeArcFlag:s,start:i,end:a}=n;if(i.equals(a))throw Error("Arc must have different start and end points.");this.angleStart=x.Angle(r,i),this.angleEnd=x.Angle(r,a),this.radius=x.Dist(r,i),this.measure=SX(this.angleStart,this.angleEnd,o,s),this.start=i,this.end=a,this.sweepFlag=o,this.largeArcFlag=s,this._center=r}nearestPoint(n){const{_center:r,measure:o,radius:s,angleEnd:i,angleStart:a,start:l,end:c}=this,u=xx(o,a,i,r.angle(n));if(u<=0)return l;if(u>=1)return c;const h=r.clone().add(n.clone().sub(r).uni().mul(s));let p,f=1/0,g;for(const m of[l,c,h])g=x.Dist2(n,m),g<f&&(p=m,f=g);if(!p)throw Error("nearest point not found");return p}hitTestLineSegment(n,r){const{_center:o,radius:s,measure:i,angleStart:a,angleEnd:l}=this,c=gd(n,r,o,s);return c===null?!1:c.some(u=>{const h=xx(i,a,l,o.angle(u));return h>=0&&h<=1})}getVertices(){const{_center:n,measure:r,length:o,radius:s,angleStart:i}=this,a=[];for(let l=0,c=R1(Math.abs(o));l<c+1;l++){const u=l/c*r,h=i+u;a.push(da(n,s,h))}return a}getSvgPathData(n=!0){const{start:r,end:o,radius:s,largeArcFlag:i,sweepFlag:a}=this;return`${n?`M${r.toFixed()}`:""} A${s} ${s} 0 ${i} ${a} ${o.toFixed()}`}getLength(){return this.measure*this.radius}}class L1 extends Ti{constructor(n){super({isClosed:!0,...n});I(this,"_center");I(this,"radius");I(this,"x");I(this,"y");this.config=n;const{x:r=0,y:o=0,radius:s}=n;this.x=r,this.y=o,this._center=new x(s+r,s+o),this.radius=s}getBounds(){return new Z(this.x,this.y,this.radius*2,this.radius*2)}getVertices(){const{_center:n,radius:r}=this,o=Ne*r,s=[];for(let i=0,a=R1(o);i<a;i++){const l=i/a*Ne;s.push(da(n,r,l))}return s}nearestPoint(n){const{_center:r,radius:o}=this;return r.equals(n)?x.AddXY(r,o,0):r.clone().add(n.clone().sub(r).uni().mul(o))}hitTestLineSegment(n,r,o=0){const{_center:s,radius:i}=this;return gd(n,r,s,i+o)!==null}getSvgPathData(){const{_center:n,radius:r}=this;return`M${n.x+r},${n.y} a${r},${r} 0 1,0 ${r*2},0a${r},${r} 0 1,0 -${r*2},0`}}class an extends nc{constructor(n){const{start:r,cp1:o,cp2:s,end:i}=n;super({...n,points:[r,i]});I(this,"a");I(this,"b");I(this,"c");I(this,"d");this.a=r,this.b=o,this.c=s,this.d=i}getVertices(){const n=[],{a:r,b:o,c:s,d:i}=this;for(let a=0,l=10;a<=l;a++){const c=a/l;n.push(new x((1-c)*(1-c)*(1-c)*r.x+3*((1-c)*(1-c))*c*o.x+3*(1-c)*(c*c)*s.x+c*c*c*i.x,(1-c)*(1-c)*(1-c)*r.y+3*((1-c)*(1-c))*c*o.y+3*(1-c)*(c*c)*s.y+c*c*c*i.y))}return n}midPoint(){return an.GetAtT(this,.5)}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}getSvgPathData(n=!0){const{a:r,b:o,c:s,d:i}=this;return`${n?`M ${r.toFixed()} `:""} C${o.toFixed()} ${s.toFixed()} ${i.toFixed()}`}static GetAtT(n,r){const{a:o,b:s,c:i,d:a}=n;return new x((1-r)*(1-r)*(1-r)*o.x+3*((1-r)*(1-r))*r*s.x+3*(1-r)*(r*r)*i.x+r*r*r*a.x,(1-r)*(1-r)*(1-r)*o.y+3*((1-r)*(1-r))*r*s.y+3*(1-r)*(r*r)*i.y+r*r*r*a.y)}getLength(n=32){let r,o=this.a,s=0;for(let i=1;i<=n;i++)r=an.GetAtT(this,i/n),s+=x.Dist(o,r),o=r;return s}}class fte extends Ti{constructor(n){super({...n,isClosed:!1,isFilled:!1});I(this,"points");I(this,"_segments");const{points:r}=n;this.points=r}get segments(){if(!this._segments){this._segments=[];const{points:n}=this,r=n.length,o=r-2,s=1.25;for(let i=0;i<r-1;i++){const a=i===0?n[0]:n[i-1],l=n[i],c=n[i+1],u=i===o?c:n[i+2],h=l,p=i===0?a:new x(l.x+(c.x-a.x)/6*s,l.y+(c.y-a.y)/6*s),f=i===o?c:new x(c.x-(u.x-l.x)/6*s,c.y-(u.y-l.y)/6*s),g=c;this._segments.push(new an({start:h,cp1:p,cp2:f,end:g}))}}return this._segments}getLength(){return this.segments.reduce((n,r)=>n+r.length,0)}getVertices(){const n=this.segments.reduce((r,o)=>r.concat(o.vertices),[]);return n.push(this.points[this.points.length-1]),n}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.segments)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){return this.segments.some(o=>o.hitTestLineSegment(n,r))}getSvgPathData(){let n=this.segments.reduce((r,o,s)=>r+o.getSvgPathData(s===0),"");return this.isClosed&&(n+="Z"),n}}class gte extends Ti{constructor(n){super({...n,isClosed:!0});I(this,"w");I(this,"h");I(this,"_edges");this.config=n;const{width:r,height:o}=n;this.w=r,this.h=o}get edges(){if(!this._edges){const{vertices:n}=this;this._edges=[];for(let r=0,o=n.length;r<o;r++){const s=n[r],i=n[(r+1)%o];this._edges.push(new us({start:s,end:i}))}}return this._edges}getVertices(){const n=Math.max(1,this.w),r=Math.max(1,this.h),o=n/2,s=r/2,i=Math.pow(o-s,2)/Math.pow(o+s,2),a=De*(o+s)*(1+3*i/(10+Math.sqrt(4-3*i))),l=R1(a),c=Ne/l,u=Math.cos(c),h=Math.sin(c);let p=0,f=1,g=0,m=1;const v=Array(l);for(let y=0;y<l;y++)v[y]=new x(o+o*f,s+s*p),g=h*f+u*p,m=u*f-h*p,p=g,f=m;return v}nearestPoint(n){let r,o=1/0,s,i;for(const a of this.edges)i=a.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){return this.edges.some(o=>o.hitTestLineSegment(n,r))}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{w:n,h:r}=this,o=n/2,s=r/2,i=Math.max(0,o),a=Math.max(0,s);return ij(i,a)}getSvgPathData(n=!1){const{w:r,h:o}=this,s=r/2,i=o/2,a=Math.max(0,s),l=Math.max(0,i);return`${n?`M${s-a},${i}`:""} a${a},${l},0,1,1,${a*2},0a${a},${l},0,1,1,-${a*2},0`}}class mte extends Ti{constructor(n){super({...n,isClosed:!0});I(this,"w");I(this,"h");I(this,"a");I(this,"b");I(this,"c");I(this,"d");this.config=n;const{width:r,height:o}=n;if(this.w=r,this.h=o,o>r){const s=r/2;this.a=new ll({start:new x(0,s),end:new x(r,s),center:new x(r/2,s),sweepFlag:1,largeArcFlag:1}),this.b=new us({start:new x(r,s),end:new x(r,o-s)}),this.c=new ll({start:new x(r,o-s),end:new x(0,o-s),center:new x(r/2,o-s),sweepFlag:1,largeArcFlag:1}),this.d=new us({start:new x(0,o-s),end:new x(0,s)})}else{const s=o/2;this.a=new ll({start:new x(s,o),end:new x(s,0),center:new x(s,s),sweepFlag:1,largeArcFlag:1}),this.b=new us({start:new x(s,0),end:new x(r-s,0)}),this.c=new ll({start:new x(r-s,0),end:new x(r-s,o),center:new x(r-s,s),sweepFlag:1,largeArcFlag:1}),this.d=new us({start:new x(r-s,o),end:new x(s,o)})}}nearestPoint(n){let r,o=1/0,s,i;const{a,b:l,c,d:u}=this;for(const h of[a,l,c,u])i=h.nearestPoint(n),s=x.Dist2(i,n),s<o&&(r=i,o=s);if(!r)throw Error("nearest point not found");return r}hitTestLineSegment(n,r){const{a:o,b:s,c:i,d:a}=this;return[o,s,i,a].some(l=>l.hitTestLineSegment(n,r))}getVertices(){const{a:n,b:r,c:o,d:s}=this;return[n,r,o,s].reduce((i,a)=>(i.push(...a.vertices),i),[])}getBounds(){return new Z(0,0,this.w,this.h)}getLength(){const{h:n,w:r}=this;return n>r?(De*(r/2)+(n-r))*2:(De*(n/2)+(r-n))*2}getSvgPathData(){const{a:n,b:r,c:o,d:s}=this;return[n,r,o,s].map((i,a)=>i.getSvgPathData(a===0)).join(" ")+" Z"}}async function yte({shouldReload:t=!0}={}){cB();for(const e of xf.connectedInstances)await e.close();await Promise.all(Qw().map(e=>dA(e))),lB(),t&&window.location.reload()}typeof window<"u"&&(window.__tldraw__hardReset=yte);function Ste(t,e="_blank"){$g.openWindow(t,e)}Ci("@tldraw/editor","3.7.0-canary.8e16c48b63b1","esm");function ZR(){const[t,e]=w.useState(!1);return w.useEffect(()=>{if(typeof window>"u"||!("matchMedia"in window))return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>{e(n.matches)};return r(),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}const QR=()=>{},JR=w.createContext(null);function vte({onEvent:t,children:e}){return d.jsx(JR.Provider,{value:t??QR,children:e})}function Qt(){return w.useContext(JR)??QR}function oe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t==null||t(o),n===!1||!o.defaultPrevented)return e==null?void 0:e(o)}}function xte(t,e){const n=w.createContext(e),r=s=>{const{children:i,...a}=s,l=w.useMemo(()=>a,Object.values(a));return d.jsx(n.Provider,{value:l,children:i})};r.displayName=t+"Provider";function o(s){const i=w.useContext(n);if(i)return i;if(e!==void 0)return e;throw new Error(`\`${s}\` must be used within \`${t}\``)}return[r,o]}function Go(t,e=[]){let n=[];function r(s,i){const a=w.createContext(i),l=n.length;n=[...n,i];const c=h=>{var y;const{scope:p,children:f,...g}=h,m=((y=p==null?void 0:p[t])==null?void 0:y[l])||a,v=w.useMemo(()=>g,Object.values(g));return d.jsx(m.Provider,{value:v,children:f})};c.displayName=s+"Provider";function u(h,p){var m;const f=((m=p==null?void 0:p[t])==null?void 0:m[l])||a,g=w.useContext(f);if(g)return g;if(i!==void 0)return i;throw new Error(`\`${h}\` must be used within \`${s}\``)}return[c,u]}const o=()=>{const s=n.map(i=>w.createContext(i));return function(a){const l=(a==null?void 0:a[t])||s;return w.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,wte(o,...e)]}function wte(...t){const e=t[0];if(t.length===1)return e;const n=()=>{const r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const h=l(s)[`__scope${c}`];return{...a,...h}},{});return w.useMemo(()=>({[`__scope${e.scopeName}`]:i}),[i])}};return n.scopeName=e.scopeName,n}function WI(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Qg(...t){return e=>{let n=!1;const r=t.map(o=>{const s=WI(o,e);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():WI(t[o],null)}}}}function Ze(...t){return w.useCallback(Qg(...t),t)}var ha=w.forwardRef((t,e)=>{const{children:n,...r}=t,o=w.Children.toArray(n),s=o.find(Pte);if(s){const i=s.props.children,a=o.map(l=>l===s?w.Children.count(i)>1?w.Children.only(null):w.isValidElement(i)?i.props.children:null:l);return d.jsx(Dx,{...r,ref:e,children:w.isValidElement(i)?w.cloneElement(i,void 0,a):null})}return d.jsx(Dx,{...r,ref:e,children:n})});ha.displayName="Slot";var Dx=w.forwardRef((t,e)=>{const{children:n,...r}=t;if(w.isValidElement(n)){const o=_te(n);return w.cloneElement(n,{...Cte(r,n.props),ref:e?Qg(e,o):o})}return w.Children.count(n)>1?w.Children.only(null):null});Dx.displayName="SlotClone";var bte=({children:t})=>d.jsx(d.Fragment,{children:t});function Pte(t){return w.isValidElement(t)&&t.type===bte}function Cte(t,e){const n={...e};for(const r in e){const o=t[r],s=e[r];/^on[A-Z]/.test(r)?o&&s?n[r]=(...a)=>{s(...a),o(...a)}:o&&(n[r]=o):r==="style"?n[r]={...o,...s}:r==="className"&&(n[r]=[o,s].filter(Boolean).join(" "))}return{...t,...n}}function _te(t){var r,o;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Ite=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=Ite.reduce((t,e)=>{const n=w.forwardRef((r,o)=>{const{asChild:s,...i}=r,a=s?ha:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(a,{...i,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});function $1(t,e){t&&wa.flushSync(()=>t.dispatchEvent(e))}function Jg(t){const e=t+"CollectionProvider",[n,r]=Go(e),[o,s]=n(e,{collectionRef:{current:null},itemMap:new Map}),i=f=>{const{scope:g,children:m}=f,v=Te.useRef(null),y=Te.useRef(new Map).current;return d.jsx(o,{scope:g,itemMap:y,collectionRef:v,children:m})};i.displayName=e;const a=t+"CollectionSlot",l=Te.forwardRef((f,g)=>{const{scope:m,children:v}=f,y=s(a,m),S=Ze(g,y.collectionRef);return d.jsx(ha,{ref:S,children:v})});l.displayName=a;const c=t+"CollectionItemSlot",u="data-radix-collection-item",h=Te.forwardRef((f,g)=>{const{scope:m,children:v,...y}=f,S=Te.useRef(null),b=Ze(g,S),P=s(c,m);return Te.useEffect(()=>(P.itemMap.set(S,{ref:S,...y}),()=>void P.itemMap.delete(S))),d.jsx(ha,{[u]:"",ref:b,children:v})});h.displayName=c;function p(f){const g=s(t+"CollectionConsumer",f);return Te.useCallback(()=>{const v=g.collectionRef.current;if(!v)return[];const y=Array.from(v.querySelectorAll(`[${u}]`));return Array.from(g.itemMap.values()).sort((P,C)=>y.indexOf(P.ref.current)-y.indexOf(C.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:i,Slot:l,ItemSlot:h},p,r]}var Ete=w.createContext(void 0);function F1(t){const e=w.useContext(Ete);return t||e||"ltr"}function Xt(t){const e=w.useRef(t);return w.useEffect(()=>{e.current=t}),w.useMemo(()=>(...n)=>{var r;return(r=e.current)==null?void 0:r.call(e,...n)},[])}function kte(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t);w.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var Tte="DismissableLayer",Rx="dismissableLayer.update",Mte="dismissableLayer.pointerDownOutside",Ate="dismissableLayer.focusOutside",GI,e3=w.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),wd=w.forwardRef((t,e)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=t,c=w.useContext(e3),[u,h]=w.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=w.useState({}),g=Ze(e,E=>h(E)),m=Array.from(c.layers),[v]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=m.indexOf(v),S=u?m.indexOf(u):-1,b=c.layersWithOutsidePointerEventsDisabled.size>0,P=S>=y,C=Ote(E=>{const k=E.target,D=[...c.branches].some(T=>T.contains(k));!P||D||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},p),_=Dte(E=>{const k=E.target;[...c.branches].some(T=>T.contains(k))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},p);return kte(E=>{S===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},p),w.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(GI=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),VI(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=GI)}},[u,p,n,c]),w.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),VI())},[u,c]),w.useEffect(()=>{const E=()=>f({});return document.addEventListener(Rx,E),()=>document.removeEventListener(Rx,E)},[]),d.jsx(Ae.div,{...l,ref:g,style:{pointerEvents:b?P?"auto":"none":void 0,...t.style},onFocusCapture:oe(t.onFocusCapture,_.onFocusCapture),onBlurCapture:oe(t.onBlurCapture,_.onBlurCapture),onPointerDownCapture:oe(t.onPointerDownCapture,C.onPointerDownCapture)})});wd.displayName=Tte;var jte="DismissableLayerBranch",t3=w.forwardRef((t,e)=>{const n=w.useContext(e3),r=w.useRef(null),o=Ze(e,r);return w.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),d.jsx(Ae.div,{...t,ref:o})});t3.displayName=jte;function Ote(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t),r=w.useRef(!1),o=w.useRef(()=>{});return w.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){n3(Mte,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=l,e.addEventListener("click",o.current,{once:!0})):l()}else e.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{e.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),e.removeEventListener("pointerdown",s),e.removeEventListener("click",o.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function Dte(t,e=globalThis==null?void 0:globalThis.document){const n=Xt(t),r=w.useRef(!1);return w.useEffect(()=>{const o=s=>{s.target&&!r.current&&n3(Ate,n,{originalEvent:s},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function VI(){const t=new CustomEvent(Rx);document.dispatchEvent(t)}function n3(t,e,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?$1(o,s):o.dispatchEvent(s)}var Rte=wd,Lte=t3,nS=0;function N1(){w.useEffect(()=>{const t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??YI()),document.body.insertAdjacentElement("beforeend",t[1]??YI()),nS++,()=>{nS===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),nS--}},[])}function YI(){const t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var rS="focusScope.autoFocusOnMount",oS="focusScope.autoFocusOnUnmount",XI={bubbles:!1,cancelable:!0},$te="FocusScope",em=w.forwardRef((t,e)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=t,[a,l]=w.useState(null),c=Xt(o),u=Xt(s),h=w.useRef(null),p=Ze(e,m=>l(m)),f=w.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;w.useEffect(()=>{if(r){let m=function(b){if(f.paused||!a)return;const P=b.target;a.contains(P)?h.current=P:Bs(h.current,{select:!0})},v=function(b){if(f.paused||!a)return;const P=b.relatedTarget;P!==null&&(a.contains(P)||Bs(h.current,{select:!0}))},y=function(b){if(document.activeElement===document.body)for(const C of b)C.removedNodes.length>0&&Bs(a)};document.addEventListener("focusin",m),document.addEventListener("focusout",v);const S=new MutationObserver(y);return a&&S.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",m),document.removeEventListener("focusout",v),S.disconnect()}}},[r,a,f.paused]),w.useEffect(()=>{if(a){ZI.add(f);const m=document.activeElement;if(!a.contains(m)){const y=new CustomEvent(rS,XI);a.addEventListener(rS,c),a.dispatchEvent(y),y.defaultPrevented||(Fte(Hte(r3(a)),{select:!0}),document.activeElement===m&&Bs(a))}return()=>{a.removeEventListener(rS,c),setTimeout(()=>{const y=new CustomEvent(oS,XI);a.addEventListener(oS,u),a.dispatchEvent(y),y.defaultPrevented||Bs(m??document.body,{select:!0}),a.removeEventListener(oS,u),ZI.remove(f)},0)}}},[a,c,u,f]);const g=w.useCallback(m=>{if(!n&&!r||f.paused)return;const v=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,y=document.activeElement;if(v&&y){const S=m.currentTarget,[b,P]=Nte(S);b&&P?!m.shiftKey&&y===P?(m.preventDefault(),n&&Bs(b,{select:!0})):m.shiftKey&&y===b&&(m.preventDefault(),n&&Bs(P,{select:!0})):y===S&&m.preventDefault()}},[n,r,f.paused]);return d.jsx(Ae.div,{tabIndex:-1,...i,ref:p,onKeyDown:g})});em.displayName=$te;function Fte(t,{select:e=!1}={}){const n=document.activeElement;for(const r of t)if(Bs(r,{select:e}),document.activeElement!==n)return}function Nte(t){const e=r3(t),n=qI(e,t),r=qI(e.reverse(),t);return[n,r]}function r3(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function qI(t,e){for(const n of t)if(!zte(n,{upTo:e}))return n}function zte(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function Bte(t){return t instanceof HTMLInputElement&&"select"in t}function Bs(t,{select:e=!1}={}){if(t&&t.focus){const n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&Bte(t)&&e&&t.select()}}var ZI=Ute();function Ute(){let t=[];return{add(e){const n=t[0];e!==n&&(n==null||n.pause()),t=QI(t,e),t.unshift(e)},remove(e){var n;t=QI(t,e),(n=t[0])==null||n.resume()}}}function QI(t,e){const n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function Hte(t){return t.filter(e=>e.tagName!=="A")}var mi=globalThis!=null&&globalThis.document?w.useLayoutEffect:()=>{},Kte=e6.useId||(()=>{}),Wte=0;function ms(t){const[e,n]=w.useState(Kte());return mi(()=>{t||n(r=>r??String(Wte++))},[t]),t||(e?`radix-${e}`:"")}const Gte=["top","right","bottom","left"],yi=Math.min,sr=Math.max,Ff=Math.round,bh=Math.floor,Do=t=>({x:t,y:t}),Vte={left:"right",right:"left",bottom:"top",top:"bottom"},Yte={start:"end",end:"start"};function Lx(t,e,n){return sr(t,yi(e,n))}function bs(t,e){return typeof t=="function"?t(e):t}function Ps(t){return t.split("-")[0]}function ic(t){return t.split("-")[1]}function z1(t){return t==="x"?"y":"x"}function B1(t){return t==="y"?"height":"width"}function Si(t){return["top","bottom"].includes(Ps(t))?"y":"x"}function U1(t){return z1(Si(t))}function Xte(t,e,n){n===void 0&&(n=!1);const r=ic(t),o=U1(t),s=B1(o);let i=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[s]>e.floating[s]&&(i=Nf(i)),[i,Nf(i)]}function qte(t){const e=Nf(t);return[$x(t),e,$x(e)]}function $x(t){return t.replace(/start|end/g,e=>Yte[e])}function Zte(t,e,n){const r=["left","right"],o=["right","left"],s=["top","bottom"],i=["bottom","top"];switch(t){case"top":case"bottom":return n?e?o:r:e?r:o;case"left":case"right":return e?s:i;default:return[]}}function Qte(t,e,n,r){const o=ic(t);let s=Zte(Ps(t),n==="start",r);return o&&(s=s.map(i=>i+"-"+o),e&&(s=s.concat(s.map($x)))),s}function Nf(t){return t.replace(/left|right|bottom|top/g,e=>Vte[e])}function Jte(t){return{top:0,right:0,bottom:0,left:0,...t}}function o3(t){return typeof t!="number"?Jte(t):{top:t,right:t,bottom:t,left:t}}function zf(t){const{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function JI(t,e,n){let{reference:r,floating:o}=t;const s=Si(e),i=U1(e),a=B1(i),l=Ps(e),c=s==="y",u=r.x+r.width/2-o.width/2,h=r.y+r.height/2-o.height/2,p=r[a]/2-o[a]/2;let f;switch(l){case"top":f={x:u,y:r.y-o.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-o.width,y:h};break;default:f={x:r.x,y:r.y}}switch(ic(e)){case"start":f[i]-=p*(n&&c?-1:1);break;case"end":f[i]+=p*(n&&c?-1:1);break}return f}const ene=async(t,e,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:s=[],platform:i}=n,a=s.filter(Boolean),l=await(i.isRTL==null?void 0:i.isRTL(e));let c=await i.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:h}=JI(c,r,l),p=r,f={},g=0;for(let m=0;m<a.length;m++){const{name:v,fn:y}=a[m],{x:S,y:b,data:P,reset:C}=await y({x:u,y:h,initialPlacement:r,placement:p,strategy:o,middlewareData:f,rects:c,platform:i,elements:{reference:t,floating:e}});u=S??u,h=b??h,f={...f,[v]:{...f[v],...P}},C&&g<=50&&(g++,typeof C=="object"&&(C.placement&&(p=C.placement),C.rects&&(c=C.rects===!0?await i.getElementRects({reference:t,floating:e,strategy:o}):C.rects),{x:u,y:h}=JI(c,p,l)),m=-1)}return{x:u,y:h,placement:p,strategy:o,middlewareData:f}};async function Ku(t,e){var n;e===void 0&&(e={});const{x:r,y:o,platform:s,rects:i,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:p=!1,padding:f=0}=bs(e,t),g=o3(f),v=a[p?h==="floating"?"reference":"floating":h],y=zf(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(v)))==null||n?v:v.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),S=h==="floating"?{x:r,y:o,width:i.floating.width,height:i.floating.height}:i.reference,b=await(s.getOffsetParent==null?void 0:s.getOffsetParent(a.floating)),P=await(s.isElement==null?void 0:s.isElement(b))?await(s.getScale==null?void 0:s.getScale(b))||{x:1,y:1}:{x:1,y:1},C=zf(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:S,offsetParent:b,strategy:l}):S);return{top:(y.top-C.top+g.top)/P.y,bottom:(C.bottom-y.bottom+g.bottom)/P.y,left:(y.left-C.left+g.left)/P.x,right:(C.right-y.right+g.right)/P.x}}const tne=t=>({name:"arrow",options:t,async fn(e){const{x:n,y:r,placement:o,rects:s,platform:i,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=bs(t,e)||{};if(c==null)return{};const h=o3(u),p={x:n,y:r},f=U1(o),g=B1(f),m=await i.getDimensions(c),v=f==="y",y=v?"top":"left",S=v?"bottom":"right",b=v?"clientHeight":"clientWidth",P=s.reference[g]+s.reference[f]-p[f]-s.floating[g],C=p[f]-s.reference[f],_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(c));let E=_?_[b]:0;(!E||!await(i.isElement==null?void 0:i.isElement(_)))&&(E=a.floating[b]||s.floating[g]);const k=P/2-C/2,D=E/2-m[g]/2-1,T=yi(h[y],D),j=yi(h[S],D),$=T,M=E-m[g]-j,O=E/2-m[g]/2+k,F=Lx($,O,M),B=!l.arrow&&ic(o)!=null&&O!==F&&s.reference[g]/2-(O<$?T:j)-m[g]/2<0,K=B?O<$?O-$:O-M:0;return{[f]:p[f]+K,data:{[f]:F,centerOffset:O-F-K,...B&&{alignmentOffset:K}},reset:B}}}),nne=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;const{placement:o,middlewareData:s,rects:i,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:h=!0,fallbackPlacements:p,fallbackStrategy:f="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:m=!0,...v}=bs(t,e);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const y=Ps(o),S=Si(a),b=Ps(a)===a,P=await(l.isRTL==null?void 0:l.isRTL(c.floating)),C=p||(b||!m?[Nf(a)]:qte(a)),_=g!=="none";!p&&_&&C.push(...Qte(a,m,g,P));const E=[a,...C],k=await Ku(e,v),D=[];let T=((r=s.flip)==null?void 0:r.overflows)||[];if(u&&D.push(k[y]),h){const O=Xte(o,i,P);D.push(k[O[0]],k[O[1]])}if(T=[...T,{placement:o,overflows:D}],!D.every(O=>O<=0)){var j,$;const O=(((j=s.flip)==null?void 0:j.index)||0)+1,F=E[O];if(F)return{data:{index:O,overflows:T},reset:{placement:F}};let B=($=T.filter(K=>K.overflows[0]<=0).sort((K,R)=>K.overflows[1]-R.overflows[1])[0])==null?void 0:$.placement;if(!B)switch(f){case"bestFit":{var M;const K=(M=T.filter(R=>{if(_){const H=Si(R.placement);return H===S||H==="y"}return!0}).map(R=>[R.placement,R.overflows.filter(H=>H>0).reduce((H,Y)=>H+Y,0)]).sort((R,H)=>R[1]-H[1])[0])==null?void 0:M[0];K&&(B=K);break}case"initialPlacement":B=a;break}if(o!==B)return{reset:{placement:B}}}return{}}}};function eE(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function tE(t){return Gte.some(e=>t[e]>=0)}const rne=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){const{rects:n}=e,{strategy:r="referenceHidden",...o}=bs(t,e);switch(r){case"referenceHidden":{const s=await Ku(e,{...o,elementContext:"reference"}),i=eE(s,n.reference);return{data:{referenceHiddenOffsets:i,referenceHidden:tE(i)}}}case"escaped":{const s=await Ku(e,{...o,altBoundary:!0}),i=eE(s,n.floating);return{data:{escapedOffsets:i,escaped:tE(i)}}}default:return{}}}}};async function one(t,e){const{placement:n,platform:r,elements:o}=t,s=await(r.isRTL==null?void 0:r.isRTL(o.floating)),i=Ps(n),a=ic(n),l=Si(n)==="y",c=["left","top"].includes(i)?-1:1,u=s&&l?-1:1,h=bs(e,t);let{mainAxis:p,crossAxis:f,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return a&&typeof g=="number"&&(f=a==="end"?g*-1:g),l?{x:f*u,y:p*c}:{x:p*c,y:f*u}}const sne=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;const{x:o,y:s,placement:i,middlewareData:a}=e,l=await one(e,t);return i===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:s+l.y,data:{...l,placement:i}}}}},ine=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){const{x:n,y:r,placement:o}=e,{mainAxis:s=!0,crossAxis:i=!1,limiter:a={fn:v=>{let{x:y,y:S}=v;return{x:y,y:S}}},...l}=bs(t,e),c={x:n,y:r},u=await Ku(e,l),h=Si(Ps(o)),p=z1(h);let f=c[p],g=c[h];if(s){const v=p==="y"?"top":"left",y=p==="y"?"bottom":"right",S=f+u[v],b=f-u[y];f=Lx(S,f,b)}if(i){const v=h==="y"?"top":"left",y=h==="y"?"bottom":"right",S=g+u[v],b=g-u[y];g=Lx(S,g,b)}const m=a.fn({...e,[p]:f,[h]:g});return{...m,data:{x:m.x-n,y:m.y-r,enabled:{[p]:s,[h]:i}}}}}},ane=function(t){return t===void 0&&(t={}),{options:t,fn(e){const{x:n,y:r,placement:o,rects:s,middlewareData:i}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=bs(t,e),u={x:n,y:r},h=Si(o),p=z1(h);let f=u[p],g=u[h];const m=bs(a,e),v=typeof m=="number"?{mainAxis:m,crossAxis:0}:{mainAxis:0,crossAxis:0,...m};if(l){const b=p==="y"?"height":"width",P=s.reference[p]-s.floating[b]+v.mainAxis,C=s.reference[p]+s.reference[b]-v.mainAxis;f<P?f=P:f>C&&(f=C)}if(c){var y,S;const b=p==="y"?"width":"height",P=["top","left"].includes(Ps(o)),C=s.reference[h]-s.floating[b]+(P&&((y=i.offset)==null?void 0:y[h])||0)+(P?0:v.crossAxis),_=s.reference[h]+s.reference[b]+(P?0:((S=i.offset)==null?void 0:S[h])||0)-(P?v.crossAxis:0);g<C?g=C:g>_&&(g=_)}return{[p]:f,[h]:g}}}},lne=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;const{placement:o,rects:s,platform:i,elements:a}=e,{apply:l=()=>{},...c}=bs(t,e),u=await Ku(e,c),h=Ps(o),p=ic(o),f=Si(o)==="y",{width:g,height:m}=s.floating;let v,y;h==="top"||h==="bottom"?(v=h,y=p===(await(i.isRTL==null?void 0:i.isRTL(a.floating))?"start":"end")?"left":"right"):(y=h,v=p==="end"?"top":"bottom");const S=m-u.top-u.bottom,b=g-u.left-u.right,P=yi(m-u[v],S),C=yi(g-u[y],b),_=!e.middlewareData.shift;let E=P,k=C;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(k=b),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(E=S),_&&!p){const T=sr(u.left,0),j=sr(u.right,0),$=sr(u.top,0),M=sr(u.bottom,0);f?k=g-2*(T!==0||j!==0?T+j:sr(u.left,u.right)):E=m-2*($!==0||M!==0?$+M:sr(u.top,u.bottom))}await l({...e,availableWidth:k,availableHeight:E});const D=await i.getDimensions(a.floating);return g!==D.width||m!==D.height?{reset:{rects:!0}}:{}}}};function tm(){return typeof window<"u"}function ac(t){return s3(t)?(t.nodeName||"").toLowerCase():"#document"}function pr(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function Vo(t){var e;return(e=(s3(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function s3(t){return tm()?t instanceof Node||t instanceof pr(t).Node:!1}function ao(t){return tm()?t instanceof Element||t instanceof pr(t).Element:!1}function zo(t){return tm()?t instanceof HTMLElement||t instanceof pr(t).HTMLElement:!1}function nE(t){return!tm()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof pr(t).ShadowRoot}function bd(t){const{overflow:e,overflowX:n,overflowY:r,display:o}=lo(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!["inline","contents"].includes(o)}function cne(t){return["table","td","th"].includes(ac(t))}function nm(t){return[":popover-open",":modal"].some(e=>{try{return t.matches(e)}catch{return!1}})}function H1(t){const e=K1(),n=ao(t)?lo(t):t;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function une(t){let e=vi(t);for(;zo(e)&&!Rl(e);){if(H1(e))return e;if(nm(e))return null;e=vi(e)}return null}function K1(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Rl(t){return["html","body","#document"].includes(ac(t))}function lo(t){return pr(t).getComputedStyle(t)}function rm(t){return ao(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function vi(t){if(ac(t)==="html")return t;const e=t.assignedSlot||t.parentNode||nE(t)&&t.host||Vo(t);return nE(e)?e.host:e}function i3(t){const e=vi(t);return Rl(e)?t.ownerDocument?t.ownerDocument.body:t.body:zo(e)&&bd(e)?e:i3(e)}function Wu(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);const o=i3(t),s=o===((r=t.ownerDocument)==null?void 0:r.body),i=pr(o);if(s){const a=Fx(i);return e.concat(i,i.visualViewport||[],bd(o)?o:[],a&&n?Wu(a):[])}return e.concat(o,Wu(o,[],n))}function Fx(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function a3(t){const e=lo(t);let n=parseFloat(e.width)||0,r=parseFloat(e.height)||0;const o=zo(t),s=o?t.offsetWidth:n,i=o?t.offsetHeight:r,a=Ff(n)!==s||Ff(r)!==i;return a&&(n=s,r=i),{width:n,height:r,$:a}}function W1(t){return ao(t)?t:t.contextElement}function Pl(t){const e=W1(t);if(!zo(e))return Do(1);const n=e.getBoundingClientRect(),{width:r,height:o,$:s}=a3(e);let i=(s?Ff(n.width):n.width)/r,a=(s?Ff(n.height):n.height)/o;return(!i||!Number.isFinite(i))&&(i=1),(!a||!Number.isFinite(a))&&(a=1),{x:i,y:a}}const dne=Do(0);function l3(t){const e=pr(t);return!K1()||!e.visualViewport?dne:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function hne(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==pr(t)?!1:e}function pa(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);const o=t.getBoundingClientRect(),s=W1(t);let i=Do(1);e&&(r?ao(r)&&(i=Pl(r)):i=Pl(t));const a=hne(s,n,r)?l3(s):Do(0);let l=(o.left+a.x)/i.x,c=(o.top+a.y)/i.y,u=o.width/i.x,h=o.height/i.y;if(s){const p=pr(s),f=r&&ao(r)?pr(r):r;let g=p,m=Fx(g);for(;m&&r&&f!==g;){const v=Pl(m),y=m.getBoundingClientRect(),S=lo(m),b=y.left+(m.clientLeft+parseFloat(S.paddingLeft))*v.x,P=y.top+(m.clientTop+parseFloat(S.paddingTop))*v.y;l*=v.x,c*=v.y,u*=v.x,h*=v.y,l+=b,c+=P,g=pr(m),m=Fx(g)}}return zf({width:u,height:h,x:l,y:c})}function G1(t,e){const n=rm(t).scrollLeft;return e?e.left+n:pa(Vo(t)).left+n}function c3(t,e,n){n===void 0&&(n=!1);const r=t.getBoundingClientRect(),o=r.left+e.scrollLeft-(n?0:G1(t,r)),s=r.top+e.scrollTop;return{x:o,y:s}}function pne(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t;const s=o==="fixed",i=Vo(r),a=e?nm(e.floating):!1;if(r===i||a&&s)return n;let l={scrollLeft:0,scrollTop:0},c=Do(1);const u=Do(0),h=zo(r);if((h||!h&&!s)&&((ac(r)!=="body"||bd(i))&&(l=rm(r)),zo(r))){const f=pa(r);c=Pl(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const p=i&&!h&&!s?c3(i,l,!0):Do(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+p.x,y:n.y*c.y-l.scrollTop*c.y+u.y+p.y}}function fne(t){return Array.from(t.getClientRects())}function gne(t){const e=Vo(t),n=rm(t),r=t.ownerDocument.body,o=sr(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),s=sr(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let i=-n.scrollLeft+G1(t);const a=-n.scrollTop;return lo(r).direction==="rtl"&&(i+=sr(e.clientWidth,r.clientWidth)-o),{width:o,height:s,x:i,y:a}}function mne(t,e){const n=pr(t),r=Vo(t),o=n.visualViewport;let s=r.clientWidth,i=r.clientHeight,a=0,l=0;if(o){s=o.width,i=o.height;const c=K1();(!c||c&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}return{width:s,height:i,x:a,y:l}}function yne(t,e){const n=pa(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,s=zo(t)?Pl(t):Do(1),i=t.clientWidth*s.x,a=t.clientHeight*s.y,l=o*s.x,c=r*s.y;return{width:i,height:a,x:l,y:c}}function rE(t,e,n){let r;if(e==="viewport")r=mne(t,n);else if(e==="document")r=gne(Vo(t));else if(ao(e))r=yne(e,n);else{const o=l3(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return zf(r)}function u3(t,e){const n=vi(t);return n===e||!ao(n)||Rl(n)?!1:lo(n).position==="fixed"||u3(n,e)}function Sne(t,e){const n=e.get(t);if(n)return n;let r=Wu(t,[],!1).filter(a=>ao(a)&&ac(a)!=="body"),o=null;const s=lo(t).position==="fixed";let i=s?vi(t):t;for(;ao(i)&&!Rl(i);){const a=lo(i),l=H1(i);!l&&a.position==="fixed"&&(o=null),(s?!l&&!o:!l&&a.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||bd(i)&&!l&&u3(t,i))?r=r.filter(u=>u!==i):o=a,i=vi(i)}return e.set(t,r),r}function vne(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t;const i=[...n==="clippingAncestors"?nm(e)?[]:Sne(e,this._c):[].concat(n),r],a=i[0],l=i.reduce((c,u)=>{const h=rE(e,u,o);return c.top=sr(h.top,c.top),c.right=yi(h.right,c.right),c.bottom=yi(h.bottom,c.bottom),c.left=sr(h.left,c.left),c},rE(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function xne(t){const{width:e,height:n}=a3(t);return{width:e,height:n}}function wne(t,e,n){const r=zo(e),o=Vo(e),s=n==="fixed",i=pa(t,!0,s,e);let a={scrollLeft:0,scrollTop:0};const l=Do(0);if(r||!r&&!s)if((ac(e)!=="body"||bd(o))&&(a=rm(e)),r){const p=pa(e,!0,s,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&(l.x=G1(o));const c=o&&!r&&!s?c3(o,a):Do(0),u=i.left+a.scrollLeft-l.x-c.x,h=i.top+a.scrollTop-l.y-c.y;return{x:u,y:h,width:i.width,height:i.height}}function sS(t){return lo(t).position==="static"}function oE(t,e){if(!zo(t)||lo(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return Vo(t)===n&&(n=n.ownerDocument.body),n}function d3(t,e){const n=pr(t);if(nm(t))return n;if(!zo(t)){let o=vi(t);for(;o&&!Rl(o);){if(ao(o)&&!sS(o))return o;o=vi(o)}return n}let r=oE(t,e);for(;r&&cne(r)&&sS(r);)r=oE(r,e);return r&&Rl(r)&&sS(r)&&!H1(r)?n:r||une(t)||n}const bne=async function(t){const e=this.getOffsetParent||d3,n=this.getDimensions,r=await n(t.floating);return{reference:wne(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Pne(t){return lo(t).direction==="rtl"}const Cne={convertOffsetParentRelativeRectToViewportRelativeRect:pne,getDocumentElement:Vo,getClippingRect:vne,getOffsetParent:d3,getElementRects:bne,getClientRects:fne,getDimensions:xne,getScale:Pl,isElement:ao,isRTL:Pne};function _ne(t,e){let n=null,r;const o=Vo(t);function s(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function i(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),s();const{left:c,top:u,width:h,height:p}=t.getBoundingClientRect();if(a||e(),!h||!p)return;const f=bh(u),g=bh(o.clientWidth-(c+h)),m=bh(o.clientHeight-(u+p)),v=bh(c),S={rootMargin:-f+"px "+-g+"px "+-m+"px "+-v+"px",threshold:sr(0,yi(1,l))||1};let b=!0;function P(C){const _=C[0].intersectionRatio;if(_!==l){if(!b)return i();_?i(!1,_):r=setTimeout(()=>{i(!1,1e-7)},1e3)}b=!1}try{n=new IntersectionObserver(P,{...S,root:o.ownerDocument})}catch{n=new IntersectionObserver(P,S)}n.observe(t)}return i(!0),s}function Ine(t,e,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:s=!0,elementResize:i=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=W1(t),u=o||s?[...c?Wu(c):[],...Wu(e)]:[];u.forEach(y=>{o&&y.addEventListener("scroll",n,{passive:!0}),s&&y.addEventListener("resize",n)});const h=c&&a?_ne(c,n):null;let p=-1,f=null;i&&(f=new ResizeObserver(y=>{let[S]=y;S&&S.target===c&&f&&(f.unobserve(e),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=f)==null||b.observe(e)})),n()}),c&&!l&&f.observe(c),f.observe(e));let g,m=l?pa(t):null;l&&v();function v(){const y=pa(t);m&&(y.x!==m.x||y.y!==m.y||y.width!==m.width||y.height!==m.height)&&n(),m=y,g=requestAnimationFrame(v)}return n(),()=>{var y;u.forEach(S=>{o&&S.removeEventListener("scroll",n),s&&S.removeEventListener("resize",n)}),h==null||h(),(y=f)==null||y.disconnect(),f=null,l&&cancelAnimationFrame(g)}}const Ene=sne,kne=ine,Tne=nne,Mne=lne,Ane=rne,sE=tne,jne=ane,One=(t,e,n)=>{const r=new Map,o={platform:Cne,...n},s={...o.platform,_c:r};return ene(t,e,{...o,platform:s})};var hp=typeof document<"u"?w.useLayoutEffect:w.useEffect;function Bf(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,o;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!Bf(t[r],e[r]))return!1;return!0}if(o=Object.keys(t),n=o.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,o[r]))return!1;for(r=n;r--!==0;){const s=o[r];if(!(s==="_owner"&&t.$$typeof)&&!Bf(t[s],e[s]))return!1}return!0}return t!==t&&e!==e}function h3(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function iE(t,e){const n=h3(t);return Math.round(e*n)/n}function iS(t){const e=w.useRef(t);return hp(()=>{e.current=t}),e}function Dne(t){t===void 0&&(t={});const{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:s,floating:i}={},transform:a=!0,whileElementsMounted:l,open:c}=t,[u,h]=w.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[p,f]=w.useState(r);Bf(p,r)||f(r);const[g,m]=w.useState(null),[v,y]=w.useState(null),S=w.useCallback(R=>{R!==_.current&&(_.current=R,m(R))},[]),b=w.useCallback(R=>{R!==E.current&&(E.current=R,y(R))},[]),P=s||g,C=i||v,_=w.useRef(null),E=w.useRef(null),k=w.useRef(u),D=l!=null,T=iS(l),j=iS(o),$=iS(c),M=w.useCallback(()=>{if(!_.current||!E.current)return;const R={placement:e,strategy:n,middleware:p};j.current&&(R.platform=j.current),One(_.current,E.current,R).then(H=>{const Y={...H,isPositioned:$.current!==!1};O.current&&!Bf(k.current,Y)&&(k.current=Y,wa.flushSync(()=>{h(Y)}))})},[p,e,n,j,$]);hp(()=>{c===!1&&k.current.isPositioned&&(k.current.isPositioned=!1,h(R=>({...R,isPositioned:!1})))},[c]);const O=w.useRef(!1);hp(()=>(O.current=!0,()=>{O.current=!1}),[]),hp(()=>{if(P&&(_.current=P),C&&(E.current=C),P&&C){if(T.current)return T.current(P,C,M);M()}},[P,C,M,T,D]);const F=w.useMemo(()=>({reference:_,floating:E,setReference:S,setFloating:b}),[S,b]),B=w.useMemo(()=>({reference:P,floating:C}),[P,C]),K=w.useMemo(()=>{const R={position:n,left:0,top:0};if(!B.floating)return R;const H=iE(B.floating,u.x),Y=iE(B.floating,u.y);return a?{...R,transform:"translate("+H+"px, "+Y+"px)",...h3(B.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:Y}},[n,a,B.floating,u.x,u.y]);return w.useMemo(()=>({...u,update:M,refs:F,elements:B,floatingStyles:K}),[u,M,F,B,K])}const Rne=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){const{element:r,padding:o}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?sE({element:r.current,padding:o}).fn(n):{}:r?sE({element:r,padding:o}).fn(n):{}}}},Lne=(t,e)=>({...Ene(t),options:[t,e]}),$ne=(t,e)=>({...kne(t),options:[t,e]}),Fne=(t,e)=>({...jne(t),options:[t,e]}),Nne=(t,e)=>({...Tne(t),options:[t,e]}),zne=(t,e)=>({...Mne(t),options:[t,e]}),Bne=(t,e)=>({...Ane(t),options:[t,e]}),Une=(t,e)=>({...Rne(t),options:[t,e]});var Hne="Arrow",p3=w.forwardRef((t,e)=>{const{children:n,width:r=10,height:o=5,...s}=t;return d.jsx(Ae.svg,{...s,ref:e,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:d.jsx("polygon",{points:"0,0 30,0 15,10"})})});p3.displayName=Hne;var Kne=p3;function f3(t){const[e,n]=w.useState(void 0);return mi(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const s=o[0];let i,a;if("borderBoxSize"in s){const l=s.borderBoxSize,c=Array.isArray(l)?l[0]:l;i=c.inlineSize,a=c.blockSize}else i=t.offsetWidth,a=t.offsetHeight;n({width:i,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var V1="Popper",[g3,om]=Go(V1),[Wne,m3]=g3(V1),y3=t=>{const{__scopePopper:e,children:n}=t,[r,o]=w.useState(null);return d.jsx(Wne,{scope:e,anchor:r,onAnchorChange:o,children:n})};y3.displayName=V1;var S3="PopperAnchor",v3=w.forwardRef((t,e)=>{const{__scopePopper:n,virtualRef:r,...o}=t,s=m3(S3,n),i=w.useRef(null),a=Ze(e,i);return w.useEffect(()=>{s.onAnchorChange((r==null?void 0:r.current)||i.current)}),r?null:d.jsx(Ae.div,{...o,ref:a})});v3.displayName=S3;var Y1="PopperContent",[Gne,Vne]=g3(Y1),x3=w.forwardRef((t,e)=>{var Fe,ot,$e,lt,Ue,er;const{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:s="center",alignOffset:i=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:g,...m}=t,v=m3(Y1,n),[y,S]=w.useState(null),b=Ze(e,$t=>S($t)),[P,C]=w.useState(null),_=f3(P),E=(_==null?void 0:_.width)??0,k=(_==null?void 0:_.height)??0,D=r+(s!=="center"?"-"+s:""),T=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},j=Array.isArray(c)?c:[c],$=j.length>0,M={padding:T,boundary:j.filter(Xne),altBoundary:$},{refs:O,floatingStyles:F,placement:B,isPositioned:K,middlewareData:R}=Dne({strategy:"fixed",placement:D,whileElementsMounted:(...$t)=>Ine(...$t,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[Lne({mainAxis:o+k,alignmentAxis:i}),l&&$ne({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?Fne():void 0,...M}),l&&Nne({...M}),zne({...M,apply:({elements:$t,rects:On,availableWidth:vt,availableHeight:Jt})=>{const{width:Xo,height:cc}=On.reference,js=$t.floating.style;js.setProperty("--radix-popper-available-width",`${vt}px`),js.setProperty("--radix-popper-available-height",`${Jt}px`),js.setProperty("--radix-popper-anchor-width",`${Xo}px`),js.setProperty("--radix-popper-anchor-height",`${cc}px`)}}),P&&Une({element:P,padding:a}),qne({arrowWidth:E,arrowHeight:k}),p&&Bne({strategy:"referenceHidden",...M})]}),[H,Y]=P3(B),ee=Xt(g);mi(()=>{K&&(ee==null||ee())},[K,ee]);const he=(Fe=R.arrow)==null?void 0:Fe.x,ue=(ot=R.arrow)==null?void 0:ot.y,ke=(($e=R.arrow)==null?void 0:$e.centerOffset)!==0,[se,We]=w.useState();return mi(()=>{y&&We(window.getComputedStyle(y).zIndex)},[y]),d.jsx("div",{ref:O.setFloating,"data-radix-popper-content-wrapper":"",style:{...F,transform:K?F.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:se,"--radix-popper-transform-origin":[(lt=R.transformOrigin)==null?void 0:lt.x,(Ue=R.transformOrigin)==null?void 0:Ue.y].join(" "),...((er=R.hide)==null?void 0:er.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:d.jsx(Gne,{scope:n,placedSide:H,onArrowChange:C,arrowX:he,arrowY:ue,shouldHideArrow:ke,children:d.jsx(Ae.div,{"data-side":H,"data-align":Y,...m,ref:b,style:{...m.style,animation:K?void 0:"none"}})})})});x3.displayName=Y1;var w3="PopperArrow",Yne={top:"bottom",right:"left",bottom:"top",left:"right"},b3=w.forwardRef(function(e,n){const{__scopePopper:r,...o}=e,s=Vne(w3,r),i=Yne[s.placedSide];return d.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[i]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:d.jsx(Kne,{...o,ref:n,style:{...o.style,display:"block"}})})});b3.displayName=w3;function Xne(t){return t!==null}var qne=t=>({name:"transformOrigin",options:t,fn(e){var v,y,S;const{placement:n,rects:r,middlewareData:o}=e,i=((v=o.arrow)==null?void 0:v.centerOffset)!==0,a=i?0:t.arrowWidth,l=i?0:t.arrowHeight,[c,u]=P3(n),h={start:"0%",center:"50%",end:"100%"}[u],p=(((y=o.arrow)==null?void 0:y.x)??0)+a/2,f=(((S=o.arrow)==null?void 0:S.y)??0)+l/2;let g="",m="";return c==="bottom"?(g=i?h:`${p}px`,m=`${-l}px`):c==="top"?(g=i?h:`${p}px`,m=`${r.floating.height+l}px`):c==="right"?(g=`${-l}px`,m=i?h:`${f}px`):c==="left"&&(g=`${r.floating.width+l}px`,m=i?h:`${f}px`),{data:{x:g,y:m}}}});function P3(t){const[e,n="center"]=t.split("-");return[e,n]}var X1=y3,q1=v3,C3=x3,_3=b3,Zne="Portal",Pd=w.forwardRef((t,e)=>{var a;const{container:n,...r}=t,[o,s]=w.useState(!1);mi(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?u8.createPortal(d.jsx(Ae.div,{...r,ref:e}),i):null});Pd.displayName=Zne;function Qne(t,e){return w.useReducer((n,r)=>e[n][r]??n,t)}var ho=t=>{const{present:e,children:n}=t,r=Jne(e),o=typeof n=="function"?n({present:r.isPresent}):w.Children.only(n),s=Ze(r.ref,ere(o));return typeof n=="function"||r.isPresent?w.cloneElement(o,{ref:s}):null};ho.displayName="Presence";function Jne(t){const[e,n]=w.useState(),r=w.useRef({}),o=w.useRef(t),s=w.useRef("none"),i=t?"mounted":"unmounted",[a,l]=Qne(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return w.useEffect(()=>{const c=Ph(r.current);s.current=a==="mounted"?c:"none"},[a]),mi(()=>{const c=r.current,u=o.current;if(u!==t){const p=s.current,f=Ph(c);t?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),mi(()=>{if(e){let c;const u=e.ownerDocument.defaultView??window,h=f=>{const m=Ph(r.current).includes(f.animationName);if(f.target===e&&m&&(l("ANIMATION_END"),!o.current)){const v=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=v)})}},p=f=>{f.target===e&&(s.current=Ph(r.current))};return e.addEventListener("animationstart",p),e.addEventListener("animationcancel",h),e.addEventListener("animationend",h),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",p),e.removeEventListener("animationcancel",h),e.removeEventListener("animationend",h)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:w.useCallback(c=>{c&&(r.current=getComputedStyle(c)),n(c)},[])}}function Ph(t){return(t==null?void 0:t.animationName)||"none"}function ere(t){var r,o;let e=(r=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:r.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=(o=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:o.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}function Ai({prop:t,defaultProp:e,onChange:n=()=>{}}){const[r,o]=tre({defaultProp:e,onChange:n}),s=t!==void 0,i=s?t:r,a=Xt(n),l=w.useCallback(c=>{if(s){const h=typeof c=="function"?c(t):c;h!==t&&a(h)}else o(c)},[s,t,o,a]);return[i,l]}function tre({defaultProp:t,onChange:e}){const n=w.useState(t),[r]=n,o=w.useRef(r),s=Xt(e);return w.useEffect(()=>{o.current!==r&&(s(r),o.current=r)},[r,o,s]),n}var aS="rovingFocusGroup.onEntryFocus",nre={bubbles:!1,cancelable:!0},sm="RovingFocusGroup",[Nx,I3,rre]=Jg(sm),[ore,E3]=Go(sm,[rre]),[sre,ire]=ore(sm),k3=w.forwardRef((t,e)=>d.jsx(Nx.Provider,{scope:t.__scopeRovingFocusGroup,children:d.jsx(Nx.Slot,{scope:t.__scopeRovingFocusGroup,children:d.jsx(are,{...t,ref:e})})}));k3.displayName=sm;var are=w.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:s,currentTabStopId:i,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...h}=t,p=w.useRef(null),f=Ze(e,p),g=F1(s),[m=null,v]=Ai({prop:i,defaultProp:a,onChange:l}),[y,S]=w.useState(!1),b=Xt(c),P=I3(n),C=w.useRef(!1),[_,E]=w.useState(0);return w.useEffect(()=>{const k=p.current;if(k)return k.addEventListener(aS,b),()=>k.removeEventListener(aS,b)},[b]),d.jsx(sre,{scope:n,orientation:r,dir:g,loop:o,currentTabStopId:m,onItemFocus:w.useCallback(k=>v(k),[v]),onItemShiftTab:w.useCallback(()=>S(!0),[]),onFocusableItemAdd:w.useCallback(()=>E(k=>k+1),[]),onFocusableItemRemove:w.useCallback(()=>E(k=>k-1),[]),children:d.jsx(Ae.div,{tabIndex:y||_===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...t.style},onMouseDown:oe(t.onMouseDown,()=>{C.current=!0}),onFocus:oe(t.onFocus,k=>{const D=!C.current;if(k.target===k.currentTarget&&D&&!y){const T=new CustomEvent(aS,nre);if(k.currentTarget.dispatchEvent(T),!T.defaultPrevented){const j=P().filter(B=>B.focusable),$=j.find(B=>B.active),M=j.find(B=>B.id===m),F=[$,M,...j].filter(Boolean).map(B=>B.ref.current);A3(F,u)}}C.current=!1}),onBlur:oe(t.onBlur,()=>S(!1))})})}),T3="RovingFocusGroupItem",M3=w.forwardRef((t,e)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:s,...i}=t,a=ms(),l=s||a,c=ire(T3,n),u=c.currentTabStopId===l,h=I3(n),{onFocusableItemAdd:p,onFocusableItemRemove:f}=c;return w.useEffect(()=>{if(r)return p(),()=>f()},[r,p,f]),d.jsx(Nx.ItemSlot,{scope:n,id:l,focusable:r,active:o,children:d.jsx(Ae.span,{tabIndex:u?0:-1,"data-orientation":c.orientation,...i,ref:e,onMouseDown:oe(t.onMouseDown,g=>{r?c.onItemFocus(l):g.preventDefault()}),onFocus:oe(t.onFocus,()=>c.onItemFocus(l)),onKeyDown:oe(t.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){c.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const m=ure(g,c.orientation,c.dir);if(m!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let y=h().filter(S=>S.focusable).map(S=>S.ref.current);if(m==="last")y.reverse();else if(m==="prev"||m==="next"){m==="prev"&&y.reverse();const S=y.indexOf(g.currentTarget);y=c.loop?dre(y,S+1):y.slice(S+1)}setTimeout(()=>A3(y))}})})})});M3.displayName=T3;var lre={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cre(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function ure(t,e,n){const r=cre(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lre[r]}function A3(t,e=!1){const n=document.activeElement;for(const r of t)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function dre(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var hre=k3,pre=M3,fre=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},$a=new WeakMap,Ch=new WeakMap,_h={},lS=0,j3=function(t){return t&&(t.host||j3(t.parentNode))},gre=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=j3(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},mre=function(t,e,n,r){var o=gre(e,Array.isArray(t)?t:[t]);_h[n]||(_h[n]=new WeakMap);var s=_h[n],i=[],a=new Set,l=new Set(o),c=function(h){!h||a.has(h)||(a.add(h),c(h.parentNode))};o.forEach(c);var u=function(h){!h||l.has(h)||Array.prototype.forEach.call(h.children,function(p){if(a.has(p))u(p);else try{var f=p.getAttribute(r),g=f!==null&&f!=="false",m=($a.get(p)||0)+1,v=(s.get(p)||0)+1;$a.set(p,m),s.set(p,v),i.push(p),m===1&&g&&Ch.set(p,!0),v===1&&p.setAttribute(n,"true"),g||p.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",p,y)}})};return u(e),a.clear(),lS++,function(){i.forEach(function(h){var p=$a.get(h)-1,f=s.get(h)-1;$a.set(h,p),s.set(h,f),p||(Ch.has(h)||h.removeAttribute(r),Ch.delete(h)),f||h.removeAttribute(n)}),lS--,lS||($a=new WeakMap,$a=new WeakMap,Ch=new WeakMap,_h={})}},Z1=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),o=fre(t);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),mre(r,o,n,"aria-hidden")):function(){return null}},_o=function(){return _o=Object.assign||function(e){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},_o.apply(this,arguments)};function O3(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]]);return n}function yre(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}var pp="right-scroll-bar-position",fp="width-before-scroll-bar",Sre="with-scroll-bars-hidden",vre="--removed-body-scroll-bar-size";function cS(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}function xre(t,e){var n=w.useState(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=e,n.facade}var wre=typeof window<"u"?w.useLayoutEffect:w.useEffect,aE=new WeakMap;function bre(t,e){var n=xre(null,function(r){return t.forEach(function(o){return cS(o,r)})});return wre(function(){var r=aE.get(n);if(r){var o=new Set(r),s=new Set(t),i=n.current;o.forEach(function(a){s.has(a)||cS(a,null)}),s.forEach(function(a){o.has(a)||cS(a,i)})}aE.set(n,t)},[t]),n}function Pre(t){return t}function Cre(t,e){e===void 0&&(e=Pre);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(s){var i=e(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var u=i;i=[],u.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(u){i.push(u),c()},filter:function(u){return i=i.filter(u),n}}}};return o}function _re(t){t===void 0&&(t={});var e=Cre(null);return e.options=_o({async:!0,ssr:!1},t),e}var D3=function(t){var e=t.sideCar,n=O3(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return w.createElement(r,_o({},n))};D3.isSideCarExport=!0;function Ire(t,e){return t.useMedium(e),D3}var R3=_re(),uS=function(){},im=w.forwardRef(function(t,e){var n=w.useRef(null),r=w.useState({onScrollCapture:uS,onWheelCapture:uS,onTouchMoveCapture:uS}),o=r[0],s=r[1],i=t.forwardProps,a=t.children,l=t.className,c=t.removeScrollBar,u=t.enabled,h=t.shards,p=t.sideCar,f=t.noIsolation,g=t.inert,m=t.allowPinchZoom,v=t.as,y=v===void 0?"div":v,S=t.gapMode,b=O3(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noIsolation","inert","allowPinchZoom","as","gapMode"]),P=p,C=bre([n,e]),_=_o(_o({},b),o);return w.createElement(w.Fragment,null,u&&w.createElement(P,{sideCar:R3,removeScrollBar:c,shards:h,noIsolation:f,inert:g,setCallbacks:s,allowPinchZoom:!!m,lockRef:n,gapMode:S}),i?w.cloneElement(w.Children.only(a),_o(_o({},_),{ref:C})):w.createElement(y,_o({},_,{className:l,ref:C}),a))});im.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};im.classNames={fullWidth:fp,zeroRight:pp};var Ere=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function kre(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=Ere();return e&&t.setAttribute("nonce",e),t}function Tre(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function Mre(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var Are=function(){var t=0,e=null;return{add:function(n){t==0&&(e=kre())&&(Tre(e,n),Mre(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}},jre=function(){var t=Are();return function(e,n){w.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}},L3=function(){var t=jre(),e=function(n){var r=n.styles,o=n.dynamic;return t(r,o),null};return e},Ore={left:0,top:0,right:0,gap:0},dS=function(t){return parseInt(t||"",10)||0},Dre=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],o=e[t==="padding"?"paddingRight":"marginRight"];return[dS(n),dS(r),dS(o)]},Rre=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return Ore;var e=Dre(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}},Lre=L3(),Cl="data-scroll-locked",$re=function(t,e,n,r){var o=t.left,s=t.top,i=t.right,a=t.gap;return n===void 0&&(n="margin"),`
196
196
  .`.concat(Sre,` {
197
197
  overflow: hidden `).concat(r,`;
198
198
  padding-right: `).concat(a,"px ").concat(r,`;
@@ -236,7 +236,7 @@ To remove the watermark, please purchase a license at tldraw.dev.
236
236
 
237
237
  If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.
238
238
 
239
- For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return w.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},Nse="DialogDescriptionWarning",zse=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${p$(Nse).contentName}}.`;return w.useEffect(()=>{var s;const o=(s=t.current)==null?void 0:s.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},Bse=t$,Use=o$,Hse=s$,Kse=i$;const Bo=w.memo(function({small:e,invertIcon:n,icon:r,color:o,className:s,...i}){const a=hb(),l=a.icons[r]??a.icons["question-mark-circle"],c=w.useRef(null);return w.useLayoutEffect(()=>{l||console.error(`Icon not found: ${r}. Add it to the assetUrls.icons object.`),c!=null&&c.current&&(c.current.style.webkitMask=`url(${l}) center 100% / 100% no-repeat`)},[c,l,r]),r==="none"?d.jsx("div",{className:le("tlui-icon tlui-icon__placeholder",{"tlui-icon__small":e},s)}):d.jsx("div",{...i,ref:c,className:le("tlui-icon",{"tlui-icon__small":e},s),style:{color:o,mask:`url(${l}) center 100% / 100% no-repeat`,transform:n?"scale(-1, 1)":void 0}})});function be({icon:t,small:e,invertIcon:n}){return d.jsx(Bo,{className:"tlui-button__icon",icon:t,small:e,invertIcon:n})}function dm({className:t,children:e}){return d.jsx("div",{className:le("tlui-dialog__header",t),children:e})}function hm({className:t,children:e}){return d.jsx(l$,{dir:"ltr",className:le("tlui-dialog__header__title",t),children:e})}function pm(){return d.jsx("div",{className:"tlui-dialog__header__close",children:d.jsx(d$,{"data-testid":"dialog.close",dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon","aria-label":"Close",onTouchEnd:t=>t.target.click(),children:d.jsx(be,{small:!0,icon:"cross-2"})})})})}function Yu({className:t,children:e,style:n}){return d.jsx("div",{className:le("tlui-dialog__body",t),style:n,children:e})}function yb({className:t,children:e}){return d.jsx("div",{className:le("tlui-dialog__footer",t),children:e})}const fm=w.forwardRef(function({className:e,label:n,icon:r,iconLeft:o,autoSelect:s=!1,autoFocus:i=!1,defaultValue:a,placeholder:l,onComplete:c,onValueChange:u,onCancel:h,onFocus:p,onBlur:f,shouldManuallyMaintainScrollPositionWhenFocused:g=!1,children:m,value:v},y){const S=ki(),b=w.useRef(null);w.useImperativeHandle(y,()=>b.current);const P=Ee(),C=w.useRef(a??""),_=w.useRef(a??""),[E,k]=w.useState(!1),D=w.useCallback(M=>{k(!0);const O=M.currentTarget;_.current=O.value,S?S.timers.requestAnimationFrame(()=>{s&&O.select()}):kx.requestAnimationFrame("anon",()=>{s&&O.select()}),p==null||p()},[s,S,p]),T=w.useCallback(M=>{const O=M.currentTarget.value;_.current=O,u==null||u(O)},[u]),j=w.useCallback(M=>{switch(M.key){case"Enter":{M.currentTarget.blur(),_t(M),c==null||c(M.currentTarget.value);break}case"Escape":{M.currentTarget.value=C.current,h==null||h(M.currentTarget.value),M.currentTarget.blur(),_t(M);break}}},[c,h]),$=w.useCallback(M=>{k(!1);const O=M.currentTarget.value;f==null||f(O)},[f]);return w.useEffect(()=>{if(!Ge.isIos)return;const M=window.visualViewport;if(E&&g&&M){const O=()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})};return M.addEventListener("resize",O),M.addEventListener("scroll",O),S?S.timers.requestAnimationFrame(()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})}):kx.requestAnimationFrame("anon",()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})}),()=>{M.removeEventListener("resize",O),M.removeEventListener("scroll",O)}}},[E,S,g]),d.jsxs("div",{draggable:!1,className:"tlui-input__wrapper",children:[m,n&&d.jsx("label",{children:P(n)}),o&&d.jsx(Bo,{icon:o,className:"tlui-icon-left",small:!0}),d.jsx("input",{ref:b,className:le("tlui-input",e),type:"text",defaultValue:a,onKeyDownCapture:j,onChange:T,onFocus:D,onBlur:$,autoFocus:i,placeholder:l,value:v}),r&&d.jsx(Bo,{icon:r,small:!!n})]})});function pE(t){return gr.isValid(t)?{isValid:!0,hasProtocol:!0}:gr.isValid("https://"+t)?{isValid:!0,hasProtocol:!1}:{isValid:!1,hasProtocol:!1}}const Wse=qt(function({onClose:e}){const r=z().getOnlySelectedShape();return r&&"url"in r.props&&typeof r.props.url=="string"?d.jsx(Gse,{onClose:e,selectedShape:r}):null}),Gse=qt(function({onClose:e,selectedShape:n}){const r=z(),o=Ee(),s=w.useRef(null);w.useEffect(()=>{r.timers.requestAnimationFrame(()=>{var g;return(g=s.current)==null?void 0:g.focus()})},[r]);const i=w.useRef(n.props.url),[a,l]=w.useState(()=>{const g=pE(n.props.url),m=g.isValid===!0?g.hasProtocol?n.props.url:"https://"+n.props.url:"https://";return{actual:m,safe:m,valid:!0}}),c=w.useCallback(g=>{const m=g.replace(/https?:\/\/(https?:\/\/)/,(S,b)=>b),v=pE(m),y=v.isValid===!0?v.hasProtocol?m:"https://"+m:"https://";l({actual:m,safe:y,valid:v.isValid})},[]),u=w.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(r.updateShapes([{id:g.id,type:g.type,props:{url:""}}]),e())},[r,e]),h=w.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(g&&"url"in g.props&&g.props.url!==a.safe&&r.updateShapes([{id:g.id,type:g.type,props:{url:a.safe}}]),e())},[r,e,a]),p=w.useCallback(()=>{e()},[e]);if(!n)return e(),null;const f=i.current&&!a.valid;return d.jsxs(d.Fragment,{children:[d.jsxs(dm,{children:[d.jsx(hm,{children:o("edit-link-dialog.title")}),d.jsx(pm,{})]}),d.jsx(Yu,{children:d.jsxs("div",{className:"tlui-edit-link-dialog",children:[d.jsx(fm,{ref:s,className:"tlui-edit-link-dialog__input",label:"edit-link-dialog.url",autoFocus:!0,value:a.actual,onValueChange:c,onComplete:h,onCancel:p}),d.jsx("div",{children:a.valid?o("edit-link-dialog.detail"):o("edit-link-dialog.invalid-url")})]})}),d.jsxs(yb,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:p,onTouchEnd:p,children:d.jsx(Pt,{children:o("edit-link-dialog.cancel")})}),f?d.jsx(ce,{type:"danger",onTouchEnd:u,onClick:u,children:d.jsx(Pt,{children:o("edit-link-dialog.clear")})}):d.jsx(ce,{type:"primary",disabled:!a.valid,onTouchEnd:h,onClick:h,children:d.jsx(Pt,{children:o("edit-link-dialog.save")})})]})]})});var Vse={};const fE=/(^\/r\/[^/]+\/?$)/,Sb=[{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:t=>{const e=ge(t);if(e&&e.pathname.match(fE))return t},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(fE))return t}},{type:"figma",title:"Figma",hostnames:["figma.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{if(t.match(/https:\/\/([\w\.-]+\.)?figma.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/)&&!t.includes("figma.com/embed"))return`https://www.figma.com/embed?embed_host=share&url=${t}`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/?$/)){const n=e.searchParams.get("url");if(n)return n}}},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,overridePermissions:{"allow-presentation":!0},toEmbedUrl:t=>{if(t.includes("/maps/")){const e=t.match(/@(.*),(.*),(.*)z/);let n;if(e){const[,r,o,s]=e;n=`https://${new URL(t).host.replace("www.","")}/maps/embed/v1/view?key=${Vse.NEXT_PUBLIC_GC_API_KEY}&center=${r},${o}&zoom=${s}`}else n="";return n}},fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom"),[o,s]=e.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:t=>{const e=ge(t),n=e&&e.pathname.match(/\/v\/(.+)\/?/);if(n)return`https://www.val.town/embed/${n[1]}`},fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(n)return`https://www.val.town/v/${n[1]}`}},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/s\/([^/]+)\/?/);if(n)return`https://codesandbox.io/embed/${n[1]}`},fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://codesandbox.io/s/${n[1]}`}},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/embed/${s}`}},fromEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/pen/${s}`}}},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,toEmbedUrl:t=>{const e=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/embed/${o}`}},fromEmbedUrl:t=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/${o}`}}},{type:"youtube",title:"YouTube",hostnames:["*.youtube.com","youtube.com","youtu.be"],width:800,height:450,doesResize:!0,overridePermissions:{"allow-presentation":!0,"allow-popups-to-escape-sandbox":!0},isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(!e)return;const n=e.hostname.replace(/^www./,"");if(n==="youtu.be")return`https://www.youtube.com/embed/${e.pathname.split("/").filter(Boolean)[0]}`;if((n==="youtube.com"||n==="m.youtube.com")&&e.pathname.match(/^\/watch/))return`https://www.youtube.com/embed/${e.searchParams.get("v")}`},fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{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:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("cid");if(e!=null&&e.pathname.match(/\/calendar\/u\/0/)&&n){e.pathname="/calendar/embed";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("src",n),e.href}},fromEmbedUrl:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&n){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("cid",n),e.href}}},{type:"google_slides",title:"Google Slides",hostnames:["docs.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,overridePermissions:{"allow-popups-to-escape-sandbox":!0},toEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/pub\/?$/))){e.pathname=e.pathname.replace(/\/pub$/,"/embed");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}},fromEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0}},{type:"replit",title:"Replit",hostnames:["replit.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/))return`${t}?embed=true`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/map\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/(artist|album)\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="vimeo.com"&&e.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+e.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="player.vimeo.com"){const n=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(n)return"https://vimeo.com/"+n[1]}}},{type:"excalidraw",title:"Excalidraw",hostnames:["excalidraw.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t}},{type:"observable",title:"Observable",hostnames:["observablehq.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!1,backgroundColor:"#fff",toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}/embed${e.pathname}?cell=*`;if(e&&e.pathname.match(/^\/d\/([^/]+)\/?$/)){const n=e.pathname.replace(/^\/d/,"");return`${e.origin}/embed${n}?cell=*`}},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{type:"desmos",title:"Desmos",hostnames:["desmos.com"],width:700,height:450,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search===""&&e.hash==="")return`${t}?embed`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return t.replace("?embed","")}}],Yse={"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},Xse=Sb.map(t=>t.type);function qse(t){return Xse.includes(t)}function Zse(t){return"icon"in t}function f$(){return z().getShapeUtil("embed")}function vb(){const t=f$();return e=>t?t.getEmbedDefinition(e):void 0}function Qse(){const t=f$();return t?t.getEmbedDefinitions():[]}const g$=qt(function({onClose:e}){const n=z(),r=Ee(),o=hb(),[s,i]=w.useState(null),[a,l]=w.useState(""),[c,u]=w.useState(null),[h,p]=w.useState(!1),f=w.useRef(-1),g=Qse(),m=vb();return d.jsxs(d.Fragment,{children:[d.jsxs(dm,{children:[d.jsx(hm,{children:s?`${r("embed-dialog.title")} — ${s.title}`:r("embed-dialog.title")}),d.jsx(pm,{})]}),s?d.jsxs(d.Fragment,{children:[d.jsxs(Yu,{className:"tlui-embed-dialog__enter",children:[d.jsx(fm,{className:"tlui-embed-dialog__input",label:"embed-dialog.url",placeholder:"https://example.com",autoFocus:!0,onValueChange:v=>{l(v);const y=m(v);u(y&&y.definition.type===s.type?y:null),p(!1),clearTimeout(f.current),f.current=n.timers.setTimeout(()=>p(!y),320)}}),a===""?d.jsxs("div",{className:"tlui-embed-dialog__instruction",children:[d.jsx("span",{children:r("embed-dialog.instruction")})," ",s.instructionLink&&d.jsxs("a",{target:"_blank",rel:"noopener noreferrer",href:s.instructionLink,className:"tlui-embed-dialog__instruction__link",children:["Learn more.",d.jsx(Bo,{icon:"external-link",small:!0})]})]}):d.jsx("div",{className:"tlui-embed-dialog__warning",children:h?r("embed-dialog.invalid-url"):" "})]}),d.jsxs(yb,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:()=>{i(null),u(null),l("")},children:d.jsx(Pt,{children:r("embed-dialog.back")})}),d.jsx("div",{className:"tlui-embed__spacer"}),d.jsx(ce,{type:"normal",onClick:e,children:d.jsx(Pt,{children:r("embed-dialog.cancel")})}),d.jsx(ce,{type:"primary",disabled:!c,onClick:()=>{c&&(n.putExternalContent({type:"embed",url:a,point:n.getViewportPageBounds().center,embed:c.definition}),e())},children:d.jsx(Pt,{children:r("embed-dialog.create")})})]})]}):d.jsx(d.Fragment,{children:d.jsx(Yu,{className:"tlui-embed-dialog__list",children:g.map(v=>{const y=qse(v.type)?o.embedIcons[v.type]:Zse(v)?v.icon:void 0;return d.jsxs(ce,{type:"menu",onClick:()=>i(v),children:[d.jsx(Pt,{children:v.title}),y&&d.jsx("div",{className:"tlui-embed-dialog__item__image",style:{backgroundImage:`url(${y})`}})]},v.type)})})})]})});async function Jse(t,e,n){const r=me(e.map(a=>{const l=t.getShape(a);if(!(!l||t.getShapeUtil(l.type).toSvg===void 0))return l}));if(r.length===0)return;if(r.length===1){const a=r[0];if(!a||t.isShapeOfType(a,"image"))return}const o=[];if(n!==void 0){const a=r.map(l=>({shape:l,bounds:t.getShapeMaskedPageBounds(l).clone().expandBy(n)}));for(let l=0;l<a.length;l++){const c=a[l];if(l===0){o[0]={shapes:[c.shape],bounds:c.bounds};continue}let u=!1;for(const h of o)if(h.bounds.includes(c.bounds)){h.shapes.push(c.shape),h.bounds.expand(c.bounds),u=!0;break}u||o.push({shapes:[c.shape],bounds:c.bounds})}}else{const a=Z.Common(r.map(l=>t.getShapeMaskedPageBounds(l)));o.push({shapes:r,bounds:a})}const s=t.options.flattenImageBoundsPadding;for(const a of o){n!==void 0&&a.bounds.expandBy(-n);const l=await t.getSvgString(a.shapes,{padding:s});if(!(l!=null&&l.svg))continue;const c=new Blob([l.svg],{type:"image/svg+xml"}),u=await t.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});u&&(a.asset=u)}const i=[];return Oo(()=>{for(const a of o){const{asset:l,bounds:c,shapes:u}=a;if(!l)continue;const h=t.findCommonAncestor(u)??t.getCurrentPageId();if(!h)continue;let p="a1";for(const y of u)if(y.parentId===h){y.index>p&&(p=y.index);break}let f,g,m;if(Fn(h)){const y=t.getShape(h);if(!y)continue;const S=t.getPointInShapeSpace(y,{x:c.x,y:c.y});m=t.getShapePageTransform(h).rotation(),S.sub(new x(s,s).rot(-m)),f=S.x,g=S.y}else f=c.x-s,g=c.y-s,m=0;t.deleteShapes(u),t.createAssets([{...l,id:l.id}]);const v=Ke();t.createShape({id:v,type:"image",index:p,parentId:h,x:f,y:g,rotation:-m,props:{assetId:l.id,w:c.w+s*2,h:c.h+s*2}}),i.push(v)}}),i}function gm(){const t=ki();return(t==null?void 0:t.store.props.collaboration)!==void 0}function eie(){const t=ki();return U("sync status",()=>{var e;return(e=t==null?void 0:t.store.props.collaboration)!=null&&e.status?t.store.props.collaboration.status.get():null},[t])}const hS=[0,389,436,476,580,640,840,1023];var St=(t=>(t[t.ZERO=0]="ZERO",t[t.MOBILE_XXS=1]="MOBILE_XXS",t[t.MOBILE_XS=2]="MOBILE_XS",t[t.MOBILE_SM=3]="MOBILE_SM",t[t.MOBILE=4]="MOBILE",t[t.TABLET_SM=5]="TABLET_SM",t[t.TABLET=6]="TABLET",t[t.DESKTOP=7]="DESKTOP",t))(St||{});const m$=Te.createContext(null);function tie({forceMobile:t=!1,children:e}){const n=ki(),r=U("breakpoint",()=>{const{width:o}=(n==null?void 0:n.getViewportScreenBounds())??{width:window.innerWidth},s=t?St.MOBILE_SM:hS.length-1;for(let i=0;i<s;i++)if(o>hS[i]&&o<=hS[i+1])return i;return s},[n]);return d.jsx(m$.Provider,{value:r,children:e})}function An(){const t=w.useContext(m$);if(t===null)throw new Error("useBreakpoint must be used inside of the <BreakpointProvider /> component");return t}const y$=w.createContext(null);function nie({context:t,children:e}){const n=Qt(),r=qw("dialogs",[]),o=w.useMemo(()=>({dialogs:r,addDialog(s){const i=s.id??ze();return r.update(a=>[...a.filter(l=>l.id!==s.id),{...s,id:i}]),n("open-menu",{source:"dialog",id:i}),Vr.addOpenMenu(i,t),i},removeDialog(s){var a;const i=r.get().find(l=>l.id===s);return i&&((a=i.onClose)==null||a.call(i),n("close-menu",{source:"dialog",id:s}),Vr.deleteOpenMenu(s,t),r.update(l=>l.filter(c=>c!==i))),s},clearDialogs(){const s=r.get();s.length!==0&&(s.forEach(i=>{var a;(a=i.onClose)==null||a.call(i),n("close-menu",{source:"dialog",id:i.id}),Vr.deleteOpenMenu(i.id,t)}),r.set([]))}}),[n,r,t]);return d.jsx(y$.Provider,{value:o,children:e})}function Ed(){const t=w.useContext(y$);if(!t)throw new Error("useDialogs must be used within a DialogsProvider");return t}var rie="VisuallyHidden",xb=w.forwardRef((t,e)=>d.jsx(Ae.span,{...t,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...t.style}}));xb.displayName=rie;var wb="ToastProvider",[bb,oie,sie]=Jg("Toast"),[S$,fge]=Go("Toast",[sie]),[iie,mm]=S$(wb),v$=t=>{const{__scopeToast:e,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:s=50,children:i}=t,[a,l]=w.useState(null),[c,u]=w.useState(0),h=w.useRef(!1),p=w.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${wb}\`. Expected non-empty \`string\`.`),d.jsx(bb.Provider,{scope:e,children:d.jsx(iie,{scope:e,label:n,duration:r,swipeDirection:o,swipeThreshold:s,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:w.useCallback(()=>u(f=>f+1),[]),onToastRemove:w.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:i})})};v$.displayName=wb;var x$="ToastViewport",aie=["F8"],Hx="toast.viewportPause",Kx="toast.viewportResume",w$=w.forwardRef((t,e)=>{const{__scopeToast:n,hotkey:r=aie,label:o="Notifications ({hotkey})",...s}=t,i=mm(x$,n),a=oie(n),l=w.useRef(null),c=w.useRef(null),u=w.useRef(null),h=w.useRef(null),p=Ze(e,h,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=i.toastCount>0;w.useEffect(()=>{const v=y=>{var b;r.length!==0&&r.every(P=>y[P]||y.code===P)&&((b=h.current)==null||b.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),w.useEffect(()=>{const v=l.current,y=h.current;if(g&&v&&y){const S=()=>{if(!i.isClosePausedRef.current){const _=new CustomEvent(Hx);y.dispatchEvent(_),i.isClosePausedRef.current=!0}},b=()=>{if(i.isClosePausedRef.current){const _=new CustomEvent(Kx);y.dispatchEvent(_),i.isClosePausedRef.current=!1}},P=_=>{!v.contains(_.relatedTarget)&&b()},C=()=>{v.contains(document.activeElement)||b()};return v.addEventListener("focusin",S),v.addEventListener("focusout",P),v.addEventListener("pointermove",S),v.addEventListener("pointerleave",C),window.addEventListener("blur",S),window.addEventListener("focus",b),()=>{v.removeEventListener("focusin",S),v.removeEventListener("focusout",P),v.removeEventListener("pointermove",S),v.removeEventListener("pointerleave",C),window.removeEventListener("blur",S),window.removeEventListener("focus",b)}}},[g,i.isClosePausedRef]);const m=w.useCallback(({tabbingDirection:v})=>{const S=a().map(b=>{const P=b.ref.current,C=[P,...xie(P)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?S.reverse():S).flat()},[a]);return w.useEffect(()=>{const v=h.current;if(v){const y=S=>{var C,_,E;const b=S.altKey||S.ctrlKey||S.metaKey;if(S.key==="Tab"&&!b){const k=document.activeElement,D=S.shiftKey;if(S.target===v&&D){(C=c.current)==null||C.focus();return}const $=m({tabbingDirection:D?"backwards":"forwards"}),M=$.findIndex(O=>O===k);pS($.slice(M+1))?S.preventDefault():D?(_=c.current)==null||_.focus():(E=u.current)==null||E.focus()}};return v.addEventListener("keydown",y),()=>v.removeEventListener("keydown",y)}},[a,m]),d.jsxs(Lte,{ref:l,role:"region","aria-label":o.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&d.jsx(Wx,{ref:c,onFocusFromOutsideViewport:()=>{const v=m({tabbingDirection:"forwards"});pS(v)}}),d.jsx(bb.Slot,{scope:n,children:d.jsx(Ae.ol,{tabIndex:-1,...s,ref:p})}),g&&d.jsx(Wx,{ref:u,onFocusFromOutsideViewport:()=>{const v=m({tabbingDirection:"backwards"});pS(v)}})]})});w$.displayName=x$;var b$="ToastFocusProxy",Wx=w.forwardRef((t,e)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=t,s=mm(b$,n);return d.jsx(xb,{"aria-hidden":!0,tabIndex:0,...o,ref:e,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=s.viewport)!=null&&c.contains(a))&&r()}})});Wx.displayName=b$;var ym="Toast",lie="toast.swipeStart",cie="toast.swipeMove",uie="toast.swipeCancel",die="toast.swipeEnd",P$=w.forwardRef((t,e)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:s,...i}=t,[a=!0,l]=Ai({prop:r,defaultProp:o,onChange:s});return d.jsx(ho,{present:n||a,children:d.jsx(fie,{open:a,...i,ref:e,onClose:()=>l(!1),onPause:Xt(t.onPause),onResume:Xt(t.onResume),onSwipeStart:oe(t.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:oe(t.onSwipeMove,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:oe(t.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:oe(t.onSwipeEnd,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),l(!1)})})})});P$.displayName=ym;var[hie,pie]=S$(ym,{onClose(){}}),fie=w.forwardRef((t,e)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:s,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...g}=t,m=mm(ym,n),[v,y]=w.useState(null),S=Ze(e,O=>y(O)),b=w.useRef(null),P=w.useRef(null),C=o||m.duration,_=w.useRef(0),E=w.useRef(C),k=w.useRef(0),{onToastAdd:D,onToastRemove:T}=m,j=Xt(()=>{var F;(v==null?void 0:v.contains(document.activeElement))&&((F=m.viewport)==null||F.focus()),i()}),$=w.useCallback(O=>{!O||O===1/0||(window.clearTimeout(k.current),_.current=new Date().getTime(),k.current=window.setTimeout(j,O))},[j]);w.useEffect(()=>{const O=m.viewport;if(O){const F=()=>{$(E.current),c==null||c()},B=()=>{const K=new Date().getTime()-_.current;E.current=E.current-K,window.clearTimeout(k.current),l==null||l()};return O.addEventListener(Hx,B),O.addEventListener(Kx,F),()=>{O.removeEventListener(Hx,B),O.removeEventListener(Kx,F)}}},[m.viewport,C,l,c,$]),w.useEffect(()=>{s&&!m.isClosePausedRef.current&&$(C)},[s,C,m.isClosePausedRef,$]),w.useEffect(()=>(D(),()=>T()),[D,T]);const M=w.useMemo(()=>v?M$(v):null,[v]);return m.viewport?d.jsxs(d.Fragment,{children:[M&&d.jsx(gie,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:M}),d.jsx(hie,{scope:n,onClose:j,children:wa.createPortal(d.jsx(bb.ItemSlot,{scope:n,children:d.jsx(Rte,{asChild:!0,onEscapeKeyDown:oe(a,()=>{m.isFocusedToastEscapeKeyDownRef.current||j(),m.isFocusedToastEscapeKeyDownRef.current=!1}),children:d.jsx(Ae.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":m.swipeDirection,...g,ref:S,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:oe(t.onKeyDown,O=>{O.key==="Escape"&&(a==null||a(O.nativeEvent),O.nativeEvent.defaultPrevented||(m.isFocusedToastEscapeKeyDownRef.current=!0,j()))}),onPointerDown:oe(t.onPointerDown,O=>{O.button===0&&(b.current={x:O.clientX,y:O.clientY})}),onPointerMove:oe(t.onPointerMove,O=>{if(!b.current)return;const F=O.clientX-b.current.x,B=O.clientY-b.current.y,K=!!P.current,R=["left","right"].includes(m.swipeDirection),H=["left","up"].includes(m.swipeDirection)?Math.min:Math.max,Y=R?H(0,F):0,ee=R?0:H(0,B),he=O.pointerType==="touch"?10:2,ue={x:Y,y:ee},ke={originalEvent:O,delta:ue};K?(P.current=ue,Th(cie,h,ke,{discrete:!1})):gE(ue,m.swipeDirection,he)?(P.current=ue,Th(lie,u,ke,{discrete:!1}),O.target.setPointerCapture(O.pointerId)):(Math.abs(F)>he||Math.abs(B)>he)&&(b.current=null)}),onPointerUp:oe(t.onPointerUp,O=>{const F=P.current,B=O.target;if(B.hasPointerCapture(O.pointerId)&&B.releasePointerCapture(O.pointerId),P.current=null,b.current=null,F){const K=O.currentTarget,R={originalEvent:O,delta:F};gE(F,m.swipeDirection,m.swipeThreshold)?Th(die,f,R,{discrete:!0}):Th(uie,p,R,{discrete:!0}),K.addEventListener("click",H=>H.preventDefault(),{once:!0})}})})})}),m.viewport)})]}):null}),gie=t=>{const{__scopeToast:e,children:n,...r}=t,o=mm(ym,e),[s,i]=w.useState(!1),[a,l]=w.useState(!1);return Sie(()=>i(!0)),w.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:d.jsx(Pd,{asChild:!0,children:d.jsx(xb,{...r,children:s&&d.jsxs(d.Fragment,{children:[o.label," ",n]})})})},mie="ToastTitle",C$=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return d.jsx(Ae.div,{...r,ref:e})});C$.displayName=mie;var yie="ToastDescription",_$=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return d.jsx(Ae.div,{...r,ref:e})});_$.displayName=yie;var I$="ToastAction",E$=w.forwardRef((t,e)=>{const{altText:n,...r}=t;return n.trim()?d.jsx(T$,{altText:n,asChild:!0,children:d.jsx(Pb,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${I$}\`. Expected non-empty \`string\`.`),null)});E$.displayName=I$;var k$="ToastClose",Pb=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t,o=pie(k$,n);return d.jsx(T$,{asChild:!0,children:d.jsx(Ae.button,{type:"button",...r,ref:e,onClick:oe(t.onClick,o.onClose)})})});Pb.displayName=k$;var T$=w.forwardRef((t,e)=>{const{__scopeToast:n,altText:r,...o}=t;return d.jsx(Ae.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...o,ref:e})});function M$(t){const e=[];return Array.from(t.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),vie(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",s=r.dataset.radixToastAnnounceExclude==="";if(!o)if(s){const i=r.dataset.radixToastAnnounceAlt;i&&e.push(i)}else e.push(...M$(r))}}),e}function Th(t,e,n,{discrete:r}){const o=n.originalEvent.currentTarget,s=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?$1(o,s):o.dispatchEvent(s)}var gE=(t,e,n=0)=>{const r=Math.abs(t.x),o=Math.abs(t.y),s=r>o;return e==="left"||e==="right"?s&&r>n:!s&&o>n};function Sie(t=()=>{}){const e=Xt(t);mi(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[e])}function vie(t){return t.nodeType===t.ELEMENT_NODE}function xie(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function pS(t){const e=document.activeElement;return t.some(n=>n===e?!0:(n.focus(),document.activeElement!==e))}var wie=P$,bie=C$,Pie=_$,Cie=E$,mE=Pb;const A$=w.createContext(null);function _ie({children:t}){const e=qw("toasts",[]),n=w.useMemo(()=>({toasts:e,addToast(r){const o=r.id??ze();return e.update(s=>[...s.filter(i=>i.id!==r.id),{...r,id:o}]),o},removeToast(r){return e.update(o=>o.filter(s=>s.id!==r)),r},clearToasts(){e.set([])}}),[e]);return d.jsx(v$,{children:d.jsx(A$.Provider,{value:n,children:t})})}function Ts(){const t=w.useContext(A$);if(!t)throw new Error("useToasts must be used within a ToastsProvider");return t}var Cb={exports:{}};Cb.exports;(function(t){var e=function(){var n=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",s={};function i(l,c){if(!s[l]){s[l]={};for(var u=0;u<l.length;u++)s[l][l.charAt(u)]=u}return s[l][c]}var a={compressToBase64:function(l){if(l==null)return"";var c=a._compress(l,6,function(u){return r.charAt(u)});switch(c.length%4){default:case 0:return c;case 1:return c+"===";case 2:return c+"==";case 3:return c+"="}},decompressFromBase64:function(l){return l==null?"":l==""?null:a._decompress(l.length,32,function(c){return i(r,l.charAt(c))})},compressToUTF16:function(l){return l==null?"":a._compress(l,15,function(c){return n(c+32)})+" "},decompressFromUTF16:function(l){return l==null?"":l==""?null:a._decompress(l.length,16384,function(c){return l.charCodeAt(c)-32})},compressToUint8Array:function(l){for(var c=a.compress(l),u=new Uint8Array(c.length*2),h=0,p=c.length;h<p;h++){var f=c.charCodeAt(h);u[h*2]=f>>>8,u[h*2+1]=f%256}return u},decompressFromUint8Array:function(l){if(l==null)return a.decompress(l);for(var c=new Array(l.length/2),u=0,h=c.length;u<h;u++)c[u]=l[u*2]*256+l[u*2+1];var p=[];return c.forEach(function(f){p.push(n(f))}),a.decompress(p.join(""))},compressToEncodedURIComponent:function(l){return l==null?"":a._compress(l,6,function(c){return o.charAt(c)})},decompressFromEncodedURIComponent:function(l){return l==null?"":l==""?null:(l=l.replace(/ /g,"+"),a._decompress(l.length,32,function(c){return i(o,l.charAt(c))}))},compress:function(l){return a._compress(l,16,function(c){return n(c)})},_compress:function(l,c,u){if(l==null)return"";var h,p,f={},g={},m="",v="",y="",S=2,b=3,P=2,C=[],_=0,E=0,k;for(k=0;k<l.length;k+=1)if(m=l.charAt(k),Object.prototype.hasOwnProperty.call(f,m)||(f[m]=b++,g[m]=!0),v=y+m,Object.prototype.hasOwnProperty.call(f,v))y=v;else{if(Object.prototype.hasOwnProperty.call(g,y)){if(y.charCodeAt(0)<256){for(h=0;h<P;h++)_=_<<1,E==c-1?(E=0,C.push(u(_)),_=0):E++;for(p=y.charCodeAt(0),h=0;h<8;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}else{for(p=1,h=0;h<P;h++)_=_<<1|p,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=0;for(p=y.charCodeAt(0),h=0;h<16;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}S--,S==0&&(S=Math.pow(2,P),P++),delete g[y]}else for(p=f[y],h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;S--,S==0&&(S=Math.pow(2,P),P++),f[v]=b++,y=String(m)}if(y!==""){if(Object.prototype.hasOwnProperty.call(g,y)){if(y.charCodeAt(0)<256){for(h=0;h<P;h++)_=_<<1,E==c-1?(E=0,C.push(u(_)),_=0):E++;for(p=y.charCodeAt(0),h=0;h<8;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}else{for(p=1,h=0;h<P;h++)_=_<<1|p,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=0;for(p=y.charCodeAt(0),h=0;h<16;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}S--,S==0&&(S=Math.pow(2,P),P++),delete g[y]}else for(p=f[y],h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;S--,S==0&&(S=Math.pow(2,P),P++)}for(p=2,h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;for(;;)if(_=_<<1,E==c-1){C.push(u(_));break}else E++;return C.join("")},decompress:function(l){return l==null?"":l==""?null:a._decompress(l.length,32768,function(c){return l.charCodeAt(c)})},_decompress:function(l,c,u){var h=[],p=4,f=4,g=3,m="",v=[],y,S,b,P,C,_,E,k={val:u(0),position:c,index:1};for(y=0;y<3;y+=1)h[y]=y;for(b=0,C=Math.pow(2,2),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;switch(b){case 0:for(b=0,C=Math.pow(2,8),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;E=n(b);break;case 1:for(b=0,C=Math.pow(2,16),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;E=n(b);break;case 2:return""}for(h[3]=E,S=E,v.push(E);;){if(k.index>l)return"";for(b=0,C=Math.pow(2,g),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;switch(E=b){case 0:for(b=0,C=Math.pow(2,8),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;h[f++]=n(b),E=f-1,p--;break;case 1:for(b=0,C=Math.pow(2,16),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;h[f++]=n(b),E=f-1,p--;break;case 2:return v.join("")}if(p==0&&(p=Math.pow(2,g),g++),h[E])m=h[E];else if(E===f)m=S+S.charAt(0);else return null;v.push(m),h[f++]=S+m.charAt(0),p--,S=m,p==0&&(p=Math.pow(2,g),g++)}}};return a}();t!=null?t.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(Cb);var Iie=Cb.exports;const j$=xi(Iie),_b="web image/vnd.tldraw+png",Eie={"image/png":_b},kie={[_b]:"image/png"};function Tie(t){return hn(Eie,t)??null}function Mie(t){return hn(kie,t)??t}function Aie(t){return typeof ClipboardItem<"u"&&"supports"in ClipboardItem&&ClipboardItem.supports(t)}function jie(t){const e=Object.entries(t);for(const[n,r]of e)r.catch(o=>console.error(o));return navigator.clipboard.write([new ClipboardItem(t)]).catch(n=>(console.error(n),Promise.all(e.map(async([r,o])=>[r,await o])).then(r=>{const o=ww(r);return navigator.clipboard.write([new ClipboardItem(o)])})))}async function Oie(t,e,n){var y,S,b;const{elements:r,files:o}=e,s={shapes:[],bindings:[],rootShapeIds:[],assets:[],schema:t.store.schema.serialize()},i=new Map,a=new Map,l=t.getCurrentPageId(),c=new Map,u=[],h=new Set;r.forEach(P=>{if(c.set(P.id,Ke()),P.boundElements!==null)for(const C of P.boundElements)C.type==="text"&&h.add(C.id)});let p=ZT;for(const P of r){if(h.has(P.id))continue;const C=c.get(P.id),_={id:C,typeName:"shape",parentId:l,index:p,x:P.x,y:P.y,rotation:0,isLocked:P.locked,opacity:Die(P.opacity),meta:{}};switch(P.angle!==0&&a.set(C,P.angle),P.groupIds&&P.groupIds.length>0?i.has(P.groupIds[0])?(y=i.get(P.groupIds[0]))==null||y.push(C):i.set(P.groupIds[0],[C]):u.push(C),P.type){case"rectangle":case"ellipse":case"diamond":{let E="",k="middle";if(P.boundElements!==null){for(const T of P.boundElements)if(T.type==="text"){const j=r.find($=>$.id===T.id);j&&(E=j.text,k=Bie[j.textAlign])}}const D=P.backgroundColor==="transparent"?P.strokeColor:P.backgroundColor;s.shapes.push({..._,type:"geo",props:{geo:P.type,url:P.link??"",w:P.width,h:P.height,size:Mh[P.strokeWidth]??"draw",color:jc[D]??"black",text:E,align:k,dash:Ah(P),fill:Kie(P)}});break}case"freedraw":{s.shapes.push({..._,type:"draw",props:{dash:Ah(P),size:Mh[P.strokeWidth],color:jc[P.strokeColor]??"black",segments:[{type:"free",points:P.points.map(([E,k,D=.5])=>({x:E,y:k,z:D}))}]}});break}case"line":{if(P.points.slice().length<2)break;const k=Fu(P.points.length);s.shapes.push({..._,type:"line",props:{dash:Ah(P),size:Mh[P.strokeWidth],color:jc[P.strokeColor]??"black",spline:P.roundness?"cubic":"line",points:{...Object.fromEntries(P.points.map(([D,T],j)=>{const $=k[j];return[$,{id:$,index:$,x:D,y:T}]}))}}});break}case"arrow":{let E="";if(P.boundElements!==null){for(const $ of P.boundElements)if($.type==="text"){const M=r.find(O=>O.id===$.id);M&&(E=M.text)}}const k=P.points[0],D=P.points[P.points.length-1],T=c.get((S=P.startBinding)==null?void 0:S.elementId),j=c.get((b=P.endBinding)==null?void 0:b.elementId);s.shapes.push({..._,type:"arrow",props:{text:E,bend:Hie(P,k,D),dash:Ah(P),size:Mh[P.strokeWidth]??"m",color:jc[P.strokeColor]??"black",start:{x:k[0],y:k[1]},end:{x:D[0],y:D[1]},arrowheadEnd:yE[P.endArrowhead]??"none",arrowheadStart:yE[P.startArrowhead]??"none"}}),T&&s.bindings.push({id:Qi(),typeName:"binding",type:"arrow",fromId:C,toId:T,props:{terminal:"start",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}}),j&&s.bindings.push({id:Qi(),typeName:"binding",type:"arrow",fromId:C,toId:j,props:{terminal:"end",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}});break}case"text":{const{size:E,scale:k}=Lie(P.fontSize);s.shapes.push({..._,type:"text",props:{size:E,scale:k,font:$ie[P.fontFamily]??"draw",color:jc[P.strokeColor]??"black",text:P.text,textAlign:Uie[P.textAlign]}});break}case"image":{const E=o[P.fileId];if(!E)break;const k=Vs.createId();s.assets.push({id:k,typeName:"asset",type:"image",props:{w:P.width,h:P.height,fileSize:E.size,name:P.id??"Untitled",isAnimated:!1,mimeType:E.mimeType,src:E.dataURL},meta:{}}),s.shapes.push({..._,type:"image",props:{w:P.width,h:P.height,assetId:k}})}}p=Io(p)}const f=n??(t.inputs.shiftKey?t.inputs.currentPagePoint:void 0);t.markHistoryStoppingPoint("paste"),t.putContentOntoCurrentPage(s,{point:f,select:!1,preserveIds:!0});for(const P of i.values())if(P.length>1){t.groupShapes(P);const C=t.getShape(P[0]);C!=null&&C.parentId&&Fn(C.parentId)&&u.push(C.parentId)}for(const[P,C]of a)t.select(P),t.rotateShapesBy([P],C);const g=me(u.map(P=>t.getShape(P))),m=Z.Common(g.map(P=>t.getShapePageBounds(P))),v=t.getViewportPageBounds().center;t.updateShapes(g.map(P=>{const C={x:(P.x??0)-(m.x+m.w/2),y:(P.y??0)-(m.y+m.h/2)};return{id:P.id,type:P.type,x:v.x+C.x,y:v.y+C.y}})),t.setSelectedShapes(u)}const Die=t=>{const e=t/100;return e<.2?.1:e<.4?.25:e<.6?.5:e<.8?.75:1},Mh={1:"s",2:"m",3:"l",4:"xl"},Rie={16:"s",20:"m",28:"l",36:"xl"};function Lie(t){const e=Rie[t];return e?{size:e,scale:1}:t<16?{size:"s",scale:t/16}:t>36?{size:"xl",scale:t/36}:{size:"m",scale:1}}const $ie={1:"draw",2:"sans",3:"mono"},Fie={gray:["#f8f9fa","#e9ecef","#ced4da","#868e96","#343a40"],red:["#fff5f5","#ffc9c9","#ff8787","#fa5252","#e03131"],pink:["#fff0f6","#fcc2d7","#f783ac","#e64980","#c2255c"],grape:["#f8f0fc","#eebefa","#da77f2","#be4bdb","#9c36b5"],violet:["#f3f0ff","#d0bfff","#9775fa","#7950f2","#6741d9"],indigo:["#edf2ff","#bac8ff","#748ffc","#4c6ef5","#3b5bdb"],blue:["#e7f5ff","#a5d8ff","#4dabf7","#228be6","#1971c2"],cyan:["#e3fafc","#99e9f2","#3bc9db","#15aabf","#0c8599"],teal:["#e6fcf5","#96f2d7","#38d9a9","#12b886","#099268"],green:["#ebfbee","#b2f2bb","#69db7c","#40c057","#2f9e44"],lime:["#f4fce3","#d8f5a2","#a9e34b","#82c91e","#66a80f"],yellow:["#fff9db","#ffec99","#ffd43b","#fab005","#f08c00"],orange:["#fff4e6","#ffd8a8","#ffa94d","#fd7e14","#e8590c"]};function vo(t,e,n){const r=[0,1,2,3,4].map(o=>Fie[t][o]);return Object.fromEntries(r.map((o,s)=>[o,s<3?e:n]))}const jc={...vo("gray","grey","black"),...vo("red","light-red","red"),...vo("pink","light-red","red"),...vo("grape","light-violet","violet"),...vo("blue","light-blue","blue"),...vo("cyan","light-blue","blue"),...vo("teal","light-green","green"),...vo("green","light-green","green"),...vo("yellow","yellow","orange"),...vo("orange","yellow","orange"),"#ffffff":"white","#000000":"black"},Nie={solid:"draw",dashed:"dashed",dotted:"dotted"},zie={"cross-hatch":"pattern",hachure:"pattern",solid:"solid"},Bie={left:"start",center:"middle",right:"end"},Uie={left:"start",center:"middle",right:"end"},yE={arrow:"arrow",dot:"dot",triangle:"triangle",bar:"pipe"};function Hie(t,e,n){let r=0;if(t.points.length>2){const o=new x(e[0],e[1]),s=new x(n[0],n[1]),i=new x(t.points[1][0],t.points[1][1]),a=x.Sub(s,o),l=x.Per(a),c=x.Med(s,o),u=x.Sub(c,l),h=x.Add(c,l),p=x.NearestPointOnLineSegment(u,h,i,!1);r=x.Dist(p,c),x.Clockwise(p,s,c)&&(r*=-1)}return r}const Ah=t=>{let e=Nie[t.strokeStyle]??"draw";return e==="draw"&&t.roughness===0&&(e="solid"),e},Kie=t=>t.backgroundColor==="transparent"?"none":zie[t.fillStyle]??"solid";async function Wie(t,e,n,r){const o=e.map(s=>s instanceof File?s:new File([s],"tldrawFile",{type:s.type}));t.markHistoryStoppingPoint("paste"),await t.putExternalContent({type:"files",files:o,point:n,ignoreParent:!1,sources:r})}function Gie(t,e,n){const r=t.getSelectionPageBounds();t.markHistoryStoppingPoint("paste"),t.putContentOntoCurrentPage(e,{point:n,select:!0});const o=t.getSelectionPageBounds();r&&o&&(r!=null&&r.collides(o))&&(t.updateInstanceState({isChangingStyle:!0}),t.timers.setTimeout(()=>{t.updateInstanceState({isChangingStyle:!1})},150))}async function Gx(t,e,n,r){return t.markHistoryStoppingPoint("paste"),await t.putExternalContent({type:"url",point:n,url:e,sources:r})}const Vie=[_b,"image/png","image/jpeg","image/webp","image/svg+xml"];function Yie(t){const e=document.implementation.createHTMLDocument("");return e.documentElement.innerHTML=t.trim(),e.body.textContent||e.body.innerText||""}const Xie=t=>{try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}},qie=t=>{const e=t.split(/[\n\s]/);for(const n of e)try{const r=new URL(n);if(!(r.protocol==="http:"||r.protocol==="https:"))return}catch{return}return bj(e)},Zie=t=>/^<svg/.test(t),Qie=["input","select","textarea"];function fS(t){const{activeElement:e}=document;return t.menus.hasAnyOpenMenus()||e&&(e.getAttribute("contenteditable")||Qie.indexOf(e.tagName.toLowerCase())>-1)}const gS=(t,e,n,r)=>{const o=qie(e);if(o)for(const s of o)Gx(t,s,n);else Xie(e)?Gx(t,e,n):Zie(e)?(t.markHistoryStoppingPoint("paste"),t.putExternalContent({type:"svg-text",text:e,point:n,sources:r})):(t.markHistoryStoppingPoint("paste"),t.putExternalContent({type:"text",text:e,point:n,sources:r}))},Jie=async(t,e,n)=>{if(t.getEditingShapeId()!==null)return;if(!e)throw Error("No clipboard data");const r=[];for(const o of Object.values(e.items))switch(o.kind){case"file":{r.push({type:"file",source:new Promise(s=>s(o.getAsFile()))});break}case"string":{o.type==="text/html"?r.push({type:"html",source:new Promise(s=>o.getAsString(s))}):o.type==="text/plain"?r.push({type:"text",source:new Promise(s=>o.getAsString(s))}):r.push({type:o.type,source:new Promise(s=>o.getAsString(s))});break}}D$(t,r,n)},O$=async(t,e,n)=>{const r=[];for(const o of e){for(const s of Vie)if(o.types.includes(s)){const i=o.getType(s).then(a=>Zr.rewriteMimeType(a,Mie(s)));r.push({type:"blob",source:i});break}o.types.includes("text/html")&&r.push({type:"html",source:(async()=>{const s=await o.getType("text/html");return await Zr.blobToText(s)})()}),o.types.includes("text/uri-list")&&r.push({type:"url",source:(async()=>{const s=await o.getType("text/uri-list");return await Zr.blobToText(s)})()}),o.types.includes("text/plain")&&r.push({type:"text",source:(async()=>{const s=await o.getType("text/plain");return await Zr.blobToText(s)})()})}return await D$(t,r,n)};async function D$(t,e,n){const r=e.filter(s=>(s.type==="file"||s.type==="blob")&&s.source!==null);if(r.length){if(r.length>t.options.maxFilesAtOnce)throw Error("Too many files");const s=me(await Promise.all(r.map(i=>i.source)));return await Wie(t,s,n)}const o=await Promise.all(e.filter(s=>s.type!=="file").map(s=>new Promise(i=>{const a=s;if(a.type==="file"){i({type:"error",data:null,reason:"unexpected file"});return}a.source.then(l=>{var u;const c=(u=l.match(/<div data-tldraw[^>]*>(.*)<\/div>/))==null?void 0:u[1];if(c)try{const h=j$.decompressFromBase64(c);if(h===null){i({type:"error",data:h,reason:"found tldraw data comment but could not parse base64"});return}else{const p=JSON.parse(h);if(p.type!=="application/tldraw"&&i({type:"error",data:p,reason:`found tldraw data comment but JSON was of a different type: ${p.type}`}),typeof p.data=="string"){i({type:"error",data:p,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}i({type:"tldraw",data:p.data});return}}catch{i({type:"error",data:c,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}else{if(a.type==="html"){i({type:"text",data:l,subtype:"html"});return}if(a.type==="url"){i({type:"text",data:l,subtype:"url"});return}try{const h=JSON.parse(l);if(h.type==="excalidraw/clipboard"){i({type:"excalidraw",data:h});return}else{i({type:"text",data:l,subtype:"json"});return}}catch{i({type:"text",data:l,subtype:"text"});return}}i({type:"error",data:l,reason:"unhandled case"})})})));for(const s of o)if(s.type==="tldraw"){Gie(t,s.data,n);return}for(const s of o)if(s.type==="excalidraw"){Oie(t,s.data,n);return}for(const s of o)if(s.type==="text"&&s.subtype==="html"){const a=new DOMParser().parseFromString(s.data,"text/html").querySelector("body");if(a&&Array.from(a.children).filter(c=>c.nodeType===1).length===1&&a.firstElementChild&&a.firstElementChild.tagName==="A"&&a.firstElementChild.hasAttribute("href")&&a.firstElementChild.getAttribute("href")!==""){const c=a.firstElementChild.getAttribute("href");gS(t,c,n,o);return}if(!o.some(c=>c.type==="text"&&c.subtype!=="html")&&s.data.trim()){gS(t,Yie(s.data),n,o);return}}for(const s of o)if(s.type==="text"&&s.subtype==="url"){Gx(t,s.data,n,o);return}for(const s of o)if(s.type==="text"&&s.subtype==="text"&&s.data.trim()){gS(t,s.data,n,o);return}}const Gf=async t=>{var r;const e=await t.resolveAssetsInContent(t.getContentFromCurrentPage(t.getSelectedShapeIds()));if(!e){navigator&&navigator.clipboard&&navigator.clipboard.writeText("");return}const n=j$.compressToBase64(JSON.stringify({type:"application/tldraw",kind:"content",data:e}));if(!(typeof navigator>"u")){const o=e.shapes.map(s=>t.getShapeUtil(s).getText(s)).filter(p7);if((r=navigator.clipboard)!=null&&r.write){const s=new Blob([`<div data-tldraw>${n}</div>`],{type:"text/html"});let i=o.join(" ");i===""&&(i=" "),navigator.clipboard.write([new ClipboardItem({"text/html":s,"text/plain":new Blob([i],{type:"text/plain"})})])}else navigator.clipboard.writeText&&navigator.clipboard.writeText(`<div data-tldraw>${n}</div>`)}};function eae(){const t=z(),e=Qt(),n=w.useCallback(async function(i){t.getSelectedShapeIds().length!==0&&(await Gf(t),e("copy",{source:i}))},[t,e]),r=w.useCallback(async function(i){t.getSelectedShapeIds().length!==0&&(await Gf(t),t.deleteShapes(t.getSelectedShapeIds()),e("cut",{source:i}))},[t,e]),o=w.useCallback(async function(i,a,l){t.getEditingShapeId()===null&&(Array.isArray(i)&&i[0]instanceof ClipboardItem?(O$(t,i,l),e("paste",{source:"menu"})):navigator.clipboard.read().then(c=>{o(c,a,l)}))},[t,e]);return{copy:n,cut:r,paste:o}}function tae(){const t=z(),e=Qt(),n=U("editor.isFocused",()=>t.getInstanceState().isFocused,[t]);w.useEffect(()=>{if(!n)return;const r=async l=>{t.getSelectedShapeIds().length===0||t.getEditingShapeId()!==null||fS(t)||(xe(l),await Gf(t),e("copy",{source:"kbd"}))};async function o(l){t.getSelectedShapeIds().length===0||t.getEditingShapeId()!==null||fS(t)||(xe(l),await Gf(t),t.deleteShapes(t.getSelectedShapeIds()),e("cut",{source:"kbd"}))}let s=!1;const i=l=>{l.button===1&&(s=!0,t.timers.requestAnimationFrame(()=>{s=!1}))},a=l=>{var p;if(s){_t(l);return}if(t.getEditingShapeId()!==null||fS(t))return;let c,u=!1;t.inputs.shiftKey&&(u=!0),t.user.getIsPasteAtCursorMode()&&(u=!u),u&&(c=t.inputs.currentPagePoint);const h=()=>{l.clipboardData&&Jie(t,l.clipboardData,c)};(p=navigator.clipboard)!=null&&p.read?navigator.clipboard.read().then(f=>{Array.isArray(f)&&f[0]instanceof ClipboardItem&&O$(t,f,c)},()=>{h()}):h(),xe(l),e("paste",{source:"kbd"})};return document.addEventListener("copy",r),document.addEventListener("cut",o),document.addEventListener("paste",a),document.addEventListener("pointerup",i),()=>{document.removeEventListener("copy",r),document.removeEventListener("cut",o),document.removeEventListener("paste",a),document.removeEventListener("pointerup",i)}},[t,e,n])}/*!
239
+ For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return w.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},Nse="DialogDescriptionWarning",zse=({contentRef:t,descriptionId:e})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${p$(Nse).contentName}}.`;return w.useEffect(()=>{var s;const o=(s=t.current)==null?void 0:s.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},Bse=t$,Use=o$,Hse=s$,Kse=i$;const Bo=w.memo(function({small:e,invertIcon:n,icon:r,color:o,className:s,...i}){const a=hb(),l=a.icons[r]??a.icons["question-mark-circle"],c=w.useRef(null);return w.useLayoutEffect(()=>{l||console.error(`Icon not found: ${r}. Add it to the assetUrls.icons object.`),c!=null&&c.current&&(c.current.style.webkitMask=`url(${l}) center 100% / 100% no-repeat`)},[c,l,r]),r==="none"?d.jsx("div",{className:le("tlui-icon tlui-icon__placeholder",{"tlui-icon__small":e},s)}):d.jsx("div",{...i,ref:c,className:le("tlui-icon",{"tlui-icon__small":e},s),style:{color:o,mask:`url(${l}) center 100% / 100% no-repeat`,transform:n?"scale(-1, 1)":void 0}})});function be({icon:t,small:e,invertIcon:n}){return d.jsx(Bo,{className:"tlui-button__icon",icon:t,small:e,invertIcon:n})}function dm({className:t,children:e}){return d.jsx("div",{className:le("tlui-dialog__header",t),children:e})}function hm({className:t,children:e}){return d.jsx(l$,{dir:"ltr",className:le("tlui-dialog__header__title",t),children:e})}function pm(){return d.jsx("div",{className:"tlui-dialog__header__close",children:d.jsx(d$,{"data-testid":"dialog.close",dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon","aria-label":"Close",onTouchEnd:t=>t.target.click(),children:d.jsx(be,{small:!0,icon:"cross-2"})})})})}function Yu({className:t,children:e,style:n}){return d.jsx("div",{className:le("tlui-dialog__body",t),style:n,children:e})}function yb({className:t,children:e}){return d.jsx("div",{className:le("tlui-dialog__footer",t),children:e})}const fm=w.forwardRef(function({className:e,label:n,icon:r,iconLeft:o,autoSelect:s=!1,autoFocus:i=!1,defaultValue:a,placeholder:l,onComplete:c,onValueChange:u,onCancel:h,onFocus:p,onBlur:f,shouldManuallyMaintainScrollPositionWhenFocused:g=!1,children:m,value:v},y){const S=ki(),b=w.useRef(null);w.useImperativeHandle(y,()=>b.current);const P=Ee(),C=w.useRef(a??""),_=w.useRef(a??""),[E,k]=w.useState(!1),D=w.useCallback(M=>{k(!0);const O=M.currentTarget;_.current=O.value,S?S.timers.requestAnimationFrame(()=>{s&&O.select()}):kx.requestAnimationFrame("anon",()=>{s&&O.select()}),p==null||p()},[s,S,p]),T=w.useCallback(M=>{const O=M.currentTarget.value;_.current=O,u==null||u(O)},[u]),j=w.useCallback(M=>{switch(M.key){case"Enter":{M.currentTarget.blur(),_t(M),c==null||c(M.currentTarget.value);break}case"Escape":{M.currentTarget.value=C.current,h==null||h(M.currentTarget.value),M.currentTarget.blur(),_t(M);break}}},[c,h]),$=w.useCallback(M=>{k(!1);const O=M.currentTarget.value;f==null||f(O)},[f]);return w.useEffect(()=>{if(!Ge.isIos)return;const M=window.visualViewport;if(E&&g&&M){const O=()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})};return M.addEventListener("resize",O),M.addEventListener("scroll",O),S?S.timers.requestAnimationFrame(()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})}):kx.requestAnimationFrame("anon",()=>{var F;(F=b.current)==null||F.scrollIntoView({block:"center"})}),()=>{M.removeEventListener("resize",O),M.removeEventListener("scroll",O)}}},[E,S,g]),d.jsxs("div",{draggable:!1,className:"tlui-input__wrapper",children:[m,n&&d.jsx("label",{children:P(n)}),o&&d.jsx(Bo,{icon:o,className:"tlui-icon-left",small:!0}),d.jsx("input",{ref:b,className:le("tlui-input",e),type:"text",defaultValue:a,onKeyDownCapture:j,onChange:T,onFocus:D,onBlur:$,autoFocus:i,placeholder:l,value:v}),r&&d.jsx(Bo,{icon:r,small:!!n})]})});function pE(t){return gr.isValid(t)?{isValid:!0,hasProtocol:!0}:gr.isValid("https://"+t)?{isValid:!0,hasProtocol:!1}:{isValid:!1,hasProtocol:!1}}const Wse=qt(function({onClose:e}){const r=z().getOnlySelectedShape();return r&&"url"in r.props&&typeof r.props.url=="string"?d.jsx(Gse,{onClose:e,selectedShape:r}):null}),Gse=qt(function({onClose:e,selectedShape:n}){const r=z(),o=Ee(),s=w.useRef(null);w.useEffect(()=>{r.timers.requestAnimationFrame(()=>{var g;return(g=s.current)==null?void 0:g.focus()})},[r]);const i=w.useRef(n.props.url),[a,l]=w.useState(()=>{const g=pE(n.props.url),m=g.isValid===!0?g.hasProtocol?n.props.url:"https://"+n.props.url:"https://";return{actual:m,safe:m,valid:!0}}),c=w.useCallback(g=>{const m=g.replace(/https?:\/\/(https?:\/\/)/,(S,b)=>b),v=pE(m),y=v.isValid===!0?v.hasProtocol?m:"https://"+m:"https://";l({actual:m,safe:y,valid:v.isValid})},[]),u=w.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(r.updateShapes([{id:g.id,type:g.type,props:{url:""}}]),e())},[r,e]),h=w.useCallback(()=>{const g=r.getOnlySelectedShape();g&&(g&&"url"in g.props&&g.props.url!==a.safe&&r.updateShapes([{id:g.id,type:g.type,props:{url:a.safe}}]),e())},[r,e,a]),p=w.useCallback(()=>{e()},[e]);if(!n)return e(),null;const f=i.current&&!a.valid;return d.jsxs(d.Fragment,{children:[d.jsxs(dm,{children:[d.jsx(hm,{children:o("edit-link-dialog.title")}),d.jsx(pm,{})]}),d.jsx(Yu,{children:d.jsxs("div",{className:"tlui-edit-link-dialog",children:[d.jsx(fm,{ref:s,className:"tlui-edit-link-dialog__input",label:"edit-link-dialog.url",autoFocus:!0,value:a.actual,onValueChange:c,onComplete:h,onCancel:p}),d.jsx("div",{children:a.valid?o("edit-link-dialog.detail"):o("edit-link-dialog.invalid-url")})]})}),d.jsxs(yb,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:p,onTouchEnd:p,children:d.jsx(Pt,{children:o("edit-link-dialog.cancel")})}),f?d.jsx(ce,{type:"danger",onTouchEnd:u,onClick:u,children:d.jsx(Pt,{children:o("edit-link-dialog.clear")})}):d.jsx(ce,{type:"primary",disabled:!a.valid,onTouchEnd:h,onClick:h,children:d.jsx(Pt,{children:o("edit-link-dialog.save")})})]})]})});var Vse={};const fE=/(^\/r\/[^/]+\/?$)/,Sb=[{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:t=>{const e=ge(t);if(e&&e.pathname.match(fE))return t},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(fE))return t}},{type:"figma",title:"Figma",hostnames:["figma.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{if(t.match(/https:\/\/([\w\.-]+\.)?figma.com\/(file|proto)\/([0-9a-zA-Z]{22,128})(?:\/.*)?$/)&&!t.includes("figma.com/embed"))return`https://www.figma.com/embed?embed_host=share&url=${t}`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/?$/)){const n=e.searchParams.get("url");if(n)return n}}},{type:"google_maps",title:"Google Maps",hostnames:["google.*"],width:720,height:500,doesResize:!0,overridePermissions:{"allow-presentation":!0},toEmbedUrl:t=>{if(t.includes("/maps/")){const e=t.match(/@(.*),(.*),(.*)z/);let n;if(e){const[,r,o,s]=e;n=`https://${new URL(t).host.replace("www.","")}/maps/embed/v1/view?key=${Vse.NEXT_PUBLIC_GC_API_KEY}&center=${r},${o}&zoom=${s}`}else n="";return n}},fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.pathname.match(/^\/maps\/embed\/v1\/view\/?$/)&&e.searchParams.has("center")&&e.searchParams.get("zoom")){const r=e.searchParams.get("zoom"),[o,s]=e.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:t=>{const e=ge(t),n=e&&e.pathname.match(/\/v\/(.+)\/?/);if(n)return`https://www.val.town/embed/${n[1]}`},fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/(.+)\/?/);if(n)return`https://www.val.town/v/${n[1]}`}},{type:"codesandbox",title:"CodeSandbox",hostnames:["codesandbox.io"],minWidth:300,minHeight:300,width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/s\/([^/]+)\/?/);if(n)return`https://codesandbox.io/embed/${n[1]}`},fromEmbedUrl:t=>{const e=ge(t),n=e&&e.pathname.match(/\/embed\/([^/]+)\/?/);if(n)return`https://codesandbox.io/s/${n[1]}`}},{type:"codepen",title:"Codepen",hostnames:["codepen.io"],minWidth:300,minHeight:300,width:520,height:400,doesResize:!0,toEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/pen\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/embed/${s}`}},fromEmbedUrl:t=>{const e=/https:\/\/codepen.io\/([^/]+)\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o,s]=n;return`https://codepen.io/${o}/pen/${s}`}}},{type:"scratch",title:"Scratch",hostnames:["scratch.mit.edu"],width:520,height:400,doesResize:!1,toEmbedUrl:t=>{const e=/https?:\/\/scratch.mit.edu\/projects\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/embed/${o}`}},fromEmbedUrl:t=>{const e=/https:\/\/scratch.mit.edu\/projects\/embed\/([^/]+)/,n=t.match(e);if(n){const[r,o]=n;return`https://scratch.mit.edu/projects/${o}`}}},{type:"youtube",title:"YouTube",hostnames:["*.youtube.com","youtube.com","youtu.be"],width:800,height:450,doesResize:!0,overridePermissions:{"allow-presentation":!0,"allow-popups-to-escape-sandbox":!0},isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(!e)return;const n=e.hostname.replace(/^www./,"");if(n==="youtu.be")return`https://www.youtube.com/embed/${e.pathname.split("/").filter(Boolean)[0]}`;if((n==="youtube.com"||n==="m.youtube.com")&&e.pathname.match(/^\/watch/))return`https://www.youtube.com/embed/${e.searchParams.get("v")}`},fromEmbedUrl:t=>{const e=ge(t);if(!e)return;if(e.hostname.replace(/^www./,"")==="youtube.com"){const r=e.pathname.match(/^\/embed\/([^/]+)\/?/);if(r)return`https://www.youtube.com/watch?v=${r[1]}`}}},{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:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("cid");if(e!=null&&e.pathname.match(/\/calendar\/u\/0/)&&n){e.pathname="/calendar/embed";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("src",n),e.href}},fromEmbedUrl:t=>{const e=ge(t),n=e==null?void 0:e.searchParams.get("src");if(e!=null&&e.pathname.match(/\/calendar\/embed/)&&n){e.pathname="/calendar/u/0";const r=Array.from(e.searchParams.keys());for(const o of r)e.searchParams.delete(o);return e.searchParams.set("cid",n),e.href}}},{type:"google_slides",title:"Google Slides",hostnames:["docs.google.*"],width:720,height:500,minWidth:460,minHeight:360,doesResize:!0,overridePermissions:{"allow-popups-to-escape-sandbox":!0},toEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/pub\/?$/))){e.pathname=e.pathname.replace(/\/pub$/,"/embed");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}},fromEmbedUrl:t=>{const e=ge(t);if(e!=null&&e.pathname.match(/^\/presentation/)&&(e!=null&&e.pathname.match(/\/embed\/?$/))){e.pathname=e.pathname.replace(/\/embed$/,"/pub");const n=Array.from(e.searchParams.keys());for(const r of n)e.searchParams.delete(r);return e.href}}},{type:"github_gist",title:"GitHub Gist",hostnames:["gist.github.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/([^/]+)\/([^/]+)/))return t.split("/").pop()?t:void 0}},{type:"replit",title:"Replit",hostnames:["replit.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/))return`${t}?embed=true`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/\/@([^/]+)\/([^/]+)/)&&e.searchParams.has("embed"))return e.searchParams.delete("embed"),e.href}},{type:"felt",title:"Felt",hostnames:["felt.com"],width:720,height:500,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/map\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/map\//))return e.pathname=e.pathname.replace(/^\/embed/,""),e.href}},{type:"spotify",title:"Spotify",hostnames:["open.spotify.com"],width:720,height:500,minHeight:500,overrideOutlineRadius:12,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/(artist|album)\//))return e.origin+"/embed"+e.pathname},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/(artist|album)\//))return e.origin+e.pathname.replace(/^\/embed/,"")}},{type:"vimeo",title:"Vimeo",hostnames:["vimeo.com","player.vimeo.com"],width:640,height:360,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="vimeo.com"&&e.pathname.match(/^\/[0-9]+/))return"https://player.vimeo.com/video/"+e.pathname.split("/")[1]+"?title=0&byline=0"},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="player.vimeo.com"){const n=e.pathname.match(/^\/video\/([^/]+)\/?$/);if(n)return"https://vimeo.com/"+n[1]}}},{type:"excalidraw",title:"Excalidraw",hostnames:["excalidraw.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hash.match(/#room=/))return t}},{type:"observable",title:"Observable",hostnames:["observablehq.com"],width:720,height:500,doesResize:!0,isAspectRatioLocked:!1,backgroundColor:"#fff",toEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}/embed${e.pathname}?cell=*`;if(e&&e.pathname.match(/^\/d\/([^/]+)\/?$/)){const n=e.pathname.replace(/^\/d/,"");return`${e.origin}/embed${n}?cell=*`}},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.pathname.match(/^\/embed\/@([^/]+)\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","")}#cell-*`;if(e&&e.pathname.match(/^\/embed\/([^/]+)\/?$/))return`${e.origin}${e.pathname.replace("/embed","/d")}#cell-*`}},{type:"desmos",title:"Desmos",hostnames:["desmos.com"],width:700,height:450,doesResize:!0,toEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search===""&&e.hash==="")return`${t}?embed`},fromEmbedUrl:t=>{const e=ge(t);if(e&&e.hostname==="www.desmos.com"&&e.pathname.match(/^\/calculator\/([^/]+)\/?$/)&&e.search==="?embed"&&e.hash==="")return t.replace("?embed","")}}],Yse={"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},Xse=Sb.map(t=>t.type);function qse(t){return Xse.includes(t)}function Zse(t){return"icon"in t}function f$(){return z().getShapeUtil("embed")}function vb(){const t=f$();return e=>t?t.getEmbedDefinition(e):void 0}function Qse(){const t=f$();return t?t.getEmbedDefinitions():[]}const g$=qt(function({onClose:e}){const n=z(),r=Ee(),o=hb(),[s,i]=w.useState(null),[a,l]=w.useState(""),[c,u]=w.useState(null),[h,p]=w.useState(!1),f=w.useRef(-1),g=Qse(),m=vb();return d.jsxs(d.Fragment,{children:[d.jsxs(dm,{children:[d.jsx(hm,{children:s?`${r("embed-dialog.title")} — ${s.title}`:r("embed-dialog.title")}),d.jsx(pm,{})]}),s?d.jsxs(d.Fragment,{children:[d.jsxs(Yu,{className:"tlui-embed-dialog__enter",children:[d.jsx(fm,{className:"tlui-embed-dialog__input",label:"embed-dialog.url",placeholder:"https://example.com",autoFocus:!0,onValueChange:v=>{l(v);const y=m(v);u(y&&y.definition.type===s.type?y:null),p(!1),clearTimeout(f.current),f.current=n.timers.setTimeout(()=>p(!y),320)}}),a===""?d.jsxs("div",{className:"tlui-embed-dialog__instruction",children:[d.jsx("span",{children:r("embed-dialog.instruction")})," ",s.instructionLink&&d.jsxs("a",{target:"_blank",rel:"noopener noreferrer",href:s.instructionLink,className:"tlui-embed-dialog__instruction__link",children:["Learn more.",d.jsx(Bo,{icon:"external-link",small:!0})]})]}):d.jsx("div",{className:"tlui-embed-dialog__warning",children:h?r("embed-dialog.invalid-url"):" "})]}),d.jsxs(yb,{className:"tlui-dialog__footer__actions",children:[d.jsx(ce,{type:"normal",onClick:()=>{i(null),u(null),l("")},children:d.jsx(Pt,{children:r("embed-dialog.back")})}),d.jsx("div",{className:"tlui-embed__spacer"}),d.jsx(ce,{type:"normal",onClick:e,children:d.jsx(Pt,{children:r("embed-dialog.cancel")})}),d.jsx(ce,{type:"primary",disabled:!c,onClick:()=>{c&&(n.putExternalContent({type:"embed",url:a,point:n.getViewportPageBounds().center,embed:c.definition}),e())},children:d.jsx(Pt,{children:r("embed-dialog.create")})})]})]}):d.jsx(d.Fragment,{children:d.jsx(Yu,{className:"tlui-embed-dialog__list",children:g.map(v=>{const y=qse(v.type)?o.embedIcons[v.type]:Zse(v)?v.icon:void 0;return d.jsxs(ce,{type:"menu",onClick:()=>i(v),children:[d.jsx(Pt,{children:v.title}),y&&d.jsx("div",{className:"tlui-embed-dialog__item__image",style:{backgroundImage:`url(${y})`}})]},v.type)})})})]})});async function Jse(t,e,n){const r=me(e.map(a=>{const l=t.getShape(a);if(!(!l||t.getShapeUtil(l.type).toSvg===void 0))return l}));if(r.length===0)return;if(r.length===1){const a=r[0];if(!a||t.isShapeOfType(a,"image"))return}const o=[];if(n!==void 0){const a=r.map(l=>({shape:l,bounds:t.getShapeMaskedPageBounds(l).clone().expandBy(n)}));for(let l=0;l<a.length;l++){const c=a[l];if(l===0){o[0]={shapes:[c.shape],bounds:c.bounds};continue}let u=!1;for(const h of o)if(h.bounds.includes(c.bounds)){h.shapes.push(c.shape),h.bounds.expand(c.bounds),u=!0;break}u||o.push({shapes:[c.shape],bounds:c.bounds})}}else{const a=Z.Common(r.map(l=>t.getShapeMaskedPageBounds(l)));o.push({shapes:r,bounds:a})}const s=t.options.flattenImageBoundsPadding;for(const a of o){n!==void 0&&a.bounds.expandBy(-n);const l=await t.getSvgString(a.shapes,{padding:s});if(!(l!=null&&l.svg))continue;const c=new Blob([l.svg],{type:"image/svg+xml"}),u=await t.getAssetForExternalContent({type:"file",file:new File([c],"asset.svg",{type:"image/svg+xml"})});u&&(a.asset=u)}const i=[];return Oo(()=>{for(const a of o){const{asset:l,bounds:c,shapes:u}=a;if(!l)continue;const h=t.findCommonAncestor(u)??t.getCurrentPageId();if(!h)continue;let p="a1";for(const y of u)if(y.parentId===h){y.index>p&&(p=y.index);break}let f,g,m;if(Fn(h)){const y=t.getShape(h);if(!y)continue;const S=t.getPointInShapeSpace(y,{x:c.x,y:c.y});m=t.getShapePageTransform(h).rotation(),S.sub(new x(s,s).rot(-m)),f=S.x,g=S.y}else f=c.x-s,g=c.y-s,m=0;t.deleteShapes(u),t.createAssets([{...l,id:l.id}]);const v=Ke();t.createShape({id:v,type:"image",index:p,parentId:h,x:f,y:g,rotation:-m,props:{assetId:l.id,w:c.w+s*2,h:c.h+s*2}}),i.push(v)}}),i}function gm(){const t=ki();return(t==null?void 0:t.store.props.collaboration)!==void 0}function eie(){const t=ki();return U("sync status",()=>{var e;return(e=t==null?void 0:t.store.props.collaboration)!=null&&e.status?t.store.props.collaboration.status.get():null},[t])}const hS=[0,389,436,476,580,640,840,1023];var St=(t=>(t[t.ZERO=0]="ZERO",t[t.MOBILE_XXS=1]="MOBILE_XXS",t[t.MOBILE_XS=2]="MOBILE_XS",t[t.MOBILE_SM=3]="MOBILE_SM",t[t.MOBILE=4]="MOBILE",t[t.TABLET_SM=5]="TABLET_SM",t[t.TABLET=6]="TABLET",t[t.DESKTOP=7]="DESKTOP",t))(St||{});const m$=Te.createContext(null);function tie({forceMobile:t=!1,children:e}){const n=ki(),r=U("breakpoint",()=>{const{width:o}=(n==null?void 0:n.getViewportScreenBounds())??{width:window.innerWidth},s=t?St.MOBILE_SM:hS.length-1;for(let i=0;i<s;i++)if(o>hS[i]&&o<=hS[i+1])return i;return s},[n]);return d.jsx(m$.Provider,{value:r,children:e})}function An(){const t=w.useContext(m$);if(t===null)throw new Error("useBreakpoint must be used inside of the <BreakpointProvider /> component");return t}const y$=w.createContext(null);function nie({context:t,children:e}){const n=Qt(),r=qw("dialogs",[]),o=w.useMemo(()=>({dialogs:r,addDialog(s){const i=s.id??ze();return r.update(a=>[...a.filter(l=>l.id!==s.id),{...s,id:i}]),n("open-menu",{source:"dialog",id:i}),Vr.addOpenMenu(i,t),i},removeDialog(s){var a;const i=r.get().find(l=>l.id===s);return i&&((a=i.onClose)==null||a.call(i),n("close-menu",{source:"dialog",id:s}),Vr.deleteOpenMenu(s,t),r.update(l=>l.filter(c=>c!==i))),s},clearDialogs(){const s=r.get();s.length!==0&&(s.forEach(i=>{var a;(a=i.onClose)==null||a.call(i),n("close-menu",{source:"dialog",id:i.id}),Vr.deleteOpenMenu(i.id,t)}),r.set([]))}}),[n,r,t]);return d.jsx(y$.Provider,{value:o,children:e})}function Ed(){const t=w.useContext(y$);if(!t)throw new Error("useDialogs must be used within a DialogsProvider");return t}var rie="VisuallyHidden",xb=w.forwardRef((t,e)=>d.jsx(Ae.span,{...t,ref:e,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...t.style}}));xb.displayName=rie;var wb="ToastProvider",[bb,oie,sie]=Jg("Toast"),[S$,fge]=Go("Toast",[sie]),[iie,mm]=S$(wb),v$=t=>{const{__scopeToast:e,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:s=50,children:i}=t,[a,l]=w.useState(null),[c,u]=w.useState(0),h=w.useRef(!1),p=w.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${wb}\`. Expected non-empty \`string\`.`),d.jsx(bb.Provider,{scope:e,children:d.jsx(iie,{scope:e,label:n,duration:r,swipeDirection:o,swipeThreshold:s,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:w.useCallback(()=>u(f=>f+1),[]),onToastRemove:w.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:i})})};v$.displayName=wb;var x$="ToastViewport",aie=["F8"],Hx="toast.viewportPause",Kx="toast.viewportResume",w$=w.forwardRef((t,e)=>{const{__scopeToast:n,hotkey:r=aie,label:o="Notifications ({hotkey})",...s}=t,i=mm(x$,n),a=oie(n),l=w.useRef(null),c=w.useRef(null),u=w.useRef(null),h=w.useRef(null),p=Ze(e,h,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),g=i.toastCount>0;w.useEffect(()=>{const v=y=>{var b;r.length!==0&&r.every(P=>y[P]||y.code===P)&&((b=h.current)==null||b.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),w.useEffect(()=>{const v=l.current,y=h.current;if(g&&v&&y){const S=()=>{if(!i.isClosePausedRef.current){const _=new CustomEvent(Hx);y.dispatchEvent(_),i.isClosePausedRef.current=!0}},b=()=>{if(i.isClosePausedRef.current){const _=new CustomEvent(Kx);y.dispatchEvent(_),i.isClosePausedRef.current=!1}},P=_=>{!v.contains(_.relatedTarget)&&b()},C=()=>{v.contains(document.activeElement)||b()};return v.addEventListener("focusin",S),v.addEventListener("focusout",P),v.addEventListener("pointermove",S),v.addEventListener("pointerleave",C),window.addEventListener("blur",S),window.addEventListener("focus",b),()=>{v.removeEventListener("focusin",S),v.removeEventListener("focusout",P),v.removeEventListener("pointermove",S),v.removeEventListener("pointerleave",C),window.removeEventListener("blur",S),window.removeEventListener("focus",b)}}},[g,i.isClosePausedRef]);const m=w.useCallback(({tabbingDirection:v})=>{const S=a().map(b=>{const P=b.ref.current,C=[P,...xie(P)];return v==="forwards"?C:C.reverse()});return(v==="forwards"?S.reverse():S).flat()},[a]);return w.useEffect(()=>{const v=h.current;if(v){const y=S=>{var C,_,E;const b=S.altKey||S.ctrlKey||S.metaKey;if(S.key==="Tab"&&!b){const k=document.activeElement,D=S.shiftKey;if(S.target===v&&D){(C=c.current)==null||C.focus();return}const $=m({tabbingDirection:D?"backwards":"forwards"}),M=$.findIndex(O=>O===k);pS($.slice(M+1))?S.preventDefault():D?(_=c.current)==null||_.focus():(E=u.current)==null||E.focus()}};return v.addEventListener("keydown",y),()=>v.removeEventListener("keydown",y)}},[a,m]),d.jsxs(Lte,{ref:l,role:"region","aria-label":o.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:g?void 0:"none"},children:[g&&d.jsx(Wx,{ref:c,onFocusFromOutsideViewport:()=>{const v=m({tabbingDirection:"forwards"});pS(v)}}),d.jsx(bb.Slot,{scope:n,children:d.jsx(Ae.ol,{tabIndex:-1,...s,ref:p})}),g&&d.jsx(Wx,{ref:u,onFocusFromOutsideViewport:()=>{const v=m({tabbingDirection:"backwards"});pS(v)}})]})});w$.displayName=x$;var b$="ToastFocusProxy",Wx=w.forwardRef((t,e)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=t,s=mm(b$,n);return d.jsx(xb,{"aria-hidden":!0,tabIndex:0,...o,ref:e,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=s.viewport)!=null&&c.contains(a))&&r()}})});Wx.displayName=b$;var ym="Toast",lie="toast.swipeStart",cie="toast.swipeMove",uie="toast.swipeCancel",die="toast.swipeEnd",P$=w.forwardRef((t,e)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:s,...i}=t,[a=!0,l]=Ai({prop:r,defaultProp:o,onChange:s});return d.jsx(ho,{present:n||a,children:d.jsx(fie,{open:a,...i,ref:e,onClose:()=>l(!1),onPause:Xt(t.onPause),onResume:Xt(t.onResume),onSwipeStart:oe(t.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:oe(t.onSwipeMove,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:oe(t.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:oe(t.onSwipeEnd,c=>{const{x:u,y:h}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),l(!1)})})})});P$.displayName=ym;var[hie,pie]=S$(ym,{onClose(){}}),fie=w.forwardRef((t,e)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:s,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...g}=t,m=mm(ym,n),[v,y]=w.useState(null),S=Ze(e,O=>y(O)),b=w.useRef(null),P=w.useRef(null),C=o||m.duration,_=w.useRef(0),E=w.useRef(C),k=w.useRef(0),{onToastAdd:D,onToastRemove:T}=m,j=Xt(()=>{var F;(v==null?void 0:v.contains(document.activeElement))&&((F=m.viewport)==null||F.focus()),i()}),$=w.useCallback(O=>{!O||O===1/0||(window.clearTimeout(k.current),_.current=new Date().getTime(),k.current=window.setTimeout(j,O))},[j]);w.useEffect(()=>{const O=m.viewport;if(O){const F=()=>{$(E.current),c==null||c()},B=()=>{const K=new Date().getTime()-_.current;E.current=E.current-K,window.clearTimeout(k.current),l==null||l()};return O.addEventListener(Hx,B),O.addEventListener(Kx,F),()=>{O.removeEventListener(Hx,B),O.removeEventListener(Kx,F)}}},[m.viewport,C,l,c,$]),w.useEffect(()=>{s&&!m.isClosePausedRef.current&&$(C)},[s,C,m.isClosePausedRef,$]),w.useEffect(()=>(D(),()=>T()),[D,T]);const M=w.useMemo(()=>v?M$(v):null,[v]);return m.viewport?d.jsxs(d.Fragment,{children:[M&&d.jsx(gie,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:M}),d.jsx(hie,{scope:n,onClose:j,children:wa.createPortal(d.jsx(bb.ItemSlot,{scope:n,children:d.jsx(Rte,{asChild:!0,onEscapeKeyDown:oe(a,()=>{m.isFocusedToastEscapeKeyDownRef.current||j(),m.isFocusedToastEscapeKeyDownRef.current=!1}),children:d.jsx(Ae.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":m.swipeDirection,...g,ref:S,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:oe(t.onKeyDown,O=>{O.key==="Escape"&&(a==null||a(O.nativeEvent),O.nativeEvent.defaultPrevented||(m.isFocusedToastEscapeKeyDownRef.current=!0,j()))}),onPointerDown:oe(t.onPointerDown,O=>{O.button===0&&(b.current={x:O.clientX,y:O.clientY})}),onPointerMove:oe(t.onPointerMove,O=>{if(!b.current)return;const F=O.clientX-b.current.x,B=O.clientY-b.current.y,K=!!P.current,R=["left","right"].includes(m.swipeDirection),H=["left","up"].includes(m.swipeDirection)?Math.min:Math.max,Y=R?H(0,F):0,ee=R?0:H(0,B),he=O.pointerType==="touch"?10:2,ue={x:Y,y:ee},ke={originalEvent:O,delta:ue};K?(P.current=ue,Th(cie,h,ke,{discrete:!1})):gE(ue,m.swipeDirection,he)?(P.current=ue,Th(lie,u,ke,{discrete:!1}),O.target.setPointerCapture(O.pointerId)):(Math.abs(F)>he||Math.abs(B)>he)&&(b.current=null)}),onPointerUp:oe(t.onPointerUp,O=>{const F=P.current,B=O.target;if(B.hasPointerCapture(O.pointerId)&&B.releasePointerCapture(O.pointerId),P.current=null,b.current=null,F){const K=O.currentTarget,R={originalEvent:O,delta:F};gE(F,m.swipeDirection,m.swipeThreshold)?Th(die,f,R,{discrete:!0}):Th(uie,p,R,{discrete:!0}),K.addEventListener("click",H=>H.preventDefault(),{once:!0})}})})})}),m.viewport)})]}):null}),gie=t=>{const{__scopeToast:e,children:n,...r}=t,o=mm(ym,e),[s,i]=w.useState(!1),[a,l]=w.useState(!1);return Sie(()=>i(!0)),w.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:d.jsx(Pd,{asChild:!0,children:d.jsx(xb,{...r,children:s&&d.jsxs(d.Fragment,{children:[o.label," ",n]})})})},mie="ToastTitle",C$=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return d.jsx(Ae.div,{...r,ref:e})});C$.displayName=mie;var yie="ToastDescription",_$=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t;return d.jsx(Ae.div,{...r,ref:e})});_$.displayName=yie;var I$="ToastAction",E$=w.forwardRef((t,e)=>{const{altText:n,...r}=t;return n.trim()?d.jsx(T$,{altText:n,asChild:!0,children:d.jsx(Pb,{...r,ref:e})}):(console.error(`Invalid prop \`altText\` supplied to \`${I$}\`. Expected non-empty \`string\`.`),null)});E$.displayName=I$;var k$="ToastClose",Pb=w.forwardRef((t,e)=>{const{__scopeToast:n,...r}=t,o=pie(k$,n);return d.jsx(T$,{asChild:!0,children:d.jsx(Ae.button,{type:"button",...r,ref:e,onClick:oe(t.onClick,o.onClose)})})});Pb.displayName=k$;var T$=w.forwardRef((t,e)=>{const{__scopeToast:n,altText:r,...o}=t;return d.jsx(Ae.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...o,ref:e})});function M$(t){const e=[];return Array.from(t.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&e.push(r.textContent),vie(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",s=r.dataset.radixToastAnnounceExclude==="";if(!o)if(s){const i=r.dataset.radixToastAnnounceAlt;i&&e.push(i)}else e.push(...M$(r))}}),e}function Th(t,e,n,{discrete:r}){const o=n.originalEvent.currentTarget,s=new CustomEvent(t,{bubbles:!0,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?$1(o,s):o.dispatchEvent(s)}var gE=(t,e,n=0)=>{const r=Math.abs(t.x),o=Math.abs(t.y),s=r>o;return e==="left"||e==="right"?s&&r>n:!s&&o>n};function Sie(t=()=>{}){const e=Xt(t);mi(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(e)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[e])}function vie(t){return t.nodeType===t.ELEMENT_NODE}function xie(t){const e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function pS(t){const e=document.activeElement;return t.some(n=>n===e?!0:(n.focus(),document.activeElement!==e))}var wie=P$,bie=C$,Pie=_$,Cie=E$,mE=Pb;const A$=w.createContext(null);function _ie({children:t}){const e=qw("toasts",[]),n=w.useMemo(()=>({toasts:e,addToast(r){const o=r.id??ze();return e.update(s=>[...s.filter(i=>i.id!==r.id),{...r,id:o}]),o},removeToast(r){return e.update(o=>o.filter(s=>s.id!==r)),r},clearToasts(){e.set([])}}),[e]);return d.jsx(v$,{children:d.jsx(A$.Provider,{value:n,children:t})})}function Ts(){const t=w.useContext(A$);if(!t)throw new Error("useToasts must be used within a ToastsProvider");return t}var Cb={exports:{}};Cb.exports;(function(t){var e=function(){var n=String.fromCharCode,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",s={};function i(l,c){if(!s[l]){s[l]={};for(var u=0;u<l.length;u++)s[l][l.charAt(u)]=u}return s[l][c]}var a={compressToBase64:function(l){if(l==null)return"";var c=a._compress(l,6,function(u){return r.charAt(u)});switch(c.length%4){default:case 0:return c;case 1:return c+"===";case 2:return c+"==";case 3:return c+"="}},decompressFromBase64:function(l){return l==null?"":l==""?null:a._decompress(l.length,32,function(c){return i(r,l.charAt(c))})},compressToUTF16:function(l){return l==null?"":a._compress(l,15,function(c){return n(c+32)})+" "},decompressFromUTF16:function(l){return l==null?"":l==""?null:a._decompress(l.length,16384,function(c){return l.charCodeAt(c)-32})},compressToUint8Array:function(l){for(var c=a.compress(l),u=new Uint8Array(c.length*2),h=0,p=c.length;h<p;h++){var f=c.charCodeAt(h);u[h*2]=f>>>8,u[h*2+1]=f%256}return u},decompressFromUint8Array:function(l){if(l==null)return a.decompress(l);for(var c=new Array(l.length/2),u=0,h=c.length;u<h;u++)c[u]=l[u*2]*256+l[u*2+1];var p=[];return c.forEach(function(f){p.push(n(f))}),a.decompress(p.join(""))},compressToEncodedURIComponent:function(l){return l==null?"":a._compress(l,6,function(c){return o.charAt(c)})},decompressFromEncodedURIComponent:function(l){return l==null?"":l==""?null:(l=l.replace(/ /g,"+"),a._decompress(l.length,32,function(c){return i(o,l.charAt(c))}))},compress:function(l){return a._compress(l,16,function(c){return n(c)})},_compress:function(l,c,u){if(l==null)return"";var h,p,f={},g={},m="",v="",y="",S=2,b=3,P=2,C=[],_=0,E=0,k;for(k=0;k<l.length;k+=1)if(m=l.charAt(k),Object.prototype.hasOwnProperty.call(f,m)||(f[m]=b++,g[m]=!0),v=y+m,Object.prototype.hasOwnProperty.call(f,v))y=v;else{if(Object.prototype.hasOwnProperty.call(g,y)){if(y.charCodeAt(0)<256){for(h=0;h<P;h++)_=_<<1,E==c-1?(E=0,C.push(u(_)),_=0):E++;for(p=y.charCodeAt(0),h=0;h<8;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}else{for(p=1,h=0;h<P;h++)_=_<<1|p,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=0;for(p=y.charCodeAt(0),h=0;h<16;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}S--,S==0&&(S=Math.pow(2,P),P++),delete g[y]}else for(p=f[y],h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;S--,S==0&&(S=Math.pow(2,P),P++),f[v]=b++,y=String(m)}if(y!==""){if(Object.prototype.hasOwnProperty.call(g,y)){if(y.charCodeAt(0)<256){for(h=0;h<P;h++)_=_<<1,E==c-1?(E=0,C.push(u(_)),_=0):E++;for(p=y.charCodeAt(0),h=0;h<8;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}else{for(p=1,h=0;h<P;h++)_=_<<1|p,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=0;for(p=y.charCodeAt(0),h=0;h<16;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1}S--,S==0&&(S=Math.pow(2,P),P++),delete g[y]}else for(p=f[y],h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;S--,S==0&&(S=Math.pow(2,P),P++)}for(p=2,h=0;h<P;h++)_=_<<1|p&1,E==c-1?(E=0,C.push(u(_)),_=0):E++,p=p>>1;for(;;)if(_=_<<1,E==c-1){C.push(u(_));break}else E++;return C.join("")},decompress:function(l){return l==null?"":l==""?null:a._decompress(l.length,32768,function(c){return l.charCodeAt(c)})},_decompress:function(l,c,u){var h=[],p=4,f=4,g=3,m="",v=[],y,S,b,P,C,_,E,k={val:u(0),position:c,index:1};for(y=0;y<3;y+=1)h[y]=y;for(b=0,C=Math.pow(2,2),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;switch(b){case 0:for(b=0,C=Math.pow(2,8),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;E=n(b);break;case 1:for(b=0,C=Math.pow(2,16),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;E=n(b);break;case 2:return""}for(h[3]=E,S=E,v.push(E);;){if(k.index>l)return"";for(b=0,C=Math.pow(2,g),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;switch(E=b){case 0:for(b=0,C=Math.pow(2,8),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;h[f++]=n(b),E=f-1,p--;break;case 1:for(b=0,C=Math.pow(2,16),_=1;_!=C;)P=k.val&k.position,k.position>>=1,k.position==0&&(k.position=c,k.val=u(k.index++)),b|=(P>0?1:0)*_,_<<=1;h[f++]=n(b),E=f-1,p--;break;case 2:return v.join("")}if(p==0&&(p=Math.pow(2,g),g++),h[E])m=h[E];else if(E===f)m=S+S.charAt(0);else return null;v.push(m),h[f++]=S+m.charAt(0),p--,S=m,p==0&&(p=Math.pow(2,g),g++)}}};return a}();t!=null?t.exports=e:typeof angular<"u"&&angular!=null&&angular.module("LZString",[]).factory("LZString",function(){return e})})(Cb);var Iie=Cb.exports;const j$=xi(Iie),_b="web image/vnd.tldraw+png",Eie={"image/png":_b},kie={[_b]:"image/png"};function Tie(t){return hn(Eie,t)??null}function Mie(t){return hn(kie,t)??t}function Aie(t){return typeof ClipboardItem<"u"&&"supports"in ClipboardItem&&ClipboardItem.supports(t)}function jie(t){const e=Object.entries(t);for(const[n,r]of e)r.catch(o=>console.error(o));return navigator.clipboard.write([new ClipboardItem(t)]).catch(n=>(console.error(n),Promise.all(e.map(async([r,o])=>[r,await o])).then(r=>{const o=ww(r);return navigator.clipboard.write([new ClipboardItem(o)])})))}async function Oie(t,e,n){var y,S,b;const{elements:r,files:o}=e,s={shapes:[],bindings:[],rootShapeIds:[],assets:[],schema:t.store.schema.serialize()},i=new Map,a=new Map,l=t.getCurrentPageId(),c=new Map,u=[],h=new Set;r.forEach(P=>{if(c.set(P.id,Ke()),P.boundElements!==null)for(const C of P.boundElements)C.type==="text"&&h.add(C.id)});let p=ZT;for(const P of r){if(h.has(P.id))continue;const C=c.get(P.id),_={id:C,typeName:"shape",parentId:l,index:p,x:P.x,y:P.y,rotation:0,isLocked:P.locked,opacity:Die(P.opacity),meta:{}};switch(P.angle!==0&&a.set(C,P.angle),P.groupIds&&P.groupIds.length>0?i.has(P.groupIds[0])?(y=i.get(P.groupIds[0]))==null||y.push(C):i.set(P.groupIds[0],[C]):u.push(C),P.type){case"rectangle":case"ellipse":case"diamond":{let E="",k="middle";if(P.boundElements!==null){for(const T of P.boundElements)if(T.type==="text"){const j=r.find($=>$.id===T.id);j&&(E=j.text,k=Bie[j.textAlign])}}const D=P.backgroundColor==="transparent"?P.strokeColor:P.backgroundColor;s.shapes.push({..._,type:"geo",props:{geo:P.type,url:P.link??"",w:P.width,h:P.height,size:Mh[P.strokeWidth]??"draw",color:jc[D]??"black",text:E,align:k,dash:Ah(P),fill:Kie(P)}});break}case"freedraw":{s.shapes.push({..._,type:"draw",props:{dash:Ah(P),size:Mh[P.strokeWidth],color:jc[P.strokeColor]??"black",segments:[{type:"free",points:P.points.map(([E,k,D=.5])=>({x:E,y:k,z:D}))}]}});break}case"line":{if(P.points.slice().length<2)break;const k=Fu(P.points.length);s.shapes.push({..._,type:"line",props:{dash:Ah(P),size:Mh[P.strokeWidth],color:jc[P.strokeColor]??"black",spline:P.roundness?"cubic":"line",points:{...Object.fromEntries(P.points.map(([D,T],j)=>{const $=k[j];return[$,{id:$,index:$,x:D,y:T}]}))}}});break}case"arrow":{let E="";if(P.boundElements!==null){for(const $ of P.boundElements)if($.type==="text"){const M=r.find(O=>O.id===$.id);M&&(E=M.text)}}const k=P.points[0],D=P.points[P.points.length-1],T=c.get((S=P.startBinding)==null?void 0:S.elementId),j=c.get((b=P.endBinding)==null?void 0:b.elementId);s.shapes.push({..._,type:"arrow",props:{text:E,bend:Hie(P,k,D),dash:Ah(P),size:Mh[P.strokeWidth]??"m",color:jc[P.strokeColor]??"black",start:{x:k[0],y:k[1]},end:{x:D[0],y:D[1]},arrowheadEnd:yE[P.endArrowhead]??"none",arrowheadStart:yE[P.startArrowhead]??"none"}}),T&&s.bindings.push({id:Qi(),typeName:"binding",type:"arrow",fromId:C,toId:T,props:{terminal:"start",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}}),j&&s.bindings.push({id:Qi(),typeName:"binding",type:"arrow",fromId:C,toId:j,props:{terminal:"end",normalizedAnchor:{x:.5,y:.5},isPrecise:!1,isExact:!1},meta:{}});break}case"text":{const{size:E,scale:k}=Lie(P.fontSize);s.shapes.push({..._,type:"text",props:{size:E,scale:k,font:$ie[P.fontFamily]??"draw",color:jc[P.strokeColor]??"black",text:P.text,textAlign:Uie[P.textAlign]}});break}case"image":{const E=o[P.fileId];if(!E)break;const k=Vs.createId();s.assets.push({id:k,typeName:"asset",type:"image",props:{w:P.width,h:P.height,fileSize:E.size,name:P.id??"Untitled",isAnimated:!1,mimeType:E.mimeType,src:E.dataURL},meta:{}}),s.shapes.push({..._,type:"image",props:{w:P.width,h:P.height,assetId:k}})}}p=Io(p)}const f=n??(t.inputs.shiftKey?t.inputs.currentPagePoint:void 0);t.markHistoryStoppingPoint("paste"),t.putContentOntoCurrentPage(s,{point:f,select:!1,preserveIds:!0});for(const P of i.values())if(P.length>1){t.groupShapes(P);const C=t.getShape(P[0]);C!=null&&C.parentId&&Fn(C.parentId)&&u.push(C.parentId)}for(const[P,C]of a)t.select(P),t.rotateShapesBy([P],C);const g=me(u.map(P=>t.getShape(P))),m=Z.Common(g.map(P=>t.getShapePageBounds(P))),v=t.getViewportPageBounds().center;t.updateShapes(g.map(P=>{const C={x:(P.x??0)-(m.x+m.w/2),y:(P.y??0)-(m.y+m.h/2)};return{id:P.id,type:P.type,x:v.x+C.x,y:v.y+C.y}})),t.setSelectedShapes(u)}const Die=t=>{const e=t/100;return e<.2?.1:e<.4?.25:e<.6?.5:e<.8?.75:1},Mh={1:"s",2:"m",3:"l",4:"xl"},Rie={16:"s",20:"m",28:"l",36:"xl"};function Lie(t){const e=Rie[t];return e?{size:e,scale:1}:t<16?{size:"s",scale:t/16}:t>36?{size:"xl",scale:t/36}:{size:"m",scale:1}}const $ie={1:"draw",2:"sans",3:"mono"},Fie={gray:["#f8f9fa","#e9ecef","#ced4da","#868e96","#343a40"],red:["#fff5f5","#ffc9c9","#ff8787","#fa5252","#e03131"],pink:["#fff0f6","#fcc2d7","#f783ac","#e64980","#c2255c"],grape:["#f8f0fc","#eebefa","#da77f2","#be4bdb","#9c36b5"],violet:["#f3f0ff","#d0bfff","#9775fa","#7950f2","#6741d9"],indigo:["#edf2ff","#bac8ff","#748ffc","#4c6ef5","#3b5bdb"],blue:["#e7f5ff","#a5d8ff","#4dabf7","#228be6","#1971c2"],cyan:["#e3fafc","#99e9f2","#3bc9db","#15aabf","#0c8599"],teal:["#e6fcf5","#96f2d7","#38d9a9","#12b886","#099268"],green:["#ebfbee","#b2f2bb","#69db7c","#40c057","#2f9e44"],lime:["#f4fce3","#d8f5a2","#a9e34b","#82c91e","#66a80f"],yellow:["#fff9db","#ffec99","#ffd43b","#fab005","#f08c00"],orange:["#fff4e6","#ffd8a8","#ffa94d","#fd7e14","#e8590c"]};function vo(t,e,n){const r=[0,1,2,3,4].map(o=>Fie[t][o]);return Object.fromEntries(r.map((o,s)=>[o,s<3?e:n]))}const jc={...vo("gray","grey","black"),...vo("red","light-red","red"),...vo("pink","light-red","red"),...vo("grape","light-violet","violet"),...vo("blue","light-blue","blue"),...vo("cyan","light-blue","blue"),...vo("teal","light-green","green"),...vo("green","light-green","green"),...vo("yellow","yellow","orange"),...vo("orange","yellow","orange"),"#ffffff":"white","#000000":"black"},Nie={solid:"draw",dashed:"dashed",dotted:"dotted"},zie={"cross-hatch":"pattern",hachure:"pattern",solid:"solid"},Bie={left:"start",center:"middle",right:"end"},Uie={left:"start",center:"middle",right:"end"},yE={arrow:"arrow",dot:"dot",triangle:"triangle",bar:"pipe"};function Hie(t,e,n){let r=0;if(t.points.length>2){const o=new x(e[0],e[1]),s=new x(n[0],n[1]),i=new x(t.points[1][0],t.points[1][1]),a=x.Sub(s,o),l=x.Per(a),c=x.Med(s,o),u=x.Sub(c,l),h=x.Add(c,l),p=x.NearestPointOnLineSegment(u,h,i,!1);r=x.Dist(p,c),x.Clockwise(p,s,c)&&(r*=-1)}return r}const Ah=t=>{let e=Nie[t.strokeStyle]??"draw";return e==="draw"&&t.roughness===0&&(e="solid"),e},Kie=t=>t.backgroundColor==="transparent"?"none":zie[t.fillStyle]??"solid";async function Wie(t,e,n,r){const o=e.map(s=>s instanceof File?s:new File([s],"tldrawFile",{type:s.type}));t.markHistoryStoppingPoint("paste"),await t.putExternalContent({type:"files",files:o,point:n,ignoreParent:!1,sources:r})}function Gie(t,e,n){const r=t.getSelectionPageBounds();t.markHistoryStoppingPoint("paste"),t.putContentOntoCurrentPage(e,{point:n,select:!0});const o=t.getSelectionPageBounds();r&&o&&(r!=null&&r.collides(o))&&(t.updateInstanceState({isChangingStyle:!0}),t.timers.setTimeout(()=>{t.updateInstanceState({isChangingStyle:!1})},150))}async function Gx(t,e,n,r){return t.markHistoryStoppingPoint("paste"),await t.putExternalContent({type:"url",point:n,url:e,sources:r})}const Vie=[_b,"image/png","image/jpeg","image/webp","image/svg+xml"];function Yie(t){const e=document.implementation.createHTMLDocument("");return e.documentElement.innerHTML=t.trim(),e.body.textContent||e.body.innerText||""}const Xie=t=>{try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}},qie=t=>{const e=t.split(/[\n\s]/);for(const n of e)try{const r=new URL(n);if(!(r.protocol==="http:"||r.protocol==="https:"))return}catch{return}return bj(e)},Zie=t=>/^<svg/.test(t),Qie=["input","select","textarea"];function fS(t){const{activeElement:e}=document;return t.menus.hasAnyOpenMenus()||e&&(e.getAttribute("contenteditable")||Qie.indexOf(e.tagName.toLowerCase())>-1)}const gS=(t,e,n,r)=>{const o=qie(e);if(o)for(const s of o)Gx(t,s,n);else Xie(e)?Gx(t,e,n):Zie(e)?(t.markHistoryStoppingPoint("paste"),t.putExternalContent({type:"svg-text",text:e,point:n,sources:r})):(t.markHistoryStoppingPoint("paste"),t.putExternalContent({type:"text",text:e,point:n,sources:r}))},Jie=async(t,e,n)=>{if(t.getEditingShapeId()!==null)return;if(!e)throw Error("No clipboard data");const r=[];for(const o of Object.values(e.items))switch(o.kind){case"file":{r.push({type:"file",source:new Promise(s=>s(o.getAsFile()))});break}case"string":{o.type==="text/html"?r.push({type:"html",source:new Promise(s=>o.getAsString(s))}):o.type==="text/plain"?r.push({type:"text",source:new Promise(s=>o.getAsString(s))}):r.push({type:o.type,source:new Promise(s=>o.getAsString(s))});break}}D$(t,r,n)},O$=async(t,e,n)=>{const r=[];for(const o of e){for(const s of Vie)if(o.types.includes(s)){const i=o.getType(s).then(a=>Zr.rewriteMimeType(a,Mie(s)));r.push({type:"blob",source:i});break}o.types.includes("text/html")&&r.push({type:"html",source:(async()=>{const s=await o.getType("text/html");return await Zr.blobToText(s)})()}),o.types.includes("text/uri-list")&&r.push({type:"url",source:(async()=>{const s=await o.getType("text/uri-list");return await Zr.blobToText(s)})()}),o.types.includes("text/plain")&&r.push({type:"text",source:(async()=>{const s=await o.getType("text/plain");return await Zr.blobToText(s)})()})}return await D$(t,r,n)};async function D$(t,e,n){const r=e.filter(s=>(s.type==="file"||s.type==="blob")&&s.source!==null);if(r.length){if(r.length>t.options.maxFilesAtOnce)throw Error("Too many files");const s=me(await Promise.all(r.map(i=>i.source)));return await Wie(t,s,n)}const o=await Promise.all(e.filter(s=>s.type!=="file").map(s=>new Promise(i=>{const a=s;if(a.type==="file"){i({type:"error",data:null,reason:"unexpected file"});return}a.source.then(l=>{var u;const c=(u=l.match(/<div data-tldraw[^>]*>(.*)<\/div>/))==null?void 0:u[1];if(c)try{const h=j$.decompressFromBase64(c);if(h===null){i({type:"error",data:h,reason:"found tldraw data comment but could not parse base64"});return}else{const p=JSON.parse(h);if(p.type!=="application/tldraw"&&i({type:"error",data:p,reason:`found tldraw data comment but JSON was of a different type: ${p.type}`}),typeof p.data=="string"){i({type:"error",data:p,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}i({type:"tldraw",data:p.data});return}}catch{i({type:"error",data:c,reason:"found tldraw json but data was a string instead of a TLClipboardModel object"});return}else{if(a.type==="html"){i({type:"text",data:l,subtype:"html"});return}if(a.type==="url"){i({type:"text",data:l,subtype:"url"});return}try{const h=JSON.parse(l);if(h.type==="excalidraw/clipboard"){i({type:"excalidraw",data:h});return}else{i({type:"text",data:l,subtype:"json"});return}}catch{i({type:"text",data:l,subtype:"text"});return}}i({type:"error",data:l,reason:"unhandled case"})})})));for(const s of o)if(s.type==="tldraw"){Gie(t,s.data,n);return}for(const s of o)if(s.type==="excalidraw"){Oie(t,s.data,n);return}for(const s of o)if(s.type==="text"&&s.subtype==="html"){const a=new DOMParser().parseFromString(s.data,"text/html").querySelector("body");if(a&&Array.from(a.children).filter(c=>c.nodeType===1).length===1&&a.firstElementChild&&a.firstElementChild.tagName==="A"&&a.firstElementChild.hasAttribute("href")&&a.firstElementChild.getAttribute("href")!==""){const c=a.firstElementChild.getAttribute("href");gS(t,c,n,o);return}if(!o.some(c=>c.type==="text"&&c.subtype!=="html")&&s.data.trim()){gS(t,Yie(s.data),n,o);return}}for(const s of o)if(s.type==="text"&&s.subtype==="url"){Gx(t,s.data,n,o);return}for(const s of o)if(s.type==="text"&&s.subtype==="text"&&s.data.trim()){gS(t,s.data,n,o);return}}const Gf=async t=>{var r;const e=await t.resolveAssetsInContent(t.getContentFromCurrentPage(t.getSelectedShapeIds()));if(!e){navigator&&navigator.clipboard&&navigator.clipboard.writeText("");return}const n=j$.compressToBase64(JSON.stringify({type:"application/tldraw",kind:"content",data:e}));if(!(typeof navigator>"u")){const o=e.shapes.map(s=>t.getShapeUtil(s).getText(s)).filter(pB);if((r=navigator.clipboard)!=null&&r.write){const s=new Blob([`<div data-tldraw>${n}</div>`],{type:"text/html"});let i=o.join(" ");i===""&&(i=" "),navigator.clipboard.write([new ClipboardItem({"text/html":s,"text/plain":new Blob([i],{type:"text/plain"})})])}else navigator.clipboard.writeText&&navigator.clipboard.writeText(`<div data-tldraw>${n}</div>`)}};function eae(){const t=z(),e=Qt(),n=w.useCallback(async function(i){t.getSelectedShapeIds().length!==0&&(await Gf(t),e("copy",{source:i}))},[t,e]),r=w.useCallback(async function(i){t.getSelectedShapeIds().length!==0&&(await Gf(t),t.deleteShapes(t.getSelectedShapeIds()),e("cut",{source:i}))},[t,e]),o=w.useCallback(async function(i,a,l){t.getEditingShapeId()===null&&(Array.isArray(i)&&i[0]instanceof ClipboardItem?(O$(t,i,l),e("paste",{source:"menu"})):navigator.clipboard.read().then(c=>{o(c,a,l)}))},[t,e]);return{copy:n,cut:r,paste:o}}function tae(){const t=z(),e=Qt(),n=U("editor.isFocused",()=>t.getInstanceState().isFocused,[t]);w.useEffect(()=>{if(!n)return;const r=async l=>{t.getSelectedShapeIds().length===0||t.getEditingShapeId()!==null||fS(t)||(xe(l),await Gf(t),e("copy",{source:"kbd"}))};async function o(l){t.getSelectedShapeIds().length===0||t.getEditingShapeId()!==null||fS(t)||(xe(l),await Gf(t),t.deleteShapes(t.getSelectedShapeIds()),e("cut",{source:"kbd"}))}let s=!1;const i=l=>{l.button===1&&(s=!0,t.timers.requestAnimationFrame(()=>{s=!1}))},a=l=>{var p;if(s){_t(l);return}if(t.getEditingShapeId()!==null||fS(t))return;let c,u=!1;t.inputs.shiftKey&&(u=!0),t.user.getIsPasteAtCursorMode()&&(u=!u),u&&(c=t.inputs.currentPagePoint);const h=()=>{l.clipboardData&&Jie(t,l.clipboardData,c)};(p=navigator.clipboard)!=null&&p.read?navigator.clipboard.read().then(f=>{Array.isArray(f)&&f[0]instanceof ClipboardItem&&O$(t,f,c)},()=>{h()}):h(),xe(l),e("paste",{source:"kbd"})};return document.addEventListener("copy",r),document.addEventListener("cut",o),document.addEventListener("paste",a),document.addEventListener("pointerup",i),()=>{document.removeEventListener("copy",r),document.removeEventListener("cut",o),document.removeEventListener("paste",a),document.removeEventListener("pointerup",i)}},[t,e,n])}/*!
240
240
  * canvas-size
241
241
  * v1.2.6
242
242
  * https://github.com/jhildenbiddle/canvas-size
@@ -408,7 +408,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
408
408
 
409
409
  void main() {
410
410
  outputColor = fillColor;
411
- }`,s=e.createShader(e.FRAGMENT_SHADER);if(!s)throw new Error("Failed to create fragment shader");if(e.shaderSource(s,o),e.compileShader(s),!e.getShaderParameter(s,e.COMPILE_STATUS))throw new Error("Failed to compile fragment shader");const i=e.createProgram();if(!i)throw new Error("Failed to create program");if(e.attachShader(i,r),e.attachShader(i,s),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS))throw new Error("Failed to link program");e.useProgram(i);const a=e.getAttribLocation(i,"shapeVertexPosition");if(a<0)throw new Error("Failed to get shapeVertexPosition attribute location");e.enableVertexAttribArray(a);const l=e.getUniformLocation(i,"canvasPageBounds"),c=e.getUniformLocation(i,"fillColor");if(!e.createBuffer())throw new Error("Failed to create buffer");if(!e.createBuffer())throw new Error("Failed to create buffer");return{context:e,selectedShapes:zh(e,1024),unselectedShapes:zh(e,4096),viewport:zh(e,VF),collaborators:zh(e,1024),prepareTriangles(p,f){e.bindBuffer(e.ARRAY_BUFFER,p.buffer),e.bufferData(e.ARRAY_BUFFER,p.vertices,e.STATIC_DRAW,0,f),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,2,e.FLOAT,!1,0,0)},drawTrianglesTransparently(p){e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,p/2),e.disable(e.BLEND)},drawTriangles(p){e.drawArrays(e.TRIANGLES,0,p/2)},setFillColor(p){e.uniform4fv(c,p)},setCanvasPageBounds(p){e.uniform4fv(l,p)}}}function zh(t,e){const n=t.createBuffer();if(!n)throw new Error("Failed to create buffer");return{buffer:n,vertices:new Float32Array(e)}}function l2(t,e,n){let r=t.vertices.length;for(;r<e+n.length;)r*=2;if(r!=t.vertices.length){const o=new Float32Array(r);o.set(t.vertices),t.vertices=o}t.vertices.set(n,e)}var Nhe=Object.create,YF=Object.defineProperty,zhe=Object.getOwnPropertyDescriptor,Bhe=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),XF=t=>{throw TypeError(t)},qF=(t,e,n)=>e in t?YF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Uhe=t=>[,,,Nhe(null)],ZF=["class","method","getter","setter","accessor","field","value","get","set"],QF=t=>t!==void 0&&typeof t!="function"?XF("Function expected"):t,Hhe=(t,e,n,r,o)=>({kind:ZF[t],name:e,metadata:r,addInitializer:s=>n._?XF("Already initialized"):o.push(QF(s||null))}),Khe=(t,e)=>qF(e,Bhe("metadata"),t[3]),Whe=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Yo=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=ZF[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,zhe(o,n)),y=r.length-1;y>=0;y--)l=Hhe(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,QF(i)&&(v[g]=i);return v&&YF(o,n,v),o},es=(t,e,n)=>qF(t,typeof e!="symbol"?e+"":e,n),JF,e4,t4,n4,r4,o4,s4,i4,a4,l4,br;l4=[Kn],a4=[G],i4=[G],s4=[G],o4=[G],r4=[G],n4=[G],t4=[G],e4=[G],JF=[Kn];class Br{constructor(e,n,r){this.editor=e,this.elem=n,this.container=r,Whe(br,5,this),es(this,"disposables",[]),es(this,"gl"),es(this,"shapeGeometryCache"),es(this,"colors"),es(this,"id",ze()),es(this,"canvasBoundingClientRect",Et("canvasBoundingClientRect",new Z)),es(this,"originPagePoint",new x),es(this,"originPageCenter",new x),es(this,"isInViewport",!1),this.gl=Fhe(n),this.shapeGeometryCache=e.store.createComputedCache("webgl-geometry",o=>{const s=e.getShapeMaskedPageBounds(o.id);if(!s)return null;const i=new Float32Array(12);return Ka(i,0,s.x,s.y,s.w,s.h),i}),this.colors=this._getColors(),this.disposables.push(this._listenForCanvasResize(),jo("minimap render",this.render))}close(){return this.disposables.forEach(e=>e())}_getColors(){const e=getComputedStyle(this.editor.getContainer());return{shapeFill:Lc(e.getPropertyValue("--color-text-3").trim()),selectFill:Lc(e.getPropertyValue("--color-selected").trim()),viewportFill:Lc(e.getPropertyValue("--color-muted-1").trim()),background:Lc(e.getPropertyValue("--color-low").trim())}}updateColors(){this.colors=this._getColors()}getDpr(){return this.editor.getInstanceState().devicePixelRatio}getContentPageBounds(){const e=this.editor.getViewportPageBounds(),n=this.editor.getCurrentPageBounds();return n?Z.Expand(n,e):e}getContentScreenBounds(){const e=this.getContentPageBounds(),n=this.editor.pageToScreen(e.point),r=this.editor.pageToScreen(new x(e.maxX,e.maxY));return new Z(n.x,n.y,r.x-n.x,r.y-n.y)}_getCanvasBoundingRect(){const{x:e,y:n,width:r,height:o}=this.elem.getBoundingClientRect();return new Z(e,n,r,o)}getCanvasScreenBounds(){return this.canvasBoundingClientRect.get()}_listenForCanvasResize(){const e=new ResizeObserver(()=>{const n=this._getCanvasBoundingRect();this.canvasBoundingClientRect.set(n)});return e.observe(this.elem),e.observe(this.container),()=>e.disconnect()}getCanvasSize(){const e=this.canvasBoundingClientRect.get(),n=this.getDpr();return new x(e.width*n,e.height*n)}getCanvasClientPosition(){return this.canvasBoundingClientRect.get().point}getCanvasPageBounds(){const e=this.getCanvasScreenBounds(),n=this.getContentPageBounds(),r=e.width/e.height;let o=n.width,s=o/r;s<n.height&&(s=n.height,o=s*r);const i=new Z(0,0,o,s);return i.center=n.center,i}getZoom(){return this.getCanvasPageBounds().width/this.getCanvasScreenBounds().width}getCanvasPageBoundsArray(){const{x:e,y:n,w:r,h:o}=this.getCanvasPageBounds();return new Float32Array([e,n,r,o])}getMinimapPagePoint(e,n){const r=this.getCanvasPageBounds(),o=this.getCanvasScreenBounds();let s=e-o.x,i=n-o.y;return s*=r.width/o.width,i*=r.height/o.height,s+=r.minX,i+=r.minY,new x(s,i,1)}minimapScreenPointToPagePoint(e,n,r=!1,o=!1){const{editor:s}=this,i=s.getViewportPageBounds();let{x:a,y:l}=this.getMinimapPagePoint(e,n);if(o){const c=this.editor.getCurrentPageBounds()??new Z,u=c.minX-i.width/2,h=c.maxX+i.width/2,p=c.minY-i.height/2,f=c.maxY+i.height/2,g=Math.max(0,u+i.width-a),m=Math.max(0,-(h-i.width-a)),v=Math.max(0,p+i.height-l),y=Math.max(0,-(f-i.height-l));a+=(g-m)/2,l+=(v-y)/2,a=zt(a,u,h),l=zt(l,p,f)}if(r){const{originPagePoint:c}=this,u=Math.abs(a-c.x),h=Math.abs(l-c.y);u>h?l=c.y:a=c.x}return new x(a,l)}render(){const e=this.gl.context,n=this.getCanvasSize();this.gl.setCanvasPageBounds(this.getCanvasPageBoundsArray()),this.elem.width=n.x,this.elem.height=n.y,e.viewport(0,0,n.x,n.y),e.clearColor(this.colors.background[0],this.colors.background[1],this.colors.background[2],1),e.clear(e.COLOR_BUFFER_BIT);const r=new Set(this.editor.getSelectedShapeIds()),o=this.colors;let s=0,i=0;const a=this.editor.getCurrentPageShapeIdsSorted();for(let l=0,c=a.length;l<c;l++){const u=a[l],h=this.shapeGeometryCache.get(u);if(!h)continue;const p=h.length;r.has(u)?(l2(this.gl.selectedShapes,s,h),s+=p):(l2(this.gl.unselectedShapes,i,h),i+=p)}this.drawShapes(this.gl.unselectedShapes,i,o.shapeFill),this.drawShapes(this.gl.selectedShapes,s,o.selectFill),this.drawViewport(),this.drawCollaborators()}drawShapes(e,n,r){this.gl.prepareTriangles(e,n),this.gl.setFillColor(r),this.gl.drawTriangles(n)}drawViewport(){const e=this.editor.getViewportPageBounds(),n=$he(this.gl.viewport.vertices,e,4*this.getZoom());this.gl.prepareTriangles(this.gl.viewport,n),this.gl.setFillColor(this.colors.viewportFill),this.gl.drawTrianglesTransparently(n),Ge.isSafari&&(this.gl.drawTrianglesTransparently(n),this.gl.drawTrianglesTransparently(n),this.gl.drawTrianglesTransparently(n))}drawCollaborators(){const e=this.editor.getCollaboratorsOnCurrentPage();if(!e.length)return;const n=20,r=n*6,o=r*e.length;this.gl.collaborators.vertices.length<o&&(this.gl.collaborators.vertices=new Float32Array(o));const s=this.gl.collaborators.vertices;let i=0;const a=this.getZoom();for(const{cursor:l}of e)l&&(Ha(s,{center:x.From(l),radius:3*a,offset:i,numArcSegments:n}),i+=r);this.gl.prepareTriangles(this.gl.collaborators,o),i=0;for(const{color:l}of e)this.gl.setFillColor(Lc(l)),this.gl.context.drawArrays(this.gl.context.TRIANGLES,i/2,r/2),i+=r}}br=Uhe();Yo(br,1,"close",l4,Br);Yo(br,1,"getDpr",a4,Br);Yo(br,1,"getContentPageBounds",i4,Br);Yo(br,1,"getContentScreenBounds",s4,Br);Yo(br,1,"getCanvasSize",o4,Br);Yo(br,1,"getCanvasClientPosition",r4,Br);Yo(br,1,"getCanvasPageBounds",n4,Br);Yo(br,1,"getZoom",t4,Br);Yo(br,1,"getCanvasPageBoundsArray",e4,Br);Yo(br,1,"render",JF,Br);Khe(br,Br);function Ghe(){const t=z(),e=Mt(),n=w.useRef(null),r=w.useRef(!1),o=w.useRef();w.useEffect(()=>{try{const u=new Br(t,n.current,e);return o.current=u,o.current.close}catch(u){t.annotateError(u,{origin:"minimap",willCrashApp:!1}),t.timers.setTimeout(()=>{throw u})}},[t,e]);const s=w.useCallback(u=>{if(!t.getCurrentPageShapeIds().size||!o.current)return;const h=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),p=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);o.current.originPagePoint.setTo(p),o.current.originPageCenter.setTo(t.getViewportPageBounds().center),t.centerOnPoint(h,{animation:{duration:t.options.animationMediumMs}})},[t]),i=w.useCallback(u=>{if(!o.current)return;const h=u.currentTarget;if(dd(h,u),!t.getCurrentPageShapeIds().size)return;r.current=!0,o.current.isInViewport=!1;const p=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),f=t.getViewportPageBounds(),g=o.current.getContentPageBounds();if(new Z(g.x-f.width/2,g.y-f.height/2,g.width+f.width,g.height+f.height).containsPoint(p)&&!f.containsPoint(p)){o.current.isInViewport=f.containsPoint(p);const y=x.Sub(f.center,f.point),S=x.Add(p,y);o.current.originPagePoint.setTo(S),o.current.originPageCenter.setTo(p),t.centerOnPoint(p,{animation:{duration:t.options.animationMediumMs}})}else{const y=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);o.current.isInViewport=f.containsPoint(y),o.current.originPagePoint.setTo(y),o.current.originPageCenter.setTo(f.center)}function v(y){h&&hd(h,y),r.current=!1,document.body.removeEventListener("pointerup",v)}document.body.addEventListener("pointerup",v)},[t]),a=w.useCallback(u=>{if(!o.current)return;const h=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,u.shiftKey,!0);if(r.current){if(o.current.isInViewport){const m=o.current.originPagePoint.clone().sub(o.current.originPageCenter);t.centerOnPoint(x.Sub(h,m));return}t.centerOnPoint(h)}const p=o.current.getMinimapPagePoint(u.clientX,u.clientY),f=t.pageToScreen(p),g={type:"pointer",target:"canvas",name:"pointer_move",...lr(u),point:f,isPen:t.getInstanceState().isPenMode};t.dispatch(g)},[t]),l=w.useCallback(u=>{const h=xj(u);t.dispatch({type:"wheel",name:"wheel",delta:h,point:new x(u.clientX,u.clientY),shiftKey:u.shiftKey,altKey:u.altKey,ctrlKey:u.metaKey||u.ctrlKey,metaKey:u.metaKey,accelKey:un(u)})},[t]),c=xd();return w.useEffect(()=>{t.timers.setTimeout(()=>{var u,h;(u=o.current)==null||u.updateColors(),(h=o.current)==null||h.render()})},[c,t]),d.jsx("div",{className:"tlui-minimap",children:d.jsx("canvas",{role:"img","aria-label":"minimap",ref:n,className:"tlui-minimap__canvas",onDoubleClick:s,onPointerMove:a,onPointerDown:i,onWheelCapture:l})})}function Vhe(t,e){const[n,r]=Te.useState(e);Te.useLayoutEffect(()=>{const s=_w(t);if(s)try{r(JSON.parse(s))}catch{console.error(`Could not restore value ${t} from local storage.`)}},[t]);const o=Te.useCallback(s=>{r(i=>{const a=typeof s=="function"?s(i):s;return Iw(t,JSON.stringify(a)),a})},[t]);return[n,o]}const Yhe=w.memo(function(){const e=Ea(),n=Ee(),r=An(),o=w.useRef(null);Mi(o);const[s,i]=Vhe("minimap",!0),a=w.useCallback(()=>{i(u=>!u)},[i]),{ZoomMenu:l,Minimap:c}=Di();return r<St.MOBILE?null:d.jsxs("div",{ref:o,className:"tlui-navigation-panel",children:[d.jsx("div",{className:"tlui-buttons__horizontal",children:l&&r<St.TABLET?d.jsx(l,{}):s?d.jsxs(d.Fragment,{children:[l&&d.jsx(l,{}),c&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:n("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:a,children:d.jsx(be,{icon:s?"chevrons-ne":"chevrons-sw"})})]}):d.jsxs(d.Fragment,{children:[d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-out",title:`${n(Xu(e["zoom-out"].label))} ${Xx(e["zoom-out"].kbd)}`,onClick:()=>e["zoom-out"].onSelect("navigation-zone"),children:d.jsx(be,{icon:"minus"})}),l&&d.jsx(l,{}),d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-in",title:`${n(Xu(e["zoom-in"].label))} ${Xx(e["zoom-in"].kbd)}`,onClick:()=>e["zoom-in"].onSelect("navigation-zone"),children:d.jsx(be,{icon:"plus"})}),c&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:n("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:a,children:d.jsx(be,{icon:s?"chevrons-ne":"chevrons-sw"})})]})}),c&&r>=St.TABLET&&!s&&d.jsx(c,{})]})}),Xhe=function({name:e,id:n,isCurrentPage:r,onCancel:o}){const s=z(),i=Qt(),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(()=>{l.current=s.markHistoryStoppingPoint("rename page")},[s]),u=w.useCallback(p=>{s.renamePage(n,p||"New Page"),i("rename-page",{source:"page-menu"})},[s,n,i]),h=w.useCallback(()=>{l.current&&s.bailToMark(l.current),o()},[s,o]);return d.jsx(fm,{className:"tlui-page-menu__item__input",ref:p=>a.current=p,defaultValue:e,onValueChange:u,onCancel:h,onFocus:c,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:r,autoSelect:!0})},g0=(t,e,n,r,o)=>{let s;const i=t.getPages(),a=n>r?i[r-1]:i[r],l=n>r?i[r]:i[r+1];a&&!l?s=Io(a.index):!a&&l?s=i7(i[0].index):s=$u(a.index,l.index),s!==i[n].index&&(t.markHistoryStoppingPoint("moving page"),t.updatePage({id:e,index:s}),o("move-page",{source:"page-menu"}))},c2=qt(function({index:e,listSize:n,item:r,onRename:o}){const s=z(),i=Ee(),a=s.getPages(),l=Qt(),c=w.useCallback(()=>{s.markHistoryStoppingPoint("creating page");const f=yr.createId();s.duplicatePage(r.id,f),l("duplicate-page",{source:"page-menu"})},[s,r,l]),u=w.useCallback(()=>{g0(s,r.id,e,e-1,l)},[s,r,e,l]),h=w.useCallback(()=>{g0(s,r.id,e,e+1,l)},[s,r,e,l]),p=w.useCallback(()=>{s.markHistoryStoppingPoint("deleting page"),s.deletePage(r.id),l("delete-page",{source:"page-menu"})},[s,r,l]);return d.jsxs(ga,{id:`page item submenu ${e}`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon",title:i("page-menu.submenu.title"),children:d.jsx(be,{icon:"dots-vertical",small:!0})})}),d.jsx(ya,{alignOffset:0,side:"right",sideOffset:-4,children:d.jsxs(Fr,{type:"menu",sourceId:"page-menu",children:[d.jsxs(ve,{id:"modify",children:[o&&d.jsx(Ht,{id:"rename",label:"page-menu.submenu.rename",onSelect:o}),d.jsx(Ht,{id:"duplicate",label:"page-menu.submenu.duplicate-page",onSelect:c,disabled:a.length>=s.options.maxPages}),e>0&&d.jsx(Ht,{id:"move-up",onSelect:u,label:"page-menu.submenu.move-up"}),e<n-1&&d.jsx(Ht,{id:"move-down",label:"page-menu.submenu.move-down",onSelect:h})]}),n>1&&d.jsx(ve,{id:"delete",children:d.jsx(Ht,{id:"delete",onSelect:p,label:"page-menu.submenu.delete"})})]})})]})}),qhe=w.memo(function(){const e=z(),n=Qt(),r=Ee(),o=An(),s=w.useCallback(()=>y(!1),[]),[i,a]=Ms("page-menu",s),l=36,c=w.useRef(null),u=U("pages",()=>e.getPages(),[e]),h=U("currentPage",()=>e.getCurrentPage(),[e]),p=U("currentPageId",()=>e.getCurrentPageId(),[e]),f=wr(),g=U("maxPageCountReached",()=>e.getPages().length>=e.options.maxPages,[e]),m=U("isCoarsePointer",()=>e.getInstanceState().isCoarsePointer,[e]),[v,y]=w.useState(!1),S=w.useCallback(()=>{f||y(M=>!M)},[f]),b=w.useRef({isPointing:!1,status:"idle",pointing:null,startY:0,startIndex:0,dragIndex:0}),[P,C]=w.useState(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])));w.useLayoutEffect(()=>{C(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])))},[l,u]),w.useEffect(()=>{i&&e.timers.requestAnimationFrame(()=>{const M=document.querySelector(`[data-testid="page-menu-item-${p}"]`);if(M){const O=c.current;if(!O)return;const F=M.offsetTop,B=O.scrollTop;F<B&&O.scrollTo({top:F});const K=F+l,R=O.scrollTop+O.offsetHeight;K>R&&O.scrollTo({top:K-O.offsetHeight})}})},[l,p,i,e]);const _=w.useCallback(M=>{const{clientY:O,currentTarget:F}=M,{dataset:{id:B,index:K}}=F;if(!B||!K)return;const R=b.current;dd(M.currentTarget,M),R.status="pointing",R.pointing={id:B,index:+K};const Y=P[B].y;R.startY=O,R.startIndex=Math.max(0,Math.min(Math.round(Y/l),u.length-1))},[l,u.length,P]),E=w.useCallback(M=>{const O=b.current;if(O.status==="pointing"){const{clientY:F}=M,B=F-O.startY;Math.abs(B)>5&&(O.status="dragging")}if(O.status==="dragging"){const{clientY:F}=M,B=F-O.startY,K=P[O.pointing.id],{startIndex:R,pointing:H}=O,Y=K.y+B,ee=Math.max(0,Math.min(Math.round(Y/l),u.length-1)),he={...P};if(he[H.id]={y:K.y,offsetY:B,isSelected:!0},ee!==O.dragIndex){O.dragIndex=ee;for(let ue=0;ue<u.length;ue++){const ke=u[ue];if(ke.id===O.pointing.id)continue;let{y:se}=he[ke.id];ee===R?se=ue*l:ee<R?ee<=ue&&ue<R?se=(ue+1)*l:se=ue*l:ee>R&&(ee>=ue&&ue>R?se=(ue-1)*l:se=ue*l),se!==he[ke.id].y&&(he[ke.id]={y:se,offsetY:0,isSelected:!0})}}C(he)}},[l,u,P]),k=w.useCallback(M=>{const O=b.current;if(O.status==="dragging"){const{id:F,index:B}=O.pointing;g0(e,F,B,O.dragIndex,n)}hd(M.currentTarget,M),O.status="idle"},[e,n]),D=w.useCallback(M=>{const O=b.current;M.key==="Escape"&&(O.status==="dragging"&&C(Object.fromEntries(u.map((F,B)=>[F.id,{y:B*l,offsetY:0,isSelected:!1}]))),O.status="idle")},[l,u]),T=w.useCallback(()=>{f||(e.run(()=>{e.markHistoryStoppingPoint("creating page");const M=yr.createId();e.createPage({name:r("page-menu.new-page-initial-name"),id:M}),e.setCurrentPage(M),y(!0)}),n("new-page",{source:"page-menu"}))},[e,r,f,n]),j=w.useCallback(M=>{e.setCurrentPage(M),n("change-page",{source:"page-menu"})},[e,n]),$=w.useCallback((M,O)=>{e.renamePage(M,O),n("rename-page",{source:"page-menu"})},[e,n]);return d.jsxs(Gb,{id:"pages",onOpenChange:a,open:i,children:[d.jsx(Vb,{"data-testid":"main.page-menu",children:d.jsxs(ce,{type:"menu",title:h.name,"data-testid":"page-menu.button",className:"tlui-page-menu__trigger",children:[d.jsx("div",{className:"tlui-page-menu__name",children:h.name}),d.jsx(be,{icon:"chevron-down",small:!0})]})}),d.jsx(Yb,{side:"bottom",align:"start",sideOffset:6,disableEscapeKeyDown:v,children:d.jsxs("div",{className:"tlui-page-menu__wrapper",children:[d.jsxs("div",{className:"tlui-page-menu__header",children:[d.jsx("div",{className:"tlui-page-menu__header__title",children:r("page-menu.title")}),!f&&d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsx(ce,{type:"icon","data-testid":"page-menu.edit",title:r(v?"page-menu.edit-done":"page-menu.edit-start"),onClick:S,children:d.jsx(be,{icon:v?"check":"edit"})}),d.jsx(ce,{type:"icon","data-testid":"page-menu.create",title:r(g?"page-menu.max-page-count-reached":"page-menu.create-new-page"),disabled:g,onClick:T,children:d.jsx(be,{icon:"plus"})})]})]}),d.jsx("div",{"data-testid":"page-menu.list",className:"tlui-page-menu__list tlui-menu__group",style:{height:l*u.length+4},ref:c,children:u.map((M,O)=>{const F=P[M.id]??{position:O*40,offsetY:0};return v?d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page_menu__item__sortable",style:{zIndex:M.id===h.id?888:O,transform:`translate(0px, ${F.y+F.offsetY}px)`},children:[d.jsx(ce,{type:"icon",tabIndex:-1,className:"tlui-page_menu__item__sortable__handle",onPointerDown:_,onPointerUp:k,onPointerMove:E,onKeyDown:D,"data-id":M.id,"data-index":O,children:d.jsx(be,{icon:"drag-handle-dots"})}),o<St.TABLET_SM&&m?d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>{const B=window.prompt("Rename page",M.name);B&&B!==M.name&&$(M.id,B)},onDoubleClick:S,children:[d.jsx(f0,{checked:M.id===h.id}),d.jsx(Pt,{children:M.name})]}):d.jsx("div",{className:"tlui-page_menu__item__sortable__title",style:{height:l},children:d.jsx(Xhe,{id:M.id,name:M.name,isCurrentPage:M.id===h.id,onCancel:()=>{y(!1),e.menus.clearOpenMenus()}})}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu","data-isediting":v,children:d.jsx(c2,{index:O,item:M,listSize:u.length})})]},M.id+"_editing"):d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page-menu__item",children:[d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>j(M.id),onDoubleClick:S,title:r("page-menu.go-to-page"),children:[d.jsx(f0,{checked:M.id===h.id}),d.jsx(Pt,{children:M.name})]}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu",children:d.jsx(c2,{index:O,item:M,listSize:u.length,onRename:()=>{if(Ge.isIos){const B=window.prompt("Rename page",M.name);B&&B!==M.name&&$(M.id,B)}else y(!0),p!==M.id&&j(M.id)}})})]},M.id)})})]})})]})});function Zhe(){const t=z(),e=wr(),n=U("should display quick actions",()=>t.isInAny("select","hand","zoom"),[t]);if(!(e&&!n))return d.jsxs(d.Fragment,{children:[d.jsx(Jhe,{}),d.jsx(Qhe,{})]})}function Qhe(){const t=jn(1),e=As(),n=t&&e;return d.jsxs(d.Fragment,{children:[d.jsx(W,{actionId:"delete",disabled:!n}),d.jsx(W,{actionId:"duplicate",disabled:!n})]})}function Jhe(){const t=IF(),e=_F();return d.jsxs(d.Fragment,{children:[d.jsx(W,{actionId:"undo",disabled:!t}),d.jsx(W,{actionId:"redo",disabled:!e})]})}const epe=w.memo(function({children:e}){const n=e??d.jsx(Zhe,{});return d.jsx(Fr,{type:"small-icons",sourceId:"quick-actions",children:n})});function tpe({userId:t}){const e=Lg(t);return e?d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:e.color},children:e.userName==="New User"?"":e.userName[0]??""},t):null}const npe=qt(function({userId:e}){const n=z(),r=Ee(),o=Qt(),s=Lg(e),i=w.useCallback(()=>{n.getInstanceState().followingUserId===e?(n.stopFollowingUser(),o("stop-following",{source:"people-menu"})):(n.startFollowingUser(e),o("start-following",{source:"people-menu"}))},[n,e,o]),a=(s==null?void 0:s.followingUserId)===n.user.getId(),l=n.getInstanceState().followingUserId===e;return s?d.jsxs("div",{className:"tlui-people-menu__item tlui-buttons__horizontal",children:[d.jsxs(ce,{type:"menu",className:"tlui-people-menu__item__button",onClick:()=>n.zoomToUser(e),onDoubleClick:i,children:[d.jsx(Bo,{icon:"color",color:s.color}),d.jsx("div",{className:"tlui-people-menu__name",children:s.userName??"New User"})]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__item__follow",title:r(a?"people-menu.leading":l?"people-menu.following":"people-menu.follow"),onClick:i,disabled:a,"data-active":l||a,children:d.jsx(be,{icon:a?"leading":l?"following":"follow"})})]}):null});function rpe({count:t}){return d.jsx("div",{className:"tlui-people-menu__more",children:"+"+Math.abs(t)})}const ope=qt(function(){const e=z(),n=Mt(),r=Ee(),o=Qt(),s=w.useRef(!1),[i,a]=w.useState(!1),l=w.useCallback(m=>{a(m)},[]),c=e.user.getColor(),u=w.useCallback(m=>{e.user.updateUserPreferences({color:m}),o("set-color",{source:"people-menu"})},[e,o]),{handleButtonClick:h,handleButtonPointerDown:p,handleButtonPointerEnter:f,handleButtonPointerUp:g}=Te.useMemo(()=>{const m=()=>{s.current=!1,window.removeEventListener("pointerup",m)};return{handleButtonClick:P=>{const{id:C}=P.currentTarget.dataset;C&&c!==C&&u(C)},handleButtonPointerDown:P=>{const{id:C}=P.currentTarget.dataset;C&&(u(C),s.current=!0,window.addEventListener("pointerup",m))},handleButtonPointerEnter:P=>{if(!s.current)return;const{id:C}=P.currentTarget.dataset;C&&u(C)},handleButtonPointerUp:P=>{const{id:C}=P.currentTarget.dataset;C&&u(C)}}},[c,u]);return d.jsxs(Ub,{onOpenChange:l,open:i,children:[d.jsx(Hb,{dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__color",style:{color:e.user.getColor()},title:r("people-menu.change-color"),children:d.jsx(be,{icon:"color"})})}),d.jsx(Kb,{container:n,children:d.jsx(Wb,{dir:"ltr",className:"tlui-menu tlui-people-menu__user__color-picker",align:"start",side:"left",sideOffset:8,children:d.jsx("div",{className:"tlui-buttons__grid",children:Px.map(m=>d.jsx(ce,{type:"icon","data-id":m,"data-testid":m,"aria-label":m,"data-state":c===m?"hinted":void 0,title:m,className:"tlui-button-grid__button",style:{color:m},onPointerEnter:f,onPointerDown:p,onPointerUp:g,onClick:h,children:d.jsx(be,{icon:"color"})},m))})})})]})});function spe(){const t=z(),e=Qt(),n=U("userName",()=>t.user.getName(),[]),r=Ee(),o=w.useRef(n),s=w.useRef(n),[i,a]=w.useState(!1),l=w.useCallback(()=>{a(p=>!p)},[]),c=w.useCallback(p=>{s.current=p,t.user.updateUserPreferences({name:p})},[t]),u=w.useCallback(()=>{o.current!==s.current&&(e("change-user-name",{source:"people-menu"}),o.current=s.current)},[e]),h=w.useCallback(()=>{a(!1),t.user.updateUserPreferences({name:o.current}),t.menus.clearOpenMenus()},[t]);return d.jsxs("div",{className:"tlui-people-menu__user",children:[d.jsx(ope,{}),i?d.jsx(fm,{className:"tlui-people-menu__user__input",defaultValue:n,onValueChange:c,onComplete:l,onCancel:h,onBlur:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:!0,autoSelect:!0}):d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"tlui-people-menu__user__name",onDoubleClick:()=>{i||a(!0)},children:n}),n==="New User"?d.jsx("div",{className:"tlui-people-menu__user__label",children:r("people-menu.user")}):null]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__edit","data-testid":"people-menu.change-name",title:r("people-menu.change-name"),onClick:l,children:d.jsx(be,{icon:i?"check":"edit"})})]})}function ipe({displayUserWhenAlone:t,children:e}){const n=Ee(),r=Mt(),o=z(),s=Pj(),i=U("user",()=>o.user.getColor(),[o]),a=U("user",()=>o.user.getName(),[o]),[l,c]=Ms("people menu");return d.jsxs(Ub,{onOpenChange:c,open:l,children:[d.jsx(Hb,{dir:"ltr",asChild:!0,children:d.jsxs("button",{className:"tlui-people-menu__avatars-button",title:n("people-menu.title"),children:[s.length>5&&d.jsx(rpe,{count:s.length-5}),d.jsxs("div",{className:"tlui-people-menu__avatars",children:[s.slice(-5).map(u=>d.jsx(tpe,{userId:u},u)),(t||s.length>0)&&d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:i},children:a==="New User"?"":a[0]??""})]})]})}),d.jsx(Kb,{container:r,children:d.jsx(Wb,{dir:"ltr",className:"tlui-menu",side:"bottom",sideOffset:2,collisionPadding:4,onEscapeKeyDown:xe,children:d.jsxs("div",{className:"tlui-people-menu__wrapper",children:[d.jsx("div",{className:"tlui-people-menu__section",children:d.jsx(spe,{})}),s.length>0&&d.jsx("div",{className:"tlui-people-menu__section",children:s.map(u=>d.jsx(npe,{userId:u},u+"_presence"))}),e]})})})]})}function ape(){return d.jsx("div",{className:"tlui-share-zone",draggable:!1,children:d.jsx(ipe,{displayUserWhenAlone:!0})})}const lpe=Object.freeze([mr,ca,ua,Fo]);function c4(t=lpe){const e=z();return U("getRelevantStyles",()=>{var s;const n=new Tx(e.getSharedStyles()),r=!!((s=e.root.getCurrent())!=null&&s.shapeType),o=e.isIn("select")&&e.getSelectedShapeIds().length>0;if(n.size===0&&e.isIn("select")&&e.getSelectedShapeIds().length===0)for(const i of t)n.applyValue(i,e.getStyleForNextShape(i));return r||o||n.size>0?n:null},[e])}const jr={color:[{value:"black",icon:"color"},{value:"grey",icon:"color"},{value:"light-violet",icon:"color"},{value:"violet",icon:"color"},{value:"blue",icon:"color"},{value:"light-blue",icon:"color"},{value:"yellow",icon:"color"},{value:"orange",icon:"color"},{value:"green",icon:"color"},{value:"light-green",icon:"color"},{value:"light-red",icon:"color"},{value:"red",icon:"color"}],fill:[{value:"none",icon:"fill-none"},{value:"semi",icon:"fill-semi"},{value:"solid",icon:"fill-solid"},{value:"pattern",icon:"fill-pattern"}],dash:[{value:"draw",icon:"dash-draw"},{value:"dashed",icon:"dash-dashed"},{value:"dotted",icon:"dash-dotted"},{value:"solid",icon:"dash-solid"}],size:[{value:"s",icon:"size-small"},{value:"m",icon:"size-medium"},{value:"l",icon:"size-large"},{value:"xl",icon:"size-extra-large"}],font:[{value:"draw",icon:"font-draw"},{value:"sans",icon:"font-sans"},{value:"serif",icon:"font-serif"},{value:"mono",icon:"font-mono"}],textAlign:[{value:"start",icon:"text-align-left"},{value:"middle",icon:"text-align-center"},{value:"end",icon:"text-align-right"}],horizontalAlign:[{value:"start",icon:"horizontal-align-start"},{value:"middle",icon:"horizontal-align-middle"},{value:"end",icon:"horizontal-align-end"}],verticalAlign:[{value:"start",icon:"vertical-align-start"},{value:"middle",icon:"vertical-align-middle"},{value:"end",icon:"vertical-align-end"}],geo:[{value:"rectangle",icon:"geo-rectangle"},{value:"ellipse",icon:"geo-ellipse"},{value:"triangle",icon:"geo-triangle"},{value:"diamond",icon:"geo-diamond"},{value:"star",icon:"geo-star"},{value:"pentagon",icon:"geo-pentagon"},{value:"hexagon",icon:"geo-hexagon"},{value:"octagon",icon:"geo-octagon"},{value:"rhombus",icon:"geo-rhombus"},{value:"rhombus-2",icon:"geo-rhombus-2"},{value:"oval",icon:"geo-oval"},{value:"trapezoid",icon:"geo-trapezoid"},{value:"arrow-left",icon:"geo-arrow-left"},{value:"arrow-up",icon:"geo-arrow-up"},{value:"arrow-down",icon:"geo-arrow-down"},{value:"arrow-right",icon:"geo-arrow-right"},{value:"cloud",icon:"geo-cloud"},{value:"x-box",icon:"geo-x-box"},{value:"check-box",icon:"geo-check-box"},{value:"heart",icon:"geo-heart"}],arrowheadStart:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],arrowheadEnd:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],spline:[{value:"line",icon:"spline-line"},{value:"cubic",icon:"spline-cubic"}]},Yi=w.memo(function(e){const{uiType:n,items:r,title:o,style:s,value:i,onValueChange:a,onHistoryMark:l,theme:c}=e,u=Ee(),h=w.useRef(!1),p=w.useRef(null),{handleButtonClick:f,handleButtonPointerDown:g,handleButtonPointerEnter:m,handleButtonPointerUp:v}=w.useMemo(()=>{const y=()=>{h.current=!1,window.removeEventListener("pointerup",y);const _=p.current;_&&["TEXTAREA","INPUT"].includes(_.nodeName)&&_.focus(),p.current=null};return{handleButtonClick:_=>{const{id:E}=_.currentTarget.dataset;i.type==="shared"&&i.value===E||(l==null||l("point picker item"),a(s,E))},handleButtonPointerDown:_=>{const{id:E}=_.currentTarget.dataset;l==null||l("point picker item"),a(s,E),h.current=!0,p.current=document.activeElement,window.addEventListener("pointerup",y)},handleButtonPointerEnter:_=>{if(!h.current)return;const{id:E}=_.currentTarget.dataset;a(s,E)},handleButtonPointerUp:_=>{const{id:E}=_.currentTarget.dataset;i.type==="shared"&&i.value===E||a(s,E)}}},[i,l,a,s]);return d.jsx("div",{"data-testid":`style.${n}`,className:le("tlui-buttons__grid"),children:r.map(y=>d.jsx(ce,{type:"icon","data-id":y.value,"data-testid":`style.${n}.${y.value}`,"aria-label":y.value,"data-state":i.type==="shared"&&i.value===y.value?"hinted":void 0,title:o+" — "+u(`${n}-style.${y.value}`),className:le("tlui-button-grid__button"),style:s===mr?{color:c[y.value].solid}:void 0,onPointerEnter:m,onPointerDown:g,onPointerUp:v,onClick:f,children:d.jsx(be,{icon:y.icon})},y.value))})});function u4(t,[e,n]){return Math.min(n,Math.max(e,t))}function cpe(t){const e=w.useRef({value:t,previous:t});return w.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var d4=["PageUp","PageDown"],h4=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],p4={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},lc="Slider",[m0,upe,dpe]=Jg(lc),[f4,Dge]=Go(lc,[dpe]),[hpe,Tm]=f4(lc),g4=w.forwardRef((t,e)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,form:g,...m}=t,v=w.useRef(new Set),y=w.useRef(0),b=i==="horizontal"?ppe:fpe,[P=[],C]=Ai({prop:u,defaultProp:c,onChange:j=>{var M;(M=[...v.current][y.current])==null||M.focus(),h(j)}}),_=w.useRef(P);function E(j){const $=vpe(P,j);T(j,$)}function k(j){T(j,y.current)}function D(){const j=_.current[y.current];P[y.current]!==j&&p(P)}function T(j,$,{commit:M}={commit:!1}){const O=Ppe(s),F=Cpe(Math.round((j-r)/s)*s+r,O),B=u4(F,[r,o]);C((K=[])=>{const R=ype(K,B,$);if(bpe(R,l*s)){y.current=R.indexOf(B);const H=String(R)!==String(K);return H&&M&&p(R),H?R:K}else return K})}return d.jsx(hpe,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:v.current,values:P,orientation:i,form:g,children:d.jsx(m0.Provider,{scope:t.__scopeSlider,children:d.jsx(m0.Slot,{scope:t.__scopeSlider,children:d.jsx(b,{"aria-disabled":a,"data-disabled":a?"":void 0,...m,ref:e,onPointerDown:oe(m.onPointerDown,()=>{a||(_.current=P)}),min:r,max:o,inverted:f,onSlideStart:a?void 0:E,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&T(r,0,{commit:!0}),onEndKeyDown:()=>!a&&T(o,P.length-1,{commit:!0}),onStepKeyDown:({event:j,direction:$})=>{if(!a){const F=d4.includes(j.key)||j.shiftKey&&h4.includes(j.key)?10:1,B=y.current,K=P[B],R=s*F*$;T(K+R,B,{commit:!0})}}})})})})});g4.displayName=lc;var[m4,y4]=f4(lc,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ppe=w.forwardRef((t,e)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=t,[h,p]=w.useState(null),f=Ze(e,b=>p(b)),g=w.useRef(void 0),m=F1(o),v=m==="ltr",y=v&&!s||!v&&s;function S(b){const P=g.current||h.getBoundingClientRect(),C=[0,P.width],E=qb(C,y?[n,r]:[r,n]);return g.current=P,E(b-P.left)}return d.jsx(m4,{scope:t.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:d.jsx(S4,{dir:m,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{const P=S(b.clientX);i==null||i(P)},onSlideMove:b=>{const P=S(b.clientX);a==null||a(P)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:b=>{const C=p4[y?"from-left":"from-right"].includes(b.key);c==null||c({event:b,direction:C?-1:1})}})})}),fpe=w.forwardRef((t,e)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=t,u=w.useRef(null),h=Ze(e,u),p=w.useRef(void 0),f=!o;function g(m){const v=p.current||u.current.getBoundingClientRect(),y=[0,v.height],b=qb(y,f?[r,n]:[n,r]);return p.current=v,b(m-v.top)}return d.jsx(m4,{scope:t.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:d.jsx(S4,{"data-orientation":"vertical",...c,ref:h,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{const v=g(m.clientY);s==null||s(v)},onSlideMove:m=>{const v=g(m.clientY);i==null||i(v)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:m=>{const y=p4[f?"from-bottom":"from-top"].includes(m.key);l==null||l({event:m,direction:y?-1:1})}})})}),S4=w.forwardRef((t,e)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=t,u=Tm(lc,n);return d.jsx(Ae.span,{...c,ref:e,onKeyDown:oe(t.onKeyDown,h=>{h.key==="Home"?(i(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):d4.concat(h4).includes(h.key)&&(l(h),h.preventDefault())}),onPointerDown:oe(t.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:oe(t.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&o(h)}),onPointerUp:oe(t.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),s(h))})})}),v4="SliderTrack",x4=w.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,o=Tm(v4,n);return d.jsx(Ae.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:e})});x4.displayName=v4;var y0="SliderRange",w4=w.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,o=Tm(y0,n),s=y4(y0,n),i=w.useRef(null),a=Ze(e,i),l=o.values.length,c=o.values.map(p=>P4(p,o.min,o.max)),u=l>1?Math.min(...c):0,h=100-Math.max(...c);return d.jsx(Ae.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...t.style,[s.startEdge]:u+"%",[s.endEdge]:h+"%"}})});w4.displayName=y0;var S0="SliderThumb",b4=w.forwardRef((t,e)=>{const n=upe(t.__scopeSlider),[r,o]=w.useState(null),s=Ze(e,a=>o(a)),i=w.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return d.jsx(gpe,{...t,ref:s,index:i})}),gpe=w.forwardRef((t,e)=>{const{__scopeSlider:n,index:r,name:o,...s}=t,i=Tm(S0,n),a=y4(S0,n),[l,c]=w.useState(null),u=Ze(e,S=>c(S)),h=l?i.form||!!l.closest("form"):!0,p=f3(l),f=i.values[r],g=f===void 0?0:P4(f,i.min,i.max),m=Spe(r,i.values.length),v=p==null?void 0:p[a.size],y=v?xpe(v,g,a.direction):0;return w.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[d.jsx(m0.ItemSlot,{scope:t.__scopeSlider,children:d.jsx(Ae.span,{role:"slider","aria-label":t["aria-label"]||m,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:u,style:f===void 0?{display:"none"}:t.style,onFocus:oe(t.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),h&&d.jsx(mpe,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},r)]})});b4.displayName=S0;var mpe=t=>{const{value:e,...n}=t,r=w.useRef(null),o=cpe(e);return w.useEffect(()=>{const s=r.current,i=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(i,"value").set;if(o!==e&&l){const c=new Event("input",{bubbles:!0});l.call(s,e),s.dispatchEvent(c)}},[o,e]),d.jsx("input",{style:{display:"none"},...n,ref:r,defaultValue:e})};function ype(t=[],e,n){const r=[...t];return r[n]=e,r.sort((o,s)=>o-s)}function P4(t,e,n){const s=100/(n-e)*(t-e);return u4(s,[0,100])}function Spe(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function vpe(t,e){if(t.length===1)return 0;const n=t.map(o=>Math.abs(o-e)),r=Math.min(...n);return n.indexOf(r)}function xpe(t,e,n){const r=t/2,s=qb([0,50],[0,r]);return(r-s(e)*n)*n}function wpe(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function bpe(t,e){if(e>0){const n=wpe(t);return Math.min(...n)>=e}return!0}function qb(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function Ppe(t){return(String(t).split(".")[1]||"").length}function Cpe(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}var _pe=g4,Ipe=x4,Epe=w4,kpe=b4;const Tpe=w.memo(function({onHistoryMark:e,title:n,steps:r,value:o,label:s,onValueChange:i,["data-testid"]:a}){const l=Ee(),c=w.useCallback(p=>{i(p[0])},[i]),u=w.useCallback(()=>{e("click slider")},[e]),h=w.useCallback(()=>{o&&i(o)},[o,i]);return d.jsx("div",{className:"tlui-slider__container",children:d.jsxs(_pe,{"data-testid":a,className:"tlui-slider","area-label":"Opacity",dir:"ltr",min:0,max:r,step:1,value:o?[o]:void 0,onPointerDown:u,onValueChange:c,onPointerUp:h,title:n+" — "+l(s),children:[d.jsx(Ipe,{className:"tlui-slider__track",dir:"ltr",children:o!==null&&d.jsx(Epe,{className:"tlui-slider__range",dir:"ltr"})}),o!==null&&d.jsx(kpe,{className:"tlui-slider__thumb",dir:"ltr"})]})})});function Mpe({label:t,uiTypeA:e,uiTypeB:n,labelA:r,labelB:o,itemsA:s,itemsB:i,styleA:a,styleB:l,valueA:c,valueB:u,onValueChange:h}){const p=Ee(),f=w.useMemo(()=>{var m;return((m=s.find(v=>c.type==="shared"&&c.value===v.value))==null?void 0:m.icon)??"mixed"},[s,c]),g=w.useMemo(()=>{var m;return((m=i.find(v=>u.type==="shared"&&u.value===v.value))==null?void 0:m.icon)??"mixed"},[i,u]);return c===void 0&&u===void 0?null:d.jsxs("div",{className:"tlui-style-panel__double-select-picker",children:[d.jsx("div",{title:p(t),className:"tlui-style-panel__double-select-picker-label",children:p(t)}),d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsxs(ga,{id:`style panel ${e} A`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon","data-testid":`style.${e}`,title:p(r)+" — "+(c===null||c.type==="mixed"?p("style-panel.mixed"):p(`${e}-style.${c.value}`)),children:d.jsx(be,{icon:f,small:!0,invertIcon:!0})})}),d.jsx(ya,{side:"left",align:"center",sideOffset:80,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map((m,v)=>d.jsx(qu,{"data-testid":`style.${e}.${m.value}`,children:d.jsx(ce,{type:"icon",onClick:()=>h(a,m.value),title:`${p(r)} — ${p(`${e}-style.${m.value}`)}`,children:d.jsx(be,{icon:m.icon,invertIcon:!0})},m.value)},v))})})]}),d.jsxs(ga,{id:`style panel ${n}`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}`,title:p(o)+" — "+(u===null||u.type==="mixed"?p("style-panel.mixed"):p(`${n}-style.${u.value}`)),children:d.jsx(be,{icon:g,small:!0})})}),d.jsx(ya,{side:"left",align:"center",sideOffset:116,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:i.map(m=>d.jsx(qu,{children:d.jsx(ce,{type:"icon",title:`${p(o)} — ${p(`${n}-style.${m.value}`)}`,"data-testid":`style.${n}.${m.value}`,onClick:()=>h(l,m.value),children:d.jsx(be,{icon:m.icon})})},m.value))})})]})]})]})}const Ape=w.memo(Mpe);function jpe({id:t,label:e,uiType:n,stylePanelType:r,style:o,items:s,type:i,value:a,onValueChange:l}){const c=Ee(),u=z(),h=w.useMemo(()=>{var m;return(m=s.find(v=>a.type==="shared"&&v.value===a.value))==null?void 0:m.icon},[s,a]),p=c(`style-panel.${r}`),f=a.type==="mixed"?c("style-panel.mixed"):p+" — "+c(`${n}-style.${a.value}`),g=e?c(e):"";return d.jsxs(ga,{id:`style panel ${t}`,children:[d.jsx(ma,{children:d.jsxs(ce,{type:i,"data-testid":`style.${n}`,title:f,children:[g&&d.jsx(Pt,{children:g}),d.jsx(be,{icon:h??"mixed"})]})}),d.jsx(ya,{side:"left",align:"center",alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map(m=>d.jsx(qu,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}.${m.value}`,title:p+" — "+c(`${n}-style.${m.value}`),onClick:()=>{u.markHistoryStoppingPoint("select style dropdown item"),l(o,m.value)},children:d.jsx(be,{icon:m.icon})})},m.value))})})]})}const Zb=w.memo(jpe);function Ope({styles:t}){const e=xd();if(!t)return null;const n=t.get(Jr),r=t.get(Tf),o=t.get(kf),s=t.get(Of),i=t.get($o),a=n===void 0,l=r===void 0&&o===void 0,c=s===void 0,u=i===void 0,h=ks({isDarkMode:e});return d.jsxs(d.Fragment,{children:[d.jsx(Dpe,{theme:h,styles:t}),!u&&d.jsx(Rpe,{theme:h,styles:t}),!(a&&l&&c)&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[d.jsx(Lpe,{styles:t}),d.jsx(Fpe,{styles:t}),d.jsx($pe,{styles:t})]})]})}function Td(){const t=z(),e=Qt();return Te.useMemo(()=>function(r,o){t.run(()=>{t.isIn("select")&&t.setStyleForSelectedShapes(r,o),t.setStyleForNextShapes(r,o),t.updateInstanceState({isChangingStyle:!0})}),e("set-style",{source:"style-panel",id:r.id,value:o})},[t,e])}function Dpe({styles:t,theme:e}){const n=Ee(),r=z(),o=w.useCallback(h=>r.markHistoryStoppingPoint(h),[r]),s=Td(),i=t.get(mr),a=t.get(ua),l=t.get(ca),c=t.get(Fo),u=a!==void 0||l!==void 0||c!==void 0;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{tabIndex:-1,className:"tlui-style-panel__section__common","aria-label":"style panel styles","data-testid":"style.panel",children:[i===void 0?null:d.jsx(Yi,{title:n("style-panel.color"),uiType:"color",style:mr,items:jr.color,value:i,onValueChange:s,theme:e,onHistoryMark:o}),d.jsx(Npe,{})]}),u&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[a===void 0?null:d.jsx(Yi,{title:n("style-panel.fill"),uiType:"fill",style:ua,items:jr.fill,value:a,onValueChange:s,theme:e,onHistoryMark:o}),l===void 0?null:d.jsx(Yi,{title:n("style-panel.dash"),uiType:"dash",style:ca,items:jr.dash,value:l,onValueChange:s,theme:e,onHistoryMark:o}),c===void 0?null:d.jsx(Yi,{title:n("style-panel.size"),uiType:"size",style:Fo,items:jr.size,value:c,onValueChange:(h,p)=>{s(h,p);const f=r.getSelectedShapeIds();f.length>0&&Ye(r,f)},theme:e,onHistoryMark:o})]})]})}function Rpe({theme:t,styles:e}){const n=Ee(),r=Td(),o=z(),s=w.useCallback(u=>o.markHistoryStoppingPoint(u),[o]),i=e.get($o),a=e.get(Sx),l=e.get(Af),c=e.get(jf);return i===void 0&&l===void 0?null:d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel text",children:[i===void 0?null:d.jsx(Yi,{title:n("style-panel.font"),uiType:"font",style:$o,items:jr.font,value:i,onValueChange:r,theme:t,onHistoryMark:s}),a===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(Yi,{title:n("style-panel.align"),uiType:"align",style:Sx,items:jr.textAlign,value:a,onValueChange:r,theme:t,onHistoryMark:s}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:d.jsx(ce,{type:"icon",title:n("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(be,{icon:"vertical-align-middle"})})})]}),l===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(Yi,{title:n("style-panel.label-align"),uiType:"align",style:Af,items:jr.horizontalAlign,value:l,onValueChange:r,theme:t,onHistoryMark:s}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:c===void 0?d.jsx(ce,{type:"icon",title:n("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(be,{icon:"vertical-align-middle"})}):d.jsx(Zb,{type:"icon",id:"geo-vertical-alignment",uiType:"verticalAlign",stylePanelType:"vertical-align",style:jf,items:jr.verticalAlign,value:c,onValueChange:r})})]})]})}function Lpe({styles:t}){const e=Td(),n=t.get(Jr);return n===void 0?null:d.jsx(Zb,{id:"geo",type:"menu",label:"style-panel.geo",uiType:"geo",stylePanelType:"geo",style:Jr,items:jr.geo,value:n,onValueChange:e})}function $pe({styles:t}){const e=Td(),n=t.get(Of);return n===void 0?null:d.jsx(Zb,{id:"spline",type:"menu",label:"style-panel.spline",uiType:"spline",stylePanelType:"spline",style:Of,items:jr.spline,value:n,onValueChange:e})}function Fpe({styles:t}){const e=Td(),n=t.get(Tf),r=t.get(kf);return!n||!r?null:d.jsx(Ape,{label:"style-panel.arrowheads",uiTypeA:"arrowheadStart",styleA:kf,itemsA:jr.arrowheadStart,valueA:r,uiTypeB:"arrowheadEnd",styleB:Tf,itemsB:jr.arrowheadEnd,valueB:n,onValueChange:e,labelA:"style-panel.arrowhead-start",labelB:"style-panel.arrowhead-end"})}const $c=[.1,.25,.5,.75,1];function Npe(){const t=z(),e=w.useCallback(a=>t.markHistoryStoppingPoint(a),[t]),n=U("opacity",()=>t.getSharedOpacity(),[t]),r=Qt(),o=Ee(),s=Te.useCallback(a=>{const l=$c[a];t.run(()=>{t.isIn("select")&&t.setOpacityForSelectedShapes(l),t.setOpacityForNextShapes(l),t.updateInstanceState({isChangingStyle:!0})}),r("set-style",{source:"style-panel",id:"opacity",value:a})},[t,r]);if(n===void 0)return null;const i=n.type==="mixed"?-1:$c.indexOf(T9($c,a=>Math.abs(a-n.value)));return d.jsx(Tpe,{"data-testid":"style.opacity",value:i>=0?i:$c.length-1,label:n.type==="mixed"?"style-panel.mixed":`opacity-style.${n.value}`,onValueChange:s,steps:$c.length-1,title:o("style-panel.opacity"),onHistoryMark:e})}const zpe=w.memo(function({isMobile:e,children:n}){const r=z(),o=w.useRef(null);Mi(o);const s=c4(),i=w.useCallback(()=>{e||r.updateInstanceState({isChangingStyle:!1})},[r,e]),a=n??d.jsx(Ope,{styles:s});return d.jsx("div",{ref:o,className:le("tlui-style-panel",{"tlui-style-panel__wrapper":!e}),"data-ismobile":e,onPointerLeave:i,children:a})});function Bpe(){const t=z(),e=Ee(),n=c4(),r=n==null?void 0:n.get(mr),o=ks({isDarkMode:t.user.getIsDarkMode()}),s=((r==null?void 0:r.type)==="shared"?o[r.value]:o.black).solid,i=U("disable style panel",()=>t.isInAny("hand","zoom","eraser","laser"),[t]),a=w.useCallback(c=>{c||t.updateInstanceState({isChangingStyle:!1})},[t]),{StylePanel:l}=Di();return l?d.jsxs(Gb,{id:"mobile style menu",onOpenChange:a,children:[d.jsx(Vb,{children:d.jsx(ce,{type:"tool","data-testid":"mobile-styles.button",style:{color:i?"var(--color-muted-1)":s},title:e("style-panel.title"),disabled:i,children:d.jsx(be,{icon:i?"blob":(r==null?void 0:r.type)==="mixed"?"mixed":"blob"})})}),d.jsx(Yb,{side:"top",align:"end",children:l&&d.jsx(l,{isMobile:!0})})]}):null}function Upe(){return d.jsxs(d.Fragment,{children:[d.jsx(Kpe,{}),d.jsx(Wpe,{}),d.jsx(Gpe,{}),d.jsx(Vpe,{}),d.jsx(Ype,{}),d.jsx(Xpe,{}),d.jsx(qpe,{}),d.jsx(Zpe,{}),d.jsx(Qpe,{}),d.jsx(Jpe,{}),d.jsx(tfe,{}),d.jsx(efe,{}),d.jsx(ofe,{}),d.jsx(afe,{}),d.jsx(nfe,{}),d.jsx(ife,{}),d.jsx(sfe,{}),d.jsx(rfe,{}),d.jsx(lfe,{}),d.jsx(cfe,{}),d.jsx(ufe,{}),d.jsx(dfe,{}),d.jsx(hfe,{}),d.jsx(pfe,{}),d.jsx(ffe,{}),d.jsx(gfe,{}),d.jsx(yfe,{}),d.jsx(mfe,{})]})}function Hpe(t){var r;const e=z(),n=(r=t.meta)==null?void 0:r.geo;return U("is tool selected",()=>{const o=e.getCurrentToolId(),s=e.getSharedStyles().getAsKnownValue(Jr);return n?o==="geo"&&s===n:o===t.id},[e,t.id,n])}function Ve({tool:t}){const e=Eb(),n=Hpe(e[t]);return d.jsx(Ln,{toolId:t,isSelected:n})}function Kpe(){return d.jsx(Ve,{tool:"select"})}function Wpe(){return d.jsx(Ve,{tool:"hand"})}function Gpe(){return d.jsx(Ve,{tool:"draw"})}function Vpe(){return d.jsx(Ve,{tool:"eraser"})}function Ype(){return d.jsx(Ve,{tool:"arrow"})}function Xpe(){return d.jsx(Ve,{tool:"text"})}function qpe(){return d.jsx(Ve,{tool:"note"})}function Zpe(){return d.jsx(Ln,{toolId:"asset"})}function Qpe(){return d.jsx(Ve,{tool:"rectangle"})}function Jpe(){return d.jsx(Ve,{tool:"ellipse"})}function efe(){return d.jsx(Ve,{tool:"diamond"})}function tfe(){return d.jsx(Ve,{tool:"triangle"})}function nfe(){return d.jsx(Ve,{tool:"rhombus"})}function rfe(){return d.jsx(Ve,{tool:"heart"})}function ofe(){return d.jsx(Ve,{tool:"hexagon"})}function sfe(){return d.jsx(Ve,{tool:"cloud"})}function ife(){return d.jsx(Ve,{tool:"star"})}function afe(){return d.jsx(Ve,{tool:"oval"})}function lfe(){return d.jsx(Ve,{tool:"x-box"})}function cfe(){return d.jsx(Ve,{tool:"check-box"})}function ufe(){return d.jsx(Ve,{tool:"arrow-left"})}function dfe(){return d.jsx(Ve,{tool:"arrow-up"})}function hfe(){return d.jsx(Ve,{tool:"arrow-down"})}function pfe(){return d.jsx(Ve,{tool:"arrow-right"})}function ffe(){return d.jsx(Ve,{tool:"line"})}function gfe(){return d.jsx(Ve,{tool:"highlight"})}function mfe(){return d.jsx(Ve,{tool:"frame"})}function yfe(){return d.jsx(Ve,{tool:"laser"})}const TS=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function MS(t,e,n,r){t.addEventListener?t.addEventListener(e,n,r):t.attachEvent&&t.attachEvent("on".concat(e),n)}function Fc(t,e,n,r){t.removeEventListener?t.removeEventListener(e,n,r):t.detachEvent&&t.detachEvent("on".concat(e),n)}function C4(t,e){const n=e.slice(0,e.length-1);for(let r=0;r<n.length;r++)n[r]=t[n[r].toLowerCase()];return n}function _4(t){typeof t!="string"&&(t=""),t=t.replace(/\s/g,"");const e=t.split(",");let n=e.lastIndexOf("");for(;n>=0;)e[n-1]+=",",e.splice(n,1),n=e.lastIndexOf("");return e}function Sfe(t,e){const n=t.length>=e.length?t:e,r=t.length>=e.length?e:t;let o=!0;for(let s=0;s<n.length;s++)r.indexOf(n[s])===-1&&(o=!1);return o}const Zu={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":TS?173:189,"=":TS?61:187,";":TS?59:186,"'":222,"[":219,"]":221,"\\":220},Ho={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,command:91},$p={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},Bt={16:!1,18:!1,17:!1,91:!1},pt={};for(let t=1;t<20;t++)Zu["f".concat(t)]=111+t;let it=[],gu=null,I4="all";const os=new Map,Md=t=>Zu[t.toLowerCase()]||Ho[t.toLowerCase()]||t.toUpperCase().charCodeAt(0),vfe=t=>Object.keys(Zu).find(e=>Zu[e]===t),xfe=t=>Object.keys(Ho).find(e=>Ho[e]===t);function E4(t){I4=t||"all"}function Qu(){return I4||"all"}function wfe(){return it.slice(0)}function bfe(){return it.map(t=>vfe(t)||xfe(t)||String.fromCharCode(t))}function Pfe(){const t=[];return Object.keys(pt).forEach(e=>{pt[e].forEach(n=>{let{key:r,scope:o,mods:s,shortcut:i}=n;t.push({scope:o,shortcut:i,mods:s,keys:r.split("+").map(a=>Md(a))})})}),t}function Cfe(t){const e=t.target||t.srcElement,{tagName:n}=e;let r=!0;const o=n==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(o||n==="TEXTAREA"||n==="SELECT")&&!e.readOnly)&&(r=!1),r}function _fe(t){return typeof t=="string"&&(t=Md(t)),it.indexOf(t)!==-1}function Ife(t,e){let n,r;t||(t=Qu());for(const o in pt)if(Object.prototype.hasOwnProperty.call(pt,o))for(n=pt[o],r=0;r<n.length;)n[r].scope===t?n.splice(r,1).forEach(i=>{let{element:a}=i;return Qb(a)}):r++;Qu()===t&&E4(e||"all")}function Efe(t){let e=t.keyCode||t.which||t.charCode;const n=it.indexOf(e);if(n>=0&&it.splice(n,1),t.key&&t.key.toLowerCase()==="meta"&&it.splice(0,it.length),(e===93||e===224)&&(e=91),e in Bt){Bt[e]=!1;for(const r in Ho)Ho[r]===e&&(Wn[r]=!1)}}function k4(t){if(typeof t>"u")Object.keys(pt).forEach(o=>{Array.isArray(pt[o])&&pt[o].forEach(s=>Bh(s)),delete pt[o]}),Qb(null);else if(Array.isArray(t))t.forEach(o=>{o.key&&Bh(o)});else if(typeof t=="object")t.key&&Bh(t);else if(typeof t=="string"){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];let[o,s]=n;typeof o=="function"&&(s=o,o=""),Bh({key:t,scope:o,method:s,splitKey:"+"})}}const Bh=t=>{let{key:e,scope:n,method:r,splitKey:o="+"}=t;_4(e).forEach(i=>{const a=i.split(o),l=a.length,c=a[l-1],u=c==="*"?"*":Md(c);if(!pt[u])return;n||(n=Qu());const h=l>1?C4(Ho,a):[],p=[];pt[u]=pt[u].filter(f=>{const m=(r?f.method===r:!0)&&f.scope===n&&Sfe(f.mods,h);return m&&p.push(f.element),!m}),p.forEach(f=>Qb(f))})};function u2(t,e,n,r){if(e.element!==r)return;let o;if(e.scope===n||e.scope==="all"){o=e.mods.length>0;for(const s in Bt)Object.prototype.hasOwnProperty.call(Bt,s)&&(!Bt[s]&&e.mods.indexOf(+s)>-1||Bt[s]&&e.mods.indexOf(+s)===-1)&&(o=!1);(e.mods.length===0&&!Bt[16]&&!Bt[18]&&!Bt[17]&&!Bt[91]||o||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(it),e.method(t,e)===!1&&(t.preventDefault?t.preventDefault():t.returnValue=!1,t.stopPropagation&&t.stopPropagation(),t.cancelBubble&&(t.cancelBubble=!0)))}}function d2(t,e){const n=pt["*"];let r=t.keyCode||t.which||t.charCode;if(!Wn.filter.call(this,t))return;if((r===93||r===224)&&(r=91),it.indexOf(r)===-1&&r!==229&&it.push(r),["metaKey","ctrlKey","altKey","shiftKey"].forEach(a=>{const l=$p[a];t[a]&&it.indexOf(l)===-1?it.push(l):!t[a]&&it.indexOf(l)>-1?it.splice(it.indexOf(l),1):a==="metaKey"&&t[a]&&(it=it.filter(c=>c in $p||c===r))}),r in Bt){Bt[r]=!0;for(const a in Ho)Ho[a]===r&&(Wn[a]=!0);if(!n)return}for(const a in Bt)Object.prototype.hasOwnProperty.call(Bt,a)&&(Bt[a]=t[$p[a]]);t.getModifierState&&!(t.altKey&&!t.ctrlKey)&&t.getModifierState("AltGraph")&&(it.indexOf(17)===-1&&it.push(17),it.indexOf(18)===-1&&it.push(18),Bt[17]=!0,Bt[18]=!0);const o=Qu();if(n)for(let a=0;a<n.length;a++)n[a].scope===o&&(t.type==="keydown"&&n[a].keydown||t.type==="keyup"&&n[a].keyup)&&u2(t,n[a],o,e);if(!(r in pt))return;const s=pt[r],i=s.length;for(let a=0;a<i;a++)if((t.type==="keydown"&&s[a].keydown||t.type==="keyup"&&s[a].keyup)&&s[a].key){const l=s[a],{splitKey:c}=l,u=l.key.split(c),h=[];for(let p=0;p<u.length;p++)h.push(Md(u[p]));h.sort().join("")===it.sort().join("")&&u2(t,l,o,e)}}function Wn(t,e,n){it=[];const r=_4(t);let o=[],s="all",i=document,a=0,l=!1,c=!0,u="+",h=!1,p=!1;for(n===void 0&&typeof e=="function"&&(n=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(s=e.scope),e.element&&(i=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(c=e.keydown),e.capture!==void 0&&(h=e.capture),typeof e.splitKey=="string"&&(u=e.splitKey),e.single===!0&&(p=!0)),typeof e=="string"&&(s=e),p&&k4(t,s);a<r.length;a++)t=r[a].split(u),o=[],t.length>1&&(o=C4(Ho,t)),t=t[t.length-1],t=t==="*"?"*":Md(t),t in pt||(pt[t]=[]),pt[t].push({keyup:l,keydown:c,scope:s,mods:o,shortcut:r[a],method:n,key:r[a],splitKey:u,element:i});if(typeof i<"u"&&window){if(!os.has(i)){const f=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return d2(m,i)},g=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;d2(m,i),Efe(m)};os.set(i,{keydownListener:f,keyupListenr:g,capture:h}),MS(i,"keydown",f,h),MS(i,"keyup",g,h)}if(!gu){const f=()=>{it=[]};gu={listener:f,capture:h},MS(window,"focus",f,h)}}}function kfe(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(pt).forEach(n=>{pt[n].filter(o=>o.scope===e&&o.shortcut===t).forEach(o=>{o&&o.method&&o.method()})})}function Qb(t){const e=Object.values(pt).flat();if(e.findIndex(r=>{let{element:o}=r;return o===t})<0){const{keydownListener:r,keyupListenr:o,capture:s}=os.get(t)||{};r&&o&&(Fc(t,"keyup",o,s),Fc(t,"keydown",r,s),os.delete(t))}if((e.length<=0||os.size<=0)&&(Object.keys(os).forEach(o=>{const{keydownListener:s,keyupListenr:i,capture:a}=os.get(o)||{};s&&i&&(Fc(o,"keyup",i,a),Fc(o,"keydown",s,a),os.delete(o))}),os.clear(),Object.keys(pt).forEach(o=>delete pt[o]),gu)){const{listener:o,capture:s}=gu;Fc(window,"focus",o,s),gu=null}}const AS={getPressedKeyString:bfe,setScope:E4,getScope:Qu,deleteScope:Ife,getPressedKeyCodes:wfe,getAllKeyCodes:Pfe,isPressed:_fe,filter:Cfe,trigger:kfe,unbind:k4,keyMap:Zu,modifier:Ho,modifierMap:$p};for(const t in AS)Object.prototype.hasOwnProperty.call(AS,t)&&(Wn[t]=AS[t]);if(typeof window<"u"){const t=window.hotkeys;Wn.noConflict=e=>(e&&window.hotkeys===Wn&&(window.hotkeys=t),Wn),window.hotkeys=Wn}const h2=["copy","cut","paste","asset"];function Tfe(){const t=z(),e=wr(),n=Ea(),r=Eb(),o=U("is focused",()=>t.getInstanceState().isFocused,[t]);w.useEffect(()=>{if(!o)return;const s=new Array,i=(l,c)=>{Wn(l,{element:document.body},c),s.push(()=>{Wn.unbind(l,c)})},a=(l,c)=>{Wn(l,{element:document.body,keyup:!0,keydown:!1},c),s.push(()=>{Wn.unbind(l,c)})};for(const l of Object.values(n))l.kbd&&(e&&!l.readonlyOk||h2.includes(l.id)||i(p2(l.kbd),c=>{Qc(t)||(xe(c),l.onSelect("kbd"))}));for(const l of Object.values(r))!l.kbd||!l.readonlyOk&&t.getIsReadonly()||h2.includes(l.id)||i(p2(l.kbd),c=>{Qc(t)||(xe(c),l.onSelect("kbd"))});return i(",",l=>{if(Qc(t)||t.inputs.keys.has("Comma"))return;xe(l),t.focus(),t.inputs.keys.add("Comma");const{x:c,y:u,z:h}=t.inputs.currentPagePoint,p=t.pageToScreen({x:c,y:u}),f={type:"pointer",name:"pointer_down",point:{x:p.x,y:p.y,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:un(l),pointerId:0,button:0,isPen:t.getInstanceState().isPenMode,target:"canvas"};t.dispatch(f)}),a(",",l=>{if(Qc(t)||!t.inputs.keys.has("Comma"))return;t.inputs.keys.delete("Comma");const{x:c,y:u,z:h}=t.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_up",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:un(l),pointerId:0,button:0,isPen:t.getInstanceState().isPenMode,target:"canvas"};t.dispatch(p)}),()=>{s.forEach(l=>l())}},[n,r,e,t,o])}function p2(t){return Mfe(t).map(e=>{let n="";const r=e.split("");return r.length===1?n=r[0]:r[0]==="!"?n=`shift+${r[1]}`:r[0]==="?"?r.length===3&&r[1]==="!"?n=`alt+shift+${r[2]}`:n=`alt+${r[1]}`:r[0]==="$"?r[1]==="!"?n=`cmd+shift+${r[2]},ctrl+shift+${r[2]}`:r[1]==="?"?n=`cmd+⌥+${r[2]},ctrl+alt+${r[2]}`:n=`cmd+${r[1]},ctrl+${r[1]}`:n=e,n}).join(",")}function Mfe(t){typeof t!="string"&&(t=""),t=t.replace(/\s/g,"");const e=t.split(",");let n=e.lastIndexOf("");for(;n>=0;)e[n-1]+=",",e.splice(n,1),n=e.lastIndexOf("");return e}function Qc(t){return t.menus.hasAnyOpenMenus()||t.getEditingShapeId()!==null||t.getCrashingError()}const Afe=w.createContext(!1);function jfe({children:t}){const e=z(),n=Jl(),r=An(),o=Ee(),s=Math.min(8,5+r),[i,a]=w.useState(0),l=w.useRef(null),[c,u]=w.useState(null),h=w.useMemo(()=>{const f=c?`:not([data-value="${c}"])`:"";return`
411
+ }`,s=e.createShader(e.FRAGMENT_SHADER);if(!s)throw new Error("Failed to create fragment shader");if(e.shaderSource(s,o),e.compileShader(s),!e.getShaderParameter(s,e.COMPILE_STATUS))throw new Error("Failed to compile fragment shader");const i=e.createProgram();if(!i)throw new Error("Failed to create program");if(e.attachShader(i,r),e.attachShader(i,s),e.linkProgram(i),!e.getProgramParameter(i,e.LINK_STATUS))throw new Error("Failed to link program");e.useProgram(i);const a=e.getAttribLocation(i,"shapeVertexPosition");if(a<0)throw new Error("Failed to get shapeVertexPosition attribute location");e.enableVertexAttribArray(a);const l=e.getUniformLocation(i,"canvasPageBounds"),c=e.getUniformLocation(i,"fillColor");if(!e.createBuffer())throw new Error("Failed to create buffer");if(!e.createBuffer())throw new Error("Failed to create buffer");return{context:e,selectedShapes:zh(e,1024),unselectedShapes:zh(e,4096),viewport:zh(e,VF),collaborators:zh(e,1024),prepareTriangles(p,f){e.bindBuffer(e.ARRAY_BUFFER,p.buffer),e.bufferData(e.ARRAY_BUFFER,p.vertices,e.STATIC_DRAW,0,f),e.enableVertexAttribArray(a),e.vertexAttribPointer(a,2,e.FLOAT,!1,0,0)},drawTrianglesTransparently(p){e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.drawArrays(e.TRIANGLES,0,p/2),e.disable(e.BLEND)},drawTriangles(p){e.drawArrays(e.TRIANGLES,0,p/2)},setFillColor(p){e.uniform4fv(c,p)},setCanvasPageBounds(p){e.uniform4fv(l,p)}}}function zh(t,e){const n=t.createBuffer();if(!n)throw new Error("Failed to create buffer");return{buffer:n,vertices:new Float32Array(e)}}function l2(t,e,n){let r=t.vertices.length;for(;r<e+n.length;)r*=2;if(r!=t.vertices.length){const o=new Float32Array(r);o.set(t.vertices),t.vertices=o}t.vertices.set(n,e)}var Nhe=Object.create,YF=Object.defineProperty,zhe=Object.getOwnPropertyDescriptor,Bhe=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),XF=t=>{throw TypeError(t)},qF=(t,e,n)=>e in t?YF(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Uhe=t=>[,,,Nhe(null)],ZF=["class","method","getter","setter","accessor","field","value","get","set"],QF=t=>t!==void 0&&typeof t!="function"?XF("Function expected"):t,Hhe=(t,e,n,r,o)=>({kind:ZF[t],name:e,metadata:r,addInitializer:s=>n._?XF("Already initialized"):o.push(QF(s||null))}),Khe=(t,e)=>qF(e,Bhe("metadata"),t[3]),Whe=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)s[o].call(n);return r},Yo=(t,e,n,r,o,s)=>{for(var i,a,l,c,u=e&7,h=!!(e&8),p=!!(e&16),f=2,g=ZF[u+5],m=t[f]||(t[f]=[]),v=(o=o.prototype,zhe(o,n)),y=r.length-1;y>=0;y--)l=Hhe(u,n,a={},t[3],m),l.static=h,l.private=p,c=l.access={has:S=>n in S},c.get=S=>S[n],i=(0,r[y])(v[g],l),a._=1,QF(i)&&(v[g]=i);return v&&YF(o,n,v),o},es=(t,e,n)=>qF(t,typeof e!="symbol"?e+"":e,n),JF,e4,t4,n4,r4,o4,s4,i4,a4,l4,br;l4=[Kn],a4=[G],i4=[G],s4=[G],o4=[G],r4=[G],n4=[G],t4=[G],e4=[G],JF=[Kn];class Br{constructor(e,n,r){this.editor=e,this.elem=n,this.container=r,Whe(br,5,this),es(this,"disposables",[]),es(this,"gl"),es(this,"shapeGeometryCache"),es(this,"colors"),es(this,"id",ze()),es(this,"canvasBoundingClientRect",Et("canvasBoundingClientRect",new Z)),es(this,"originPagePoint",new x),es(this,"originPageCenter",new x),es(this,"isInViewport",!1),this.gl=Fhe(n),this.shapeGeometryCache=e.store.createComputedCache("webgl-geometry",o=>{const s=e.getShapeMaskedPageBounds(o.id);if(!s)return null;const i=new Float32Array(12);return Ka(i,0,s.x,s.y,s.w,s.h),i}),this.colors=this._getColors(),this.disposables.push(this._listenForCanvasResize(),jo("minimap render",this.render))}close(){return this.disposables.forEach(e=>e())}_getColors(){const e=getComputedStyle(this.editor.getContainer());return{shapeFill:Lc(e.getPropertyValue("--color-text-3").trim()),selectFill:Lc(e.getPropertyValue("--color-selected").trim()),viewportFill:Lc(e.getPropertyValue("--color-muted-1").trim()),background:Lc(e.getPropertyValue("--color-low").trim())}}updateColors(){this.colors=this._getColors()}getDpr(){return this.editor.getInstanceState().devicePixelRatio}getContentPageBounds(){const e=this.editor.getViewportPageBounds(),n=this.editor.getCurrentPageBounds();return n?Z.Expand(n,e):e}getContentScreenBounds(){const e=this.getContentPageBounds(),n=this.editor.pageToScreen(e.point),r=this.editor.pageToScreen(new x(e.maxX,e.maxY));return new Z(n.x,n.y,r.x-n.x,r.y-n.y)}_getCanvasBoundingRect(){const{x:e,y:n,width:r,height:o}=this.elem.getBoundingClientRect();return new Z(e,n,r,o)}getCanvasScreenBounds(){return this.canvasBoundingClientRect.get()}_listenForCanvasResize(){const e=new ResizeObserver(()=>{const n=this._getCanvasBoundingRect();this.canvasBoundingClientRect.set(n)});return e.observe(this.elem),e.observe(this.container),()=>e.disconnect()}getCanvasSize(){const e=this.canvasBoundingClientRect.get(),n=this.getDpr();return new x(e.width*n,e.height*n)}getCanvasClientPosition(){return this.canvasBoundingClientRect.get().point}getCanvasPageBounds(){const e=this.getCanvasScreenBounds(),n=this.getContentPageBounds(),r=e.width/e.height;let o=n.width,s=o/r;s<n.height&&(s=n.height,o=s*r);const i=new Z(0,0,o,s);return i.center=n.center,i}getZoom(){return this.getCanvasPageBounds().width/this.getCanvasScreenBounds().width}getCanvasPageBoundsArray(){const{x:e,y:n,w:r,h:o}=this.getCanvasPageBounds();return new Float32Array([e,n,r,o])}getMinimapPagePoint(e,n){const r=this.getCanvasPageBounds(),o=this.getCanvasScreenBounds();let s=e-o.x,i=n-o.y;return s*=r.width/o.width,i*=r.height/o.height,s+=r.minX,i+=r.minY,new x(s,i,1)}minimapScreenPointToPagePoint(e,n,r=!1,o=!1){const{editor:s}=this,i=s.getViewportPageBounds();let{x:a,y:l}=this.getMinimapPagePoint(e,n);if(o){const c=this.editor.getCurrentPageBounds()??new Z,u=c.minX-i.width/2,h=c.maxX+i.width/2,p=c.minY-i.height/2,f=c.maxY+i.height/2,g=Math.max(0,u+i.width-a),m=Math.max(0,-(h-i.width-a)),v=Math.max(0,p+i.height-l),y=Math.max(0,-(f-i.height-l));a+=(g-m)/2,l+=(v-y)/2,a=zt(a,u,h),l=zt(l,p,f)}if(r){const{originPagePoint:c}=this,u=Math.abs(a-c.x),h=Math.abs(l-c.y);u>h?l=c.y:a=c.x}return new x(a,l)}render(){const e=this.gl.context,n=this.getCanvasSize();this.gl.setCanvasPageBounds(this.getCanvasPageBoundsArray()),this.elem.width=n.x,this.elem.height=n.y,e.viewport(0,0,n.x,n.y),e.clearColor(this.colors.background[0],this.colors.background[1],this.colors.background[2],1),e.clear(e.COLOR_BUFFER_BIT);const r=new Set(this.editor.getSelectedShapeIds()),o=this.colors;let s=0,i=0;const a=this.editor.getCurrentPageShapeIdsSorted();for(let l=0,c=a.length;l<c;l++){const u=a[l],h=this.shapeGeometryCache.get(u);if(!h)continue;const p=h.length;r.has(u)?(l2(this.gl.selectedShapes,s,h),s+=p):(l2(this.gl.unselectedShapes,i,h),i+=p)}this.drawShapes(this.gl.unselectedShapes,i,o.shapeFill),this.drawShapes(this.gl.selectedShapes,s,o.selectFill),this.drawViewport(),this.drawCollaborators()}drawShapes(e,n,r){this.gl.prepareTriangles(e,n),this.gl.setFillColor(r),this.gl.drawTriangles(n)}drawViewport(){const e=this.editor.getViewportPageBounds(),n=$he(this.gl.viewport.vertices,e,4*this.getZoom());this.gl.prepareTriangles(this.gl.viewport,n),this.gl.setFillColor(this.colors.viewportFill),this.gl.drawTrianglesTransparently(n),Ge.isSafari&&(this.gl.drawTrianglesTransparently(n),this.gl.drawTrianglesTransparently(n),this.gl.drawTrianglesTransparently(n))}drawCollaborators(){const e=this.editor.getCollaboratorsOnCurrentPage();if(!e.length)return;const n=20,r=n*6,o=r*e.length;this.gl.collaborators.vertices.length<o&&(this.gl.collaborators.vertices=new Float32Array(o));const s=this.gl.collaborators.vertices;let i=0;const a=this.getZoom();for(const{cursor:l}of e)l&&(Ha(s,{center:x.From(l),radius:3*a,offset:i,numArcSegments:n}),i+=r);this.gl.prepareTriangles(this.gl.collaborators,o),i=0;for(const{color:l}of e)this.gl.setFillColor(Lc(l)),this.gl.context.drawArrays(this.gl.context.TRIANGLES,i/2,r/2),i+=r}}br=Uhe();Yo(br,1,"close",l4,Br);Yo(br,1,"getDpr",a4,Br);Yo(br,1,"getContentPageBounds",i4,Br);Yo(br,1,"getContentScreenBounds",s4,Br);Yo(br,1,"getCanvasSize",o4,Br);Yo(br,1,"getCanvasClientPosition",r4,Br);Yo(br,1,"getCanvasPageBounds",n4,Br);Yo(br,1,"getZoom",t4,Br);Yo(br,1,"getCanvasPageBoundsArray",e4,Br);Yo(br,1,"render",JF,Br);Khe(br,Br);function Ghe(){const t=z(),e=Mt(),n=w.useRef(null),r=w.useRef(!1),o=w.useRef();w.useEffect(()=>{try{const u=new Br(t,n.current,e);return o.current=u,o.current.close}catch(u){t.annotateError(u,{origin:"minimap",willCrashApp:!1}),t.timers.setTimeout(()=>{throw u})}},[t,e]);const s=w.useCallback(u=>{if(!t.getCurrentPageShapeIds().size||!o.current)return;const h=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),p=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);o.current.originPagePoint.setTo(p),o.current.originPageCenter.setTo(t.getViewportPageBounds().center),t.centerOnPoint(h,{animation:{duration:t.options.animationMediumMs}})},[t]),i=w.useCallback(u=>{if(!o.current)return;const h=u.currentTarget;if(dd(h,u),!t.getCurrentPageShapeIds().size)return;r.current=!0,o.current.isInViewport=!1;const p=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!1),f=t.getViewportPageBounds(),g=o.current.getContentPageBounds();if(new Z(g.x-f.width/2,g.y-f.height/2,g.width+f.width,g.height+f.height).containsPoint(p)&&!f.containsPoint(p)){o.current.isInViewport=f.containsPoint(p);const y=x.Sub(f.center,f.point),S=x.Add(p,y);o.current.originPagePoint.setTo(S),o.current.originPageCenter.setTo(p),t.centerOnPoint(p,{animation:{duration:t.options.animationMediumMs}})}else{const y=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,!1,!0);o.current.isInViewport=f.containsPoint(y),o.current.originPagePoint.setTo(y),o.current.originPageCenter.setTo(f.center)}function v(y){h&&hd(h,y),r.current=!1,document.body.removeEventListener("pointerup",v)}document.body.addEventListener("pointerup",v)},[t]),a=w.useCallback(u=>{if(!o.current)return;const h=o.current.minimapScreenPointToPagePoint(u.clientX,u.clientY,u.shiftKey,!0);if(r.current){if(o.current.isInViewport){const m=o.current.originPagePoint.clone().sub(o.current.originPageCenter);t.centerOnPoint(x.Sub(h,m));return}t.centerOnPoint(h)}const p=o.current.getMinimapPagePoint(u.clientX,u.clientY),f=t.pageToScreen(p),g={type:"pointer",target:"canvas",name:"pointer_move",...lr(u),point:f,isPen:t.getInstanceState().isPenMode};t.dispatch(g)},[t]),l=w.useCallback(u=>{const h=xj(u);t.dispatch({type:"wheel",name:"wheel",delta:h,point:new x(u.clientX,u.clientY),shiftKey:u.shiftKey,altKey:u.altKey,ctrlKey:u.metaKey||u.ctrlKey,metaKey:u.metaKey,accelKey:un(u)})},[t]),c=xd();return w.useEffect(()=>{t.timers.setTimeout(()=>{var u,h;(u=o.current)==null||u.updateColors(),(h=o.current)==null||h.render()})},[c,t]),d.jsx("div",{className:"tlui-minimap",children:d.jsx("canvas",{role:"img","aria-label":"minimap",ref:n,className:"tlui-minimap__canvas",onDoubleClick:s,onPointerMove:a,onPointerDown:i,onWheelCapture:l})})}function Vhe(t,e){const[n,r]=Te.useState(e);Te.useLayoutEffect(()=>{const s=_w(t);if(s)try{r(JSON.parse(s))}catch{console.error(`Could not restore value ${t} from local storage.`)}},[t]);const o=Te.useCallback(s=>{r(i=>{const a=typeof s=="function"?s(i):s;return Iw(t,JSON.stringify(a)),a})},[t]);return[n,o]}const Yhe=w.memo(function(){const e=Ea(),n=Ee(),r=An(),o=w.useRef(null);Mi(o);const[s,i]=Vhe("minimap",!0),a=w.useCallback(()=>{i(u=>!u)},[i]),{ZoomMenu:l,Minimap:c}=Di();return r<St.MOBILE?null:d.jsxs("div",{ref:o,className:"tlui-navigation-panel",children:[d.jsx("div",{className:"tlui-buttons__horizontal",children:l&&r<St.TABLET?d.jsx(l,{}):s?d.jsxs(d.Fragment,{children:[l&&d.jsx(l,{}),c&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:n("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:a,children:d.jsx(be,{icon:s?"chevrons-ne":"chevrons-sw"})})]}):d.jsxs(d.Fragment,{children:[d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-out",title:`${n(Xu(e["zoom-out"].label))} ${Xx(e["zoom-out"].kbd)}`,onClick:()=>e["zoom-out"].onSelect("navigation-zone"),children:d.jsx(be,{icon:"minus"})}),l&&d.jsx(l,{}),d.jsx(ce,{type:"icon","data-testid":"minimap.zoom-in",title:`${n(Xu(e["zoom-in"].label))} ${Xx(e["zoom-in"].kbd)}`,onClick:()=>e["zoom-in"].onSelect("navigation-zone"),children:d.jsx(be,{icon:"plus"})}),c&&d.jsx(ce,{type:"icon","data-testid":"minimap.toggle-button",title:n("navigation-zone.toggle-minimap"),className:"tlui-navigation-panel__toggle",onClick:a,children:d.jsx(be,{icon:s?"chevrons-ne":"chevrons-sw"})})]})}),c&&r>=St.TABLET&&!s&&d.jsx(c,{})]})}),Xhe=function({name:e,id:n,isCurrentPage:r,onCancel:o}){const s=z(),i=Qt(),a=w.useRef(null),l=w.useRef(null),c=w.useCallback(()=>{l.current=s.markHistoryStoppingPoint("rename page")},[s]),u=w.useCallback(p=>{s.renamePage(n,p||"New Page"),i("rename-page",{source:"page-menu"})},[s,n,i]),h=w.useCallback(()=>{l.current&&s.bailToMark(l.current),o()},[s,o]);return d.jsx(fm,{className:"tlui-page-menu__item__input",ref:p=>a.current=p,defaultValue:e,onValueChange:u,onCancel:h,onFocus:c,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:r,autoSelect:!0})},g0=(t,e,n,r,o)=>{let s;const i=t.getPages(),a=n>r?i[r-1]:i[r],l=n>r?i[r]:i[r+1];a&&!l?s=Io(a.index):!a&&l?s=iB(i[0].index):s=$u(a.index,l.index),s!==i[n].index&&(t.markHistoryStoppingPoint("moving page"),t.updatePage({id:e,index:s}),o("move-page",{source:"page-menu"}))},c2=qt(function({index:e,listSize:n,item:r,onRename:o}){const s=z(),i=Ee(),a=s.getPages(),l=Qt(),c=w.useCallback(()=>{s.markHistoryStoppingPoint("creating page");const f=yr.createId();s.duplicatePage(r.id,f),l("duplicate-page",{source:"page-menu"})},[s,r,l]),u=w.useCallback(()=>{g0(s,r.id,e,e-1,l)},[s,r,e,l]),h=w.useCallback(()=>{g0(s,r.id,e,e+1,l)},[s,r,e,l]),p=w.useCallback(()=>{s.markHistoryStoppingPoint("deleting page"),s.deletePage(r.id),l("delete-page",{source:"page-menu"})},[s,r,l]);return d.jsxs(ga,{id:`page item submenu ${e}`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon",title:i("page-menu.submenu.title"),children:d.jsx(be,{icon:"dots-vertical",small:!0})})}),d.jsx(ya,{alignOffset:0,side:"right",sideOffset:-4,children:d.jsxs(Fr,{type:"menu",sourceId:"page-menu",children:[d.jsxs(ve,{id:"modify",children:[o&&d.jsx(Ht,{id:"rename",label:"page-menu.submenu.rename",onSelect:o}),d.jsx(Ht,{id:"duplicate",label:"page-menu.submenu.duplicate-page",onSelect:c,disabled:a.length>=s.options.maxPages}),e>0&&d.jsx(Ht,{id:"move-up",onSelect:u,label:"page-menu.submenu.move-up"}),e<n-1&&d.jsx(Ht,{id:"move-down",label:"page-menu.submenu.move-down",onSelect:h})]}),n>1&&d.jsx(ve,{id:"delete",children:d.jsx(Ht,{id:"delete",onSelect:p,label:"page-menu.submenu.delete"})})]})})]})}),qhe=w.memo(function(){const e=z(),n=Qt(),r=Ee(),o=An(),s=w.useCallback(()=>y(!1),[]),[i,a]=Ms("page-menu",s),l=36,c=w.useRef(null),u=U("pages",()=>e.getPages(),[e]),h=U("currentPage",()=>e.getCurrentPage(),[e]),p=U("currentPageId",()=>e.getCurrentPageId(),[e]),f=wr(),g=U("maxPageCountReached",()=>e.getPages().length>=e.options.maxPages,[e]),m=U("isCoarsePointer",()=>e.getInstanceState().isCoarsePointer,[e]),[v,y]=w.useState(!1),S=w.useCallback(()=>{f||y(M=>!M)},[f]),b=w.useRef({isPointing:!1,status:"idle",pointing:null,startY:0,startIndex:0,dragIndex:0}),[P,C]=w.useState(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])));w.useLayoutEffect(()=>{C(Object.fromEntries(u.map((M,O)=>[M.id,{y:O*l,offsetY:0,isSelected:!1}])))},[l,u]),w.useEffect(()=>{i&&e.timers.requestAnimationFrame(()=>{const M=document.querySelector(`[data-testid="page-menu-item-${p}"]`);if(M){const O=c.current;if(!O)return;const F=M.offsetTop,B=O.scrollTop;F<B&&O.scrollTo({top:F});const K=F+l,R=O.scrollTop+O.offsetHeight;K>R&&O.scrollTo({top:K-O.offsetHeight})}})},[l,p,i,e]);const _=w.useCallback(M=>{const{clientY:O,currentTarget:F}=M,{dataset:{id:B,index:K}}=F;if(!B||!K)return;const R=b.current;dd(M.currentTarget,M),R.status="pointing",R.pointing={id:B,index:+K};const Y=P[B].y;R.startY=O,R.startIndex=Math.max(0,Math.min(Math.round(Y/l),u.length-1))},[l,u.length,P]),E=w.useCallback(M=>{const O=b.current;if(O.status==="pointing"){const{clientY:F}=M,B=F-O.startY;Math.abs(B)>5&&(O.status="dragging")}if(O.status==="dragging"){const{clientY:F}=M,B=F-O.startY,K=P[O.pointing.id],{startIndex:R,pointing:H}=O,Y=K.y+B,ee=Math.max(0,Math.min(Math.round(Y/l),u.length-1)),he={...P};if(he[H.id]={y:K.y,offsetY:B,isSelected:!0},ee!==O.dragIndex){O.dragIndex=ee;for(let ue=0;ue<u.length;ue++){const ke=u[ue];if(ke.id===O.pointing.id)continue;let{y:se}=he[ke.id];ee===R?se=ue*l:ee<R?ee<=ue&&ue<R?se=(ue+1)*l:se=ue*l:ee>R&&(ee>=ue&&ue>R?se=(ue-1)*l:se=ue*l),se!==he[ke.id].y&&(he[ke.id]={y:se,offsetY:0,isSelected:!0})}}C(he)}},[l,u,P]),k=w.useCallback(M=>{const O=b.current;if(O.status==="dragging"){const{id:F,index:B}=O.pointing;g0(e,F,B,O.dragIndex,n)}hd(M.currentTarget,M),O.status="idle"},[e,n]),D=w.useCallback(M=>{const O=b.current;M.key==="Escape"&&(O.status==="dragging"&&C(Object.fromEntries(u.map((F,B)=>[F.id,{y:B*l,offsetY:0,isSelected:!1}]))),O.status="idle")},[l,u]),T=w.useCallback(()=>{f||(e.run(()=>{e.markHistoryStoppingPoint("creating page");const M=yr.createId();e.createPage({name:r("page-menu.new-page-initial-name"),id:M}),e.setCurrentPage(M),y(!0)}),n("new-page",{source:"page-menu"}))},[e,r,f,n]),j=w.useCallback(M=>{e.setCurrentPage(M),n("change-page",{source:"page-menu"})},[e,n]),$=w.useCallback((M,O)=>{e.renamePage(M,O),n("rename-page",{source:"page-menu"})},[e,n]);return d.jsxs(Gb,{id:"pages",onOpenChange:a,open:i,children:[d.jsx(Vb,{"data-testid":"main.page-menu",children:d.jsxs(ce,{type:"menu",title:h.name,"data-testid":"page-menu.button",className:"tlui-page-menu__trigger",children:[d.jsx("div",{className:"tlui-page-menu__name",children:h.name}),d.jsx(be,{icon:"chevron-down",small:!0})]})}),d.jsx(Yb,{side:"bottom",align:"start",sideOffset:6,disableEscapeKeyDown:v,children:d.jsxs("div",{className:"tlui-page-menu__wrapper",children:[d.jsxs("div",{className:"tlui-page-menu__header",children:[d.jsx("div",{className:"tlui-page-menu__header__title",children:r("page-menu.title")}),!f&&d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsx(ce,{type:"icon","data-testid":"page-menu.edit",title:r(v?"page-menu.edit-done":"page-menu.edit-start"),onClick:S,children:d.jsx(be,{icon:v?"check":"edit"})}),d.jsx(ce,{type:"icon","data-testid":"page-menu.create",title:r(g?"page-menu.max-page-count-reached":"page-menu.create-new-page"),disabled:g,onClick:T,children:d.jsx(be,{icon:"plus"})})]})]}),d.jsx("div",{"data-testid":"page-menu.list",className:"tlui-page-menu__list tlui-menu__group",style:{height:l*u.length+4},ref:c,children:u.map((M,O)=>{const F=P[M.id]??{position:O*40,offsetY:0};return v?d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page_menu__item__sortable",style:{zIndex:M.id===h.id?888:O,transform:`translate(0px, ${F.y+F.offsetY}px)`},children:[d.jsx(ce,{type:"icon",tabIndex:-1,className:"tlui-page_menu__item__sortable__handle",onPointerDown:_,onPointerUp:k,onPointerMove:E,onKeyDown:D,"data-id":M.id,"data-index":O,children:d.jsx(be,{icon:"drag-handle-dots"})}),o<St.TABLET_SM&&m?d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>{const B=window.prompt("Rename page",M.name);B&&B!==M.name&&$(M.id,B)},onDoubleClick:S,children:[d.jsx(f0,{checked:M.id===h.id}),d.jsx(Pt,{children:M.name})]}):d.jsx("div",{className:"tlui-page_menu__item__sortable__title",style:{height:l},children:d.jsx(Xhe,{id:M.id,name:M.name,isCurrentPage:M.id===h.id,onCancel:()=>{y(!1),e.menus.clearOpenMenus()}})}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu","data-isediting":v,children:d.jsx(c2,{index:O,item:M,listSize:u.length})})]},M.id+"_editing"):d.jsxs("div",{"data-testid":"page-menu.item",className:"tlui-page-menu__item",children:[d.jsxs(ce,{type:"normal",className:"tlui-page-menu__item__button",onClick:()=>j(M.id),onDoubleClick:S,title:r("page-menu.go-to-page"),children:[d.jsx(f0,{checked:M.id===h.id}),d.jsx(Pt,{children:M.name})]}),!f&&d.jsx("div",{className:"tlui-page_menu__item__submenu",children:d.jsx(c2,{index:O,item:M,listSize:u.length,onRename:()=>{if(Ge.isIos){const B=window.prompt("Rename page",M.name);B&&B!==M.name&&$(M.id,B)}else y(!0),p!==M.id&&j(M.id)}})})]},M.id)})})]})})]})});function Zhe(){const t=z(),e=wr(),n=U("should display quick actions",()=>t.isInAny("select","hand","zoom"),[t]);if(!(e&&!n))return d.jsxs(d.Fragment,{children:[d.jsx(Jhe,{}),d.jsx(Qhe,{})]})}function Qhe(){const t=jn(1),e=As(),n=t&&e;return d.jsxs(d.Fragment,{children:[d.jsx(W,{actionId:"delete",disabled:!n}),d.jsx(W,{actionId:"duplicate",disabled:!n})]})}function Jhe(){const t=IF(),e=_F();return d.jsxs(d.Fragment,{children:[d.jsx(W,{actionId:"undo",disabled:!t}),d.jsx(W,{actionId:"redo",disabled:!e})]})}const epe=w.memo(function({children:e}){const n=e??d.jsx(Zhe,{});return d.jsx(Fr,{type:"small-icons",sourceId:"quick-actions",children:n})});function tpe({userId:t}){const e=Lg(t);return e?d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:e.color},children:e.userName==="New User"?"":e.userName[0]??""},t):null}const npe=qt(function({userId:e}){const n=z(),r=Ee(),o=Qt(),s=Lg(e),i=w.useCallback(()=>{n.getInstanceState().followingUserId===e?(n.stopFollowingUser(),o("stop-following",{source:"people-menu"})):(n.startFollowingUser(e),o("start-following",{source:"people-menu"}))},[n,e,o]),a=(s==null?void 0:s.followingUserId)===n.user.getId(),l=n.getInstanceState().followingUserId===e;return s?d.jsxs("div",{className:"tlui-people-menu__item tlui-buttons__horizontal",children:[d.jsxs(ce,{type:"menu",className:"tlui-people-menu__item__button",onClick:()=>n.zoomToUser(e),onDoubleClick:i,children:[d.jsx(Bo,{icon:"color",color:s.color}),d.jsx("div",{className:"tlui-people-menu__name",children:s.userName??"New User"})]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__item__follow",title:r(a?"people-menu.leading":l?"people-menu.following":"people-menu.follow"),onClick:i,disabled:a,"data-active":l||a,children:d.jsx(be,{icon:a?"leading":l?"following":"follow"})})]}):null});function rpe({count:t}){return d.jsx("div",{className:"tlui-people-menu__more",children:"+"+Math.abs(t)})}const ope=qt(function(){const e=z(),n=Mt(),r=Ee(),o=Qt(),s=w.useRef(!1),[i,a]=w.useState(!1),l=w.useCallback(m=>{a(m)},[]),c=e.user.getColor(),u=w.useCallback(m=>{e.user.updateUserPreferences({color:m}),o("set-color",{source:"people-menu"})},[e,o]),{handleButtonClick:h,handleButtonPointerDown:p,handleButtonPointerEnter:f,handleButtonPointerUp:g}=Te.useMemo(()=>{const m=()=>{s.current=!1,window.removeEventListener("pointerup",m)};return{handleButtonClick:P=>{const{id:C}=P.currentTarget.dataset;C&&c!==C&&u(C)},handleButtonPointerDown:P=>{const{id:C}=P.currentTarget.dataset;C&&(u(C),s.current=!0,window.addEventListener("pointerup",m))},handleButtonPointerEnter:P=>{if(!s.current)return;const{id:C}=P.currentTarget.dataset;C&&u(C)},handleButtonPointerUp:P=>{const{id:C}=P.currentTarget.dataset;C&&u(C)}}},[c,u]);return d.jsxs(Ub,{onOpenChange:l,open:i,children:[d.jsx(Hb,{dir:"ltr",asChild:!0,children:d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__color",style:{color:e.user.getColor()},title:r("people-menu.change-color"),children:d.jsx(be,{icon:"color"})})}),d.jsx(Kb,{container:n,children:d.jsx(Wb,{dir:"ltr",className:"tlui-menu tlui-people-menu__user__color-picker",align:"start",side:"left",sideOffset:8,children:d.jsx("div",{className:"tlui-buttons__grid",children:Px.map(m=>d.jsx(ce,{type:"icon","data-id":m,"data-testid":m,"aria-label":m,"data-state":c===m?"hinted":void 0,title:m,className:"tlui-button-grid__button",style:{color:m},onPointerEnter:f,onPointerDown:p,onPointerUp:g,onClick:h,children:d.jsx(be,{icon:"color"})},m))})})})]})});function spe(){const t=z(),e=Qt(),n=U("userName",()=>t.user.getName(),[]),r=Ee(),o=w.useRef(n),s=w.useRef(n),[i,a]=w.useState(!1),l=w.useCallback(()=>{a(p=>!p)},[]),c=w.useCallback(p=>{s.current=p,t.user.updateUserPreferences({name:p})},[t]),u=w.useCallback(()=>{o.current!==s.current&&(e("change-user-name",{source:"people-menu"}),o.current=s.current)},[e]),h=w.useCallback(()=>{a(!1),t.user.updateUserPreferences({name:o.current}),t.menus.clearOpenMenus()},[t]);return d.jsxs("div",{className:"tlui-people-menu__user",children:[d.jsx(ope,{}),i?d.jsx(fm,{className:"tlui-people-menu__user__input",defaultValue:n,onValueChange:c,onComplete:l,onCancel:h,onBlur:u,shouldManuallyMaintainScrollPositionWhenFocused:!0,autoFocus:!0,autoSelect:!0}):d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"tlui-people-menu__user__name",onDoubleClick:()=>{i||a(!0)},children:n}),n==="New User"?d.jsx("div",{className:"tlui-people-menu__user__label",children:r("people-menu.user")}):null]}),d.jsx(ce,{type:"icon",className:"tlui-people-menu__user__edit","data-testid":"people-menu.change-name",title:r("people-menu.change-name"),onClick:l,children:d.jsx(be,{icon:i?"check":"edit"})})]})}function ipe({displayUserWhenAlone:t,children:e}){const n=Ee(),r=Mt(),o=z(),s=Pj(),i=U("user",()=>o.user.getColor(),[o]),a=U("user",()=>o.user.getName(),[o]),[l,c]=Ms("people menu");return d.jsxs(Ub,{onOpenChange:c,open:l,children:[d.jsx(Hb,{dir:"ltr",asChild:!0,children:d.jsxs("button",{className:"tlui-people-menu__avatars-button",title:n("people-menu.title"),children:[s.length>5&&d.jsx(rpe,{count:s.length-5}),d.jsxs("div",{className:"tlui-people-menu__avatars",children:[s.slice(-5).map(u=>d.jsx(tpe,{userId:u},u)),(t||s.length>0)&&d.jsx("div",{className:"tlui-people-menu__avatar",style:{backgroundColor:i},children:a==="New User"?"":a[0]??""})]})]})}),d.jsx(Kb,{container:r,children:d.jsx(Wb,{dir:"ltr",className:"tlui-menu",side:"bottom",sideOffset:2,collisionPadding:4,onEscapeKeyDown:xe,children:d.jsxs("div",{className:"tlui-people-menu__wrapper",children:[d.jsx("div",{className:"tlui-people-menu__section",children:d.jsx(spe,{})}),s.length>0&&d.jsx("div",{className:"tlui-people-menu__section",children:s.map(u=>d.jsx(npe,{userId:u},u+"_presence"))}),e]})})})]})}function ape(){return d.jsx("div",{className:"tlui-share-zone",draggable:!1,children:d.jsx(ipe,{displayUserWhenAlone:!0})})}const lpe=Object.freeze([mr,ca,ua,Fo]);function c4(t=lpe){const e=z();return U("getRelevantStyles",()=>{var s;const n=new Tx(e.getSharedStyles()),r=!!((s=e.root.getCurrent())!=null&&s.shapeType),o=e.isIn("select")&&e.getSelectedShapeIds().length>0;if(n.size===0&&e.isIn("select")&&e.getSelectedShapeIds().length===0)for(const i of t)n.applyValue(i,e.getStyleForNextShape(i));return r||o||n.size>0?n:null},[e])}const jr={color:[{value:"black",icon:"color"},{value:"grey",icon:"color"},{value:"light-violet",icon:"color"},{value:"violet",icon:"color"},{value:"blue",icon:"color"},{value:"light-blue",icon:"color"},{value:"yellow",icon:"color"},{value:"orange",icon:"color"},{value:"green",icon:"color"},{value:"light-green",icon:"color"},{value:"light-red",icon:"color"},{value:"red",icon:"color"}],fill:[{value:"none",icon:"fill-none"},{value:"semi",icon:"fill-semi"},{value:"solid",icon:"fill-solid"},{value:"pattern",icon:"fill-pattern"}],dash:[{value:"draw",icon:"dash-draw"},{value:"dashed",icon:"dash-dashed"},{value:"dotted",icon:"dash-dotted"},{value:"solid",icon:"dash-solid"}],size:[{value:"s",icon:"size-small"},{value:"m",icon:"size-medium"},{value:"l",icon:"size-large"},{value:"xl",icon:"size-extra-large"}],font:[{value:"draw",icon:"font-draw"},{value:"sans",icon:"font-sans"},{value:"serif",icon:"font-serif"},{value:"mono",icon:"font-mono"}],textAlign:[{value:"start",icon:"text-align-left"},{value:"middle",icon:"text-align-center"},{value:"end",icon:"text-align-right"}],horizontalAlign:[{value:"start",icon:"horizontal-align-start"},{value:"middle",icon:"horizontal-align-middle"},{value:"end",icon:"horizontal-align-end"}],verticalAlign:[{value:"start",icon:"vertical-align-start"},{value:"middle",icon:"vertical-align-middle"},{value:"end",icon:"vertical-align-end"}],geo:[{value:"rectangle",icon:"geo-rectangle"},{value:"ellipse",icon:"geo-ellipse"},{value:"triangle",icon:"geo-triangle"},{value:"diamond",icon:"geo-diamond"},{value:"star",icon:"geo-star"},{value:"pentagon",icon:"geo-pentagon"},{value:"hexagon",icon:"geo-hexagon"},{value:"octagon",icon:"geo-octagon"},{value:"rhombus",icon:"geo-rhombus"},{value:"rhombus-2",icon:"geo-rhombus-2"},{value:"oval",icon:"geo-oval"},{value:"trapezoid",icon:"geo-trapezoid"},{value:"arrow-left",icon:"geo-arrow-left"},{value:"arrow-up",icon:"geo-arrow-up"},{value:"arrow-down",icon:"geo-arrow-down"},{value:"arrow-right",icon:"geo-arrow-right"},{value:"cloud",icon:"geo-cloud"},{value:"x-box",icon:"geo-x-box"},{value:"check-box",icon:"geo-check-box"},{value:"heart",icon:"geo-heart"}],arrowheadStart:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],arrowheadEnd:[{value:"none",icon:"arrowhead-none"},{value:"arrow",icon:"arrowhead-arrow"},{value:"triangle",icon:"arrowhead-triangle"},{value:"square",icon:"arrowhead-square"},{value:"dot",icon:"arrowhead-dot"},{value:"diamond",icon:"arrowhead-diamond"},{value:"inverted",icon:"arrowhead-triangle-inverted"},{value:"bar",icon:"arrowhead-bar"}],spline:[{value:"line",icon:"spline-line"},{value:"cubic",icon:"spline-cubic"}]},Yi=w.memo(function(e){const{uiType:n,items:r,title:o,style:s,value:i,onValueChange:a,onHistoryMark:l,theme:c}=e,u=Ee(),h=w.useRef(!1),p=w.useRef(null),{handleButtonClick:f,handleButtonPointerDown:g,handleButtonPointerEnter:m,handleButtonPointerUp:v}=w.useMemo(()=>{const y=()=>{h.current=!1,window.removeEventListener("pointerup",y);const _=p.current;_&&["TEXTAREA","INPUT"].includes(_.nodeName)&&_.focus(),p.current=null};return{handleButtonClick:_=>{const{id:E}=_.currentTarget.dataset;i.type==="shared"&&i.value===E||(l==null||l("point picker item"),a(s,E))},handleButtonPointerDown:_=>{const{id:E}=_.currentTarget.dataset;l==null||l("point picker item"),a(s,E),h.current=!0,p.current=document.activeElement,window.addEventListener("pointerup",y)},handleButtonPointerEnter:_=>{if(!h.current)return;const{id:E}=_.currentTarget.dataset;a(s,E)},handleButtonPointerUp:_=>{const{id:E}=_.currentTarget.dataset;i.type==="shared"&&i.value===E||a(s,E)}}},[i,l,a,s]);return d.jsx("div",{"data-testid":`style.${n}`,className:le("tlui-buttons__grid"),children:r.map(y=>d.jsx(ce,{type:"icon","data-id":y.value,"data-testid":`style.${n}.${y.value}`,"aria-label":y.value,"data-state":i.type==="shared"&&i.value===y.value?"hinted":void 0,title:o+" — "+u(`${n}-style.${y.value}`),className:le("tlui-button-grid__button"),style:s===mr?{color:c[y.value].solid}:void 0,onPointerEnter:m,onPointerDown:g,onPointerUp:v,onClick:f,children:d.jsx(be,{icon:y.icon})},y.value))})});function u4(t,[e,n]){return Math.min(n,Math.max(e,t))}function cpe(t){const e=w.useRef({value:t,previous:t});return w.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var d4=["PageUp","PageDown"],h4=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],p4={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},lc="Slider",[m0,upe,dpe]=Jg(lc),[f4,Dge]=Go(lc,[dpe]),[hpe,Tm]=f4(lc),g4=w.forwardRef((t,e)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,form:g,...m}=t,v=w.useRef(new Set),y=w.useRef(0),b=i==="horizontal"?ppe:fpe,[P=[],C]=Ai({prop:u,defaultProp:c,onChange:j=>{var M;(M=[...v.current][y.current])==null||M.focus(),h(j)}}),_=w.useRef(P);function E(j){const $=vpe(P,j);T(j,$)}function k(j){T(j,y.current)}function D(){const j=_.current[y.current];P[y.current]!==j&&p(P)}function T(j,$,{commit:M}={commit:!1}){const O=Ppe(s),F=Cpe(Math.round((j-r)/s)*s+r,O),B=u4(F,[r,o]);C((K=[])=>{const R=ype(K,B,$);if(bpe(R,l*s)){y.current=R.indexOf(B);const H=String(R)!==String(K);return H&&M&&p(R),H?R:K}else return K})}return d.jsx(hpe,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:v.current,values:P,orientation:i,form:g,children:d.jsx(m0.Provider,{scope:t.__scopeSlider,children:d.jsx(m0.Slot,{scope:t.__scopeSlider,children:d.jsx(b,{"aria-disabled":a,"data-disabled":a?"":void 0,...m,ref:e,onPointerDown:oe(m.onPointerDown,()=>{a||(_.current=P)}),min:r,max:o,inverted:f,onSlideStart:a?void 0:E,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&T(r,0,{commit:!0}),onEndKeyDown:()=>!a&&T(o,P.length-1,{commit:!0}),onStepKeyDown:({event:j,direction:$})=>{if(!a){const F=d4.includes(j.key)||j.shiftKey&&h4.includes(j.key)?10:1,B=y.current,K=P[B],R=s*F*$;T(K+R,B,{commit:!0})}}})})})})});g4.displayName=lc;var[m4,y4]=f4(lc,{startEdge:"left",endEdge:"right",size:"width",direction:1}),ppe=w.forwardRef((t,e)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=t,[h,p]=w.useState(null),f=Ze(e,b=>p(b)),g=w.useRef(void 0),m=F1(o),v=m==="ltr",y=v&&!s||!v&&s;function S(b){const P=g.current||h.getBoundingClientRect(),C=[0,P.width],E=qb(C,y?[n,r]:[r,n]);return g.current=P,E(b-P.left)}return d.jsx(m4,{scope:t.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:d.jsx(S4,{dir:m,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:b=>{const P=S(b.clientX);i==null||i(P)},onSlideMove:b=>{const P=S(b.clientX);a==null||a(P)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:b=>{const C=p4[y?"from-left":"from-right"].includes(b.key);c==null||c({event:b,direction:C?-1:1})}})})}),fpe=w.forwardRef((t,e)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...c}=t,u=w.useRef(null),h=Ze(e,u),p=w.useRef(void 0),f=!o;function g(m){const v=p.current||u.current.getBoundingClientRect(),y=[0,v.height],b=qb(y,f?[r,n]:[n,r]);return p.current=v,b(m-v.top)}return d.jsx(m4,{scope:t.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:d.jsx(S4,{"data-orientation":"vertical",...c,ref:h,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:m=>{const v=g(m.clientY);s==null||s(v)},onSlideMove:m=>{const v=g(m.clientY);i==null||i(v)},onSlideEnd:()=>{p.current=void 0,a==null||a()},onStepKeyDown:m=>{const y=p4[f?"from-bottom":"from-top"].includes(m.key);l==null||l({event:m,direction:y?-1:1})}})})}),S4=w.forwardRef((t,e)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...c}=t,u=Tm(lc,n);return d.jsx(Ae.span,{...c,ref:e,onKeyDown:oe(t.onKeyDown,h=>{h.key==="Home"?(i(h),h.preventDefault()):h.key==="End"?(a(h),h.preventDefault()):d4.concat(h4).includes(h.key)&&(l(h),h.preventDefault())}),onPointerDown:oe(t.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:oe(t.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&o(h)}),onPointerUp:oe(t.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),s(h))})})}),v4="SliderTrack",x4=w.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,o=Tm(v4,n);return d.jsx(Ae.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:e})});x4.displayName=v4;var y0="SliderRange",w4=w.forwardRef((t,e)=>{const{__scopeSlider:n,...r}=t,o=Tm(y0,n),s=y4(y0,n),i=w.useRef(null),a=Ze(e,i),l=o.values.length,c=o.values.map(p=>P4(p,o.min,o.max)),u=l>1?Math.min(...c):0,h=100-Math.max(...c);return d.jsx(Ae.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...t.style,[s.startEdge]:u+"%",[s.endEdge]:h+"%"}})});w4.displayName=y0;var S0="SliderThumb",b4=w.forwardRef((t,e)=>{const n=upe(t.__scopeSlider),[r,o]=w.useState(null),s=Ze(e,a=>o(a)),i=w.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return d.jsx(gpe,{...t,ref:s,index:i})}),gpe=w.forwardRef((t,e)=>{const{__scopeSlider:n,index:r,name:o,...s}=t,i=Tm(S0,n),a=y4(S0,n),[l,c]=w.useState(null),u=Ze(e,S=>c(S)),h=l?i.form||!!l.closest("form"):!0,p=f3(l),f=i.values[r],g=f===void 0?0:P4(f,i.min,i.max),m=Spe(r,i.values.length),v=p==null?void 0:p[a.size],y=v?xpe(v,g,a.direction):0;return w.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[d.jsx(m0.ItemSlot,{scope:t.__scopeSlider,children:d.jsx(Ae.span,{role:"slider","aria-label":t["aria-label"]||m,"aria-valuemin":i.min,"aria-valuenow":f,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:u,style:f===void 0?{display:"none"}:t.style,onFocus:oe(t.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),h&&d.jsx(mpe,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:f},r)]})});b4.displayName=S0;var mpe=t=>{const{value:e,...n}=t,r=w.useRef(null),o=cpe(e);return w.useEffect(()=>{const s=r.current,i=window.HTMLInputElement.prototype,l=Object.getOwnPropertyDescriptor(i,"value").set;if(o!==e&&l){const c=new Event("input",{bubbles:!0});l.call(s,e),s.dispatchEvent(c)}},[o,e]),d.jsx("input",{style:{display:"none"},...n,ref:r,defaultValue:e})};function ype(t=[],e,n){const r=[...t];return r[n]=e,r.sort((o,s)=>o-s)}function P4(t,e,n){const s=100/(n-e)*(t-e);return u4(s,[0,100])}function Spe(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function vpe(t,e){if(t.length===1)return 0;const n=t.map(o=>Math.abs(o-e)),r=Math.min(...n);return n.indexOf(r)}function xpe(t,e,n){const r=t/2,s=qb([0,50],[0,r]);return(r-s(e)*n)*n}function wpe(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function bpe(t,e){if(e>0){const n=wpe(t);return Math.min(...n)>=e}return!0}function qb(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];const r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function Ppe(t){return(String(t).split(".")[1]||"").length}function Cpe(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}var _pe=g4,Ipe=x4,Epe=w4,kpe=b4;const Tpe=w.memo(function({onHistoryMark:e,title:n,steps:r,value:o,label:s,onValueChange:i,["data-testid"]:a}){const l=Ee(),c=w.useCallback(p=>{i(p[0])},[i]),u=w.useCallback(()=>{e("click slider")},[e]),h=w.useCallback(()=>{o&&i(o)},[o,i]);return d.jsx("div",{className:"tlui-slider__container",children:d.jsxs(_pe,{"data-testid":a,className:"tlui-slider","area-label":"Opacity",dir:"ltr",min:0,max:r,step:1,value:o?[o]:void 0,onPointerDown:u,onValueChange:c,onPointerUp:h,title:n+" — "+l(s),children:[d.jsx(Ipe,{className:"tlui-slider__track",dir:"ltr",children:o!==null&&d.jsx(Epe,{className:"tlui-slider__range",dir:"ltr"})}),o!==null&&d.jsx(kpe,{className:"tlui-slider__thumb",dir:"ltr"})]})})});function Mpe({label:t,uiTypeA:e,uiTypeB:n,labelA:r,labelB:o,itemsA:s,itemsB:i,styleA:a,styleB:l,valueA:c,valueB:u,onValueChange:h}){const p=Ee(),f=w.useMemo(()=>{var m;return((m=s.find(v=>c.type==="shared"&&c.value===v.value))==null?void 0:m.icon)??"mixed"},[s,c]),g=w.useMemo(()=>{var m;return((m=i.find(v=>u.type==="shared"&&u.value===v.value))==null?void 0:m.icon)??"mixed"},[i,u]);return c===void 0&&u===void 0?null:d.jsxs("div",{className:"tlui-style-panel__double-select-picker",children:[d.jsx("div",{title:p(t),className:"tlui-style-panel__double-select-picker-label",children:p(t)}),d.jsxs("div",{className:"tlui-buttons__horizontal",children:[d.jsxs(ga,{id:`style panel ${e} A`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon","data-testid":`style.${e}`,title:p(r)+" — "+(c===null||c.type==="mixed"?p("style-panel.mixed"):p(`${e}-style.${c.value}`)),children:d.jsx(be,{icon:f,small:!0,invertIcon:!0})})}),d.jsx(ya,{side:"left",align:"center",sideOffset:80,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map((m,v)=>d.jsx(qu,{"data-testid":`style.${e}.${m.value}`,children:d.jsx(ce,{type:"icon",onClick:()=>h(a,m.value),title:`${p(r)} — ${p(`${e}-style.${m.value}`)}`,children:d.jsx(be,{icon:m.icon,invertIcon:!0})},m.value)},v))})})]}),d.jsxs(ga,{id:`style panel ${n}`,children:[d.jsx(ma,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}`,title:p(o)+" — "+(u===null||u.type==="mixed"?p("style-panel.mixed"):p(`${n}-style.${u.value}`)),children:d.jsx(be,{icon:g,small:!0})})}),d.jsx(ya,{side:"left",align:"center",sideOffset:116,alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:i.map(m=>d.jsx(qu,{children:d.jsx(ce,{type:"icon",title:`${p(o)} — ${p(`${n}-style.${m.value}`)}`,"data-testid":`style.${n}.${m.value}`,onClick:()=>h(l,m.value),children:d.jsx(be,{icon:m.icon})})},m.value))})})]})]})]})}const Ape=w.memo(Mpe);function jpe({id:t,label:e,uiType:n,stylePanelType:r,style:o,items:s,type:i,value:a,onValueChange:l}){const c=Ee(),u=z(),h=w.useMemo(()=>{var m;return(m=s.find(v=>a.type==="shared"&&v.value===a.value))==null?void 0:m.icon},[s,a]),p=c(`style-panel.${r}`),f=a.type==="mixed"?c("style-panel.mixed"):p+" — "+c(`${n}-style.${a.value}`),g=e?c(e):"";return d.jsxs(ga,{id:`style panel ${t}`,children:[d.jsx(ma,{children:d.jsxs(ce,{type:i,"data-testid":`style.${n}`,title:f,children:[g&&d.jsx(Pt,{children:g}),d.jsx(be,{icon:h??"mixed"})]})}),d.jsx(ya,{side:"left",align:"center",alignOffset:0,children:d.jsx("div",{className:"tlui-buttons__grid",children:s.map(m=>d.jsx(qu,{children:d.jsx(ce,{type:"icon","data-testid":`style.${n}.${m.value}`,title:p+" — "+c(`${n}-style.${m.value}`),onClick:()=>{u.markHistoryStoppingPoint("select style dropdown item"),l(o,m.value)},children:d.jsx(be,{icon:m.icon})})},m.value))})})]})}const Zb=w.memo(jpe);function Ope({styles:t}){const e=xd();if(!t)return null;const n=t.get(Jr),r=t.get(Tf),o=t.get(kf),s=t.get(Of),i=t.get($o),a=n===void 0,l=r===void 0&&o===void 0,c=s===void 0,u=i===void 0,h=ks({isDarkMode:e});return d.jsxs(d.Fragment,{children:[d.jsx(Dpe,{theme:h,styles:t}),!u&&d.jsx(Rpe,{theme:h,styles:t}),!(a&&l&&c)&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[d.jsx(Lpe,{styles:t}),d.jsx(Fpe,{styles:t}),d.jsx($pe,{styles:t})]})]})}function Td(){const t=z(),e=Qt();return Te.useMemo(()=>function(r,o){t.run(()=>{t.isIn("select")&&t.setStyleForSelectedShapes(r,o),t.setStyleForNextShapes(r,o),t.updateInstanceState({isChangingStyle:!0})}),e("set-style",{source:"style-panel",id:r.id,value:o})},[t,e])}function Dpe({styles:t,theme:e}){const n=Ee(),r=z(),o=w.useCallback(h=>r.markHistoryStoppingPoint(h),[r]),s=Td(),i=t.get(mr),a=t.get(ua),l=t.get(ca),c=t.get(Fo),u=a!==void 0||l!==void 0||c!==void 0;return d.jsxs(d.Fragment,{children:[d.jsxs("div",{tabIndex:-1,className:"tlui-style-panel__section__common","aria-label":"style panel styles","data-testid":"style.panel",children:[i===void 0?null:d.jsx(Yi,{title:n("style-panel.color"),uiType:"color",style:mr,items:jr.color,value:i,onValueChange:s,theme:e,onHistoryMark:o}),d.jsx(Npe,{})]}),u&&d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel styles",children:[a===void 0?null:d.jsx(Yi,{title:n("style-panel.fill"),uiType:"fill",style:ua,items:jr.fill,value:a,onValueChange:s,theme:e,onHistoryMark:o}),l===void 0?null:d.jsx(Yi,{title:n("style-panel.dash"),uiType:"dash",style:ca,items:jr.dash,value:l,onValueChange:s,theme:e,onHistoryMark:o}),c===void 0?null:d.jsx(Yi,{title:n("style-panel.size"),uiType:"size",style:Fo,items:jr.size,value:c,onValueChange:(h,p)=>{s(h,p);const f=r.getSelectedShapeIds();f.length>0&&Ye(r,f)},theme:e,onHistoryMark:o})]})]})}function Rpe({theme:t,styles:e}){const n=Ee(),r=Td(),o=z(),s=w.useCallback(u=>o.markHistoryStoppingPoint(u),[o]),i=e.get($o),a=e.get(Sx),l=e.get(Af),c=e.get(jf);return i===void 0&&l===void 0?null:d.jsxs("div",{className:"tlui-style-panel__section","aria-label":"style panel text",children:[i===void 0?null:d.jsx(Yi,{title:n("style-panel.font"),uiType:"font",style:$o,items:jr.font,value:i,onValueChange:r,theme:t,onHistoryMark:s}),a===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(Yi,{title:n("style-panel.align"),uiType:"align",style:Sx,items:jr.textAlign,value:a,onValueChange:r,theme:t,onHistoryMark:s}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:d.jsx(ce,{type:"icon",title:n("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(be,{icon:"vertical-align-middle"})})})]}),l===void 0?null:d.jsxs("div",{className:"tlui-style-panel__row",children:[d.jsx(Yi,{title:n("style-panel.label-align"),uiType:"align",style:Af,items:jr.horizontalAlign,value:l,onValueChange:r,theme:t,onHistoryMark:s}),d.jsx("div",{className:"tlui-style-panel__row__extra-button",children:c===void 0?d.jsx(ce,{type:"icon",title:n("style-panel.vertical-align"),"data-testid":"vertical-align",disabled:!0,children:d.jsx(be,{icon:"vertical-align-middle"})}):d.jsx(Zb,{type:"icon",id:"geo-vertical-alignment",uiType:"verticalAlign",stylePanelType:"vertical-align",style:jf,items:jr.verticalAlign,value:c,onValueChange:r})})]})]})}function Lpe({styles:t}){const e=Td(),n=t.get(Jr);return n===void 0?null:d.jsx(Zb,{id:"geo",type:"menu",label:"style-panel.geo",uiType:"geo",stylePanelType:"geo",style:Jr,items:jr.geo,value:n,onValueChange:e})}function $pe({styles:t}){const e=Td(),n=t.get(Of);return n===void 0?null:d.jsx(Zb,{id:"spline",type:"menu",label:"style-panel.spline",uiType:"spline",stylePanelType:"spline",style:Of,items:jr.spline,value:n,onValueChange:e})}function Fpe({styles:t}){const e=Td(),n=t.get(Tf),r=t.get(kf);return!n||!r?null:d.jsx(Ape,{label:"style-panel.arrowheads",uiTypeA:"arrowheadStart",styleA:kf,itemsA:jr.arrowheadStart,valueA:r,uiTypeB:"arrowheadEnd",styleB:Tf,itemsB:jr.arrowheadEnd,valueB:n,onValueChange:e,labelA:"style-panel.arrowhead-start",labelB:"style-panel.arrowhead-end"})}const $c=[.1,.25,.5,.75,1];function Npe(){const t=z(),e=w.useCallback(a=>t.markHistoryStoppingPoint(a),[t]),n=U("opacity",()=>t.getSharedOpacity(),[t]),r=Qt(),o=Ee(),s=Te.useCallback(a=>{const l=$c[a];t.run(()=>{t.isIn("select")&&t.setOpacityForSelectedShapes(l),t.setOpacityForNextShapes(l),t.updateInstanceState({isChangingStyle:!0})}),r("set-style",{source:"style-panel",id:"opacity",value:a})},[t,r]);if(n===void 0)return null;const i=n.type==="mixed"?-1:$c.indexOf(T9($c,a=>Math.abs(a-n.value)));return d.jsx(Tpe,{"data-testid":"style.opacity",value:i>=0?i:$c.length-1,label:n.type==="mixed"?"style-panel.mixed":`opacity-style.${n.value}`,onValueChange:s,steps:$c.length-1,title:o("style-panel.opacity"),onHistoryMark:e})}const zpe=w.memo(function({isMobile:e,children:n}){const r=z(),o=w.useRef(null);Mi(o);const s=c4(),i=w.useCallback(()=>{e||r.updateInstanceState({isChangingStyle:!1})},[r,e]),a=n??d.jsx(Ope,{styles:s});return d.jsx("div",{ref:o,className:le("tlui-style-panel",{"tlui-style-panel__wrapper":!e}),"data-ismobile":e,onPointerLeave:i,children:a})});function Bpe(){const t=z(),e=Ee(),n=c4(),r=n==null?void 0:n.get(mr),o=ks({isDarkMode:t.user.getIsDarkMode()}),s=((r==null?void 0:r.type)==="shared"?o[r.value]:o.black).solid,i=U("disable style panel",()=>t.isInAny("hand","zoom","eraser","laser"),[t]),a=w.useCallback(c=>{c||t.updateInstanceState({isChangingStyle:!1})},[t]),{StylePanel:l}=Di();return l?d.jsxs(Gb,{id:"mobile style menu",onOpenChange:a,children:[d.jsx(Vb,{children:d.jsx(ce,{type:"tool","data-testid":"mobile-styles.button",style:{color:i?"var(--color-muted-1)":s},title:e("style-panel.title"),disabled:i,children:d.jsx(be,{icon:i?"blob":(r==null?void 0:r.type)==="mixed"?"mixed":"blob"})})}),d.jsx(Yb,{side:"top",align:"end",children:l&&d.jsx(l,{isMobile:!0})})]}):null}function Upe(){return d.jsxs(d.Fragment,{children:[d.jsx(Kpe,{}),d.jsx(Wpe,{}),d.jsx(Gpe,{}),d.jsx(Vpe,{}),d.jsx(Ype,{}),d.jsx(Xpe,{}),d.jsx(qpe,{}),d.jsx(Zpe,{}),d.jsx(Qpe,{}),d.jsx(Jpe,{}),d.jsx(tfe,{}),d.jsx(efe,{}),d.jsx(ofe,{}),d.jsx(afe,{}),d.jsx(nfe,{}),d.jsx(ife,{}),d.jsx(sfe,{}),d.jsx(rfe,{}),d.jsx(lfe,{}),d.jsx(cfe,{}),d.jsx(ufe,{}),d.jsx(dfe,{}),d.jsx(hfe,{}),d.jsx(pfe,{}),d.jsx(ffe,{}),d.jsx(gfe,{}),d.jsx(yfe,{}),d.jsx(mfe,{})]})}function Hpe(t){var r;const e=z(),n=(r=t.meta)==null?void 0:r.geo;return U("is tool selected",()=>{const o=e.getCurrentToolId(),s=e.getSharedStyles().getAsKnownValue(Jr);return n?o==="geo"&&s===n:o===t.id},[e,t.id,n])}function Ve({tool:t}){const e=Eb(),n=Hpe(e[t]);return d.jsx(Ln,{toolId:t,isSelected:n})}function Kpe(){return d.jsx(Ve,{tool:"select"})}function Wpe(){return d.jsx(Ve,{tool:"hand"})}function Gpe(){return d.jsx(Ve,{tool:"draw"})}function Vpe(){return d.jsx(Ve,{tool:"eraser"})}function Ype(){return d.jsx(Ve,{tool:"arrow"})}function Xpe(){return d.jsx(Ve,{tool:"text"})}function qpe(){return d.jsx(Ve,{tool:"note"})}function Zpe(){return d.jsx(Ln,{toolId:"asset"})}function Qpe(){return d.jsx(Ve,{tool:"rectangle"})}function Jpe(){return d.jsx(Ve,{tool:"ellipse"})}function efe(){return d.jsx(Ve,{tool:"diamond"})}function tfe(){return d.jsx(Ve,{tool:"triangle"})}function nfe(){return d.jsx(Ve,{tool:"rhombus"})}function rfe(){return d.jsx(Ve,{tool:"heart"})}function ofe(){return d.jsx(Ve,{tool:"hexagon"})}function sfe(){return d.jsx(Ve,{tool:"cloud"})}function ife(){return d.jsx(Ve,{tool:"star"})}function afe(){return d.jsx(Ve,{tool:"oval"})}function lfe(){return d.jsx(Ve,{tool:"x-box"})}function cfe(){return d.jsx(Ve,{tool:"check-box"})}function ufe(){return d.jsx(Ve,{tool:"arrow-left"})}function dfe(){return d.jsx(Ve,{tool:"arrow-up"})}function hfe(){return d.jsx(Ve,{tool:"arrow-down"})}function pfe(){return d.jsx(Ve,{tool:"arrow-right"})}function ffe(){return d.jsx(Ve,{tool:"line"})}function gfe(){return d.jsx(Ve,{tool:"highlight"})}function mfe(){return d.jsx(Ve,{tool:"frame"})}function yfe(){return d.jsx(Ve,{tool:"laser"})}const TS=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function MS(t,e,n,r){t.addEventListener?t.addEventListener(e,n,r):t.attachEvent&&t.attachEvent("on".concat(e),n)}function Fc(t,e,n,r){t.removeEventListener?t.removeEventListener(e,n,r):t.detachEvent&&t.detachEvent("on".concat(e),n)}function C4(t,e){const n=e.slice(0,e.length-1);for(let r=0;r<n.length;r++)n[r]=t[n[r].toLowerCase()];return n}function _4(t){typeof t!="string"&&(t=""),t=t.replace(/\s/g,"");const e=t.split(",");let n=e.lastIndexOf("");for(;n>=0;)e[n-1]+=",",e.splice(n,1),n=e.lastIndexOf("");return e}function Sfe(t,e){const n=t.length>=e.length?t:e,r=t.length>=e.length?e:t;let o=!0;for(let s=0;s<n.length;s++)r.indexOf(n[s])===-1&&(o=!1);return o}const Zu={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":TS?173:189,"=":TS?61:187,";":TS?59:186,"'":222,"[":219,"]":221,"\\":220},Ho={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,command:91},$p={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},Bt={16:!1,18:!1,17:!1,91:!1},pt={};for(let t=1;t<20;t++)Zu["f".concat(t)]=111+t;let it=[],gu=null,I4="all";const os=new Map,Md=t=>Zu[t.toLowerCase()]||Ho[t.toLowerCase()]||t.toUpperCase().charCodeAt(0),vfe=t=>Object.keys(Zu).find(e=>Zu[e]===t),xfe=t=>Object.keys(Ho).find(e=>Ho[e]===t);function E4(t){I4=t||"all"}function Qu(){return I4||"all"}function wfe(){return it.slice(0)}function bfe(){return it.map(t=>vfe(t)||xfe(t)||String.fromCharCode(t))}function Pfe(){const t=[];return Object.keys(pt).forEach(e=>{pt[e].forEach(n=>{let{key:r,scope:o,mods:s,shortcut:i}=n;t.push({scope:o,shortcut:i,mods:s,keys:r.split("+").map(a=>Md(a))})})}),t}function Cfe(t){const e=t.target||t.srcElement,{tagName:n}=e;let r=!0;const o=n==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(o||n==="TEXTAREA"||n==="SELECT")&&!e.readOnly)&&(r=!1),r}function _fe(t){return typeof t=="string"&&(t=Md(t)),it.indexOf(t)!==-1}function Ife(t,e){let n,r;t||(t=Qu());for(const o in pt)if(Object.prototype.hasOwnProperty.call(pt,o))for(n=pt[o],r=0;r<n.length;)n[r].scope===t?n.splice(r,1).forEach(i=>{let{element:a}=i;return Qb(a)}):r++;Qu()===t&&E4(e||"all")}function Efe(t){let e=t.keyCode||t.which||t.charCode;const n=it.indexOf(e);if(n>=0&&it.splice(n,1),t.key&&t.key.toLowerCase()==="meta"&&it.splice(0,it.length),(e===93||e===224)&&(e=91),e in Bt){Bt[e]=!1;for(const r in Ho)Ho[r]===e&&(Wn[r]=!1)}}function k4(t){if(typeof t>"u")Object.keys(pt).forEach(o=>{Array.isArray(pt[o])&&pt[o].forEach(s=>Bh(s)),delete pt[o]}),Qb(null);else if(Array.isArray(t))t.forEach(o=>{o.key&&Bh(o)});else if(typeof t=="object")t.key&&Bh(t);else if(typeof t=="string"){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];let[o,s]=n;typeof o=="function"&&(s=o,o=""),Bh({key:t,scope:o,method:s,splitKey:"+"})}}const Bh=t=>{let{key:e,scope:n,method:r,splitKey:o="+"}=t;_4(e).forEach(i=>{const a=i.split(o),l=a.length,c=a[l-1],u=c==="*"?"*":Md(c);if(!pt[u])return;n||(n=Qu());const h=l>1?C4(Ho,a):[],p=[];pt[u]=pt[u].filter(f=>{const m=(r?f.method===r:!0)&&f.scope===n&&Sfe(f.mods,h);return m&&p.push(f.element),!m}),p.forEach(f=>Qb(f))})};function u2(t,e,n,r){if(e.element!==r)return;let o;if(e.scope===n||e.scope==="all"){o=e.mods.length>0;for(const s in Bt)Object.prototype.hasOwnProperty.call(Bt,s)&&(!Bt[s]&&e.mods.indexOf(+s)>-1||Bt[s]&&e.mods.indexOf(+s)===-1)&&(o=!1);(e.mods.length===0&&!Bt[16]&&!Bt[18]&&!Bt[17]&&!Bt[91]||o||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(it),e.method(t,e)===!1&&(t.preventDefault?t.preventDefault():t.returnValue=!1,t.stopPropagation&&t.stopPropagation(),t.cancelBubble&&(t.cancelBubble=!0)))}}function d2(t,e){const n=pt["*"];let r=t.keyCode||t.which||t.charCode;if(!Wn.filter.call(this,t))return;if((r===93||r===224)&&(r=91),it.indexOf(r)===-1&&r!==229&&it.push(r),["metaKey","ctrlKey","altKey","shiftKey"].forEach(a=>{const l=$p[a];t[a]&&it.indexOf(l)===-1?it.push(l):!t[a]&&it.indexOf(l)>-1?it.splice(it.indexOf(l),1):a==="metaKey"&&t[a]&&(it=it.filter(c=>c in $p||c===r))}),r in Bt){Bt[r]=!0;for(const a in Ho)Ho[a]===r&&(Wn[a]=!0);if(!n)return}for(const a in Bt)Object.prototype.hasOwnProperty.call(Bt,a)&&(Bt[a]=t[$p[a]]);t.getModifierState&&!(t.altKey&&!t.ctrlKey)&&t.getModifierState("AltGraph")&&(it.indexOf(17)===-1&&it.push(17),it.indexOf(18)===-1&&it.push(18),Bt[17]=!0,Bt[18]=!0);const o=Qu();if(n)for(let a=0;a<n.length;a++)n[a].scope===o&&(t.type==="keydown"&&n[a].keydown||t.type==="keyup"&&n[a].keyup)&&u2(t,n[a],o,e);if(!(r in pt))return;const s=pt[r],i=s.length;for(let a=0;a<i;a++)if((t.type==="keydown"&&s[a].keydown||t.type==="keyup"&&s[a].keyup)&&s[a].key){const l=s[a],{splitKey:c}=l,u=l.key.split(c),h=[];for(let p=0;p<u.length;p++)h.push(Md(u[p]));h.sort().join("")===it.sort().join("")&&u2(t,l,o,e)}}function Wn(t,e,n){it=[];const r=_4(t);let o=[],s="all",i=document,a=0,l=!1,c=!0,u="+",h=!1,p=!1;for(n===void 0&&typeof e=="function"&&(n=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(s=e.scope),e.element&&(i=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(c=e.keydown),e.capture!==void 0&&(h=e.capture),typeof e.splitKey=="string"&&(u=e.splitKey),e.single===!0&&(p=!0)),typeof e=="string"&&(s=e),p&&k4(t,s);a<r.length;a++)t=r[a].split(u),o=[],t.length>1&&(o=C4(Ho,t)),t=t[t.length-1],t=t==="*"?"*":Md(t),t in pt||(pt[t]=[]),pt[t].push({keyup:l,keydown:c,scope:s,mods:o,shortcut:r[a],method:n,key:r[a],splitKey:u,element:i});if(typeof i<"u"&&window){if(!os.has(i)){const f=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return d2(m,i)},g=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;d2(m,i),Efe(m)};os.set(i,{keydownListener:f,keyupListenr:g,capture:h}),MS(i,"keydown",f,h),MS(i,"keyup",g,h)}if(!gu){const f=()=>{it=[]};gu={listener:f,capture:h},MS(window,"focus",f,h)}}}function kfe(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(pt).forEach(n=>{pt[n].filter(o=>o.scope===e&&o.shortcut===t).forEach(o=>{o&&o.method&&o.method()})})}function Qb(t){const e=Object.values(pt).flat();if(e.findIndex(r=>{let{element:o}=r;return o===t})<0){const{keydownListener:r,keyupListenr:o,capture:s}=os.get(t)||{};r&&o&&(Fc(t,"keyup",o,s),Fc(t,"keydown",r,s),os.delete(t))}if((e.length<=0||os.size<=0)&&(Object.keys(os).forEach(o=>{const{keydownListener:s,keyupListenr:i,capture:a}=os.get(o)||{};s&&i&&(Fc(o,"keyup",i,a),Fc(o,"keydown",s,a),os.delete(o))}),os.clear(),Object.keys(pt).forEach(o=>delete pt[o]),gu)){const{listener:o,capture:s}=gu;Fc(window,"focus",o,s),gu=null}}const AS={getPressedKeyString:bfe,setScope:E4,getScope:Qu,deleteScope:Ife,getPressedKeyCodes:wfe,getAllKeyCodes:Pfe,isPressed:_fe,filter:Cfe,trigger:kfe,unbind:k4,keyMap:Zu,modifier:Ho,modifierMap:$p};for(const t in AS)Object.prototype.hasOwnProperty.call(AS,t)&&(Wn[t]=AS[t]);if(typeof window<"u"){const t=window.hotkeys;Wn.noConflict=e=>(e&&window.hotkeys===Wn&&(window.hotkeys=t),Wn),window.hotkeys=Wn}const h2=["copy","cut","paste","asset"];function Tfe(){const t=z(),e=wr(),n=Ea(),r=Eb(),o=U("is focused",()=>t.getInstanceState().isFocused,[t]);w.useEffect(()=>{if(!o)return;const s=new Array,i=(l,c)=>{Wn(l,{element:document.body},c),s.push(()=>{Wn.unbind(l,c)})},a=(l,c)=>{Wn(l,{element:document.body,keyup:!0,keydown:!1},c),s.push(()=>{Wn.unbind(l,c)})};for(const l of Object.values(n))l.kbd&&(e&&!l.readonlyOk||h2.includes(l.id)||i(p2(l.kbd),c=>{Qc(t)||(xe(c),l.onSelect("kbd"))}));for(const l of Object.values(r))!l.kbd||!l.readonlyOk&&t.getIsReadonly()||h2.includes(l.id)||i(p2(l.kbd),c=>{Qc(t)||(xe(c),l.onSelect("kbd"))});return i(",",l=>{if(Qc(t)||t.inputs.keys.has("Comma"))return;xe(l),t.focus(),t.inputs.keys.add("Comma");const{x:c,y:u,z:h}=t.inputs.currentPagePoint,p=t.pageToScreen({x:c,y:u}),f={type:"pointer",name:"pointer_down",point:{x:p.x,y:p.y,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:un(l),pointerId:0,button:0,isPen:t.getInstanceState().isPenMode,target:"canvas"};t.dispatch(f)}),a(",",l=>{if(Qc(t)||!t.inputs.keys.has("Comma"))return;t.inputs.keys.delete("Comma");const{x:c,y:u,z:h}=t.inputs.currentScreenPoint,p={type:"pointer",name:"pointer_up",point:{x:c,y:u,z:h},shiftKey:l.shiftKey,altKey:l.altKey,ctrlKey:l.metaKey||l.ctrlKey,metaKey:l.metaKey,accelKey:un(l),pointerId:0,button:0,isPen:t.getInstanceState().isPenMode,target:"canvas"};t.dispatch(p)}),()=>{s.forEach(l=>l())}},[n,r,e,t,o])}function p2(t){return Mfe(t).map(e=>{let n="";const r=e.split("");return r.length===1?n=r[0]:r[0]==="!"?n=`shift+${r[1]}`:r[0]==="?"?r.length===3&&r[1]==="!"?n=`alt+shift+${r[2]}`:n=`alt+${r[1]}`:r[0]==="$"?r[1]==="!"?n=`cmd+shift+${r[2]},ctrl+shift+${r[2]}`:r[1]==="?"?n=`cmd+⌥+${r[2]},ctrl+alt+${r[2]}`:n=`cmd+${r[1]},ctrl+${r[1]}`:n=e,n}).join(",")}function Mfe(t){typeof t!="string"&&(t=""),t=t.replace(/\s/g,"");const e=t.split(",");let n=e.lastIndexOf("");for(;n>=0;)e[n-1]+=",",e.splice(n,1),n=e.lastIndexOf("");return e}function Qc(t){return t.menus.hasAnyOpenMenus()||t.getEditingShapeId()!==null||t.getCrashingError()}const Afe=w.createContext(!1);function jfe({children:t}){const e=z(),n=Jl(),r=An(),o=Ee(),s=Math.min(8,5+r),[i,a]=w.useState(0),l=w.useRef(null),[c,u]=w.useState(null),h=w.useMemo(()=>{const f=c?`:not([data-value="${c}"])`:"";return`
412
412
  #${n}_main > *:nth-child(n + ${s+(c?1:2)})${f} {
413
413
  display: none;
414
414
  }
@@ -422,4 +422,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
422
422
  font-weight: ${p.weight};
423
423
  font-style: ${p.style};
424
424
  src: url("${n}") format("${u}")
425
- }`,p}const Uh=(t,e)=>{const[n,r]=w.useState(2);return w.useEffect(()=>{let o=!1;return r(2),Yfe(t,e).then(()=>{o||r(0)}).catch(s=>{o||(console.error(s),r(1))}),()=>{o=!0}},[t,e]),n};function Xfe(t){return{draw:{url:t.fonts.draw,format:t.fonts.draw.split(".").pop()},serif:{url:t.fonts.serif,format:t.fonts.serif.split(".").pop()},sansSerif:{url:t.fonts.sansSerif,format:t.fonts.sansSerif.split(".").pop()},monospace:{url:t.fonts.monospace,format:t.fonts.monospace.split(".").pop()}}}function M4(t){const e=w.useMemo(()=>Xfe(t),[t]),n=[Uh("tldraw_draw",e.draw),Uh("tldraw_serif",e.serif),Uh("tldraw_sans",e.sansSerif),Uh("tldraw_mono",e.monospace)];return{error:n.some(r=>r===1),done:!n.some(r=>r===2)}}function qfe(t){const{children:e,maxImageDimension:n,maxAssetSize:r,acceptedImageMimeTypes:o,acceptedVideoMimeTypes:s,onMount:i,components:a={},shapeUtils:l=[],bindingUtils:c=[],tools:u=[],embeds:h,...p}=t,f=tc(a),g=w.useMemo(()=>({Scribble:PE,ShapeIndicators:sle,CollaboratorScribble:PE,SelectionForeground:nle,SelectionBackground:ele,Handles:Xae,...f}),[f]),m=Xs(l),v=w.useMemo(()=>[..._5,...m],[m]),y=Xs(c),S=w.useMemo(()=>[...V$,...y],[y]),b=Xs(u),P=w.useMemo(()=>[...ede,...Hle,...b],[b]),C=Xs(o??xg),_=Xs(s??xw),E=w.useMemo(()=>[...C,..._],[C,_]),k=cF(p.assetUrls),{done:D,error:T}=M4(k);return T?d.jsx(XR,{children:"Could not load assets. Please refresh the page."}):D?(v.find($=>$.type==="embed")&&h&&Jf.setEmbedDefinitions(h),d.jsx(ote,{initialState:"select",...p,components:g,shapeUtils:v,bindingUtils:S,tools:P,children:d.jsxs(Wfe,{...p,components:g,mediaMimeTypes:E,children:[d.jsx(Zfe,{maxImageDimension:n,maxAssetSize:r,acceptedImageMimeTypes:C,acceptedVideoMimeTypes:_,onMount:i}),e]})})):d.jsx(D1,{children:d.jsx(v1,{})})}function Zfe({maxImageDimension:t=5e3,maxAssetSize:e=10*1024*1024,acceptedImageMimeTypes:n=xg,acceptedVideoMimeTypes:r=xw,onMount:o}){const s=z(),i=Ts(),a=Ee();qR(()=>{const u=[];return u.push(Cue(s)),ble(s,{maxImageDimension:t,maxAssetSize:e,acceptedImageMimeTypes:n,acceptedVideoMimeTypes:r},{toasts:i,msg:a}),u.push(s.store.props.onMount(s)),u.push(o==null?void 0:o(s)),()=>{u.forEach(h=>h==null?void 0:h())}});const{Canvas:l}=rt(),{ContextMenu:c}=Di();return c?d.jsx(c,{}):l?d.jsx(l,{}):null}w.memo(function(e){const[n,r]=w.useState(null),[o,s]=w.useState(null),i=Xs(e.shapeUtils??[]),a=w.useMemo(()=>[..._5,...i],[i]),l=Xs(e.bindingUtils??[]),c=w.useMemo(()=>[...V$,...l],[l]),u=dte({snapshot:e.snapshot,shapeUtils:a}),h=cF(e.assetUrls),{done:p,error:f}=M4(h),{pageId:g,bounds:m,scale:v,pixelRatio:y,background:S,padding:b,darkMode:P,preserveAspectRatio:C,format:_="svg",licenseKey:E}=e;return w.useLayoutEffect(()=>{if(!o||!u||!p)return;let k=!1;const D=document.createElement("div");o.appendChild(D),o.classList.add("tl-container","tl-theme__light");const T=new Q({store:u,shapeUtils:a,bindingUtils:c,tools:[],getContainer:()=>D,licenseKey:E});g&&T.setCurrentPage(g);const j=T.getCurrentPageShapeIds();async function $(){const M=await T.getSvgString([...j],{bounds:m,scale:v,background:S,padding:b,darkMode:P,preserveAspectRatio:C});if(M&&!k){if(_==="svg"){if(!k){const O=new Blob([M.svg],{type:"image/svg+xml"}),F=URL.createObjectURL(O);r(F)}}else if(_==="png"){const O=await L$(T,M.svg,{type:_,width:M.width,height:M.height,pixelRatio:y});if(O&&!k){const F=URL.createObjectURL(O);r(F)}}}T.dispose()}return $(),()=>{k=!0}},[_,o,u,a,c,g,m,v,S,b,P,C,p,f,E,y]),f?d.jsx(XR,{children:"Could not load assets."}):p?d.jsx("div",{ref:s,style:{position:"relative",width:"100%",height:"100%"},children:n&&d.jsx("img",{src:n,referrerPolicy:"strict-origin-when-cross-origin",style:{width:"100%",height:"100%"}})}):d.jsx(D1,{children:d.jsx(v1,{})})});w.memo(function({children:e}){const n=Ee(),r=An(),o=w.useRef(null);Mi(o);const s=e??d.jsx(Ihe,{});return r<St.MOBILE?null:d.jsx("div",{ref:o,className:"tlui-help-menu",children:d.jsxs(ga,{id:"help menu",children:[d.jsx(ma,{children:d.jsx(ce,{type:"help",title:n("help-menu.title"),"data-testid":"help-menu.button",children:d.jsx(be,{icon:"question-mark",small:!0})})}),d.jsx(ya,{side:"top",align:"end",alignOffset:0,sideOffset:8,children:d.jsx(Fr,{type:"menu",sourceId:"help-menu",children:s})})]})})});const Qfe=1,Jfe=Pe({schemaVersion:mn(1),storeVersion:ip,recordVersions:If(ye,Pe({version:ip,subTypeVersions:If(ye,ip).optional(),subTypeKey:ye.optional()}))}),ege=Pe({schemaVersion:mn(2),sequences:If(ye,ip)}),tge=Pe({tldrawFileFormatVersion:nY,schema:rY("schemaVersion",{1:Jfe,2:ege}),records:Kt(Pe({id:ye,typeName:ye}).allowUnknownProperties())});function nge(t){var e;try{return!!((e=t.document)!=null&&e.version)}catch{return!1}}function rge({json:t,schema:e}){let n;try{n=tge.validate(JSON.parse(t))}catch(s){try{if(n=JSON.parse(t),nge(n))return wn.err({type:"v1File",data:n})}catch{}return wn.err({type:"notATldrawFile",cause:s})}if(n.tldrawFileFormatVersion>Qfe)return wn.err({type:"fileFormatVersionTooNew",version:n.tldrawFileFormatVersion});let r,o;try{const s=oge(n.records);o=Object.fromEntries(s.map(i=>[i.id,i])),r=e.migrateStoreSnapshot({store:o,schema:n.schema})}catch(s){return wn.err({type:"invalidRecords",cause:s})}if(r.type==="error")return wn.err({type:"migrationFailed",reason:r.reason});try{return wn.ok(Hu({snapshot:{store:o,schema:n.schema},schema:e}))}catch(s){return wn.err({type:"invalidRecords",cause:s})}}function oge(t){const e=new Set;for(const n of t)n.typeName==="shape"&&"assetId"in n.props&&n.props.assetId&&e.add(n.props.assetId);return t.filter(n=>n.typeName!=="asset"||e.has(n.id))}Ci("tldraw","3.7.0-canary.383dfd14bf86","esm");function sge(){const[t,e]=w.useState();function n(r){window.editor=r,t===void 0?fetch("/tldr-data").then(async o=>{if(!o.ok){console.log(`No tldr data to load from local endpoint (${o.status})`);return}return o.text()}).then(o=>{if(o===void 0)return;const s=rge({json:o,schema:r.store.schema});s.ok?(console.log("Loaded tldr file from local endpoint"),e(s.value)):console.error(`Couldn't parse tldr file: ${String(s.error.type)}`)}).catch(o=>{console.error("Couldn't fetch data:",o)}):(r.zoomToFit(),r.clearOpenMenus())}return d.jsx("div",{style:{inset:0,position:"fixed"},children:d.jsx(qfe,{assetUrls:d8(),onMount:n,store:t})})}QS.createRoot(document.querySelector("#root")).render(d.jsx(Te.StrictMode,{children:d.jsx(sge,{})}));
425
+ }`,p}const Uh=(t,e)=>{const[n,r]=w.useState(2);return w.useEffect(()=>{let o=!1;return r(2),Yfe(t,e).then(()=>{o||r(0)}).catch(s=>{o||(console.error(s),r(1))}),()=>{o=!0}},[t,e]),n};function Xfe(t){return{draw:{url:t.fonts.draw,format:t.fonts.draw.split(".").pop()},serif:{url:t.fonts.serif,format:t.fonts.serif.split(".").pop()},sansSerif:{url:t.fonts.sansSerif,format:t.fonts.sansSerif.split(".").pop()},monospace:{url:t.fonts.monospace,format:t.fonts.monospace.split(".").pop()}}}function M4(t){const e=w.useMemo(()=>Xfe(t),[t]),n=[Uh("tldraw_draw",e.draw),Uh("tldraw_serif",e.serif),Uh("tldraw_sans",e.sansSerif),Uh("tldraw_mono",e.monospace)];return{error:n.some(r=>r===1),done:!n.some(r=>r===2)}}function qfe(t){const{children:e,maxImageDimension:n,maxAssetSize:r,acceptedImageMimeTypes:o,acceptedVideoMimeTypes:s,onMount:i,components:a={},shapeUtils:l=[],bindingUtils:c=[],tools:u=[],embeds:h,...p}=t,f=tc(a),g=w.useMemo(()=>({Scribble:PE,ShapeIndicators:sle,CollaboratorScribble:PE,SelectionForeground:nle,SelectionBackground:ele,Handles:Xae,...f}),[f]),m=Xs(l),v=w.useMemo(()=>[..._5,...m],[m]),y=Xs(c),S=w.useMemo(()=>[...V$,...y],[y]),b=Xs(u),P=w.useMemo(()=>[...ede,...Hle,...b],[b]),C=Xs(o??xg),_=Xs(s??xw),E=w.useMemo(()=>[...C,..._],[C,_]),k=cF(p.assetUrls),{done:D,error:T}=M4(k);return T?d.jsx(XR,{children:"Could not load assets. Please refresh the page."}):D?(v.find($=>$.type==="embed")&&h&&Jf.setEmbedDefinitions(h),d.jsx(ote,{initialState:"select",...p,components:g,shapeUtils:v,bindingUtils:S,tools:P,children:d.jsxs(Wfe,{...p,components:g,mediaMimeTypes:E,children:[d.jsx(Zfe,{maxImageDimension:n,maxAssetSize:r,acceptedImageMimeTypes:C,acceptedVideoMimeTypes:_,onMount:i}),e]})})):d.jsx(D1,{children:d.jsx(v1,{})})}function Zfe({maxImageDimension:t=5e3,maxAssetSize:e=10*1024*1024,acceptedImageMimeTypes:n=xg,acceptedVideoMimeTypes:r=xw,onMount:o}){const s=z(),i=Ts(),a=Ee();qR(()=>{const u=[];return u.push(Cue(s)),ble(s,{maxImageDimension:t,maxAssetSize:e,acceptedImageMimeTypes:n,acceptedVideoMimeTypes:r},{toasts:i,msg:a}),u.push(s.store.props.onMount(s)),u.push(o==null?void 0:o(s)),()=>{u.forEach(h=>h==null?void 0:h())}});const{Canvas:l}=rt(),{ContextMenu:c}=Di();return c?d.jsx(c,{}):l?d.jsx(l,{}):null}w.memo(function(e){const[n,r]=w.useState(null),[o,s]=w.useState(null),i=Xs(e.shapeUtils??[]),a=w.useMemo(()=>[..._5,...i],[i]),l=Xs(e.bindingUtils??[]),c=w.useMemo(()=>[...V$,...l],[l]),u=dte({snapshot:e.snapshot,shapeUtils:a}),h=cF(e.assetUrls),{done:p,error:f}=M4(h),{pageId:g,bounds:m,scale:v,pixelRatio:y,background:S,padding:b,darkMode:P,preserveAspectRatio:C,format:_="svg",licenseKey:E}=e;return w.useLayoutEffect(()=>{if(!o||!u||!p)return;let k=!1;const D=document.createElement("div");o.appendChild(D),o.classList.add("tl-container","tl-theme__light");const T=new Q({store:u,shapeUtils:a,bindingUtils:c,tools:[],getContainer:()=>D,licenseKey:E});g&&T.setCurrentPage(g);const j=T.getCurrentPageShapeIds();async function $(){const M=await T.getSvgString([...j],{bounds:m,scale:v,background:S,padding:b,darkMode:P,preserveAspectRatio:C});if(M&&!k){if(_==="svg"){if(!k){const O=new Blob([M.svg],{type:"image/svg+xml"}),F=URL.createObjectURL(O);r(F)}}else if(_==="png"){const O=await L$(T,M.svg,{type:_,width:M.width,height:M.height,pixelRatio:y});if(O&&!k){const F=URL.createObjectURL(O);r(F)}}}T.dispose()}return $(),()=>{k=!0}},[_,o,u,a,c,g,m,v,S,b,P,C,p,f,E,y]),f?d.jsx(XR,{children:"Could not load assets."}):p?d.jsx("div",{ref:s,style:{position:"relative",width:"100%",height:"100%"},children:n&&d.jsx("img",{src:n,referrerPolicy:"strict-origin-when-cross-origin",style:{width:"100%",height:"100%"}})}):d.jsx(D1,{children:d.jsx(v1,{})})});w.memo(function({children:e}){const n=Ee(),r=An(),o=w.useRef(null);Mi(o);const s=e??d.jsx(Ihe,{});return r<St.MOBILE?null:d.jsx("div",{ref:o,className:"tlui-help-menu",children:d.jsxs(ga,{id:"help menu",children:[d.jsx(ma,{children:d.jsx(ce,{type:"help",title:n("help-menu.title"),"data-testid":"help-menu.button",children:d.jsx(be,{icon:"question-mark",small:!0})})}),d.jsx(ya,{side:"top",align:"end",alignOffset:0,sideOffset:8,children:d.jsx(Fr,{type:"menu",sourceId:"help-menu",children:s})})]})})});const Qfe=1,Jfe=Pe({schemaVersion:mn(1),storeVersion:ip,recordVersions:If(ye,Pe({version:ip,subTypeVersions:If(ye,ip).optional(),subTypeKey:ye.optional()}))}),ege=Pe({schemaVersion:mn(2),sequences:If(ye,ip)}),tge=Pe({tldrawFileFormatVersion:nY,schema:rY("schemaVersion",{1:Jfe,2:ege}),records:Kt(Pe({id:ye,typeName:ye}).allowUnknownProperties())});function nge(t){var e;try{return!!((e=t.document)!=null&&e.version)}catch{return!1}}function rge({json:t,schema:e}){let n;try{n=tge.validate(JSON.parse(t))}catch(s){try{if(n=JSON.parse(t),nge(n))return wn.err({type:"v1File",data:n})}catch{}return wn.err({type:"notATldrawFile",cause:s})}if(n.tldrawFileFormatVersion>Qfe)return wn.err({type:"fileFormatVersionTooNew",version:n.tldrawFileFormatVersion});let r,o;try{const s=oge(n.records);o=Object.fromEntries(s.map(i=>[i.id,i])),r=e.migrateStoreSnapshot({store:o,schema:n.schema})}catch(s){return wn.err({type:"invalidRecords",cause:s})}if(r.type==="error")return wn.err({type:"migrationFailed",reason:r.reason});try{return wn.ok(Hu({snapshot:{store:o,schema:n.schema},schema:e}))}catch(s){return wn.err({type:"invalidRecords",cause:s})}}function oge(t){const e=new Set;for(const n of t)n.typeName==="shape"&&"assetId"in n.props&&n.props.assetId&&e.add(n.props.assetId);return t.filter(n=>n.typeName!=="asset"||e.has(n.id))}Ci("tldraw","3.7.0-canary.8e16c48b63b1","esm");function sge(){const[t,e]=w.useState();function n(r){window.editor=r,t===void 0?fetch("/tldr-data").then(async o=>{if(!o.ok){console.log(`No tldr data to load from local endpoint (${o.status})`);return}return o.text()}).then(o=>{if(o===void 0)return;const s=rge({json:o,schema:r.store.schema});s.ok?(console.log("Loaded tldr file from local endpoint"),e(s.value)):console.error(`Couldn't parse tldr file: ${String(s.error.type)}`)}).catch(o=>{console.error("Couldn't fetch data:",o)}):(r.zoomToFit(),r.clearOpenMenus())}return d.jsx("div",{style:{inset:0,position:"fixed"},children:d.jsx(qfe,{assetUrls:d8(),onMount:n,store:t})})}QS.createRoot(document.querySelector("#root")).render(d.jsx(Te.StrictMode,{children:d.jsx(sge,{})}));