@orangecatai/element 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +1 -1
  2. package/dist/dev/index.js +42 -3
  3. package/dist/dev/index.js.map +2 -2
  4. package/dist/prod/index.js +1 -1
  5. package/dist/types/common/src/keys.d.ts +2 -0
  6. package/dist/types/element/src/arrows/focus.d.ts +1 -1
  7. package/dist/types/element/src/binding.d.ts +3 -3
  8. package/dist/types/element/src/bounds.d.ts +1 -1
  9. package/dist/types/element/src/collision.d.ts +1 -1
  10. package/dist/types/element/src/delta.d.ts +2 -2
  11. package/dist/types/element/src/dragElements.d.ts +1 -1
  12. package/dist/types/element/src/duplicate.d.ts +1 -1
  13. package/dist/types/element/src/embeddable.d.ts +1 -1
  14. package/dist/types/element/src/flowchart.d.ts +1 -1
  15. package/dist/types/element/src/frame.d.ts +4 -4
  16. package/dist/types/element/src/groups.d.ts +1 -1
  17. package/dist/types/element/src/renderElement.d.ts +1 -1
  18. package/dist/types/element/src/selection.d.ts +1 -1
  19. package/dist/types/element/src/shape.d.ts +2 -2
  20. package/dist/types/element/src/store.d.ts +2 -2
  21. package/dist/types/element/src/textElement.d.ts +1 -1
  22. package/dist/types/element/src/transform.d.ts +1 -1
  23. package/dist/types/element/src/utils.d.ts +1 -1
  24. package/dist/types/element/src/zindex.d.ts +1 -1
  25. package/dist/types/excalidraw/actions/actionAddToLibrary.d.ts +1 -1
  26. package/dist/types/excalidraw/actions/actionCanvas.d.ts +184 -7
  27. package/dist/types/excalidraw/actions/actionClipboard.d.ts +7 -7
  28. package/dist/types/excalidraw/actions/actionCropEditor.d.ts +2 -2
  29. package/dist/types/excalidraw/actions/actionDuplicateSelection.d.ts +2 -2
  30. package/dist/types/excalidraw/actions/actionElementLink.d.ts +6 -6
  31. package/dist/types/excalidraw/actions/actionEmbeddable.d.ts +1 -1
  32. package/dist/types/excalidraw/actions/actionExport.d.ts +9 -9
  33. package/dist/types/excalidraw/actions/actionFrame.d.ts +178 -0
  34. package/dist/types/excalidraw/actions/actionLinearEditor.d.ts +7 -7
  35. package/dist/types/excalidraw/actions/actionLink.d.ts +3 -3
  36. package/dist/types/excalidraw/actions/actionMenu.d.ts +1 -1
  37. package/dist/types/excalidraw/actions/actionProperties.d.ts +1 -1
  38. package/dist/types/excalidraw/actions/actionSelectAll.d.ts +4 -4
  39. package/dist/types/excalidraw/actions/actionStyles.d.ts +2 -2
  40. package/dist/types/excalidraw/actions/actionToggleObjectsSnapMode.d.ts +4 -4
  41. package/dist/types/excalidraw/actions/actionToggleShapeSwitch.d.ts +3 -3
  42. package/dist/types/excalidraw/actions/actionToggleStats.d.ts +2 -2
  43. package/dist/types/excalidraw/actions/actionToggleViewMode.d.ts +4 -4
  44. package/dist/types/excalidraw/actions/actionToggleZenMode.d.ts +4 -4
  45. package/dist/types/excalidraw/actions/actionZindex.d.ts +8 -8
  46. package/dist/types/excalidraw/actions/index.d.ts +1 -1
  47. package/dist/types/excalidraw/actions/shortcuts.d.ts +1 -1
  48. package/dist/types/excalidraw/actions/types.d.ts +1 -1
  49. package/dist/types/excalidraw/appState.d.ts +4 -4
  50. package/dist/types/excalidraw/components/AIChatPanel.d.ts +114 -0
  51. package/dist/types/excalidraw/components/Actions.d.ts +4 -1
  52. package/dist/types/excalidraw/components/App.d.ts +13 -2
  53. package/dist/types/excalidraw/components/CanvasBackgroundSwatch.d.ts +7 -0
  54. package/dist/types/excalidraw/components/ColorPicker/AdvancedColorPicker.d.ts +8 -0
  55. package/dist/types/excalidraw/components/ColorPicker/ColorPicker.d.ts +2 -2
  56. package/dist/types/excalidraw/components/ColorPicker/Picker.d.ts +1 -1
  57. package/dist/types/excalidraw/components/ColorPicker/colorConversions.d.ts +27 -0
  58. package/dist/types/excalidraw/components/ConvertElementTypePopup.d.ts +1 -1
  59. package/dist/types/excalidraw/components/DarkModeToggle.d.ts +1 -1
  60. package/dist/types/excalidraw/components/DefaultSidebar.d.ts +2 -2
  61. package/dist/types/excalidraw/components/ElementCanvasButtons.d.ts +1 -1
  62. package/dist/types/excalidraw/components/ElementLinkDialog.d.ts +2 -2
  63. package/dist/types/excalidraw/components/EyeDropper.d.ts +1 -1
  64. package/dist/types/excalidraw/components/FontPicker/FontPicker.d.ts +1 -1
  65. package/dist/types/excalidraw/components/FontPicker/FontPickerList.d.ts +1 -1
  66. package/dist/types/excalidraw/components/FontPicker/keyboardNavHandlers.d.ts +1 -1
  67. package/dist/types/excalidraw/components/FrameToolbar.d.ts +1 -1
  68. package/dist/types/excalidraw/components/HintViewer.d.ts +1 -1
  69. package/dist/types/excalidraw/components/ImageEditToolbar.d.ts +16 -0
  70. package/dist/types/excalidraw/components/ImageExportDialog.d.ts +1 -1
  71. package/dist/types/excalidraw/components/ImageGeneratorPanel.d.ts +43 -0
  72. package/dist/types/excalidraw/components/ImageQuickEditPanel.d.ts +16 -0
  73. package/dist/types/excalidraw/components/JSONExportDialog.d.ts +1 -1
  74. package/dist/types/excalidraw/components/LayerUI.d.ts +1 -1
  75. package/dist/types/excalidraw/components/Sidebar/Sidebar.d.ts +2 -2
  76. package/dist/types/excalidraw/components/Stats/DragInput.d.ts +2 -2
  77. package/dist/types/excalidraw/components/Stats/FontSize.d.ts +1 -1
  78. package/dist/types/excalidraw/components/Stats/MultiDimension.d.ts +1 -1
  79. package/dist/types/excalidraw/components/Stats/MultiFontSize.d.ts +1 -1
  80. package/dist/types/excalidraw/components/Stats/MultiPosition.d.ts +1 -1
  81. package/dist/types/excalidraw/components/Stats/index.d.ts +1 -1
  82. package/dist/types/excalidraw/components/TTDDialog/types.d.ts +2 -2
  83. package/dist/types/excalidraw/components/TTDDialog/utils/TTDStreamFetch.d.ts +1 -0
  84. package/dist/types/excalidraw/components/ToolButton.d.ts +1 -1
  85. package/dist/types/excalidraw/components/ai-chat/agentLoop.d.ts +112 -0
  86. package/dist/types/excalidraw/components/ai-chat/audioUtils.d.ts +10 -0
  87. package/dist/types/excalidraw/components/ai-chat/canvasTools.d.ts +685 -0
  88. package/dist/types/excalidraw/components/ai-chat/htmlToExcalidraw.d.ts +53 -0
  89. package/dist/types/excalidraw/components/ai-chat/openRouterStream.d.ts +50 -0
  90. package/dist/types/excalidraw/components/ai-chat/reviewerAgent.d.ts +64 -0
  91. package/dist/types/excalidraw/components/auto-resize/AutoResizePanel.d.ts +17 -0
  92. package/dist/types/excalidraw/components/auto-resize/AutoResizePanelHost.d.ts +4 -0
  93. package/dist/types/excalidraw/components/auto-resize/AutoResizeShimmerLayer.d.ts +11 -0
  94. package/dist/types/excalidraw/components/auto-resize/autoResizeEngine.d.ts +144 -0
  95. package/dist/types/excalidraw/components/auto-resize/autoResizePanelStore.d.ts +15 -0
  96. package/dist/types/excalidraw/components/auto-resize/autoResizeStore.d.ts +16 -0
  97. package/dist/types/excalidraw/components/hyperlink/Hyperlink.d.ts +1 -1
  98. package/dist/types/excalidraw/components/icons.d.ts +1 -0
  99. package/dist/types/excalidraw/components/image-generation/pendingGenerations.d.ts +30 -0
  100. package/dist/types/excalidraw/components/main-menu/DefaultItems.d.ts +1 -1
  101. package/dist/types/excalidraw/components/template-builder/TemplateBuilderPanelHost.d.ts +4 -0
  102. package/dist/types/excalidraw/components/template-builder/TemplateBuilderTray.d.ts +4 -0
  103. package/dist/types/excalidraw/components/template-builder/slotTypes.d.ts +43 -0
  104. package/dist/types/excalidraw/components/template-builder/templateBuilderStore.d.ts +19 -0
  105. package/dist/types/excalidraw/components/ui/avatar.d.ts +6 -0
  106. package/dist/types/excalidraw/components/ui/button.d.ts +11 -0
  107. package/dist/types/excalidraw/components/ui/chat-container.d.ts +17 -0
  108. package/dist/types/excalidraw/components/ui/code-block.d.ts +16 -0
  109. package/dist/types/excalidraw/components/ui/markdown.d.ts +10 -0
  110. package/dist/types/excalidraw/components/ui/message.d.ts +35 -0
  111. package/dist/types/excalidraw/components/ui/prompt-input.d.ts +28 -0
  112. package/dist/types/excalidraw/components/ui/scroll-button.d.ts +10 -0
  113. package/dist/types/excalidraw/components/ui/textarea.d.ts +3 -0
  114. package/dist/types/excalidraw/components/ui/tooltip.d.ts +7 -0
  115. package/dist/types/excalidraw/data/blob.d.ts +19 -17
  116. package/dist/types/excalidraw/data/json.d.ts +8 -8
  117. package/dist/types/excalidraw/data/library.d.ts +1 -1
  118. package/dist/types/excalidraw/fonts/Fonts.d.ts +19 -2
  119. package/dist/types/excalidraw/i18n.d.ts +1 -1
  120. package/dist/types/excalidraw/index.d.ts +9 -0
  121. package/dist/types/excalidraw/lib/utils.d.ts +2 -0
  122. package/dist/types/excalidraw/types.d.ts +229 -0
  123. package/dist/types/excalidraw/utils/geminiApiKey.d.ts +1 -0
  124. package/dist/types/excalidraw/utils/leonardoApiKey.d.ts +1 -0
  125. package/dist/types/excalidraw/utils/openRouterApiKey.d.ts +1 -0
  126. package/dist/types/excalidraw/utils/removeBgApiKey.d.ts +1 -0
  127. package/package.json +6 -6
@@ -17,7 +17,7 @@ var iu=Object.create;var ta=Object.defineProperty;var ou=Object.getOwnPropertyDe
17
17
  L ${l-g} ${d+E}
18
18
  C ${l} ${d}, ${l} ${d}, ${l+g} ${d+E}`,_e(e,!0,s))}else a=t.polygon([[l,d],[c,u],[m,p],[f,h]],_e(e,!1,s));return a}case"ellipse":return t.ellipse(e.width/2,e.height/2,e.width,e.height,_e(e,!1,s));case"line":case"arrow":{let a,l=_e(e,!1,s),d=e.points.length?e.points:[le(0,0)];if(_(e)?d.every(c=>Math.abs(c[0])<=1e6&&Math.abs(c[1])<=1e6)?a=[t.path(vd(d,16),_e(e,!0,s))]:(console.error("Elbow arrow with extreme point positions detected. Arrow not rendered.",e.id,JSON.stringify(d)),a=[]):e.roundness?a=[t.curve(d,l)]:l.fill?a=[t.polygon(d,l)]:a=[t.linearPath(d,l)],e.type==="arrow"){let{startArrowhead:c=null,endArrowhead:u="arrow"}=e;if(c!==null){let m=Sd(e,a,"start",c,t,l,i,s);a.push(...m)}if(u!==null){let m=Sd(e,a,"end",u,t,l,i,s);a.push(...m)}}return a}case"freedraw":{let a=[];if(Dn(e.points)){let l=li(e.points,.75);a.push(t.curve(l,{..._e(e,!1,s),stroke:"none"}))}return a.push(qf(e)),a}case"frame":case"magicframe":case"text":case"image":return null;default:return Yf(e,`generateElementShape(): Unimplemented type ${e?.type}`),null}},vd=(e,t)=>{let n=[];for(let o=1;o<e.length-1;o+=1){let r=e[o-1],s=e[o+1],a=e[o],l=lt(a,r),d=lt(s,a),c=Math.min(t,Pd(e[o],s)/2,Pd(e[o],r)/2);l?r[0]<a[0]?n.push([e[o][0]-c,e[o][1]]):n.push([e[o][0]+c,e[o][1]]):r[1]<a[1]?n.push([e[o][0],e[o][1]-c]):n.push([e[o][0],e[o][1]+c]),n.push(e[o]),d?s[0]<a[0]?n.push([e[o][0]-c,e[o][1]]):n.push([e[o][0]+c,e[o][1]]):s[1]<a[1]?n.push([e[o][0],e[o][1]-c]):n.push([e[o][0],e[o][1]+c])}let i=[`M ${e[0][0]} ${e[0][1]}`];for(let o=0;o<n.length;o+=3)i.push(`L ${n[o][0]} ${n[o][1]}`),i.push(`Q ${n[o+1][0]} ${n[o+1][1]}, ${n[o+2][0]} ${n[o+2][1]}`);return i.push(`L ${e[e.length-1][0]} ${e[e.length-1][1]}`),i.join(" ")},Td=(e,t)=>{switch(e.type){case"rectangle":case"diamond":case"frame":case"magicframe":case"embeddable":case"image":case"iframe":case"text":case"selection":return ga(e);case"arrow":case"line":{let n=Ze.generateElementShape(e,null)[0],[,,,,i,o]=j(e,t);return go(e)?ba(e,n,le(e.x,e.y),e.angle,le(i,o)):xa(n,le(e.x,e.y),e.angle,le(i,o))}case"ellipse":return Ea(e);case"freedraw":{let[,,,,n,i]=j(e,t);return wa(e,le(n,i),go(e))}}},$l=(e,t)=>{let n=[...e.points];if(t){if(!za(e.points))return null;let o=n[0],r=n[n.length-1];Math.hypot(o[0]-r[0],o[1]-r[1])>Xf||n.length<4?n.push(le(o[0],o[1])):n[n.length-1]=le(o[0],o[1])}return{polygon:t,points:n}},qf=e=>Jf(Kf(e)),Kf=e=>{let t=e.simulatePressure?e.points:e.points.length?e.points.map(([n,i],o)=>[n,i,e.pressures[o]]):[[0,0,.5]];return va(t,{simulatePressure:e.simulatePressure,size:e.strokeWidth*4.25,thinning:.6,smoothing:.5,streamline:.5,easing:n=>Math.sin(n*Math.PI/2),last:!0})},Ad=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],Qf=/(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g,Jf=e=>{if(!e.length)return"";let t=e.length-1;return e.reduce((n,i,o,r)=>(o===t?n.push(i,Ad(i,r[0]),"L",r[0],"Z"):n.push(i,Ad(i,r[o+1])),n),["M",e[0],"Q"]).join(" ").replace(Qf,"$1")};var bs=class e{static boundsCache=new WeakMap;static nonRotatedBoundsCache=new WeakMap;static getBounds(t,n,i=!1){let o=i&&t.angle!==0?e.nonRotatedBoundsCache.get(t):e.boundsCache.get(t);if(o?.version&&o.version===t.version&&!ce(t))return o.bounds;if(i&&t.angle!==0){let s=e.calculateBounds({...t,angle:0},n);return e.nonRotatedBoundsCache.set(t,{version:t.version,bounds:s}),s}let r=e.calculateBounds(t,n);return e.boundsCache.set(t,{version:t.version,bounds:r}),r}static calculateBounds(t,n){let i,[o,r,s,a,l,d]=j(t,n);if(Ie(t)){let[c,u,m,p]=ys(t.points.map(([f,h])=>oe(D(f,h),D(l-t.x,d-t.y),t.angle)));return[c+t.x,u+t.y,m+t.x,p+t.y]}else if(K(t))i=lh(t,l,d,n);else if(t.type==="diamond"){let[c,u]=oe(D(l,r),D(l,d),t.angle),[m,p]=oe(D(l,a),D(l,d),t.angle),[f,h]=oe(D(o,d),D(l,d),t.angle),[g,E]=oe(D(s,d),D(l,d),t.angle),x=Math.min(c,m,f,g),w=Math.min(u,p,h,E),y=Math.max(c,m,f,g),b=Math.max(u,p,h,E);i=[x,w,y,b]}else if(t.type==="ellipse"){let c=(s-o)/2,u=(a-r)/2,m=Math.cos(t.angle),p=Math.sin(t.angle),f=Math.hypot(c*m,u*p),h=Math.hypot(u*m,c*p);i=[l-f,d-h,l+f,d+h]}else{let[c,u]=oe(D(o,r),D(l,d),t.angle),[m,p]=oe(D(o,a),D(l,d),t.angle),[f,h]=oe(D(s,a),D(l,d),t.angle),[g,E]=oe(D(s,r),D(l,d),t.angle),x=Math.min(c,m,f,g),w=Math.min(u,p,h,E),y=Math.max(c,m,f,g),b=Math.max(u,p,h,E);i=[x,w,y,b]}return i}},j=(e,t,n=!1)=>{if(Ie(e))return oh(e);if(K(e))return L.getElementAbsoluteCoords(e,t,n);if(J(e)){let i=t?Ae(e,t):null;if(H(i)){let{x:o,y:r}=L.getBoundTextElementPosition(i,e,t);return[o,r,o+e.width,r+e.height,o+e.width/2,r+e.height/2]}}return[e.x,e.y,e.x+e.width,e.y+e.height,e.x+e.width/2,e.y+e.height/2]},us=(e,t)=>{let n=Td(e,t),[i,o,r,s,a,l]=j(e,t),d=D(a,l);if(n.type==="polycurve"){let E=n.data.map(w=>vt(w,10)),x=[];if(Bt(e)&&!e.polygon||H(e))for(let w of E){let y=0;for(;y<w.length-1;)x.push(Ee(D(w[y][0],w[y][1]),D(w[y+1][0],w[y+1][1]))),y++}else{let w=E.flat(),y=0;for(;y<w.length-1;)x.push(Ee(D(w[y][0],w[y][1]),D(w[y+1][0],w[y+1][1]))),y++}return x}else{if(n.type==="polyline")return n.data;if(nh(e)){let[g,E]=Jt(e),x=E.map(y=>Ld(y,d,e.angle)).flat();return[...Bd(g,d,e.angle),...x]}else if(e.type==="diamond"){let[g,E]=en(e),x=E.map(y=>Ld(y,d,e.angle)).flat();return[...Bd(g,d,e.angle),...x]}else if(n.type==="polygon"){if(J(e)){let x=Ae(e,t);if(x&&K(x))return[Ee(D(i,o),D(r,o)),Ee(D(r,o),D(r,s)),Ee(D(r,s),D(i,s)),Ee(D(i,s),D(i,o))]}let g=n.data,E=[];for(let x=0;x<g.length-1;x++)E.push(Ee(g[x],g[x+1]));return E}else if(n.type==="ellipse")return ih(e)}let[c,u,m,p,,,f,h]=[[i,o],[r,o],[i,s],[r,s],[a,o],[a,s],[i,l],[r,l]].map(g=>oe(g,d,e.angle));return[Ee(c,u),Ee(m,p),Ee(c,m),Ee(u,p),Ee(c,h),Ee(m,h),Ee(u,f),Ee(p,f)]},nh=e=>e!=null&&(e.type==="rectangle"||e.type==="image"||e.type==="iframe"||e.type==="embeddable"||e.type==="frame"||e.type==="magicframe"||e.type==="text"&&!e.containerId),Bd=(e,t,n)=>e.map(i=>Ee(oe(i[0],t,n),oe(i[1],t,n))),Ld=(e,t,n)=>{let i=vt(e,10),o=0,r=[];for(;o<i.length-1;)r.push(Ee(oe(D(i[o][0],i[o][1]),t,n),oe(D(i[o+1][0],i[o+1][1]),t,n))),o++;return r},ih=e=>{let t=D(e.x+e.width/2,e.y+e.height/2),n=e.width/2,i=e.height/2,o=[],r=[],s=90,a=Math.PI*2/s;for(let l=0;l<s;l++){let d=l*a,c=t[0]+n*Math.cos(d),u=t[1]+i*Math.sin(d);r.push(oe(D(c,u),t,e.angle))}for(let l=0;l<r.length-1;l++)o.push(Ee(r[l],r[l+1]));return o.push(Ee(r[r.length-1],r[0])),o},j1=e=>[e.x,e.y,e.x+e.width,e.y+e.height,e.x+e.width/2,e.y+e.height/2],_n=e=>{let t=Math.floor(e.width/2)+1,n=0,i=e.width,o=Math.floor(e.height/2)+1,r=t,s=e.height;return[t,n,i,o,r,s,0,o]},Cd=(e,t,n,i,o)=>{let r=1-e;return Math.pow(r,3)*t+3*Math.pow(r,2)*e*n+3*r*Math.pow(e,2)*i+Math.pow(e,3)*o},Gd=(e,t,n,i)=>{let o=t-e,r=n-t,s=i-n,a=3*o-6*r+3*s,l=6*r-6*o,d=3*o,c=l*l-4*a*d;if(!(c>=0))return!1;let m=null,p=null,f=1/0,h=1/0;return a===0?f=h=-d/l:(f=(-l+Math.sqrt(c))/(2*a),h=(-l-Math.sqrt(c))/(2*a)),f>=0&&f<=1&&(m=Cd(f,e,t,n,i)),h>=0&&h<=1&&(p=Cd(h,e,t,n,i)),[m,p]},xo=(e,t,n,i)=>{let o=Gd(e[0],t[0],n[0],i[0]),r=Gd(e[1],t[1],n[1],i[1]),s=Math.min(e[0],i[0]),a=Math.max(e[0],i[0]);if(o){let c=o.filter(u=>u!==null);s=Math.min(s,...c),a=Math.max(a,...c)}let l=Math.min(e[1],i[1]),d=Math.max(e[1],i[1]);if(r){let c=r.filter(u=>u!==null);l=Math.min(l,...c),d=Math.max(d,...c)}return[s,l,a,d]},Di=(e,t)=>{let n=D(0,0),{minX:i,minY:o,maxX:r,maxY:s}=e.reduce((a,{op:l,data:d})=>{if(l==="move"){let c=kd(d);ws(c!=null,"Op data is not a point"),n=c}else if(l==="bcurveTo"){let c=D(d[0],d[1]),u=D(d[2],d[3]),m=D(d[4],d[5]),p=t?t(c):c,f=t?t(u):u,h=t?t(m):m,g=t?t(n):n;n=m;let[E,x,w,y]=xo(g,p,f,h);a.minX=Math.min(a.minX,E),a.minY=Math.min(a.minY,x),a.maxX=Math.max(a.maxX,w),a.maxY=Math.max(a.maxY,y)}return a},{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0});return[i,o,r,s]},ys=e=>{let t=1/0,n=1/0,i=-1/0,o=-1/0;for(let[r,s]of e)t=Math.min(t,r),n=Math.min(n,s),i=Math.max(i,r),o=Math.max(o,s);return[t,n,i,o]},oh=e=>{let[t,n,i,o]=ys(e.points),r=t+e.x,s=n+e.y,a=i+e.x,l=o+e.y;return[r,s,a,l,(r+a)/2,(s+l)/2]},rh=e=>{switch(e){case"arrow":return 25;case"diamond":case"diamond_outline":return 12;case"crowfoot_many":case"crowfoot_one":case"crowfoot_one_or_many":return 20;default:return 15}},sh=e=>{switch(e){case"bar":return 90;case"arrow":return 20;default:return 25}},Es=(e,t,n,i)=>{if(t.length<1)return null;let o=Tt(t[0]);if(o.length<1)return null;let r=n==="start"?1:o.length-1,s=o[r].data;ws(s.length===6,"Op data length is not 6");let a=D(s[4],s[5]),l=D(s[2],s[3]),d=D(s[0],s[1]),c=o[r-1],u=D(0,0);if(c.op==="move"){let O=kd(c.data);ws(O!=null,"Op data is not a point"),u=O}else c.op==="bcurveTo"&&(u=D(c.data[4],c.data[5]));let m=(O,X)=>Math.pow(1-O,3)*a[X]+3*O*Math.pow(1-O,2)*l[X]+3*Math.pow(O,2)*(1-O)*d[X]+u[X]*Math.pow(O,3),[p,f]=n==="start"?u:a,[h,g]=[m(.3,0),m(.3,1)],E=Math.hypot(p-h,f-g),x=(p-h)/E,w=(f-g)/E,y=rh(i),b=0;{let[O,X]=n==="end"?e.points[e.points.length-1]:e.points[0],[k,A]=e.points.length>1?n==="end"?e.points[e.points.length-2]:e.points[1]:[0,0];b=Math.hypot(O-k,X-A)}let S=Math.min(y,b*(i==="diamond"||i==="diamond_outline"?.25:.5)),v=p-x*S,M=f-w*S;if(i==="dot"||i==="circle"||i==="circle_outline"){let O=Math.hypot(M-f,v-p)+e.strokeWidth-2;return[p,f,O]}let R=sh(i);if(i==="crowfoot_many"||i==="crowfoot_one_or_many"){let[O,X]=oe(D(p,f),D(v,M),xs(-R)),[k,A]=oe(D(p,f),D(v,M),xs(R));return[v,M,O,X,k,A]}let[C,F]=oe(D(v,M),D(p,f),-R*Math.PI/180),[B,Y]=oe(D(v,M),D(p,f),xs(R));if(i==="diamond"||i==="diamond_outline"){let O,X;if(n==="start"){let[k,A]=e.points.length>1?e.points[1]:[0,0];[O,X]=oe(D(p+S*2,f),D(p,f),Math.atan2(A-f,k-p))}else{let[k,A]=e.points.length>1?e.points[e.points.length-2]:[0,0];[O,X]=oe(D(p-S*2,f),D(p,f),Math.atan2(f-A,p-k))}return[p,f,C,F,O,X,B,Y]}return[p,f,C,F,B,Y]},ah=e=>{let t=Mn.generator(),n=_e(e),i=e.roundness?"curve":n.fill?"polygon":"linearPath";return t[i](e.points,n)},lh=(e,t,n,i)=>{let o=$(e,i);if(e.points.length<2){let[u,m]=e.points[0],[p,f]=oe(D(e.x+u,e.y+m),D(t,n),e.angle),h=[p,f,p,f];if(o){let g=L.getMinMaxXYWithBoundText(e,i,[p,f,p,f],o);h=[g[0],g[1],g[2],g[3]]}return h}let s=Ze.get(e,null)?.[0]??ah(e),a=Tt(s),d=Di(a,([u,m])=>oe(D(e.x+u,e.y+m),D(t,n),e.angle)),c=[d[0],d[1],d[2],d[3]];if(o){let u=L.getMinMaxXYWithBoundText(e,i,c,o);c=[u[0],u[1],u[2],u[3]]}return c},he=(e,t,n=!1)=>bs.getBounds(e,t,n),Oe=(e,t)=>{if(!eh(e))return[0,0,0,0];let n=1/0,i=-1/0,o=1/0,r=-1/0,s=t||Od(e);return e.forEach(a=>{let[l,d,c,u]=he(a,s);n=Math.min(n,l),o=Math.min(o,d),i=Math.max(i,c),r=Math.max(r,u)}),[n,o,i,r]},X1=(e,t)=>{let[n,i,o,r]=Oe(e);return[n+t.x,i+t.y,o+t.x,r+t.y]},Qt=(e,t,n,i)=>{if(!(K(e)||Ie(e)))return[e.x,e.y,e.x+t,e.y+n];let o=Dd(0,t,Dd(1,n,e.points,i),i),r;if(Ie(e))r=ys(o);else{let c=Mn.generator(),u=e.roundness?c.curve(o,_e(e)):c.linearPath(o,_e(e)),m=Tt(u);r=Di(m)}let[s,a,l,d]=r;return[s+e.x,a+e.y,l+e.x,d+e.y]},rs=(e,t)=>{let n=Mn.generator(),i=e.roundness==null?n.linearPath(t,_e(e)):n.curve(t,_e(e)),o=Tt(i),[r,s,a,l]=Di(o);return[r+e.x,s+e.y,a+e.x,l+e.y]},$1=(e,t)=>{if(!e.length)return[0,0,0,0];let n=1/0,i=e[0],o=Od(e);return e.forEach(r=>{let[s,a,l,d]=he(r,o),c=th(D((s+l)/2,(a+d)/2),D(t.x,t.y));c<n&&(n=c,i=r)}),he(i,o)},Yt=e=>{let[t,n,i,o]=Oe(e);return{minX:t,minY:n,maxX:i,maxY:o,width:i-t,height:o-n,midX:(t+i)/2,midY:(n+o)/2}},V1=({scrollX:e,scrollY:t,width:n,height:i,zoom:o})=>[-e,-t,-e+n/o.value,-t+i/o.value],xt=e=>D(e[0]+(e[2]-e[0])/2,e[1]+(e[3]-e[1])/2),et=(e,t,n)=>{let i={minX:e.x,minY:e.y,maxX:e.x+e.width,maxY:e.y+e.height,midX:e.x+e.width/2,midY:e.y+e.height/2},o=re(e,t),[r,s]=oe(D(i.minX,i.minY),o,e.angle),[a,l]=oe(D(i.maxX,i.minY),o,e.angle),[d,c]=oe(D(i.maxX,i.maxY),o,e.angle),[u,m]=oe(D(i.minX,i.maxY),o,e.angle),p=[Math.min(r,a,d,u),Math.min(s,l,c,m),Math.max(r,a,d,u),Math.max(s,l,c,m)];if(n){let[f,h,g,E]=n;return[p[0]-E,p[1]-f,p[2]+h,p[3]+g]}return p},sn=(e,t)=>e[0]>t[0]&&e[0]<t[2]&&e[1]>t[1]&&e[1]<t[3],yi=(e,t)=>{if(e==null||t==null)return!1;let[n,i,o,r]=e,[s,a,l,d]=t;return n<l&&o>s&&i<d&&r>a},re=(e,t,n=0,i=0)=>{if(K(e)){let[s,a,l,d]=j(e,t),[c,u]=D((s+l)/2,(a+d)/2);return D(c+n,u+i)}let[o,r]=xt(he(e,t));return D(o+n,r+i)};var mh=.1,Rd=e=>K(e)||Ie(e)?e.points.length<2||e.points.length===2&&H(e)&&uh(e.points[0],e.points[e.points.length-1],mh):e.width===0&&e.height===0,ud=(e,t,n,i,o)=>{let[r,s,a,l]=he(e,o),d=Wo({clientX:i.offsetLeft,clientY:i.offsetTop},i),c=Wo({clientX:i.offsetLeft+t,clientY:i.offsetTop+n},i);return d.x<=a&&d.y<=l&&c.x>=r&&c.y>=s},nP=(e,t,n,i,o,r)=>{let[s,a,l,d]=Oe(e,o),c=Wo({clientX:i.offsetLeft+(r?.left||0),clientY:i.offsetTop+(r?.top||0)},i),u=Wo({clientX:i.offsetLeft+t-(r?.right||0),clientY:i.offsetTop+n-(r?.bottom||0)},i);return s>=c.x&&a>=c.y&&l<=u.x&&d<=u.y},Ps=(e,t,n)=>{let i=Math.abs(t),o=Math.abs(n);if(e==="line"||e==="arrow"||e==="freedraw"){let r=Math.round(Math.atan(o/i)/jt)*jt;r===0?n=0:r===Math.PI/2?t=0:n=i*Math.tan(r)*Math.sign(n)||n}else e!=="selection"&&(n=i*Math.sign(n));return{width:t,height:n}},Vl=(e,t,n,i,o)=>{let r=n-e,s=i-t,a=Math.atan2(s,r),l=Math.round(a/jt)*jt;if(o){let d=Math.floor(o/jt)*jt;dh(a,d,d+jt)&&(ch(a,o)<jt/6?l=o:Fd(a)>Fd(o)?l=d+jt:l=d)}if(l===0)s=0;else if(l===Math.PI/2)r=0;else{let d=Math.tan(l),c=-1,u=t-d*e,m=-1/d,p=-1,f=i-m*n,h=(c*f-p*u)/(d*p-m*c),g=(u*m-f*d)/(d*p-m*c);r=h-e,s=g-t}return{width:r,height:s}},iP=e=>{let t={width:e.width,height:e.height,x:e.x,y:e.y};if(e.width<0){let n=Math.abs(e.width);t.width=n,t.x=e.x-n}if(e.height<0){let n=Math.abs(e.height);t.height=n,t.y=e.y-n}return t};P();var dP=(e,t,n,i)=>{let o=ko(e,n.getNonDeletedElementsMap(),i),r=Yt(e);return o.flatMap(s=>{let a=ph(s,r,t);return s.map(l=>{let d=n.mutateElement(l,{x:l.x+a.x,y:l.y+a.y});return Te(l,n,{simultaneouslyUpdated:s}),d})})},ph=(e,t,{axis:n,position:i})=>{let o=Yt(e),[r,s]=n==="x"?["minX","maxX"]:["minY","maxY"],a={x:0,y:0};return i==="start"?{...a,[n]:t[r]-o[r]}:i==="end"?{...a,[n]:t[s]-o[s]}:{...a,[n]:(t[r]+t[s])/2-(o[r]+o[s])/2}};P();import{arrayToMap as ag,arrayToObject as Xt,assertNever as fc,isDevEnv as bn,isShallowEqual as hc,isTestEnv as yn,randomInteger as pc}from"@orangecatai/common";P();import{assertNever as Sh,COLOR_PALETTE as Ah,isDevEnv as Mh,isTestEnv as vh,randomId as Th,Emitter as Hd,toIterable as Zn}from"@orangecatai/common";P();import{ORIG_ID as Eh,randomId as zd,randomInteger as xh,arrayToMap as wh,castArray as Is,findLastIndex as Ci,getUpdatedTimestamp as bh,isTestEnv as yh}from"@orangecatai/common";P();import{arrayToMapWithIndex as fh}from"@orangecatai/common";var hh=e=>{let t=e.slice(),n=new Set,i=r=>{let s=r[0]?.groupIds?.join(""),a=[r[0]],l=[];for(let d of r.slice(1))d.groupIds?.join("")===s?a.push(d):l.push(d);return l.length?[...a,...i(l)]:a},o=new Map;return t.forEach((r,s)=>{if(!o.has(r.id))if(r.groupIds?.length){let a=r.groupIds[r.groupIds.length-1],l=t.slice(s).filter(d=>{let c=d?.groupIds?.some(u=>u===a);return c&&o.set(d.id,!0),c});for(let d of i(l))n.add(d)}else n.add(r)}),n.size!==e.length?(console.error("normalizeGroupElementOrder: lost some elements... bailing!"),e):[...n]},gh=e=>{let t=fh(e),n=e.slice(),i=new Set;return n.forEach((o,r)=>{o&&(o.boundElements?.length?(i.add(o),n[r]=null,o.boundElements.forEach(s=>{let a=t.get(s.id);a&&s.type==="text"&&(i.add(a[0]),n[a[1]]=null)})):o.type==="text"&&o.containerId&&t.get(o.containerId)?.[0].boundElements?.find(a=>a.id===o.id)||(i.add(o),n[r]=null))}),i.size!==e.length?(console.error("normalizeBoundElementsOrder: lost some elements... bailing!"),e):[...i]},Nd=e=>gh(hh(e));var Ph=(e,t,n,i)=>{let o=As(n);return yh()&&Ih(o,n.id),o.id=zd(),o.updated=bh(),i&&(o.seed=xh(),Ml(o)),o.groupIds=dd(o.groupIds,e,r=>(t.has(r)||t.set(r,zd()),t.get(r))),o},IP=e=>{let{elements:t}=e,n="appState"in e?e.appState:{editingGroupId:null,selectedGroupIds:{}},i=new Map,o=new Map,r=[],s=[],a=new Map,l=new Map,d=new Map,c=wh(t),u=e.type==="in-place"?e.idsOfElementsToDuplicate:new Map(t.map(g=>[g.id,g]));if(e.type==="in-place")for(let g of Object.keys(e.appState.selectedGroupIds))t.filter(E=>E.groupIds?.includes(g)).forEach(E=>u.set(E.id,E));t=Nd(t);let m=t.slice(),p=g=>{let x=Is(g).reduce((w,y)=>{if(i.has(y.id))return w;i.set(y.id,!0);let b=Ph(n.editingGroupId,o,y,e.randomizeSeed);return i.set(b.id,!0),d.set(b.id,b),a.set(y.id,b.id),l.set(b.id,y),s.push(y),r.push(b),w.push(b),w},[]);return Array.isArray(g)?x:x[0]||null},f=(g,E)=>{if(E){if(g>m.length-1){m.push(...Is(E));return}m.splice(g+1,0,...Is(E))}},h=new Set(t.filter(g=>u.has(g.id)&&q(g)).map(g=>g.id));for(let g of t){if(i.has(g.id)||!u.has(g.id))continue;let E=ls(n,g);if(E){let x=Ge(t,E).flatMap(y=>q(y)?[...fn(t,y.id),y]:[y]),w=Ci(m,y=>y.groupIds?.includes(E));f(w,p(x));continue}if(!(g.frameId&&h.has(g.frameId))){if(q(g)){let x=g.id,w=fn(t,x),y=Ci(m,b=>b.frameId===x||b.id===x);f(y,p([...w,g]));continue}if(ht(g)){let x=$(g,c),w=Ci(m,y=>y.id===g.id||"containerId"in y&&y.containerId===g.id);x?f(w,p([g,x])):f(w,p(g));continue}if(ce(g)){let x=Ae(g,c),w=Ci(m,y=>y.id===g.id||y.id===x?.id);x?f(w,p([x,g])):f(w,p(g));continue}f(Ci(m,x=>x.id===g.id),p(g))}}if(kl(r,a,d),md(m,s,a),e.overrides)for(let g of r){let E=l.get(g.id);E&&Object.assign(g,e.overrides({duplicateElement:g,origElement:E,origIdToDuplicateId:a}))}return{duplicatedElements:r,duplicateElementsMap:d,elementsWithDuplicates:m,origIdToDuplicateId:a}},Ss=(e,t=0)=>{if(e==null||typeof e!="object")return e;let n=Object.prototype.toString.call(e);if(n==="[object Object]"){let i=typeof e.constructor=="function"?Object.create(Object.getPrototypeOf(e)):{};for(let o in e)if(e.hasOwnProperty(o)){if(t===0&&(o==="shape"||o==="canvas"))continue;i[o]=Ss(e[o],t+1)}return i}if(Array.isArray(e)){let i=e.length,o=new Array(i);for(;i--;)o[i]=Ss(e[i],t+1);return o}return T.DEV&&n!=="[object Object]"&&n!=="[object Array]"&&n.startsWith("[object ")&&console.warn(`_deepCloneElement: unexpected object type ${n}. This value will not be cloned!`),e},As=e=>Ss(e),Ih=(e,t)=>{Object.defineProperty(e,Eh,{value:t,writable:!1,enumerable:!1})};var Ue={IMMEDIATELY:"IMMEDIATELY",NEVER:"NEVER",EVENTUALLY:"EVENTUALLY"},_d=class{constructor(t){this.app=t}onDurableIncrementEmitter=new Hd;onStoreIncrementEmitter=new Hd;scheduledMacroActions=new Set;scheduledMicroActions=[];_snapshot=wn.empty();get snapshot(){return this._snapshot}set snapshot(t){this._snapshot=t}scheduleAction(t){this.scheduledMacroActions.add(t),this.satisfiesScheduledActionsInvariant()}scheduleCapture(){this.scheduleAction(Ue.IMMEDIATELY)}scheduleMicroAction(t){let{action:n}=t,i;if("change"in t)i=t.change;else{let r=wn.create(this.app.scene.getElementsMapIncludingDeleted(),this.app.state),s=r.maybeClone(n,t.elements?Yd(t.elements):void 0,t.appState);i=Gi.create(r,s)}let o="delta"in t?t.delta:void 0;this.scheduledMicroActions.push(()=>this.processAction({action:n,change:i,delta:o}))}commit(t,n){this.flushMicroActions();try{let i=this.getScheduledMacroAction();this.processAction({action:i,elements:t,appState:n})}finally{this.satisfiesScheduledActionsInvariant(),this.scheduledMacroActions=new Set}}clear(){this.snapshot=wn.empty(),this.scheduledMacroActions=new Set}emitDurableIncrement(t,n=void 0,i=void 0){let o=this.snapshot,r,s;if(n?r=n:r=Gi.create(o,t),i?s=i:s=Ts.calculate(o,t),!s.isEmpty()){let a=new Ms(r,s);this.onDurableIncrementEmitter.trigger(a),this.onStoreIncrementEmitter.trigger(a)}}emitEphemeralIncrement(t,n=void 0){let i;if(n)i=n;else{let r=this.snapshot;i=Gi.create(r,t)}let o=new vs(i);this.onStoreIncrementEmitter.trigger(o)}applyChangeToSnapshot(t){let n=this.snapshot,i=this.snapshot.applyChange(t);return n===i?null:i}maybeCloneSnapshot(t,n,i){if(!n&&!i)return null;let o=this.snapshot,r=this.snapshot.maybeClone(t,n,i);return o===r?null:r}flushMicroActions(){for(let t of this.scheduledMicroActions)try{t()}catch(n){console.error("Failed to execute scheduled micro action",n)}this.scheduledMicroActions=[]}processAction(t){let{action:n}=t;if(n===Ue.EVENTUALLY&&!this.onStoreIncrementEmitter.subscribers.length)return;let i;if("change"in t?i=this.applyChangeToSnapshot(t.change):i=this.maybeCloneSnapshot(n,t.elements,t.appState),!i)return;let o="change"in t?t.change:void 0,r="delta"in t?t.delta:void 0;try{switch(n){case Ue.IMMEDIATELY:this.emitDurableIncrement(i,o,r);break;case Ue.NEVER:case Ue.EVENTUALLY:this.emitEphemeralIncrement(i,o);break;default:Sh(n,"Unknown store action")}}finally{switch(n){case Ue.IMMEDIATELY:case Ue.NEVER:this.snapshot=i;break}}}getScheduledMacroAction(){let t;return this.scheduledMacroActions.has(Ue.IMMEDIATELY)?t=Ue.IMMEDIATELY:this.scheduledMacroActions.has(Ue.NEVER)?t=Ue.NEVER:t=Ue.EVENTUALLY,t}satisfiesScheduledActionsInvariant(){if(!(this.scheduledMacroActions.size>=0&&this.scheduledMacroActions.size<=Object.keys(Ue).length)){let t=`There can be at most three store actions scheduled at the same time, but there are "${this.scheduledMacroActions.size}".`;if(console.error(t,this.scheduledMacroActions.values()),vh()||Mh())throw new Error(t)}}},Gi=class e{constructor(t,n){this.elements=t;this.appState=n}static create(t,n){let i=n.getChangedElements(t),o=n.getChangedAppState(t);return new e(i,o)}},Yo=class{constructor(t,n){this.type=t;this.change=n}static isDurable(t){return t.type==="durable"}static isEphemeral(t){return t.type==="ephemeral"}},Ms=class extends Yo{constructor(n,i){super("durable",n);this.change=n;this.delta=i}},vs=class extends Yo{constructor(n){super("ephemeral",n);this.change=n}},Ts=class e{constructor(t,n,i){this.id=t;this.elements=n;this.appState=i}static create(t,n,i={id:Th()}){return new this(i.id,t,n)}static calculate(t,n){let i=n.metadata.didElementsChange?xn.calculate(t.elements,n.elements):xn.empty(),o=n.metadata.didAppStateChange?En.calculate(t.appState,n.appState):En.empty();return this.create(i,o)}static restore(t){let{id:n,elements:i,appState:o}=t;return new this(n,xn.restore(i),En.restore(o))}static load({id:t,elements:{added:n,removed:i,updated:o},appState:{delta:r}}){let s=xn.create(n,i,o),a=En.create(r);return new this(t,s,a)}static squash(...t){let n=e.empty();for(let i of t)n.elements.squash(i.elements),n.appState.squash(i.appState);return n}static inverse(t){return this.create(t.elements.inverse(),t.appState.inverse())}static applyTo(t,n,i,o){let[r,s]=t.elements.applyTo(n,wn.empty().elements,o),[a,l]=t.appState.applyTo(i,r);return[r,a,s||l]}static applyLatestChanges(t,n,i,o){return this.create(t.elements.applyLatestChanges(n,i,o),t.appState,{id:t.id})}static empty(){return e.create(xn.empty(),En.empty())}isEmpty(){return this.elements.isEmpty()&&this.appState.isEmpty()}},wn=class e{constructor(t,n,i={didElementsChange:!1,didAppStateChange:!1,isEmpty:!1}){this.elements=t;this.appState=n;this.metadata=i}_lastChangedElementsHash=0;_lastChangedAppStateHash=0;static create(t,n,i={didElementsChange:!1,didAppStateChange:!1}){return new e(t,Ud(n)?n:qn(n),i)}static empty(){return new e(new Map,Dh(),{didElementsChange:!1,didAppStateChange:!1,isEmpty:!0})}getChangedElements(t){let n={};for(let i of Zn(t.elements))this.elements.get(i.id)||(n[i.id]=Be(i,{isDeleted:!0}));for(let i of Zn(this.elements))t.elements.get(i.id)!==i&&(n[i.id]=i);return n}getChangedAppState(t){return U.getRightDifferences(t.appState,this.appState).reduce((n,i)=>Object.assign(n,{[i]:this.appState[i]}),{})}isEmpty(){return this.metadata.isEmpty}applyChange(t){let n=new Map(this.elements);for(let[o,r]of Object.entries(t.elements))n.set(o,r);let i=qn({...this.appState,...t.appState});return e.create(n,i,{didElementsChange:Object.keys(t.elements).length>0,didAppStateChange:Object.keys(t.appState).length>0})}maybeClone(t,n,i){let o={shouldCompareHashes:!1};t===Ue.EVENTUALLY&&(o.shouldCompareHashes=!0);let r=this.maybeCreateElementsSnapshot(n,o),s=this.maybeCreateAppStateSnapshot(i,o),a=!1,l=!1;return this.elements!==r&&(a=!0),this.appState!==s&&(l=!0),!a&&!l?this:new e(r,s,{didElementsChange:a,didAppStateChange:l})}maybeCreateAppStateSnapshot(t,n={shouldCompareHashes:!1}){if(!t)return this.appState;let i=Ud(t)?t:qn(t);return this.detectChangedAppState(i,n)?i:this.appState}maybeCreateElementsSnapshot(t,n={shouldCompareHashes:!1}){if(!t)return this.elements;let i=this.detectChangedElements(t,n);return i?.size?this.createElementsSnapshot(i):this.elements}detectChangedAppState(t,n={shouldCompareHashes:!1}){if(this.appState===t)return;let i=U.isRightDifferent(this.appState,t);if(!i)return;let o=Xd(JSON.stringify(t));if(!(n.shouldCompareHashes&&this._lastChangedAppStateHash===o))return this._lastChangedAppStateHash=o,i}detectChangedElements(t,n={shouldCompareHashes:!1}){if(this.elements===t)return;let i=new Map;for(let r of Zn(this.elements))t.get(r.id)||i.set(r.id,Be(r,{isDeleted:!0}));for(let r of Zn(t)){let s=this.elements.get(r.id);if(!s||s.version<r.version){if(xe(r)&&!vn(r))continue;i.set(r.id,r)}}if(!i.size)return;let o=jd(i);if(!(n.shouldCompareHashes&&this._lastChangedElementsHash===o))return this._lastChangedElementsHash=o,i}createElementsSnapshot(t){let n=new Map;for(let i of Zn(this.elements))n.set(i.id,i);for(let i of Zn(t))n.set(i.id,As(i));return n}},Wd="__observedAppState",Dh=()=>({name:null,editingGroupId:null,viewBackgroundColor:Ah.white,selectedElementIds:{},selectedGroupIds:{},selectedLinearElement:null,croppingElementId:null,activeLockedId:null,lockedMultiSelections:{}}),qn=e=>{let t={name:e.name,editingGroupId:e.editingGroupId,viewBackgroundColor:e.viewBackgroundColor,selectedElementIds:e.selectedElementIds,selectedGroupIds:e.selectedGroupIds,croppingElementId:e.croppingElementId,activeLockedId:e.activeLockedId,lockedMultiSelections:e.lockedMultiSelections,selectedLinearElement:e.selectedLinearElement?{elementId:e.selectedLinearElement.elementId,isEditing:!!e.selectedLinearElement.isEditing}:null};return Reflect.defineProperty(t,Wd,{value:!0,enumerable:!1}),t},Ud=e=>!!Reflect.get(e,Wd);P();P();var Zd="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Qn(e,t,n){let i=n[0];if(t!=null&&e>=t)throw new Error(e+" >= "+t);if(e.slice(-1)===i||t&&t.slice(-1)===i)throw new Error("trailing zero");if(t){let s=0;for(;(e[s]||i)===t[s];)s++;if(s>0)return t.slice(0,s)+Qn(e.slice(s),t.slice(s),n)}let o=e?n.indexOf(e[0]):0,r=t!=null?n.indexOf(t[0]):n.length;if(r-o>1){let s=Math.round(.5*(o+r));return n[s]}else return t&&t.length>1?t.slice(0,1):n[o]+Qn(e.slice(1),null,n)}function qd(e){if(e.length!==Kd(e[0]))throw new Error("invalid integer part of order key: "+e)}function Kd(e){if(e>="a"&&e<="z")return e.charCodeAt(0)-97+2;if(e>="A"&&e<="Z")return 90-e.charCodeAt(0)+2;throw new Error("invalid order key head: "+e)}function Oi(e){let t=Kd(e[0]);if(t>e.length)throw new Error("invalid order key: "+e);return e.slice(0,t)}function $d(e,t){if(e==="A"+t[0].repeat(26))throw new Error("invalid order key: "+e);let n=Oi(e);if(e.slice(n.length).slice(-1)===t[0])throw new Error("invalid order key: "+e)}function Vd(e,t){qd(e);let[n,...i]=e.split(""),o=!0;for(let r=i.length-1;o&&r>=0;r--){let s=t.indexOf(i[r])+1;s===t.length?i[r]=t[0]:(i[r]=t[s],o=!1)}if(o){if(n==="Z")return"a"+t[0];if(n==="z")return null;let r=String.fromCharCode(n.charCodeAt(0)+1);return r>"a"?i.push(t[0]):i.pop(),r+i.join("")}else return n+i.join("")}function Bh(e,t){qd(e);let[n,...i]=e.split(""),o=!0;for(let r=i.length-1;o&&r>=0;r--){let s=t.indexOf(i[r])-1;s===-1?i[r]=t.slice(-1):(i[r]=t[s],o=!1)}if(o){if(n==="a")return"Z"+t.slice(-1);if(n==="A")return null;let r=String.fromCharCode(n.charCodeAt(0)-1);return r<"Z"?i.push(t.slice(-1)):i.pop(),r+i.join("")}else return n+i.join("")}function Kn(e,t,n=Zd){if(e!=null&&$d(e,n),t!=null&&$d(t,n),e!=null&&t!=null&&e>=t)throw new Error(e+" >= "+t);if(e==null){if(t==null)return"a"+n[0];let l=Oi(t),d=t.slice(l.length);if(l==="A"+n[0].repeat(26))return l+Qn("",d,n);if(l<t)return l;let c=Bh(l,n);if(c==null)throw new Error("cannot decrement any more");return c}if(t==null){let l=Oi(e),d=e.slice(l.length),c=Vd(l,n);return c??l+Qn(d,null,n)}let i=Oi(e),o=e.slice(i.length),r=Oi(t),s=t.slice(r.length);if(i===r)return i+Qn(o,s,n);let a=Vd(i,n);if(a==null)throw new Error("cannot increment any more");return a<t?a:i+Qn(o,null,n)}function jo(e,t,n,i=Zd){if(n===0)return[];if(n===1)return[Kn(e,t,i)];if(t==null){let s=Kn(e,t,i),a=[s];for(let l=0;l<n-1;l++)s=Kn(s,t,i),a.push(s);return a}if(e==null){let s=Kn(e,t,i),a=[s];for(let l=0;l<n-1;l++)s=Kn(e,s,i),a.push(s);return a.reverse(),a}let o=Math.floor(n/2),r=Kn(e,t,i);return[...jo(e,r,o,i),r,...jo(r,t,n-o-1,i)]}import{arrayToMap as Xo}from"@orangecatai/common";var Ds=class extends Error{code="ELEMENT_HAS_INVALID_INDEX"},Lh=(e,{shouldThrow:t=!1,includeBoundTextValidation:n=!1,ignoreLogs:i,reconciliationContext:o})=>{let r=[],s=l=>`${l?.index}:${l?.id}:${l?.type}:${l?.isDeleted}:${l?.version}:${l?.versionNonce}`,a=e.map(l=>l.index);for(let[l,d]of a.entries()){let c=a[l-1],u=a[l+1];if(Bs(d,c,u)||r.push(`Fractional indices invariant has been compromised: "${s(e[l-1])}", "${s(e[l])}", "${s(e[l+1])}"`),n&&ht(e[l])){let m=e[l],p=$(m,Xo(e));p&&p.index<=m.index&&r.push(`Fractional indices invariant for bound elements has been compromised: "${s(p)}", "${s(m)}"`)}}if(r.length){let l=new Ds,d=[];if(o&&(d.push("Additional reconciliation context:"),d.push(o.localElements.map(c=>s(c))),d.push(o.remoteElements.map(c=>s(c)))),i||console.error(r.join(`
19
19
 
20
- `),l.stack,e.map(c=>s(c)),...d),t)throw l}},Jd=e=>e.sort((t,n)=>Qd(t)&&Qd(n)?t.index<n.index?-1:t.index>n.index?1:t.id<n.id?-1:1:1),ki=(e,t)=>{try{let n=Xo(e),i=Ch(e,t),o=Cs(e,i),r=e.map(s=>{let a=o.get(s);return a?{...s,index:a.index}:s});Lh(r,{includeBoundTextValidation:!1,shouldThrow:!0,ignoreLogs:!0});for(let[s,{index:a}]of o)be(s,n,{index:a})}catch{Ls(e)}return e},Ls=e=>{let t=Xo(e),n=ec(e),i=Cs(e,n);for(let[o,{index:r}]of i)be(o,t,{index:r});return e},Yd=e=>{let t=Xo(e),n=ec(e),i=Cs(e,n);for(let[o,{index:r}]of i)t.set(o.id,Be(o,{index:r}));return t},Ch=(e,t)=>{let n=[],i=0;for(;i<e.length;)if(t.has(e[i].id)){let o=[i-1,i];for(;++i<e.length&&t.has(e[i].id);)o.push(i);o.push(i),n.push(o)}else i++;return n},ec=e=>{let t=[],n,i,o=-1,r=0,s=d=>{let c=e[o]?e[o].index:void 0,u=e[d-1]?.index;return!c&&u||c&&u&&u>c?[u,d-1]:[c,o]},a=d=>{let c=e[r]?e[r].index:void 0;if(c&&d<r)return[c,r];let u=r;for(;++u<e.length;){let m=e[u]?.index;if(!c&&m||c&&m&&m>c)return[m,u]}return[void 0,u]},l=0;for(;l<e.length;){let d=e[l].index;if([n,o]=s(l),[i,r]=a(l),Bs(d,n,i))l++;else{let c=[o,l];for(;++l<e.length;){let u=e[l].index,[m,p]=s(l),[f,h]=a(l);if(Bs(u,m,f))break;[n,o]=[m,p],[i,r]=[f,h],c.push(l)}c.push(r),t.push(c)}}return t},Bs=(e,t,n)=>e?t&&n?t<e&&e<n:!t&&n?e<n:t&&!n?t<e:!!e:!1,Cs=(e,t)=>{let n=new Map;for(let i of t){let o=i.shift(),r=i.pop(),s=jo(e[o]?.index,e[r]?.index,i.length);for(let a=0;a<i.length;a++){let l=e[i[a]];n.set(l,{index:s[a]})}}return n},Qd=e=>!!e.index;P();var mc=uu(rc(),1);import{randomInteger as qh,arrayToMap as sc,toBrandedType as ac,isDevEnv as lc,isTestEnv as dc,toArray as Kh}from"@orangecatai/common";import{isNonDeletedElement as Qh}from"@orangecatai/element";import{isFrameLikeElement as Jh}from"@orangecatai/element";import{getElementsInGroup as eg}from"@orangecatai/element";import{syncInvalidIndices as tg,syncMovedIndices as cc,validateFractionalIndices as ng}from"@orangecatai/element";import{getSelectedElements as ig}from"@orangecatai/element";import{mutateElement as og}from"@orangecatai/element";var uc=e=>{let t=new Map,n=[];for(let i of e)i.isDeleted||(n.push(i),t.set(i.id,i));return{elementsMap:t,elements:n}},rg=(0,mc.default)(e=>{(lc()||dc()||window?.DEBUG_FRACTIONAL_INDICES)&&ng(e,{shouldThrow:lc()||dc(),includeBoundTextValidation:!0})},1e3*60,{leading:!0,trailing:!1}),sg=e=>{let t=["includeBoundTextElement","includeElementsInFrames"],n="";for(let i of t)n+=`${i}:${e[i]?"1":"0"}`;return n},Jn=class{callbacks=new Set;nonDeletedElements=[];nonDeletedElementsMap=ac(new Map);elements=[];nonDeletedFramesLikes=[];frames=[];elementsMap=ac(new Map);selectedElementsCache={selectedElementIds:null,elements:null,cache:new Map};sceneNonce;getSceneNonce(){return this.sceneNonce}getNonDeletedElementsMap(){return this.nonDeletedElementsMap}getElementsIncludingDeleted(){return this.elements}getElementsMapIncludingDeleted(){return this.elementsMap}getNonDeletedElements(){return this.nonDeletedElements}getFramesIncludingDeleted(){return this.frames}constructor(t=null,n){t&&this.replaceAllElements(t,n)}getSelectedElements(t){let n=sg(t),i=t?.elements||this.nonDeletedElements;if(this.selectedElementsCache.elements===i&&this.selectedElementsCache.selectedElementIds===t.selectedElementIds){let r=this.selectedElementsCache.cache.get(n);if(r)return r}else t?.elements==null&&this.selectedElementsCache.cache.clear();let o=ig(i,{selectedElementIds:t.selectedElementIds},t);return t?.elements==null&&(this.selectedElementsCache.selectedElementIds=t.selectedElementIds,this.selectedElementsCache.elements=this.nonDeletedElements,this.selectedElementsCache.cache.set(n,o)),o}getNonDeletedFramesLikes(){return this.nonDeletedFramesLikes}getElement(t){return this.elementsMap.get(t)||null}getNonDeletedElement(t){let n=this.getElement(t);return n&&Qh(n)?n:null}mapElements(t){let n=!1,i=this.elements.map(o=>{let r=t(o);return r!==o&&(n=!0),r});return n&&this.replaceAllElements(i),n}replaceAllElements(t,n){let i=Kh(t),o=[];n?.skipValidation||rg(i),this.elements=tg(i),this.elementsMap.clear(),this.elements.forEach(s=>{Jh(s)&&o.push(s),this.elementsMap.set(s.id,s)});let r=uc(this.elements);this.nonDeletedElements=r.elements,this.nonDeletedElementsMap=r.elementsMap,this.frames=o,this.nonDeletedFramesLikes=uc(this.frames).elements,this.triggerUpdate()}triggerUpdate(){this.sceneNonce=qh();for(let t of Array.from(this.callbacks))t()}onUpdate(t){if(this.callbacks.has(t))throw new Error;return this.callbacks.add(t),()=>{if(!this.callbacks.has(t))throw new Error;this.callbacks.delete(t)}}destroy(){this.elements=[],this.nonDeletedElements=[],this.nonDeletedFramesLikes=[],this.frames=[],this.elementsMap.clear(),this.selectedElementsCache.selectedElementIds=null,this.selectedElementsCache.elements=null,this.selectedElementsCache.cache.clear(),this.callbacks.clear()}insertElementAtIndex(t,n){if(!Number.isFinite(n)||n<0)throw new Error("insertElementAtIndex can only be called with index >= 0");let i=[...this.elements.slice(0,n),t,...this.elements.slice(n)];cc(i,sc([t])),this.replaceAllElements(i)}insertElementsAtIndex(t,n){if(!t.length)return;if(!Number.isFinite(n)||n<0)throw new Error("insertElementAtIndex can only be called with index >= 0");let i=[...this.elements.slice(0,n),...t,...this.elements.slice(n)];cc(i,sc(t)),this.replaceAllElements(i)}insertElement=t=>{let n=t.frameId?this.getElementIndex(t.frameId):this.elements.length;this.insertElementAtIndex(t,n)};insertElements=t=>{if(!t.length)return;let n=t[0]?.frameId?this.getElementIndex(t[0].frameId):this.elements.length;this.insertElementsAtIndex(t,n)};getElementIndex(t){return this.elements.findIndex(n=>n.id===t)}getContainerElement=t=>t&&t.containerId&&this.getElement(t.containerId)||null;getElementsFromId=t=>{let n=this.getNonDeletedElementsMap(),i=n.get(t);return i?[i]:eg(n,t)};mutateElement(t,n,i={informMutation:!0,isDragging:!1}){let o=this.getNonDeletedElementsMap(),{version:r}=t,{version:s}=og(t,o,n,i);return this.elementsMap.has(t.id)&&r!==s&&i.informMutation&&this.triggerUpdate(),t}};var U=class e{constructor(t,n){this.deleted=t;this.inserted=n}static create(t,n,i,o){let r=i&&o!=="inserted"?i(t,"deleted"):t,s=i&&o!=="deleted"?i(n,"inserted"):n;return new e(r,s)}static calculate(t,n,i,o){if(t===n)return e.empty();let r={},s={};for(let d of this.getDifferences(t,n))r[d]=t[d],s[d]=n[d];let[a,l]=o?o(r,s):[r,s];return e.create(a,l,i)}static empty(){return new e({},{})}static isEmpty(t){return!Object.keys(t.deleted).length&&!Object.keys(t.inserted).length}static merge(t,n,i=e.empty()){return e.create({...t.deleted,...n.deleted,...i.deleted},{...t.inserted,...n.inserted,...i.inserted})}static mergeObjects(t,n,i={}){let o={...t};for(let r of Object.keys(i))delete o[r];return{...o,...n}}static mergeArrays(t,n,i,o){return Object.values(e.mergeObjects(Xt(t??[],o),Xt(n??[],o),Xt(i??[],o)))}static diffObjects(t,n,i,o){if(!t[i]&&!n[i])return;let r=t[i]!==null&&typeof t[i]=="object",s=n[i]!==null&&typeof n[i]=="object";if(r||s){let a=t[i]??{},l=n[i]??{},d=e.getLeftDifferences(a,l).reduce((u,m)=>(u[m]=o(a[m]),u),{}),c=e.getRightDifferences(a,l).reduce((u,m)=>(u[m]=o(l[m]),u),{});Object.keys(d).length||Object.keys(c).length?(Reflect.set(t,i,d),Reflect.set(n,i,c)):(Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i))}else t[i]===n[i]&&(Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i))}static diffArrays(t,n,i,o){if(!(!t[i]&&!n[i])&&(Array.isArray(t[i])||Array.isArray(n[i]))){let r=Array.isArray(t[i])?t[i]:[],s=Array.isArray(n[i])?n[i]:[],a=Xt(e.getLeftDifferences(Xt(r,o),Xt(s,o)),d=>d),l=Xt(e.getRightDifferences(Xt(r,o),Xt(s,o)),d=>d);if(Object.keys(a).length||Object.keys(l).length){let d=r.filter(u=>a[o?o(u):String(u)]),c=s.filter(u=>l[o?o(u):String(u)]);Reflect.set(t,i,d),Reflect.set(n,i,c)}else Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i)}}static isLeftDifferent(t,n,i=!1){return!!this.distinctKeysIterator("left",t,n,i).next().value}static isRightDifferent(t,n,i=!1){return!!this.distinctKeysIterator("right",t,n,i).next().value}static isInnerDifferent(t,n,i=!1){return!!!!this.distinctKeysIterator("inner",t,n,i).next().value}static isDifferent(t,n,i=!1){return!!!!this.distinctKeysIterator("full",t,n,i).next().value}static getLeftDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("left",t,n,i)).sort()}static getRightDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("right",t,n,i)).sort()}static getInnerDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("inner",t,n,i)).sort()}static getDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("full",t,n,i)).sort()}static*distinctKeysIterator(t,n,i,o=!1){if(n===i)return;let r=[];t==="left"?r=Object.keys(n):t==="right"?r=Object.keys(i):t==="inner"?r=Object.keys(n).filter(s=>s in i):t==="full"?r=Array.from(new Set([...Object.keys(n),...Object.keys(i)])):fc(t,`Unknown distinctKeysIterator's join param "${t}"`,!0);for(let s of r){let a=n[s],l=i[s];if(a!==l){if(!o&&typeof a=="object"&&typeof l=="object"&&a!==null&&l!==null&&hc(a,l))continue;yield s}}}},En=class e{constructor(t){this.delta=t}static create(t){return new e(t)}static calculate(t,n){let i=U.calculate(t,n,e.orderAppStateKeys,e.postProcess);return new e(i)}static restore(t){let{delta:n}=t;return new e(n)}static empty(){return new e(U.create({},{}))}inverse(){let t=U.create(this.delta.inserted,this.delta.deleted);return new e(t)}squash(t){if(t.isEmpty())return this;let n=U.mergeObjects(this.delta.deleted.selectedElementIds??{},t.delta.deleted.selectedElementIds??{}),i=U.mergeObjects(this.delta.inserted.selectedElementIds??{},t.delta.inserted.selectedElementIds??{}),o=U.mergeObjects(this.delta.deleted.selectedGroupIds??{},t.delta.deleted.selectedGroupIds??{}),r=U.mergeObjects(this.delta.inserted.selectedGroupIds??{},t.delta.inserted.selectedGroupIds??{}),s=U.mergeObjects(this.delta.deleted.lockedMultiSelections??{},t.delta.deleted.lockedMultiSelections??{}),a=U.mergeObjects(this.delta.inserted.lockedMultiSelections??{},t.delta.inserted.lockedMultiSelections??{}),l={},d={};return(Object.keys(n).length||Object.keys(i).length)&&(d.selectedElementIds=n,l.selectedElementIds=i),(Object.keys(o).length||Object.keys(r).length)&&(d.selectedGroupIds=o,l.selectedGroupIds=r),(Object.keys(s).length||Object.keys(a).length)&&(d.lockedMultiSelections=s,l.lockedMultiSelections=a),this.delta=U.merge(this.delta,t.delta,U.create(d,l)),this}applyTo(t,n){try{let{selectedElementIds:i={},selectedGroupIds:o={},lockedMultiSelections:r={}}=this.delta.deleted,{selectedElementIds:s={},selectedGroupIds:a={},lockedMultiSelections:l={},selectedLinearElement:d,...c}=this.delta.inserted,u=U.mergeObjects(t.selectedElementIds,s,i),m=U.mergeObjects(t.selectedGroupIds,a,o),p=U.mergeObjects(t.lockedMultiSelections,l,r),f=d&&n.has(d.elementId)?new L(n.get(d.elementId),n,d.isEditing):null,h={...t,...c,selectedElementIds:u,selectedGroupIds:m,lockedMultiSelections:p,selectedLinearElement:typeof d<"u"?f:t.selectedLinearElement},g=this.filterInvisibleChanges(t,h,n);return[h,g]}catch(i){if(console.error("Couldn't apply appstate change",i),yn()||bn())throw i;return[t,!1]}}isEmpty(){return U.isEmpty(this.delta)}filterInvisibleChanges(t,n,i){let o=qn(t),r=qn(n),s=U.isRightDifferent(e.stripElementsProps(o),e.stripElementsProps(r)),a=U.isRightDifferent(e.stripStandaloneProps(o),e.stripStandaloneProps(r));if(!s&&!a)return!1;let l={value:s};if(a){let d=U.getRightDifferences(e.stripStandaloneProps(o),e.stripStandaloneProps(r)),c=new Set;(d.includes("editingGroupId")||d.includes("selectedGroupIds"))&&(c=sd(i));for(let u of d)switch(u){case"selectedElementIds":n[u]=e.filterSelectedElements(n[u],i,l);break;case"selectedGroupIds":n[u]=e.filterSelectedGroups(n[u],c,l);break;case"croppingElementId":{let x=n[u];if(!x)l.value=!0;else{let w=i.get(x);w&&!w.isDeleted?l.value=!0:n[u]=null}break}case"editingGroupId":let m=n[u];m?c.has(m)?l.value=!0:n[u]=null:l.value=!0;break;case"selectedLinearElement":let p=n[u];if(!p)l.value=!0;else{let x=i.get(p.elementId);x&&!x.isDeleted?l.value=!0:n[u]=null}break;case"lockedMultiSelections":let f=t[u]||{},h=n[u]||{};hc(f,h)||(l.value=!0);break;case"activeLockedId":let g=t[u]||null,E=n[u]||null;g!==E&&(l.value=!0);break;default:fc(u,`Unknown ObservedElementsAppState's key "${u}"`,!0)}}return l.value}static filterSelectedElements(t,n,i){let o=Object.keys(t);if(!o.length)return i.value=!0,t;let r={...t};for(let s of o){let a=n.get(s);a&&!a.isDeleted?i.value=!0:delete r[s]}return r}static filterSelectedGroups(t,n,i){if(!Object.keys(t).length)return i.value=!0,t;let r={...t};for(let s of Object.keys(r))n.has(s)?i.value=!0:delete r[s];return r}static stripElementsProps(t){let{editingGroupId:n,selectedGroupIds:i,selectedElementIds:o,selectedLinearElement:r,croppingElementId:s,lockedMultiSelections:a,activeLockedId:l,...d}=t;return d}static stripStandaloneProps(t){let{name:n,viewBackgroundColor:i,...o}=t;return o}static postProcess(t,n){try{U.diffObjects(t,n,"selectedElementIds",i=>!0),U.diffObjects(t,n,"selectedGroupIds",i=>i??!1),U.diffObjects(t,n,"lockedMultiSelections",i=>i??{})}catch(i){if(console.error("Couldn't postprocess appstate change deltas."),yn()||bn())throw i}finally{return[t,n]}}static orderAppStateKeys(t){let n={};for(let i of Object.keys(t).sort())n[i]=t[i];return n}},xn=class e{constructor(t,n,i){this.added=t;this.removed=n;this.updated=i}static create(t,n,i,o={shouldRedistribute:!1}){let r;if(o.shouldRedistribute){let s={},a={},l={},d=[...Object.entries(t),...Object.entries(n),...Object.entries(i)];for(let[c,u]of d)this.satisfiesAddition(u)?s[c]=u:this.satisfiesRemoval(u)?a[c]=u:l[c]=u;r=new e(s,a,l)}else r=new e(t,n,i);return(yn()||bn())&&(e.validate(r,"added",this.satisfiesAddition),e.validate(r,"removed",this.satisfiesRemoval),e.validate(r,"updated",this.satisfiesUpdate)),r}static restore(t){let{added:n,removed:i,updated:o}=t;return e.create(n,i,o)}static satisfiesAddition=({deleted:t,inserted:n})=>t.isDeleted===!0&&!n.isDeleted;static satisfiesRemoval=({deleted:t,inserted:n})=>!t.isDeleted&&n.isDeleted===!0;static satisfiesUpdate=({deleted:t,inserted:n})=>!!t.isDeleted==!!n.isDeleted;static satisfiesCommmonInvariants=({deleted:t,inserted:n})=>!!(Number.isInteger(t.version)&&Number.isInteger(n.version)&&t.version>=0&&n.version>=0&&t.version!==n.version);static satisfiesUniqueInvariants=(t,n)=>{let{added:i,removed:o,updated:r}=t;return[i[n],o[n],r[n]].filter(Boolean).length===1};static validate(t,n,i){for(let[o,r]of Object.entries(t[n]))if(!this.satisfiesCommmonInvariants(r)||!this.satisfiesUniqueInvariants(t,o)||!i(r))throw console.error(`Broken invariant for "${n}" delta, element "${o}", delta:`,r),new Error(`ElementsDelta invariant broken for element "${o}".`)}static calculate(t,n){if(t===n)return e.empty();let i={},o={},r={};for(let s of t.values())if(!n.get(s.id)){let l={...s},d={isDeleted:!0,version:s.version+1,versionNonce:pc()},c=U.create(l,d,e.stripIrrelevantProps);s.isDeleted?r[s.id]=c:o[s.id]=c}for(let s of n.values()){let a=t.get(s.id);if(!a){let l={isDeleted:!0,version:s.version-1,versionNonce:pc()},d={...s},c=U.create(l,d,e.stripIrrelevantProps);s.isDeleted?r[s.id]=c:i[s.id]=c;continue}if(a.versionNonce!==s.versionNonce){let l=U.calculate(a,s,e.stripIrrelevantProps,e.postProcess);if(typeof a.isDeleted=="boolean"&&typeof s.isDeleted=="boolean"&&a.isDeleted!==s.isDeleted){a.isDeleted&&!s.isDeleted?i[s.id]=l:o[s.id]=l;continue}r[s.id]=l}}return e.create(i,o,r)}static empty(){return e.create({},{},{})}inverse(){let t=r=>{let s={};for(let[a,{inserted:l,deleted:d}]of Object.entries(r))s[a]=U.create({...l},{...d});return s},n=t(this.added),i=t(this.removed),o=t(this.updated);return e.create(i,n,o)}isEmpty(){return Object.keys(this.added).length===0&&Object.keys(this.removed).length===0&&Object.keys(this.updated).length===0}applyLatestChanges(t,n,i){let o=(d,c)=>(u,m)=>{let p;switch(m){case"deleted":p=d;break;case"inserted":p=c;break}if(!p)return console.error("Element not found when trying to apply latest changes"),u;let f={};for(let h of Object.keys(u))switch(h){case"boundElements":f[h]=u[h];break;default:f[h]=p[h]}return f},r=d=>{let c={};for(let[u,m]of Object.entries(d)){let p=t.get(u),f=n.get(u),h=null;p||f?h=U.create(m.deleted,m.inserted,o(p,f),i):h=m,U.isInnerDifferent(h.deleted,h.inserted)&&(c[u]=h)}return c},s=r(this.added),a=r(this.removed),l=r(this.updated);return e.create(s,a,l,{shouldRedistribute:!0})}applyTo(t,n=wn.empty().elements,i){let o=new Map(t),r,s={containsVisibleDifference:!1,containsZindexDifference:!1,applyDirection:void 0};try{let a=e.createApplier(t,o,n,s,i),l=a(this.added),d=a(this.removed),c=a(this.updated),u=this.resolveConflicts(t,o,s.applyDirection);r=new Map([...l,...d,...c,...u])}catch(a){if(console.error("Couldn't apply elements delta",a),yn()||bn())throw a;return[t,!0]}try{o=e.reorderElements(o,r,s),e.redrawElements(o,r)}catch(a){if(console.error("Couldn't mutate elements after applying elements change",a),yn()||bn())throw a}finally{return[o,s.containsVisibleDifference]}}squash(t){if(t.isEmpty())return this;let{added:n,removed:i,updated:o}=t,r=(s,a)=>{let l=U.mergeArrays(s.deleted.boundElements??[],a.deleted.boundElements??[],void 0,c=>c.id)??[],d=U.mergeArrays(s.inserted.boundElements??[],a.inserted.boundElements??[],void 0,c=>c.id)??[];if(!(!l.length&&!d.length))return U.create({boundElements:l},{boundElements:d})};for(let[s,a]of Object.entries(n)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.added[s]=a;else{let d=r(l,a);delete this.removed[s],delete this.updated[s],this.added[s]=U.merge(l,a,d)}}for(let[s,a]of Object.entries(i)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.removed[s]=a;else{let d=r(l,a);delete this.added[s],delete this.updated[s],this.removed[s]=U.merge(l,a,d)}}for(let[s,a]of Object.entries(o)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.updated[s]=a;else{let d=r(l,a),c=U.merge(l,a,d);l===this.added[s]?this.added[s]=c:l===this.removed[s]?this.removed[s]=c:this.updated[s]=c}}return(yn()||bn())&&(e.validate(this,"added",e.satisfiesAddition),e.validate(this,"removed",e.satisfiesRemoval),e.validate(this,"updated",e.satisfiesUpdate)),this}static createApplier=(t,n,i,o,r)=>s=>{let a=e.createGetter(n,i,o);return Object.entries(s).reduce((l,[d,c])=>{let u=a(d,c.inserted);if(u){let m=e.applyDelta(u,c,o,r);if(n.set(m.id,m),l.set(m.id,m),!o.applyDirection){let p=t.get(d);p&&(o.applyDirection=p.version>m.version?"backward":"forward")}}return l},new Map)};static createGetter=(t,n,i)=>(o,r)=>{let s=t.get(o);return s||(s=n.get(o),s?(i.containsZindexDifference=!0,(!r.isDeleted||r.isDeleted&&!s.isDeleted)&&(i.containsVisibleDifference=!0)):s=Be({id:o,version:1},{...r})),s};static applyDelta(t,n,i,o){let r={};for(let s of Object.keys(n.inserted)){if(s==="boundElements"||o?.excludedProperties?.has(s))continue;let a=n.inserted[s];Reflect.set(r,s,a)}if(n.deleted.boundElements?.length||n.inserted.boundElements?.length){let s=U.mergeArrays(t.boundElements,n.inserted.boundElements,n.deleted.boundElements,a=>a.id);Object.assign(r,{boundElements:s})}if(!i.containsVisibleDifference){let{index:s,...a}=r,l=e.checkForVisibleDifference(t,a);i.containsVisibleDifference=l}return i.containsZindexDifference||(i.containsZindexDifference=n.deleted.index!==n.inserted.index),Be(t,r,!0)}static checkForVisibleDifference(t,n){return t.isDeleted&&n.isDeleted!==!1?!1:t.isDeleted&&n.isDeleted===!1||t.isDeleted===!1&&n.isDeleted?!0:U.isRightDifferent(t,n)}resolveConflicts(t,n,i="forward"){let o=new Map,r=(a,l)=>{let d=n.get(a.id);if(!d)return;let c=t.get(a.id),u=i==="forward"?d.version+1:d.version-1,m=l,p;c===d?p=Be(d,{...m,version:u},!0):p=be(d,n,{...m,version:c?.version!==d.version?d.version:u}),o.set(p.id,p),n.set(p.id,p)};for(let a of Object.keys(this.removed))e.unbindAffected(t,n,a,r);for(let a of Object.keys(this.added))e.rebindAffected(t,n,a,r);for(let[a]of Array.from(Object.entries(this.updated)).filter(([l,d])=>Object.keys({...d.deleted,...d.inserted}).find(c=>Fl.has(c)))){let l=n.get(a);!l||l.isDeleted||e.rebindAffected(t,n,a,r)}let s=new Map(Array.from(t).filter(([a])=>o.has(a)));return this.squash(e.calculate(s,o)),o}static unbindAffected(t,n,i,o){let r=()=>t.get(i),s=()=>n.get(i);un.unbindAffected(n,r(),o),un.unbindAffected(n,s(),o),mn.unbindAffected(n,r(),o),mn.unbindAffected(n,s(),o)}static rebindAffected(t,n,i,o){let r=()=>t.get(i),s=()=>n.get(i);un.unbindAffected(n,r(),o),un.rebindAffected(n,s(),o),mn.unbindAffected(n,r(),(a,l)=>{J(a)&&o(a,l)}),mn.rebindAffected(n,s(),o)}static redrawElements(t,n){try{let i=new Jn(t,{skipValidation:!0});e.redrawTextBoundingBoxes(i,n),e.redrawBoundArrows(i,n)}catch(i){if(console.error("Couldn't redraw elements",i),yn()||bn())throw i}finally{return t}}static redrawTextBoundingBoxes(t,n){let i=t.getNonDeletedElementsMap(),o=new Map;for(let r of n.values()){if(ce(r)){let{containerId:s}=r,a=s?i.get(s):void 0;a&&o.set(a.id,{container:a,boundText:r})}if(ht(r)){let s=Ft(r),a=s?i.get(s):void 0;a&&o.set(r.id,{container:r,boundText:a})}}for(let{container:r,boundText:s}of o.values())r.isDeleted||s.isDeleted||fo(s,r,t)}static redrawBoundArrows(t,n){for(let i of n.values())!i.isDeleted&&de(i)&&Te(i,t,{changedElements:n})}static reorderElements(t,n,i){if(!i.containsZindexDifference)return t;let o=Array.from(t.values()),r=Jd([...o]),s=U.getRightDifferences(o,r,!0).reduce((a,l)=>{let d=o[Number(l)];return d&&n.has(d.id)&&a.set(d.id,d),a},new Map);return!i.containsVisibleDifference&&s.size&&(i.containsVisibleDifference=!0),ag(ki(r,s))}static postProcess(t,n){try{U.diffArrays(t,n,"boundElements",r=>r.id);let i=t.points??[],o=n.points??[];U.isDifferent(i,o)||(Reflect.deleteProperty(t,"points"),Reflect.deleteProperty(n,"points"))}catch(i){if(console.error("Couldn't postprocess elements delta."),yn()||bn())throw i}finally{return[t,n]}}static stripIrrelevantProps(t){let{id:n,updated:i,...o}=t;return o}};P();var hI=(e,t,n,i,o)=>{let[r,s,a,l]=n.axis==="x"?["minX","midX","maxX","width"]:["minY","midY","maxY","height"],d=Yt(e),c=ko(e,t,i).map(f=>[f,Yt(f)]).sort((f,h)=>f[1][s]-h[1][s]),u=0;for(let f of c)u+=f[1][l];let m=(d[l]-u)/(c.length-1);if(m<0){let f=c.findIndex(x=>x[1][r]===d[r]),h=c.findIndex(x=>x[1][a]===d[a]),g=(c[h][1][s]-c[f][1][s])/(c.length-1),E=c[f][1][s];return c.flatMap(([x,w],y)=>{let b={x:0,y:0};return y!==f&&y!==h&&(E+=g,b[n.axis]=E-w[s]),x.map(I=>{let S=o.mutateElement(I,{x:I.x+b.x,y:I.y+b.y});return Te(I,o,{simultaneouslyUpdated:x}),S})})}let p=d[r];return c.flatMap(([f,h])=>{let g={x:0,y:0};return g[n.axis]=p-h[r],p+=m,p+=h[l],f.map(E=>{let x=o.mutateElement(E,{x:E.x+g.x,y:E.y+g.y});return Te(E,o,{simultaneouslyUpdated:f}),x})})};P();import{TEXT_AUTOWRAP_THRESHOLD as lg,getGridPoint as dg,getFontString as cg,DRAGGING_THRESHOLD as ug}from"@orangecatai/common";var AI=(e,t,n,i,o,r)=>{if(t.length===1&&_(t[0])&&(t[0].startBinding||t[0].endBinding))return;let s=t.filter(m=>{if(_(m)&&m.startBinding&&m.endBinding){let p=t.find(h=>h.id===m.startBinding?.elementId),f=t.find(h=>h.id===m.endBinding?.elementId);return p&&f}return!0}),a=new Set(s),l=s.filter(m=>q(m)).map(m=>m.id);if(l.length>0)for(let m of i.getNonDeletedElements())m.frameId!==null&&l.includes(m.frameId)&&a.add(m);let d=[];for(let m of a){let p=e.originalElements.get(m.id);if(!p)return;d.push(p)}let c=mg(Oe(d),n,o,r),u=new Set(Array.from(a,m=>m.id));a.forEach(m=>{let p=!H(m),f=p||(m.startBinding?u.has(m.startBinding.elementId):!1),h=p||(m.endBinding?u.has(m.endBinding.elementId):!1);if(H(m)){if(a.size>1||Math.max(Math.abs(c.x),Math.abs(c.y))>ug||!m.startBinding&&!m.endBinding){Os(e,m,i,c);let g=m.startBinding&&!f,E=m.endBinding&&!h;(g||E)&&(g&&ve(m,"start",i),E&&ve(m,"end",i))}}else{Os(e,m,i,c);let g=$(m,i.getNonDeletedElementsMap());g&&Os(e,g,i,c),Te(m,i,{simultaneouslyUpdated:Array.from(a)})}})},mg=(e,t,n,i)=>{let[o,r]=e,s=o+t.x+n.x,a=r+t.y+n.y;if(n.x===0||n.y===0){let[l,d]=dg(o+t.x,r+t.y,i);n.x===0&&(s=l),n.y===0&&(a=d)}return{x:s-o,y:a-r}},Os=(e,t,n,i)=>{let o=e.originalElements.get(t.id)??t,r=o.x+i.x,s=o.y+i.y;n.mutateElement(t,{x:r,y:s})},MI=(e,t,n)=>{let[i,o]=Oe(e);return[t-i,n-o]},vI=({newElement:e,elementType:t,originX:n,originY:i,x:o,y:r,width:s,height:a,shouldMaintainAspectRatio:l,shouldResizeFromCenter:d,zoom:c,scene:u,widthAspectRatio:m=null,originOffset:p=null,informMutation:f=!0})=>{l&&e.type!=="selection"&&(m?a=s/m:(Math.abs(r-i)>Math.abs(o-n)?{width:s,height:a}=Ps(t,a,o<n?-s:s):{width:s,height:a}=Ps(t,s,r<i?-a:a),a<0&&(a=-a)));let h=o<n?n-s:n,g=r<i?i-a:i;d&&(s+=s,a+=a,h=n-s/2,g=i-a/2);let E=null;if(J(e)){a=e.height;let x=co(cg({fontSize:e.fontSize,fontFamily:e.fontFamily}),e.lineHeight);s=Math.max(s,x),Math.abs(o-n)>lg/c&&(E={autoResize:!1}),g=i,d&&(h=n-s/2)}if(s!==0&&a!==0){let x=null;xe(e)&&(x={initialWidth:s,initialHeight:a}),u.mutateElement(e,{x:h+(p?.x??0),y:g+(p?.y??0),width:s,height:a,...E,...x},{informMutation:f,isDragging:!1})}};P();import{ELEMENT_LINK_KEY as Vo,normalizeLink as gc}from"@orangecatai/common";var CI=(e,t)=>{let n=window.location.href;try{let i=new URL(n);return i.searchParams.set(Vo,e),gc(i.toString())}catch(i){console.error(i)}return gc(n)},GI=(e,t)=>{if(e.length>0&&pg(e)){if(e.length===1)return{id:e[0].id,type:"element"};if(e.length>1){let n=Object.keys(t.selectedGroupIds)[0];return n?{id:n,type:"group"}:{id:e[0].groupIds[0],type:"group"}}}return null},pg=e=>!!(e.length===1||e.length>1&&ad(e)),OI=e=>{try{let t=new URL(e);return t.searchParams.has(Vo)&&t.host===window.location.host}catch{return!1}},kI=e=>{try{let{searchParams:t}=new URL(e);if(t.has(Vo))return t.get(Vo)}catch{}return null};P();import{FONT_FAMILY as Ag,VERTICAL_ALIGN as Mg,escapeDoubleQuotes as ks,getFontString as vg}from"@orangecatai/common";P();import{DEFAULT_ELEMENT_PROPS as Pn,DEFAULT_FONT_FAMILY as fg,DEFAULT_FONT_SIZE as hg,DEFAULT_TEXT_ALIGN as gg,DEFAULT_VERTICAL_ALIGN as Eg,VERTICAL_ALIGN as xg,randomInteger as wg,randomId as bg,getFontString as Zo,getUpdatedTimestamp as yg,getLineHeight as Pg}from"@orangecatai/common";var ct=(e,{x:t,y:n,strokeColor:i=Pn.strokeColor,backgroundColor:o=Pn.backgroundColor,fillStyle:r=Pn.fillStyle,strokeWidth:s=Pn.strokeWidth,strokeStyle:a=Pn.strokeStyle,roughness:l=Pn.roughness,opacity:d=Pn.opacity,width:c=0,height:u=0,angle:m=0,groupIds:p=[],frameId:f=null,index:h=null,roundness:g=null,boundElements:E=null,link:x=null,locked:w=Pn.locked,...y})=>((t<-1e6||t>1e6||n<-1e6||n>1e6||c<-1e6||c>1e6||u<-1e6||u>1e6)&&console.error("New element size or position is too large",{x:t,y:n,width:c,height:u,points:y.points}),{id:y.id||bg(),type:e,x:t,y:n,width:c,height:u,angle:m,strokeColor:i,backgroundColor:o,fillStyle:r,strokeWidth:s,strokeStyle:a,roughness:l,opacity:d,groupIds:p,frameId:f,index:h,roundness:g,seed:y.seed??wg(),version:y.version||1,versionNonce:y.versionNonce??0,isDeleted:!1,boundElements:E,updated:yg(),link:x,locked:w,customData:y.customData}),Fn=e=>ct(e.type,e),jI=e=>ct("embeddable",e),XI=e=>({...ct("iframe",e)}),Ec=e=>Be({...ct("frame",e),type:"frame",name:e?.name||null},{}),xc=e=>Be({...ct("magicframe",e),type:"magicframe",name:e?.name||null},{}),wc=(e,t)=>({x:e.textAlign==="center"?t.width/2:e.textAlign==="right"?t.width:0,y:e.verticalAlign==="middle"?t.height/2:0}),Rn=e=>{let t=e.fontFamily||fg,n=e.fontSize||hg,i=e.lineHeight||Pg(t),o=Ei(e.text),r=Xe(o,Zo({fontFamily:t,fontSize:n}),i),s=e.textAlign||gg,a=e.verticalAlign||Eg,l=wc({textAlign:s,verticalAlign:a},r),d={...ct("text",e),text:o,fontSize:n,fontFamily:t,textAlign:s,verticalAlign:a,x:e.x-l.x,y:e.y-l.y,width:r.width,height:r.height,containerId:e.containerId||null,originalText:e.originalText??o,autoResize:e.autoResize??!0,lineHeight:i};return Be(d,{})},Ig=(e,t,n)=>{let{width:i,height:o}=Xe(n,Zo(e),e.lineHeight);e.autoResize||(i=e.width);let{textAlign:r,verticalAlign:s}=e,a,l;if(r==="center"&&s===xg.MIDDLE&&!e.containerId&&e.autoResize){let d=Xe(e.text,Zo(e),e.lineHeight),c=wc(e,{width:i-d.width,height:o-d.height});a=e.x-c.x,l=e.y-c.y}else{let[d,c,u,m]=j(e,t),[p,f,h,g]=Qt(e,i,o,!1),E=(d-p)/2,x=(c-f)/2,w=(u-h)/2,y=(m-g)/2;[a,l]=Sg({s:!0,e:r==="center"||r==="left",w:r==="center"||r==="right"},e.x,e.y,e.angle,E,x,w,y)}return{width:i,height:o,x:Number.isFinite(a)?a:e.x,y:Number.isFinite(l)?l:e.y}},Sg=(e,t,n,i,o,r,s,a)=>{let l=Math.cos(i),d=Math.sin(i);return e.e&&e.w?t+=o+s:e.e?(t+=o*(1+l),n+=o*d,t+=s*(1-l),n+=s*-d):e.w&&(t+=o*(1-l),n+=o*-d,t+=s*(1+l),n+=s*d),e.n&&e.s?n+=r+a:e.n?(t+=r*d,n+=r*(1-l),t+=a*-d,n+=a*(1+l)):e.s&&(t+=r*-d,n+=r*(1+l),t+=a*d,n+=a*(1-l)),[t,n]},$I=(e,t,n,i=e.text)=>{if(e.isDeleted)return;(t||!e.autoResize)&&(i=kt(i,Zo(e),t?at(t,e):e.width));let o=Ig(e,n,i);return{text:i,...o}},VI=e=>({...ct(e.type,e),points:e.points||[],pressures:e.pressures||[],simulatePressure:e.simulatePressure}),bc=e=>{let t={...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:null,endArrowhead:null};return Bt(t)?{...t,polygon:e.polygon??!1}:t},qo=e=>e.elbowed?{...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:e.startArrowhead||null,endArrowhead:e.endArrowhead||null,elbowed:!0,fixedSegments:e.fixedSegments||[],startIsSpecial:!1,endIsSpecial:!1}:{...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:e.startArrowhead||null,endArrowhead:e.endArrowhead||null,elbowed:!1},yc=e=>({...ct("image",e),strokeColor:"transparent",status:e.status??"pending",fileId:e.fileId??null,scale:e.scale??[1,1],crop:e.crop??null});var ut=new Map,Tg=/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)/,Dg=/^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/,Bg=/^https:\/\/(?:www\.)?figma\.com/,Pc=/^https:\/\/gist\.github\.com\/([\w_-]+)\/([\w_-]+)/,Lg=/^<script[\s\S]*?\ssrc=["'](https:\/\/gist\.github\.com\/.*?)\.js["']/i,Cg=/^(?:https?:\/\/)?forms\.microsoft\.com\//,Ic=/(?:https?:\/\/)?(?:(?:w){3}\.)?(?:twitter|x)\.com\/[^/]+\/status\/(\d+)/,Gg=/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:twitter|x)\.com\/[^"']*)/i,Og=/^https:\/\/(?:www\.)?val\.town\/(v|embed)\/[a-zA-Z_$][0-9a-zA-Z_$]+\.[a-zA-Z_$][0-9a-zA-Z_$]+/,kg=/^<(?:iframe|blockquote)[\s\S]*?\s(?:src|href)=["']([^"']*)["'][\s\S]*?>$/i,Sc=/giphy.com\/(?:clips|embed|gifs)\/[a-zA-Z0-9]*?-?([a-zA-Z0-9]+)(?:[^a-zA-Z0-9]|$)/,Ac=/^(?:http(?:s)?:\/\/)?(?:www\.)?reddit\.com\/r\/([a-zA-Z0-9_]+)\/comments\/([a-zA-Z0-9_]+)\/([a-zA-Z0-9_]+)\/?(?:\?[^#\s]*)?(?:#[^\s]*)?$/,Fg=/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:www\.)?reddit\.com\/[^"']*)/i,vc=e=>{let t;try{let s=new URL(e.startsWith("http")?e:`https://${e}`);t=s.searchParams.get("t")||s.searchParams.get("start")}catch{t=e.match(/[?&#](?:t|start)=([^&#\s]+)/)?.[1]}if(!t)return 0;if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(!n)return 0;let[,i="0",o="0",r="0"]=n;return parseInt(i)*3600+parseInt(o)*60+parseInt(r)},Rg=e=>{try{let t=new URL(e.startsWith("http")?e:`https://${e}`);if(t.hostname.replace(/^www\./,"")!=="drive.google.com")return null;let i=null,o=t.pathname.match(/^\/file\/d\/([^/]+)(?:\/|$)/);if(o?.[1]?i=o[1]:(t.pathname==="/open"||t.pathname==="/uc")&&(i=t.searchParams.get("id")),!i||!/^[a-zA-Z0-9_-]+$/.test(i))return null;let r=t.searchParams.get("resourcekey"),s=vc(t.toString());return{fileId:i,resourceKey:r&&/^[a-zA-Z0-9_-]+$/.test(r)?r:void 0,timestamp:s>0?s:void 0}}catch{return null}},Rs=new Set(["youtube.com","youtu.be","vimeo.com","player.vimeo.com","drive.google.com","figma.com","link.excalidraw.com","gist.github.com","twitter.com","x.com","*.simplepdf.eu","stackblitz.com","val.town","giphy.com","reddit.com","forms.microsoft.com"]),Mc=new Set(["youtube.com","youtu.be","vimeo.com","player.vimeo.com","drive.google.com","figma.com","twitter.com","x.com","*.simplepdf.eu","stackblitz.com","reddit.com","forms.microsoft.com"]),Fs=e=>`<html><body>${e}</body></html>`,tS=e=>{if(!e)return null;if(ut.has(e))return ut.get(e);let t=e,n=Mc.has(Ns(e,Mc)||""),i="generic",o={w:560,h:840},r=e.match(Tg);if(r?.[2]){let c=vc(t),u=c>0?`&start=${c}`:"",m=e.includes("shorts");switch(i="video",r[1]){case"embed/":case"watch?v=":case"shorts/":e=`https://www.youtube.com/embed/${r[2]}?enablejsapi=1${u}`;break;case"playlist?list=":case"embed/videoseries?list=":e=`https://www.youtube.com/embed/videoseries?list=${r[2]}&enablejsapi=1${u}`;break;default:e=`https://www.youtube.com/embed/${r[2]}?enablejsapi=1${u}`;break}return o=m?{w:315,h:560}:{w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}}let s=e.match(Dg);if(s?.[1]){let c=s?.[1],u=/^\d+$/.test(c)?void 0:new URIError("Invalid embed link format");return i="video",e=`https://player.vimeo.com/video/${c}?api=1`,o={w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,error:u,sandbox:{allowSameOrigin:n}}}let a=Rg(e);if(a){i="video";let c=new URLSearchParams;a.resourceKey&&c.set("resourcekey",a.resourceKey),a.timestamp&&c.set("t",`${a.timestamp}`);let u=c.toString();return e=`https://drive.google.com/file/d/${a.fileId}/preview${u?`?${u}`:""}`,o={w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}}if(e.match(Bg))return i="generic",e=`https://www.figma.com/embed?embed_host=share&url=${encodeURIComponent(e)}`,o={w:550,h:550},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}};let d=e.match(Og);if(d)return e=d[1]==="embed"?d[0]:d[0].replace("/v","/embed"),ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}};if(Cg.test(e)&&!e.includes("embed=true")&&(e+=e.includes("?")?"&embed=true":"?embed=true"),Ic.test(e)){let c=e.match(Ic)[1],u=ks(`https://twitter.com/x/status/${c}`),m={type:"document",srcdoc:p=>Fs(`<blockquote class="twitter-tweet" data-dnt="true" data-theme="${p}"><a href="${u}"></a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"><\/script>`),intrinsicSize:{w:480,h:480},sandbox:{allowSameOrigin:n}};return ut.set(t,m),m}if(Ac.test(e)){let[,c,u,m]=e.match(Ac),p=ks(`https://reddit.com/r/${c}/comments/${u}/${m}`),f={type:"document",srcdoc:h=>Fs(`<blockquote class="reddit-embed-bq" data-embed-theme="${h}"><a href="${p}"></a><br></blockquote><script async="" src="https://embed.reddit.com/widgets.js" charset="UTF-8"><\/script>`),intrinsicSize:{w:480,h:480},sandbox:{allowSameOrigin:n}};return ut.set(t,f),f}if(Pc.test(e)){let[,c,u]=e.match(Pc),m=ks(`https://gist.github.com/${c}/${u}`),p={type:"document",srcdoc:()=>Fs(`
20
+ `),l.stack,e.map(c=>s(c)),...d),t)throw l}},Jd=e=>e.sort((t,n)=>Qd(t)&&Qd(n)?t.index<n.index?-1:t.index>n.index?1:t.id<n.id?-1:1:1),ki=(e,t)=>{try{let n=Xo(e),i=Ch(e,t),o=Cs(e,i),r=e.map(s=>{let a=o.get(s);return a?{...s,index:a.index}:s});Lh(r,{includeBoundTextValidation:!1,shouldThrow:!0,ignoreLogs:!0});for(let[s,{index:a}]of o)be(s,n,{index:a})}catch{Ls(e)}return e},Ls=e=>{let t=Xo(e),n=ec(e),i=Cs(e,n);for(let[o,{index:r}]of i)be(o,t,{index:r});return e},Yd=e=>{let t=Xo(e),n=ec(e),i=Cs(e,n);for(let[o,{index:r}]of i)t.set(o.id,Be(o,{index:r}));return t},Ch=(e,t)=>{let n=[],i=0;for(;i<e.length;)if(t.has(e[i].id)){let o=[i-1,i];for(;++i<e.length&&t.has(e[i].id);)o.push(i);o.push(i),n.push(o)}else i++;return n},ec=e=>{let t=[],n,i,o=-1,r=0,s=d=>{let c=e[o]?e[o].index:void 0,u=e[d-1]?.index;return!c&&u||c&&u&&u>c?[u,d-1]:[c,o]},a=d=>{let c=e[r]?e[r].index:void 0;if(c&&d<r)return[c,r];let u=r;for(;++u<e.length;){let m=e[u]?.index;if(!c&&m||c&&m&&m>c)return[m,u]}return[void 0,u]},l=0;for(;l<e.length;){let d=e[l].index;if([n,o]=s(l),[i,r]=a(l),Bs(d,n,i))l++;else{let c=[o,l];for(;++l<e.length;){let u=e[l].index,[m,p]=s(l),[f,h]=a(l);if(Bs(u,m,f))break;[n,o]=[m,p],[i,r]=[f,h],c.push(l)}c.push(r),t.push(c)}}return t},Bs=(e,t,n)=>e?t&&n?t<e&&e<n:!t&&n?e<n:t&&!n?t<e:!!e:!1,Cs=(e,t)=>{let n=new Map;for(let i of t){let o=i.shift(),r=i.pop(),s=jo(e[o]?.index,e[r]?.index,i.length);for(let a=0;a<i.length;a++){let l=e[i[a]];n.set(l,{index:s[a]})}}return n},Qd=e=>!!e.index;P();var mc=uu(rc(),1);import{randomInteger as qh,arrayToMap as sc,toBrandedType as ac,isDevEnv as lc,isTestEnv as dc,toArray as Kh}from"@orangecatai/common";import{isNonDeletedElement as Qh}from"@orangecatai/element";import{isFrameLikeElement as Jh}from"@orangecatai/element";import{getElementsInGroup as eg}from"@orangecatai/element";import{syncInvalidIndices as tg,syncMovedIndices as cc,validateFractionalIndices as ng}from"@orangecatai/element";import{getSelectedElements as ig}from"@orangecatai/element";import{mutateElement as og}from"@orangecatai/element";var uc=e=>{let t=new Map,n=[];for(let i of e)i.isDeleted||(n.push(i),t.set(i.id,i));return{elementsMap:t,elements:n}},rg=(0,mc.default)(e=>{(lc()||dc()||window?.DEBUG_FRACTIONAL_INDICES)&&ng(e,{shouldThrow:lc()||dc(),includeBoundTextValidation:!0})},1e3*60,{leading:!0,trailing:!1}),sg=e=>{let t=["includeBoundTextElement","includeElementsInFrames"],n="";for(let i of t)n+=`${i}:${e[i]?"1":"0"}`;return n},Jn=class{callbacks=new Set;nonDeletedElements=[];nonDeletedElementsMap=ac(new Map);elements=[];nonDeletedFramesLikes=[];frames=[];elementsMap=ac(new Map);selectedElementsCache={selectedElementIds:null,elements:null,cache:new Map};sceneNonce;getSceneNonce(){return this.sceneNonce}getNonDeletedElementsMap(){return this.nonDeletedElementsMap}getElementsIncludingDeleted(){return this.elements}getElementsMapIncludingDeleted(){return this.elementsMap}getNonDeletedElements(){return this.nonDeletedElements}getFramesIncludingDeleted(){return this.frames}constructor(t=null,n){t&&this.replaceAllElements(t,n)}getSelectedElements(t){let n=sg(t),i=t?.elements||this.nonDeletedElements;if(this.selectedElementsCache.elements===i&&this.selectedElementsCache.selectedElementIds===t.selectedElementIds){let r=this.selectedElementsCache.cache.get(n);if(r)return r}else t?.elements==null&&this.selectedElementsCache.cache.clear();let o=ig(i,{selectedElementIds:t.selectedElementIds},t);return t?.elements==null&&(this.selectedElementsCache.selectedElementIds=t.selectedElementIds,this.selectedElementsCache.elements=this.nonDeletedElements,this.selectedElementsCache.cache.set(n,o)),o}getNonDeletedFramesLikes(){return this.nonDeletedFramesLikes}getElement(t){return this.elementsMap.get(t)||null}getNonDeletedElement(t){let n=this.getElement(t);return n&&Qh(n)?n:null}mapElements(t){let n=!1,i=this.elements.map(o=>{let r=t(o);return r!==o&&(n=!0),r});return n&&this.replaceAllElements(i),n}replaceAllElements(t,n){let i=Kh(t),o=[];n?.skipValidation||rg(i),this.elements=tg(i),this.elementsMap.clear(),this.elements.forEach(s=>{Jh(s)&&o.push(s),this.elementsMap.set(s.id,s)});let r=uc(this.elements);this.nonDeletedElements=r.elements,this.nonDeletedElementsMap=r.elementsMap,this.frames=o,this.nonDeletedFramesLikes=uc(this.frames).elements,this.triggerUpdate()}triggerUpdate(){this.sceneNonce=qh();for(let t of Array.from(this.callbacks))t()}onUpdate(t){if(this.callbacks.has(t))throw new Error;return this.callbacks.add(t),()=>{if(!this.callbacks.has(t))throw new Error;this.callbacks.delete(t)}}destroy(){this.elements=[],this.nonDeletedElements=[],this.nonDeletedFramesLikes=[],this.frames=[],this.elementsMap.clear(),this.selectedElementsCache.selectedElementIds=null,this.selectedElementsCache.elements=null,this.selectedElementsCache.cache.clear(),this.callbacks.clear()}insertElementAtIndex(t,n){if(!Number.isFinite(n)||n<0)throw new Error("insertElementAtIndex can only be called with index >= 0");let i=[...this.elements.slice(0,n),t,...this.elements.slice(n)];cc(i,sc([t])),this.replaceAllElements(i)}insertElementsAtIndex(t,n){if(!t.length)return;if(!Number.isFinite(n)||n<0)throw new Error("insertElementAtIndex can only be called with index >= 0");let i=[...this.elements.slice(0,n),...t,...this.elements.slice(n)];cc(i,sc(t)),this.replaceAllElements(i)}insertElement=t=>{let n;if(t.frameId){let i=this.getElementIndex(t.frameId);if(i===-1)n=this.elements.length;else{let o=i;for(let r=i+1;r<this.elements.length&&this.elements[r].frameId===t.frameId;r++)o=r;n=o+1}}else n=this.elements.length;this.insertElementAtIndex(t,n)};insertElements=t=>{if(!t.length)return;let n,i=t[0];if(i?.frameId){let o=this.getElementIndex(i.frameId);if(o===-1)n=this.elements.length;else{let r=o;for(let s=o+1;s<this.elements.length&&this.elements[s].frameId===i.frameId;s++)r=s;n=r+1}}else n=this.elements.length;this.insertElementsAtIndex(t,n)};getElementIndex(t){return this.elements.findIndex(n=>n.id===t)}getContainerElement=t=>t&&t.containerId&&this.getElement(t.containerId)||null;getElementsFromId=t=>{let n=this.getNonDeletedElementsMap(),i=n.get(t);return i?[i]:eg(n,t)};mutateElement(t,n,i={informMutation:!0,isDragging:!1}){let o=this.getNonDeletedElementsMap(),{version:r}=t,{version:s}=og(t,o,n,i);return this.elementsMap.has(t.id)&&r!==s&&i.informMutation&&this.triggerUpdate(),t}};var U=class e{constructor(t,n){this.deleted=t;this.inserted=n}static create(t,n,i,o){let r=i&&o!=="inserted"?i(t,"deleted"):t,s=i&&o!=="deleted"?i(n,"inserted"):n;return new e(r,s)}static calculate(t,n,i,o){if(t===n)return e.empty();let r={},s={};for(let d of this.getDifferences(t,n))r[d]=t[d],s[d]=n[d];let[a,l]=o?o(r,s):[r,s];return e.create(a,l,i)}static empty(){return new e({},{})}static isEmpty(t){return!Object.keys(t.deleted).length&&!Object.keys(t.inserted).length}static merge(t,n,i=e.empty()){return e.create({...t.deleted,...n.deleted,...i.deleted},{...t.inserted,...n.inserted,...i.inserted})}static mergeObjects(t,n,i={}){let o={...t};for(let r of Object.keys(i))delete o[r];return{...o,...n}}static mergeArrays(t,n,i,o){return Object.values(e.mergeObjects(Xt(t??[],o),Xt(n??[],o),Xt(i??[],o)))}static diffObjects(t,n,i,o){if(!t[i]&&!n[i])return;let r=t[i]!==null&&typeof t[i]=="object",s=n[i]!==null&&typeof n[i]=="object";if(r||s){let a=t[i]??{},l=n[i]??{},d=e.getLeftDifferences(a,l).reduce((u,m)=>(u[m]=o(a[m]),u),{}),c=e.getRightDifferences(a,l).reduce((u,m)=>(u[m]=o(l[m]),u),{});Object.keys(d).length||Object.keys(c).length?(Reflect.set(t,i,d),Reflect.set(n,i,c)):(Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i))}else t[i]===n[i]&&(Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i))}static diffArrays(t,n,i,o){if(!(!t[i]&&!n[i])&&(Array.isArray(t[i])||Array.isArray(n[i]))){let r=Array.isArray(t[i])?t[i]:[],s=Array.isArray(n[i])?n[i]:[],a=Xt(e.getLeftDifferences(Xt(r,o),Xt(s,o)),d=>d),l=Xt(e.getRightDifferences(Xt(r,o),Xt(s,o)),d=>d);if(Object.keys(a).length||Object.keys(l).length){let d=r.filter(u=>a[o?o(u):String(u)]),c=s.filter(u=>l[o?o(u):String(u)]);Reflect.set(t,i,d),Reflect.set(n,i,c)}else Reflect.deleteProperty(t,i),Reflect.deleteProperty(n,i)}}static isLeftDifferent(t,n,i=!1){return!!this.distinctKeysIterator("left",t,n,i).next().value}static isRightDifferent(t,n,i=!1){return!!this.distinctKeysIterator("right",t,n,i).next().value}static isInnerDifferent(t,n,i=!1){return!!!!this.distinctKeysIterator("inner",t,n,i).next().value}static isDifferent(t,n,i=!1){return!!!!this.distinctKeysIterator("full",t,n,i).next().value}static getLeftDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("left",t,n,i)).sort()}static getRightDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("right",t,n,i)).sort()}static getInnerDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("inner",t,n,i)).sort()}static getDifferences(t,n,i=!1){return Array.from(this.distinctKeysIterator("full",t,n,i)).sort()}static*distinctKeysIterator(t,n,i,o=!1){if(n===i)return;let r=[];t==="left"?r=Object.keys(n):t==="right"?r=Object.keys(i):t==="inner"?r=Object.keys(n).filter(s=>s in i):t==="full"?r=Array.from(new Set([...Object.keys(n),...Object.keys(i)])):fc(t,`Unknown distinctKeysIterator's join param "${t}"`,!0);for(let s of r){let a=n[s],l=i[s];if(a!==l){if(!o&&typeof a=="object"&&typeof l=="object"&&a!==null&&l!==null&&hc(a,l))continue;yield s}}}},En=class e{constructor(t){this.delta=t}static create(t){return new e(t)}static calculate(t,n){let i=U.calculate(t,n,e.orderAppStateKeys,e.postProcess);return new e(i)}static restore(t){let{delta:n}=t;return new e(n)}static empty(){return new e(U.create({},{}))}inverse(){let t=U.create(this.delta.inserted,this.delta.deleted);return new e(t)}squash(t){if(t.isEmpty())return this;let n=U.mergeObjects(this.delta.deleted.selectedElementIds??{},t.delta.deleted.selectedElementIds??{}),i=U.mergeObjects(this.delta.inserted.selectedElementIds??{},t.delta.inserted.selectedElementIds??{}),o=U.mergeObjects(this.delta.deleted.selectedGroupIds??{},t.delta.deleted.selectedGroupIds??{}),r=U.mergeObjects(this.delta.inserted.selectedGroupIds??{},t.delta.inserted.selectedGroupIds??{}),s=U.mergeObjects(this.delta.deleted.lockedMultiSelections??{},t.delta.deleted.lockedMultiSelections??{}),a=U.mergeObjects(this.delta.inserted.lockedMultiSelections??{},t.delta.inserted.lockedMultiSelections??{}),l={},d={};return(Object.keys(n).length||Object.keys(i).length)&&(d.selectedElementIds=n,l.selectedElementIds=i),(Object.keys(o).length||Object.keys(r).length)&&(d.selectedGroupIds=o,l.selectedGroupIds=r),(Object.keys(s).length||Object.keys(a).length)&&(d.lockedMultiSelections=s,l.lockedMultiSelections=a),this.delta=U.merge(this.delta,t.delta,U.create(d,l)),this}applyTo(t,n){try{let{selectedElementIds:i={},selectedGroupIds:o={},lockedMultiSelections:r={}}=this.delta.deleted,{selectedElementIds:s={},selectedGroupIds:a={},lockedMultiSelections:l={},selectedLinearElement:d,...c}=this.delta.inserted,u=U.mergeObjects(t.selectedElementIds,s,i),m=U.mergeObjects(t.selectedGroupIds,a,o),p=U.mergeObjects(t.lockedMultiSelections,l,r),f=d&&n.has(d.elementId)?new L(n.get(d.elementId),n,d.isEditing):null,h={...t,...c,selectedElementIds:u,selectedGroupIds:m,lockedMultiSelections:p,selectedLinearElement:typeof d<"u"?f:t.selectedLinearElement},g=this.filterInvisibleChanges(t,h,n);return[h,g]}catch(i){if(console.error("Couldn't apply appstate change",i),yn()||bn())throw i;return[t,!1]}}isEmpty(){return U.isEmpty(this.delta)}filterInvisibleChanges(t,n,i){let o=qn(t),r=qn(n),s=U.isRightDifferent(e.stripElementsProps(o),e.stripElementsProps(r)),a=U.isRightDifferent(e.stripStandaloneProps(o),e.stripStandaloneProps(r));if(!s&&!a)return!1;let l={value:s};if(a){let d=U.getRightDifferences(e.stripStandaloneProps(o),e.stripStandaloneProps(r)),c=new Set;(d.includes("editingGroupId")||d.includes("selectedGroupIds"))&&(c=sd(i));for(let u of d)switch(u){case"selectedElementIds":n[u]=e.filterSelectedElements(n[u],i,l);break;case"selectedGroupIds":n[u]=e.filterSelectedGroups(n[u],c,l);break;case"croppingElementId":{let x=n[u];if(!x)l.value=!0;else{let w=i.get(x);w&&!w.isDeleted?l.value=!0:n[u]=null}break}case"editingGroupId":let m=n[u];m?c.has(m)?l.value=!0:n[u]=null:l.value=!0;break;case"selectedLinearElement":let p=n[u];if(!p)l.value=!0;else{let x=i.get(p.elementId);x&&!x.isDeleted?l.value=!0:n[u]=null}break;case"lockedMultiSelections":let f=t[u]||{},h=n[u]||{};hc(f,h)||(l.value=!0);break;case"activeLockedId":let g=t[u]||null,E=n[u]||null;g!==E&&(l.value=!0);break;default:fc(u,`Unknown ObservedElementsAppState's key "${u}"`,!0)}}return l.value}static filterSelectedElements(t,n,i){let o=Object.keys(t);if(!o.length)return i.value=!0,t;let r={...t};for(let s of o){let a=n.get(s);a&&!a.isDeleted?i.value=!0:delete r[s]}return r}static filterSelectedGroups(t,n,i){if(!Object.keys(t).length)return i.value=!0,t;let r={...t};for(let s of Object.keys(r))n.has(s)?i.value=!0:delete r[s];return r}static stripElementsProps(t){let{editingGroupId:n,selectedGroupIds:i,selectedElementIds:o,selectedLinearElement:r,croppingElementId:s,lockedMultiSelections:a,activeLockedId:l,...d}=t;return d}static stripStandaloneProps(t){let{name:n,viewBackgroundColor:i,...o}=t;return o}static postProcess(t,n){try{U.diffObjects(t,n,"selectedElementIds",i=>!0),U.diffObjects(t,n,"selectedGroupIds",i=>i??!1),U.diffObjects(t,n,"lockedMultiSelections",i=>i??{})}catch(i){if(console.error("Couldn't postprocess appstate change deltas."),yn()||bn())throw i}finally{return[t,n]}}static orderAppStateKeys(t){let n={};for(let i of Object.keys(t).sort())n[i]=t[i];return n}},xn=class e{constructor(t,n,i){this.added=t;this.removed=n;this.updated=i}static create(t,n,i,o={shouldRedistribute:!1}){let r;if(o.shouldRedistribute){let s={},a={},l={},d=[...Object.entries(t),...Object.entries(n),...Object.entries(i)];for(let[c,u]of d)this.satisfiesAddition(u)?s[c]=u:this.satisfiesRemoval(u)?a[c]=u:l[c]=u;r=new e(s,a,l)}else r=new e(t,n,i);return(yn()||bn())&&(e.validate(r,"added",this.satisfiesAddition),e.validate(r,"removed",this.satisfiesRemoval),e.validate(r,"updated",this.satisfiesUpdate)),r}static restore(t){let{added:n,removed:i,updated:o}=t;return e.create(n,i,o)}static satisfiesAddition=({deleted:t,inserted:n})=>t.isDeleted===!0&&!n.isDeleted;static satisfiesRemoval=({deleted:t,inserted:n})=>!t.isDeleted&&n.isDeleted===!0;static satisfiesUpdate=({deleted:t,inserted:n})=>!!t.isDeleted==!!n.isDeleted;static satisfiesCommmonInvariants=({deleted:t,inserted:n})=>!!(Number.isInteger(t.version)&&Number.isInteger(n.version)&&t.version>=0&&n.version>=0&&t.version!==n.version);static satisfiesUniqueInvariants=(t,n)=>{let{added:i,removed:o,updated:r}=t;return[i[n],o[n],r[n]].filter(Boolean).length===1};static validate(t,n,i){for(let[o,r]of Object.entries(t[n]))if(!this.satisfiesCommmonInvariants(r)||!this.satisfiesUniqueInvariants(t,o)||!i(r))throw console.error(`Broken invariant for "${n}" delta, element "${o}", delta:`,r),new Error(`ElementsDelta invariant broken for element "${o}".`)}static calculate(t,n){if(t===n)return e.empty();let i={},o={},r={};for(let s of t.values())if(!n.get(s.id)){let l={...s},d={isDeleted:!0,version:s.version+1,versionNonce:pc()},c=U.create(l,d,e.stripIrrelevantProps);s.isDeleted?r[s.id]=c:o[s.id]=c}for(let s of n.values()){let a=t.get(s.id);if(!a){let l={isDeleted:!0,version:s.version-1,versionNonce:pc()},d={...s},c=U.create(l,d,e.stripIrrelevantProps);s.isDeleted?r[s.id]=c:i[s.id]=c;continue}if(a.versionNonce!==s.versionNonce){let l=U.calculate(a,s,e.stripIrrelevantProps,e.postProcess);if(typeof a.isDeleted=="boolean"&&typeof s.isDeleted=="boolean"&&a.isDeleted!==s.isDeleted){a.isDeleted&&!s.isDeleted?i[s.id]=l:o[s.id]=l;continue}r[s.id]=l}}return e.create(i,o,r)}static empty(){return e.create({},{},{})}inverse(){let t=r=>{let s={};for(let[a,{inserted:l,deleted:d}]of Object.entries(r))s[a]=U.create({...l},{...d});return s},n=t(this.added),i=t(this.removed),o=t(this.updated);return e.create(i,n,o)}isEmpty(){return Object.keys(this.added).length===0&&Object.keys(this.removed).length===0&&Object.keys(this.updated).length===0}applyLatestChanges(t,n,i){let o=(d,c)=>(u,m)=>{let p;switch(m){case"deleted":p=d;break;case"inserted":p=c;break}if(!p)return console.error("Element not found when trying to apply latest changes"),u;let f={};for(let h of Object.keys(u))switch(h){case"boundElements":f[h]=u[h];break;default:f[h]=p[h]}return f},r=d=>{let c={};for(let[u,m]of Object.entries(d)){let p=t.get(u),f=n.get(u),h=null;p||f?h=U.create(m.deleted,m.inserted,o(p,f),i):h=m,U.isInnerDifferent(h.deleted,h.inserted)&&(c[u]=h)}return c},s=r(this.added),a=r(this.removed),l=r(this.updated);return e.create(s,a,l,{shouldRedistribute:!0})}applyTo(t,n=wn.empty().elements,i){let o=new Map(t),r,s={containsVisibleDifference:!1,containsZindexDifference:!1,applyDirection:void 0};try{let a=e.createApplier(t,o,n,s,i),l=a(this.added),d=a(this.removed),c=a(this.updated),u=this.resolveConflicts(t,o,s.applyDirection);r=new Map([...l,...d,...c,...u])}catch(a){if(console.error("Couldn't apply elements delta",a),yn()||bn())throw a;return[t,!0]}try{o=e.reorderElements(o,r,s),e.redrawElements(o,r)}catch(a){if(console.error("Couldn't mutate elements after applying elements change",a),yn()||bn())throw a}finally{return[o,s.containsVisibleDifference]}}squash(t){if(t.isEmpty())return this;let{added:n,removed:i,updated:o}=t,r=(s,a)=>{let l=U.mergeArrays(s.deleted.boundElements??[],a.deleted.boundElements??[],void 0,c=>c.id)??[],d=U.mergeArrays(s.inserted.boundElements??[],a.inserted.boundElements??[],void 0,c=>c.id)??[];if(!(!l.length&&!d.length))return U.create({boundElements:l},{boundElements:d})};for(let[s,a]of Object.entries(n)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.added[s]=a;else{let d=r(l,a);delete this.removed[s],delete this.updated[s],this.added[s]=U.merge(l,a,d)}}for(let[s,a]of Object.entries(i)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.removed[s]=a;else{let d=r(l,a);delete this.added[s],delete this.updated[s],this.removed[s]=U.merge(l,a,d)}}for(let[s,a]of Object.entries(o)){let l=this.added[s]??this.removed[s]??this.updated[s];if(!l)this.updated[s]=a;else{let d=r(l,a),c=U.merge(l,a,d);l===this.added[s]?this.added[s]=c:l===this.removed[s]?this.removed[s]=c:this.updated[s]=c}}return(yn()||bn())&&(e.validate(this,"added",e.satisfiesAddition),e.validate(this,"removed",e.satisfiesRemoval),e.validate(this,"updated",e.satisfiesUpdate)),this}static createApplier=(t,n,i,o,r)=>s=>{let a=e.createGetter(n,i,o);return Object.entries(s).reduce((l,[d,c])=>{let u=a(d,c.inserted);if(u){let m=e.applyDelta(u,c,o,r);if(n.set(m.id,m),l.set(m.id,m),!o.applyDirection){let p=t.get(d);p&&(o.applyDirection=p.version>m.version?"backward":"forward")}}return l},new Map)};static createGetter=(t,n,i)=>(o,r)=>{let s=t.get(o);return s||(s=n.get(o),s?(i.containsZindexDifference=!0,(!r.isDeleted||r.isDeleted&&!s.isDeleted)&&(i.containsVisibleDifference=!0)):s=Be({id:o,version:1},{...r})),s};static applyDelta(t,n,i,o){let r={};for(let s of Object.keys(n.inserted)){if(s==="boundElements"||o?.excludedProperties?.has(s))continue;let a=n.inserted[s];Reflect.set(r,s,a)}if(n.deleted.boundElements?.length||n.inserted.boundElements?.length){let s=U.mergeArrays(t.boundElements,n.inserted.boundElements,n.deleted.boundElements,a=>a.id);Object.assign(r,{boundElements:s})}if(!i.containsVisibleDifference){let{index:s,...a}=r,l=e.checkForVisibleDifference(t,a);i.containsVisibleDifference=l}return i.containsZindexDifference||(i.containsZindexDifference=n.deleted.index!==n.inserted.index),Be(t,r,!0)}static checkForVisibleDifference(t,n){return t.isDeleted&&n.isDeleted!==!1?!1:t.isDeleted&&n.isDeleted===!1||t.isDeleted===!1&&n.isDeleted?!0:U.isRightDifferent(t,n)}resolveConflicts(t,n,i="forward"){let o=new Map,r=(a,l)=>{let d=n.get(a.id);if(!d)return;let c=t.get(a.id),u=i==="forward"?d.version+1:d.version-1,m=l,p;c===d?p=Be(d,{...m,version:u},!0):p=be(d,n,{...m,version:c?.version!==d.version?d.version:u}),o.set(p.id,p),n.set(p.id,p)};for(let a of Object.keys(this.removed))e.unbindAffected(t,n,a,r);for(let a of Object.keys(this.added))e.rebindAffected(t,n,a,r);for(let[a]of Array.from(Object.entries(this.updated)).filter(([l,d])=>Object.keys({...d.deleted,...d.inserted}).find(c=>Fl.has(c)))){let l=n.get(a);!l||l.isDeleted||e.rebindAffected(t,n,a,r)}let s=new Map(Array.from(t).filter(([a])=>o.has(a)));return this.squash(e.calculate(s,o)),o}static unbindAffected(t,n,i,o){let r=()=>t.get(i),s=()=>n.get(i);un.unbindAffected(n,r(),o),un.unbindAffected(n,s(),o),mn.unbindAffected(n,r(),o),mn.unbindAffected(n,s(),o)}static rebindAffected(t,n,i,o){let r=()=>t.get(i),s=()=>n.get(i);un.unbindAffected(n,r(),o),un.rebindAffected(n,s(),o),mn.unbindAffected(n,r(),(a,l)=>{J(a)&&o(a,l)}),mn.rebindAffected(n,s(),o)}static redrawElements(t,n){try{let i=new Jn(t,{skipValidation:!0});e.redrawTextBoundingBoxes(i,n),e.redrawBoundArrows(i,n)}catch(i){if(console.error("Couldn't redraw elements",i),yn()||bn())throw i}finally{return t}}static redrawTextBoundingBoxes(t,n){let i=t.getNonDeletedElementsMap(),o=new Map;for(let r of n.values()){if(ce(r)){let{containerId:s}=r,a=s?i.get(s):void 0;a&&o.set(a.id,{container:a,boundText:r})}if(ht(r)){let s=Ft(r),a=s?i.get(s):void 0;a&&o.set(r.id,{container:r,boundText:a})}}for(let{container:r,boundText:s}of o.values())r.isDeleted||s.isDeleted||fo(s,r,t)}static redrawBoundArrows(t,n){for(let i of n.values())!i.isDeleted&&de(i)&&Te(i,t,{changedElements:n})}static reorderElements(t,n,i){if(!i.containsZindexDifference)return t;let o=Array.from(t.values()),r=Jd([...o]),s=U.getRightDifferences(o,r,!0).reduce((a,l)=>{let d=o[Number(l)];return d&&n.has(d.id)&&a.set(d.id,d),a},new Map);return!i.containsVisibleDifference&&s.size&&(i.containsVisibleDifference=!0),ag(ki(r,s))}static postProcess(t,n){try{U.diffArrays(t,n,"boundElements",r=>r.id);let i=t.points??[],o=n.points??[];U.isDifferent(i,o)||(Reflect.deleteProperty(t,"points"),Reflect.deleteProperty(n,"points"))}catch(i){if(console.error("Couldn't postprocess elements delta."),yn()||bn())throw i}finally{return[t,n]}}static stripIrrelevantProps(t){let{id:n,updated:i,...o}=t;return o}};P();var hI=(e,t,n,i,o)=>{let[r,s,a,l]=n.axis==="x"?["minX","midX","maxX","width"]:["minY","midY","maxY","height"],d=Yt(e),c=ko(e,t,i).map(f=>[f,Yt(f)]).sort((f,h)=>f[1][s]-h[1][s]),u=0;for(let f of c)u+=f[1][l];let m=(d[l]-u)/(c.length-1);if(m<0){let f=c.findIndex(x=>x[1][r]===d[r]),h=c.findIndex(x=>x[1][a]===d[a]),g=(c[h][1][s]-c[f][1][s])/(c.length-1),E=c[f][1][s];return c.flatMap(([x,w],y)=>{let b={x:0,y:0};return y!==f&&y!==h&&(E+=g,b[n.axis]=E-w[s]),x.map(I=>{let S=o.mutateElement(I,{x:I.x+b.x,y:I.y+b.y});return Te(I,o,{simultaneouslyUpdated:x}),S})})}let p=d[r];return c.flatMap(([f,h])=>{let g={x:0,y:0};return g[n.axis]=p-h[r],p+=m,p+=h[l],f.map(E=>{let x=o.mutateElement(E,{x:E.x+g.x,y:E.y+g.y});return Te(E,o,{simultaneouslyUpdated:f}),x})})};P();import{TEXT_AUTOWRAP_THRESHOLD as lg,getGridPoint as dg,getFontString as cg,DRAGGING_THRESHOLD as ug}from"@orangecatai/common";var AI=(e,t,n,i,o,r)=>{if(t.length===1&&_(t[0])&&(t[0].startBinding||t[0].endBinding))return;let s=t.filter(m=>{if(_(m)&&m.startBinding&&m.endBinding){let p=t.find(h=>h.id===m.startBinding?.elementId),f=t.find(h=>h.id===m.endBinding?.elementId);return p&&f}return!0}),a=new Set(s),l=s.filter(m=>q(m)).map(m=>m.id);if(l.length>0)for(let m of i.getNonDeletedElements())m.frameId!==null&&l.includes(m.frameId)&&a.add(m);let d=[];for(let m of a){let p=e.originalElements.get(m.id);if(!p)return;d.push(p)}let c=mg(Oe(d),n,o,r),u=new Set(Array.from(a,m=>m.id));a.forEach(m=>{let p=!H(m),f=p||(m.startBinding?u.has(m.startBinding.elementId):!1),h=p||(m.endBinding?u.has(m.endBinding.elementId):!1);if(H(m)){if(a.size>1||Math.max(Math.abs(c.x),Math.abs(c.y))>ug||!m.startBinding&&!m.endBinding){Os(e,m,i,c);let g=m.startBinding&&!f,E=m.endBinding&&!h;(g||E)&&(g&&ve(m,"start",i),E&&ve(m,"end",i))}}else{Os(e,m,i,c);let g=$(m,i.getNonDeletedElementsMap());g&&Os(e,g,i,c),Te(m,i,{simultaneouslyUpdated:Array.from(a)})}})},mg=(e,t,n,i)=>{let[o,r]=e,s=o+t.x+n.x,a=r+t.y+n.y;if(n.x===0||n.y===0){let[l,d]=dg(o+t.x,r+t.y,i);n.x===0&&(s=l),n.y===0&&(a=d)}return{x:s-o,y:a-r}},Os=(e,t,n,i)=>{let o=e.originalElements.get(t.id)??t,r=o.x+i.x,s=o.y+i.y;n.mutateElement(t,{x:r,y:s})},MI=(e,t,n)=>{let[i,o]=Oe(e);return[t-i,n-o]},vI=({newElement:e,elementType:t,originX:n,originY:i,x:o,y:r,width:s,height:a,shouldMaintainAspectRatio:l,shouldResizeFromCenter:d,zoom:c,scene:u,widthAspectRatio:m=null,originOffset:p=null,informMutation:f=!0})=>{l&&e.type!=="selection"&&(m?a=s/m:(Math.abs(r-i)>Math.abs(o-n)?{width:s,height:a}=Ps(t,a,o<n?-s:s):{width:s,height:a}=Ps(t,s,r<i?-a:a),a<0&&(a=-a)));let h=o<n?n-s:n,g=r<i?i-a:i;d&&(s+=s,a+=a,h=n-s/2,g=i-a/2);let E=null;if(J(e)){a=e.height;let x=co(cg({fontSize:e.fontSize,fontFamily:e.fontFamily}),e.lineHeight);s=Math.max(s,x),Math.abs(o-n)>lg/c&&(E={autoResize:!1}),g=i,d&&(h=n-s/2)}if(s!==0&&a!==0){let x=null;xe(e)&&(x={initialWidth:s,initialHeight:a}),u.mutateElement(e,{x:h+(p?.x??0),y:g+(p?.y??0),width:s,height:a,...E,...x},{informMutation:f,isDragging:!1})}};P();import{ELEMENT_LINK_KEY as Vo,normalizeLink as gc}from"@orangecatai/common";var CI=(e,t)=>{let n=window.location.href;try{let i=new URL(n);return i.searchParams.set(Vo,e),gc(i.toString())}catch(i){console.error(i)}return gc(n)},GI=(e,t)=>{if(e.length>0&&pg(e)){if(e.length===1)return{id:e[0].id,type:"element"};if(e.length>1){let n=Object.keys(t.selectedGroupIds)[0];return n?{id:n,type:"group"}:{id:e[0].groupIds[0],type:"group"}}}return null},pg=e=>!!(e.length===1||e.length>1&&ad(e)),OI=e=>{try{let t=new URL(e);return t.searchParams.has(Vo)&&t.host===window.location.host}catch{return!1}},kI=e=>{try{let{searchParams:t}=new URL(e);if(t.has(Vo))return t.get(Vo)}catch{}return null};P();import{FONT_FAMILY as Ag,VERTICAL_ALIGN as Mg,escapeDoubleQuotes as ks,getFontString as vg}from"@orangecatai/common";P();import{DEFAULT_ELEMENT_PROPS as Pn,DEFAULT_FONT_FAMILY as fg,DEFAULT_FONT_SIZE as hg,DEFAULT_TEXT_ALIGN as gg,DEFAULT_VERTICAL_ALIGN as Eg,VERTICAL_ALIGN as xg,randomInteger as wg,randomId as bg,getFontString as Zo,getUpdatedTimestamp as yg,getLineHeight as Pg}from"@orangecatai/common";var ct=(e,{x:t,y:n,strokeColor:i=Pn.strokeColor,backgroundColor:o=Pn.backgroundColor,fillStyle:r=Pn.fillStyle,strokeWidth:s=Pn.strokeWidth,strokeStyle:a=Pn.strokeStyle,roughness:l=Pn.roughness,opacity:d=Pn.opacity,width:c=0,height:u=0,angle:m=0,groupIds:p=[],frameId:f=null,index:h=null,roundness:g=null,boundElements:E=null,link:x=null,locked:w=Pn.locked,...y})=>((t<-1e6||t>1e6||n<-1e6||n>1e6||c<-1e6||c>1e6||u<-1e6||u>1e6)&&console.error("New element size or position is too large",{x:t,y:n,width:c,height:u,points:y.points}),{id:y.id||bg(),type:e,x:t,y:n,width:c,height:u,angle:m,strokeColor:i,backgroundColor:o,fillStyle:r,strokeWidth:s,strokeStyle:a,roughness:l,opacity:d,groupIds:p,frameId:f,index:h,roundness:g,seed:y.seed??wg(),version:y.version||1,versionNonce:y.versionNonce??0,isDeleted:!1,boundElements:E,updated:yg(),link:x,locked:w,customData:y.customData}),Fn=e=>ct(e.type,e),jI=e=>ct("embeddable",e),XI=e=>({...ct("iframe",e)}),Ec=e=>Be({...ct("frame",e),type:"frame",name:e?.name||null},{}),xc=e=>Be({...ct("magicframe",e),type:"magicframe",name:e?.name||null},{}),wc=(e,t)=>({x:e.textAlign==="center"?t.width/2:e.textAlign==="right"?t.width:0,y:e.verticalAlign==="middle"?t.height/2:0}),Rn=e=>{let t=e.fontFamily||fg,n=e.fontSize||hg,i=e.lineHeight||Pg(t),o=Ei(e.text),r=Xe(o,Zo({fontFamily:t,fontSize:n}),i),s=e.textAlign||gg,a=e.verticalAlign||Eg,l=wc({textAlign:s,verticalAlign:a},r),d={...ct("text",e),text:o,fontSize:n,fontFamily:t,textAlign:s,verticalAlign:a,x:e.x-l.x,y:e.y-l.y,width:r.width,height:r.height,containerId:e.containerId||null,originalText:e.originalText??o,autoResize:e.autoResize??!0,lineHeight:i};return Be(d,{})},Ig=(e,t,n)=>{let{width:i,height:o}=Xe(n,Zo(e),e.lineHeight);e.autoResize||(i=e.width);let{textAlign:r,verticalAlign:s}=e,a,l;if(r==="center"&&s===xg.MIDDLE&&!e.containerId&&e.autoResize){let d=Xe(e.text,Zo(e),e.lineHeight),c=wc(e,{width:i-d.width,height:o-d.height});a=e.x-c.x,l=e.y-c.y}else{let[d,c,u,m]=j(e,t),[p,f,h,g]=Qt(e,i,o,!1),E=(d-p)/2,x=(c-f)/2,w=(u-h)/2,y=(m-g)/2;[a,l]=Sg({s:!0,e:r==="center"||r==="left",w:r==="center"||r==="right"},e.x,e.y,e.angle,E,x,w,y)}return{width:i,height:o,x:Number.isFinite(a)?a:e.x,y:Number.isFinite(l)?l:e.y}},Sg=(e,t,n,i,o,r,s,a)=>{let l=Math.cos(i),d=Math.sin(i);return e.e&&e.w?t+=o+s:e.e?(t+=o*(1+l),n+=o*d,t+=s*(1-l),n+=s*-d):e.w&&(t+=o*(1-l),n+=o*-d,t+=s*(1+l),n+=s*d),e.n&&e.s?n+=r+a:e.n?(t+=r*d,n+=r*(1-l),t+=a*-d,n+=a*(1+l)):e.s&&(t+=r*-d,n+=r*(1+l),t+=a*d,n+=a*(1-l)),[t,n]},$I=(e,t,n,i=e.text)=>{if(e.isDeleted)return;(t||!e.autoResize)&&(i=kt(i,Zo(e),t?at(t,e):e.width));let o=Ig(e,n,i);return{text:i,...o}},VI=e=>({...ct(e.type,e),points:e.points||[],pressures:e.pressures||[],simulatePressure:e.simulatePressure}),bc=e=>{let t={...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:null,endArrowhead:null};return Bt(t)?{...t,polygon:e.polygon??!1}:t},qo=e=>e.elbowed?{...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:e.startArrowhead||null,endArrowhead:e.endArrowhead||null,elbowed:!0,fixedSegments:e.fixedSegments||[],startIsSpecial:!1,endIsSpecial:!1}:{...ct(e.type,e),points:e.points||[],startBinding:null,endBinding:null,startArrowhead:e.startArrowhead||null,endArrowhead:e.endArrowhead||null,elbowed:!1},yc=e=>({...ct("image",e),strokeColor:"transparent",status:e.status??"pending",fileId:e.fileId??null,scale:e.scale??[1,1],crop:e.crop??null});var ut=new Map,Tg=/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)/,Dg=/^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/,Bg=/^https:\/\/(?:www\.)?figma\.com/,Pc=/^https:\/\/gist\.github\.com\/([\w_-]+)\/([\w_-]+)/,Lg=/^<script[\s\S]*?\ssrc=["'](https:\/\/gist\.github\.com\/.*?)\.js["']/i,Cg=/^(?:https?:\/\/)?forms\.microsoft\.com\//,Ic=/(?:https?:\/\/)?(?:(?:w){3}\.)?(?:twitter|x)\.com\/[^/]+\/status\/(\d+)/,Gg=/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:twitter|x)\.com\/[^"']*)/i,Og=/^https:\/\/(?:www\.)?val\.town\/(v|embed)\/[a-zA-Z_$][0-9a-zA-Z_$]+\.[a-zA-Z_$][0-9a-zA-Z_$]+/,kg=/^<(?:iframe|blockquote)[\s\S]*?\s(?:src|href)=["']([^"']*)["'][\s\S]*?>$/i,Sc=/giphy.com\/(?:clips|embed|gifs)\/[a-zA-Z0-9]*?-?([a-zA-Z0-9]+)(?:[^a-zA-Z0-9]|$)/,Ac=/^(?:http(?:s)?:\/\/)?(?:www\.)?reddit\.com\/r\/([a-zA-Z0-9_]+)\/comments\/([a-zA-Z0-9_]+)\/([a-zA-Z0-9_]+)\/?(?:\?[^#\s]*)?(?:#[^\s]*)?$/,Fg=/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:www\.)?reddit\.com\/[^"']*)/i,vc=e=>{let t;try{let s=new URL(e.startsWith("http")?e:`https://${e}`);t=s.searchParams.get("t")||s.searchParams.get("start")}catch{t=e.match(/[?&#](?:t|start)=([^&#\s]+)/)?.[1]}if(!t)return 0;if(/^\d+$/.test(t))return parseInt(t,10);let n=t.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);if(!n)return 0;let[,i="0",o="0",r="0"]=n;return parseInt(i)*3600+parseInt(o)*60+parseInt(r)},Rg=e=>{try{let t=new URL(e.startsWith("http")?e:`https://${e}`);if(t.hostname.replace(/^www\./,"")!=="drive.google.com")return null;let i=null,o=t.pathname.match(/^\/file\/d\/([^/]+)(?:\/|$)/);if(o?.[1]?i=o[1]:(t.pathname==="/open"||t.pathname==="/uc")&&(i=t.searchParams.get("id")),!i||!/^[a-zA-Z0-9_-]+$/.test(i))return null;let r=t.searchParams.get("resourcekey"),s=vc(t.toString());return{fileId:i,resourceKey:r&&/^[a-zA-Z0-9_-]+$/.test(r)?r:void 0,timestamp:s>0?s:void 0}}catch{return null}},Rs=new Set(["youtube.com","youtu.be","vimeo.com","player.vimeo.com","drive.google.com","figma.com","link.excalidraw.com","gist.github.com","twitter.com","x.com","*.simplepdf.eu","stackblitz.com","val.town","giphy.com","reddit.com","forms.microsoft.com"]),Mc=new Set(["youtube.com","youtu.be","vimeo.com","player.vimeo.com","drive.google.com","figma.com","twitter.com","x.com","*.simplepdf.eu","stackblitz.com","reddit.com","forms.microsoft.com"]),Fs=e=>`<html><body>${e}</body></html>`,tS=e=>{if(!e)return null;if(ut.has(e))return ut.get(e);let t=e,n=Mc.has(Ns(e,Mc)||""),i="generic",o={w:560,h:840},r=e.match(Tg);if(r?.[2]){let c=vc(t),u=c>0?`&start=${c}`:"",m=e.includes("shorts");switch(i="video",r[1]){case"embed/":case"watch?v=":case"shorts/":e=`https://www.youtube.com/embed/${r[2]}?enablejsapi=1${u}`;break;case"playlist?list=":case"embed/videoseries?list=":e=`https://www.youtube.com/embed/videoseries?list=${r[2]}&enablejsapi=1${u}`;break;default:e=`https://www.youtube.com/embed/${r[2]}?enablejsapi=1${u}`;break}return o=m?{w:315,h:560}:{w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}}let s=e.match(Dg);if(s?.[1]){let c=s?.[1],u=/^\d+$/.test(c)?void 0:new URIError("Invalid embed link format");return i="video",e=`https://player.vimeo.com/video/${c}?api=1`,o={w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,error:u,sandbox:{allowSameOrigin:n}}}let a=Rg(e);if(a){i="video";let c=new URLSearchParams;a.resourceKey&&c.set("resourcekey",a.resourceKey),a.timestamp&&c.set("t",`${a.timestamp}`);let u=c.toString();return e=`https://drive.google.com/file/d/${a.fileId}/preview${u?`?${u}`:""}`,o={w:560,h:315},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}}if(e.match(Bg))return i="generic",e=`https://www.figma.com/embed?embed_host=share&url=${encodeURIComponent(e)}`,o={w:550,h:550},ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}};let d=e.match(Og);if(d)return e=d[1]==="embed"?d[0]:d[0].replace("/v","/embed"),ut.set(t,{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}}),{link:e,intrinsicSize:o,type:i,sandbox:{allowSameOrigin:n}};if(Cg.test(e)&&!e.includes("embed=true")&&(e+=e.includes("?")?"&embed=true":"?embed=true"),Ic.test(e)){let c=e.match(Ic)[1],u=ks(`https://twitter.com/x/status/${c}`),m={type:"document",srcdoc:p=>Fs(`<blockquote class="twitter-tweet" data-dnt="true" data-theme="${p}"><a href="${u}"></a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"><\/script>`),intrinsicSize:{w:480,h:480},sandbox:{allowSameOrigin:n}};return ut.set(t,m),m}if(Ac.test(e)){let[,c,u,m]=e.match(Ac),p=ks(`https://reddit.com/r/${c}/comments/${u}/${m}`),f={type:"document",srcdoc:h=>Fs(`<blockquote class="reddit-embed-bq" data-embed-theme="${h}"><a href="${p}"></a><br></blockquote><script async="" src="https://embed.reddit.com/widgets.js" charset="UTF-8"><\/script>`),intrinsicSize:{w:480,h:480},sandbox:{allowSameOrigin:n}};return ut.set(t,f),f}if(Pc.test(e)){let[,c,u]=e.match(Pc),m=ks(`https://gist.github.com/${c}/${u}`),p={type:"document",srcdoc:()=>Fs(`
21
21
  <script src="${m}.js"><\/script>
22
22
  <style type="text/css">
23
23
  * { margin: 0px; }
@@ -53,6 +53,7 @@ export declare const KEYS: {
53
53
  readonly G: "g";
54
54
  readonly H: "h";
55
55
  readonly I: "i";
56
+ readonly J: "j";
56
57
  readonly L: "l";
57
58
  readonly O: "o";
58
59
  readonly P: "p";
@@ -108,6 +109,7 @@ export declare const KeyCodeMap: Map<ValueOf<{
108
109
  readonly G: "g";
109
110
  readonly H: "h";
110
111
  readonly I: "i";
112
+ readonly J: "j";
111
113
  readonly L: "l";
112
114
  readonly O: "o";
113
115
  readonly P: "p";
@@ -1,6 +1,6 @@
1
1
  import { type GlobalPoint } from "@orangecatai/math";
2
- import type { AppState, NullableGridSize } from "@orangecatai/adgen-canvas/types";
3
2
  import { LinearElementEditor } from "../linearElementEditor";
3
+ import type { AppState, NullableGridSize } from "@orangecatai/adgen-canvas/types";
4
4
  import type { ElementsMap, ExcalidrawArrowElement, ExcalidrawBindableElement, NonDeletedSceneElementsMap } from "../types";
5
5
  import type { Scene } from "../Scene";
6
6
  export declare const isFocusPointVisible: (focusPoint: GlobalPoint, arrow: ExcalidrawArrowElement, bindableElement: ExcalidrawBindableElement, elementsMap: ElementsMap, appState: {
@@ -1,8 +1,8 @@
1
1
  import { type GlobalPoint } from "@orangecatai/math";
2
- import type { LineSegment, LocalPoint } from "@orangecatai/math";
3
- import type { AppState } from "@orangecatai/adgen-canvas/types";
4
- import type { Bounds } from "@orangecatai/common";
5
2
  import { type Heading } from "./heading";
3
+ import type { Bounds } from "@orangecatai/common";
4
+ import type { AppState } from "@orangecatai/adgen-canvas/types";
5
+ import type { LineSegment, LocalPoint } from "@orangecatai/math";
6
6
  import type { Scene } from "./Scene";
7
7
  import type { ElementUpdate } from "./mutateElement";
8
8
  import type { BindMode, ElementsMap, ExcalidrawArrowElement, ExcalidrawBindableElement, ExcalidrawElbowArrowElement, ExcalidrawElement, FixedPoint, FixedPointBinding, NonDeleted, NonDeletedExcalidrawElement, NonDeletedSceneElementsMap, Ordered, PointsPositionUpdates } from "./types";
@@ -1,6 +1,6 @@
1
1
  import { type Bounds } from "@orangecatai/common";
2
- import type { Degrees, GlobalPoint, LineSegment, LocalPoint } from "@orangecatai/math";
3
2
  import type { AppState } from "@orangecatai/adgen-canvas/types";
3
+ import type { Degrees, GlobalPoint, LineSegment, LocalPoint } from "@orangecatai/math";
4
4
  import type { Drawable, Op } from "roughjs/bin/core";
5
5
  import type { Arrowhead, ElementsMap, ElementsMapOrArray, ExcalidrawElement, ExcalidrawFreeDrawElement, ExcalidrawLinearElement, NonDeleted } from "./types";
6
6
  export type RectangleBox = {
@@ -1,5 +1,5 @@
1
- import type { GlobalPoint, LineSegment } from "@orangecatai/math";
2
1
  import type { FrameNameBounds } from "@orangecatai/adgen-canvas/types";
2
+ import type { GlobalPoint, LineSegment } from "@orangecatai/math";
3
3
  import type { ElementsMap, ExcalidrawArrowElement, ExcalidrawBindableElement, ExcalidrawElement, NonDeleted, NonDeletedExcalidrawElement, NonDeletedSceneElementsMap, Ordered } from "./types";
4
4
  export declare const shouldTestInside: (element: ExcalidrawElement) => boolean;
5
5
  export type HitTestArgs = {
@@ -1,7 +1,7 @@
1
- import type { ExcalidrawElement, Ordered, OrderedExcalidrawElement, SceneElementsMap } from "@orangecatai/element/types";
1
+ import { StoreSnapshot } from "./store";
2
2
  import type { DTO, ValueOf } from "@orangecatai/common/utility-types";
3
3
  import type { AppState, ObservedAppState } from "@orangecatai/adgen-canvas/types";
4
- import { StoreSnapshot } from "./store";
4
+ import type { ExcalidrawElement, Ordered, OrderedExcalidrawElement, SceneElementsMap } from "@orangecatai/element/types";
5
5
  /**
6
6
  * Represents the difference between two objects of the same type.
7
7
  *
@@ -1,5 +1,5 @@
1
- import type { AppState, NormalizedZoomValue, NullableGridSize, PointerDownState } from "@orangecatai/adgen-canvas/types";
2
1
  import type { NonDeletedExcalidrawElement } from "@orangecatai/element/types";
2
+ import type { AppState, NormalizedZoomValue, NullableGridSize, PointerDownState } from "@orangecatai/adgen-canvas/types";
3
3
  import type { Scene } from "./Scene";
4
4
  export declare const dragSelectedElements: (pointerDownState: PointerDownState, _selectedElements: NonDeletedExcalidrawElement[], offset: {
5
5
  x: number;
@@ -1,5 +1,5 @@
1
- import type { Mutable } from "@orangecatai/common/utility-types";
2
1
  import type { AppState } from "@orangecatai/adgen-canvas/types";
2
+ import type { Mutable } from "@orangecatai/common/utility-types";
3
3
  import type { ExcalidrawElement, GroupId } from "./types";
4
4
  /**
5
5
  * Duplicate an element, often used in the alt-drag operation.
@@ -1,5 +1,5 @@
1
- import type { ExcalidrawProps } from "@orangecatai/adgen-canvas/types";
2
1
  import type { MarkRequired } from "@orangecatai/common/utility-types";
2
+ import type { ExcalidrawProps } from "@orangecatai/adgen-canvas/types";
3
3
  import type { ExcalidrawElement, ExcalidrawIframeLikeElement, IframeData } from "./types";
4
4
  type IframeDataWithSandbox = MarkRequired<IframeData, "sandbox">;
5
5
  export declare const createSrcDoc: (body: string) => string;
@@ -1,5 +1,5 @@
1
- import type { AppState, PendingExcalidrawElements } from "@orangecatai/adgen-canvas/types";
2
1
  import { type ElementsMap, type ExcalidrawBindableElement, type ExcalidrawElement, type ExcalidrawFlowchartNodeElement } from "./types";
2
+ import type { AppState, PendingExcalidrawElements } from "@orangecatai/adgen-canvas/types";
3
3
  import type { Scene } from "./Scene";
4
4
  type LinkDirection = "up" | "right" | "down" | "left";
5
5
  export declare const getLinkDirectionFromKey: (key: string) => LinkDirection;
@@ -1,5 +1,5 @@
1
- import type { AppClassProperties, AppState, StaticCanvasAppState } from "@orangecatai/adgen-canvas/types";
2
1
  import type { ReadonlySetLike } from "@orangecatai/common/utility-types";
2
+ import type { AppClassProperties, AppState, StaticCanvasAppState } from "@orangecatai/adgen-canvas/types";
3
3
  import type { ExcalidrawElementsIncludingDeleted } from "./Scene";
4
4
  import type { ElementsMap, ElementsMapOrArray, ExcalidrawElement, ExcalidrawFrameLikeElement, NonDeleted, NonDeletedExcalidrawElement } from "./types";
5
5
  export declare const bindElementsToFramesAfterDuplication: (nextElements: readonly ExcalidrawElement[], origElements: readonly ExcalidrawElement[], origIdToDuplicateId: Map<ExcalidrawElement["id"], ExcalidrawElement["id"]>) => void;
@@ -37,9 +37,9 @@ export declare const getContainingFrame: (element: ExcalidrawElement, elementsMa
37
37
  /** */
38
38
  export declare const filterElementsEligibleAsFrameChildren: (elements: readonly ExcalidrawElement[], frame: ExcalidrawFrameLikeElement) => ExcalidrawElement[];
39
39
  /**
40
- * Retains (or repairs for target frame) the ordering invriant where children
41
- * elements come right before the parent frame:
42
- * [el, el, child, child, frame, el]
40
+ * Retains (or repairs for target frame) the ordering invariant where the frame
41
+ * comes before its children elements:
42
+ * [el, el, frame, child, child, el]
43
43
  *
44
44
  * @returns mutated allElements (same data structure)
45
45
  */
@@ -1,5 +1,5 @@
1
- import type { AppClassProperties, AppState, InteractiveCanvasAppState } from "@orangecatai/adgen-canvas/types";
2
1
  import type { Mutable } from "@orangecatai/common/utility-types";
2
+ import type { AppClassProperties, AppState, InteractiveCanvasAppState } from "@orangecatai/adgen-canvas/types";
3
3
  import type { GroupId, ExcalidrawElement, NonDeleted, NonDeletedExcalidrawElement, ElementsMapOrArray, ElementsMap } from "./types";
4
4
  export declare const selectGroup: (groupId: GroupId, appState: InteractiveCanvasAppState, elements: readonly NonDeleted<ExcalidrawElement>[]) => Pick<InteractiveCanvasAppState, "selectedGroupIds" | "selectedElementIds" | "editingGroupId">;
5
5
  export declare const selectGroupsForSelectedElements: {
@@ -1,6 +1,6 @@
1
1
  import { type GlobalPoint } from "@orangecatai/math";
2
- import type { AppState, StaticCanvasAppState, InteractiveCanvasAppState, ElementsPendingErasure, PendingExcalidrawElements } from "@orangecatai/adgen-canvas/types";
3
2
  import type { StaticCanvasRenderConfig, RenderableElementsMap, InteractiveCanvasRenderConfig } from "@orangecatai/adgen-canvas/scene/types";
3
+ import type { AppState, StaticCanvasAppState, InteractiveCanvasAppState, ElementsPendingErasure, PendingExcalidrawElements } from "@orangecatai/adgen-canvas/types";
4
4
  import type { ExcalidrawElement, ExcalidrawTextElement, NonDeletedExcalidrawElement, ExcalidrawFreeDrawElement, ExcalidrawImageElement, ExcalidrawFrameLikeElement, NonDeletedSceneElementsMap, ElementsMap } from "./types";
5
5
  import type { RoughCanvas } from "roughjs/bin/canvas";
6
6
  export declare const getRenderOpacity: (element: ExcalidrawElement, containingFrame: ExcalidrawFrameLikeElement | null, elementsPendingErasure: ElementsPendingErasure, pendingNodes: Readonly<PendingExcalidrawElements> | null, globalAlpha?: number) => number;
@@ -1,5 +1,5 @@
1
- import type { AppState, InteractiveCanvasAppState } from "@orangecatai/adgen-canvas/types";
2
1
  import { LinearElementEditor } from "./linearElementEditor";
2
+ import type { AppState, InteractiveCanvasAppState } from "@orangecatai/adgen-canvas/types";
3
3
  import type { ElementsMap, ElementsMapOrArray, ExcalidrawElement, NonDeletedExcalidrawElement } from "./types";
4
4
  /**
5
5
  * Frames and their containing elements are not to be selected at the same time.
@@ -1,8 +1,8 @@
1
1
  import { type GeometricShape } from "@orangecatai/utils/shape";
2
2
  import { type LocalPoint } from "@orangecatai/math";
3
- import type { GlobalPoint } from "@orangecatai/math";
4
- import type { AppState, EmbedsValidationStatus } from "@orangecatai/adgen-canvas/types";
5
3
  import type { ElementShape, ElementShapes } from "@orangecatai/adgen-canvas/scene/types";
4
+ import type { AppState, EmbedsValidationStatus } from "@orangecatai/adgen-canvas/types";
5
+ import type { GlobalPoint } from "@orangecatai/math";
6
6
  import type { ExcalidrawElement, ExcalidrawSelectionElement, ExcalidrawLinearElement, ExcalidrawFreeDrawElement, ElementsMap, ExcalidrawLineElement } from "./types";
7
7
  import type { Drawable, Options } from "roughjs/bin/core";
8
8
  export declare class ShapeCache {
@@ -1,8 +1,8 @@
1
1
  import { Emitter } from "@orangecatai/common";
2
- import type App from "@orangecatai/adgen-canvas/components/App";
2
+ import { ElementsDelta, AppStateDelta } from "./delta";
3
3
  import type { DTO, ValueOf } from "@orangecatai/common/utility-types";
4
4
  import type { AppState, ObservedAppState } from "@orangecatai/adgen-canvas/types";
5
- import { ElementsDelta, AppStateDelta } from "./delta";
5
+ import type App from "@orangecatai/adgen-canvas/components/App";
6
6
  import type { ApplyToOptions } from "./delta";
7
7
  import type { ExcalidrawElement, OrderedExcalidrawElement, SceneElementsMap } from "./types";
8
8
  export declare const CaptureUpdateAction: {
@@ -1,6 +1,6 @@
1
1
  import { type Radians } from "@orangecatai/math";
2
- import type { AppState } from "@orangecatai/adgen-canvas/types";
3
2
  import type { ExtractSetType } from "@orangecatai/common/utility-types";
3
+ import type { AppState } from "@orangecatai/adgen-canvas/types";
4
4
  import type { Scene } from "./Scene";
5
5
  import type { MaybeTransformHandleType } from "./transformHandles";
6
6
  import type { ElementsMap, ExcalidrawElement, ExcalidrawElementType, ExcalidrawTextContainer, ExcalidrawTextElement, ExcalidrawTextElementWithContainer, NonDeletedExcalidrawElement } from "./types";
@@ -1,5 +1,5 @@
1
- import type { MarkOptional } from "@orangecatai/common/utility-types";
2
1
  import { type ElementConstructorOpts } from "./newElement";
2
+ import type { MarkOptional } from "@orangecatai/common/utility-types";
3
3
  import type { ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFreeDrawElement, ExcalidrawGenericElement, ExcalidrawIframeLikeElement, ExcalidrawImageElement, ExcalidrawLinearElement, ExcalidrawMagicFrameElement, ExcalidrawSelectionElement, ExcalidrawTextElement, FileId, FontFamilyValues, TextAlign, VerticalAlign } from "./types";
4
4
  export type ValidLinearElement = {
5
5
  type: "arrow" | "line";
@@ -1,6 +1,6 @@
1
1
  import { type GlobalPoint } from "@orangecatai/math";
2
- import type { Curve, LineSegment } from "@orangecatai/math";
3
2
  import type { AppState, Zoom } from "@orangecatai/adgen-canvas/types";
3
+ import type { Curve, LineSegment } from "@orangecatai/math";
4
4
  import type { ElementsMap, ExcalidrawArrowElement, ExcalidrawBindableElement, ExcalidrawDiamondElement, ExcalidrawElement, ExcalidrawFreeDrawElement, ExcalidrawLinearElement, ExcalidrawRectanguloidElement } from "./types";
5
5
  /**
6
6
  * Returns the **rotated** components of freedraw, line or arrow elements.
@@ -1,5 +1,5 @@
1
- import type { AppState } from "@orangecatai/adgen-canvas/types";
2
1
  import type { GlobalPoint } from "@orangecatai/math";
2
+ import type { AppState } from "@orangecatai/adgen-canvas/types";
3
3
  import type { Scene } from "./Scene";
4
4
  import type { ExcalidrawArrowElement, ExcalidrawElement, NonDeletedExcalidrawElement, NonDeletedSceneElementsMap, Ordered, OrderedExcalidrawElement } from "./types";
5
5
  /**
@@ -3,7 +3,7 @@ export declare const actionAddToLibrary: {
3
3
  trackEvent: {
4
4
  category: "element";
5
5
  };
6
- perform: (elements: readonly import("@orangecatai/element/types").OrderedExcalidrawElement[], appState: Readonly<import("../types").AppState>, _: unknown, app: import("../types").AppClassProperties) => Promise<{
6
+ perform: (elements: readonly import("@orangecatai/element/types").OrderedExcalidrawElement[], appState: Readonly<import("..").AppState>, _: unknown, app: import("../types").AppClassProperties) => Promise<{
7
7
  captureUpdate: "EVENTUALLY";
8
8
  appState: {
9
9
  toast: {